summaryrefslogtreecommitdiff
path: root/addMutex.go
blob: cfd31b3bc7bb654a7304271ac9c9f5a151d65e7f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package main

// will this help things?
// this is a hack for testing for now
// cram a mutex in the pb.go file

import (
	"fmt"
	"os"
	"strings"

	"go.wit.com/log"
)

func (pb *Files) addMutex(f *File) error {
	fullname := f.Pbfilename
	log.Info("pb filename:", fullname)
	data, err := os.ReadFile(fullname)
	if err != nil {
		log.Info("pb filename failed to read:", err)
		return err
	}

	// check if autogenpb has already looked at this file
	for _, line := range strings.Split(string(data), "\n") {
		if strings.Contains(line, "autogenpb DO NOT EDIT") {
			log.Info("autogenpb has already been run on", fullname)
			return nil
		}
	}

	w, _ := os.OpenFile(f.Pbfilename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)

	pbHeaderComment(w)

	lines := strings.Split(string(data), "\n")
	for _, line := range lines {
		if strings.HasPrefix(line, "package ") {
			log.Info("CHANGING package:", line, "to package:", f.Package)
			fmt.Fprintln(w, "package "+f.Package)
			// log.Info("CHANGING package:", line, "to package:main")
			// fmt.Fprintln(w, "package "+"main")
			continue
		}

		if f.structMatch(line) {
			if argv.Mutex {
				log.Info("Adding Mutex to:", line)
				fmt.Fprintln(w, line)
				fmt.Fprintln(w, "\tLock sync.RWMutex // auto-added by go.wit.com/apps/autogenpb")
				fmt.Fprintln(w, "")
			} else {
				log.Info("Skipping. Mutex = false for:", line)
				fmt.Fprintln(w, line)
				fmt.Fprintln(w, "\t// Lock sync.RWMutex // autogenpb skipped this. needs --mutex command line arg")
				fmt.Fprintln(w, "")
			}
		} else {
			fmt.Fprintln(w, line)
		}
	}
	for _, msg := range f.MsgNames {
		if !msg.MutexFound && msg.DoMutex {
			return fmt.Errorf("addMutex() parse didn't work for %s", msg.Name)
		}
	}
	return nil
}

// is this struct supposed to have a Mutex added?
func (pf *File) structMatch(line string) bool {
	var msg *MsgName
	var start string

	msg = pf.Bases
	start = "type " + msg.Name + " struct {"
	if strings.HasPrefix(line, start) {
		msg.MutexFound = true
		return true
	}

	msg = pf.Base
	start = "type " + msg.Name + " struct {"
	if strings.HasPrefix(line, start) {
		msg.MutexFound = true
		return true
	}

	for _, msg = range pf.MsgNames {
		start = "type " + msg.Name + " struct {"
		if strings.HasPrefix(line, start) {
			msg.MutexFound = true
			return true
		}
	}
	return false
}