autogenpb/addMutex.go

81 lines
1.9 KiB
Go
Raw Normal View History

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")
return nil
}
}
w, _ := os.OpenFile(f.Pbfilename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
2025-01-09 06:05:38 -06:00
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 {
for _, msg := range pf.MsgNames {
start := "type " + msg.Name + " struct {"
if strings.HasPrefix(line, start) {
msg.MutexFound = true
return true
}
}
return false
}