add Save()

This commit is contained in:
Jeff Carr 2025-09-10 14:56:48 -05:00
parent c0a3642ed2
commit 5f886d7c07
2 changed files with 43 additions and 16 deletions

View File

@ -45,7 +45,7 @@ func ConfigLoad(pb proto.Message, argname string, protoname string) error {
return ErrEmpty // file is empty return ErrEmpty // file is empty
} }
// Unmarshal() // Unmarshal()
if err = prototext.Unmarshal(data, pb); err != nil { if err = prototext.Unmarshal(data, pb); err != nil {
return err return err
} }

57
save.go
View File

@ -1,7 +1,47 @@
package config package config
// functions to import and export the protobuf import (
// data to and from config files "fmt"
"os"
"path/filepath"
"go.wit.com/log"
"google.golang.org/protobuf/encoding/prototext"
"google.golang.org/protobuf/proto"
)
var ErrProtoFilename error = log.Errorf("proto does not have Filename")
func ConfigSave(pb proto.Message) error {
// get pb.Filename if it is there in the .proto file
fullname, ok := GetFilename(pb)
if !ok {
return ErrProtoFilename
}
// Unmarshal()
data, err := prototext.Marshal(pb)
if err != nil {
return err
}
log.Infof("ConfigSave() filename=%s %d\n", fullname, len(data))
return configWrite(fullname, data)
}
func configWrite(fullname string, data []byte) error {
if _, base := filepath.Split(fullname); base == "" {
return fmt.Errorf("--config option not set")
}
cfgfile, err := os.OpenFile(fullname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
defer cfgfile.Close()
if err != nil {
log.Warn("open config file :", err)
return err
}
_, err = cfgfile.Write(data)
return err
}
/* /*
@ -20,19 +60,6 @@ func (e *Events) Save() {
} }
func configWrite(fullname string, data []byte) error {
if _, base := filepath.Split(fullname); base == "" {
return fmt.Errorf("--config option not set")
}
cfgfile, err := os.OpenFile(fullname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
defer cfgfile.Close()
if err != nil {
log.Warn("open config file :", err)
return err
}
cfgfile.Write(data)
return nil
}
func (m *Portmaps) configWrite(fullname string, data []byte) error { func (m *Portmaps) configWrite(fullname string, data []byte) error {
if _, base := filepath.Split(fullname); base == "" { if _, base := filepath.Split(fullname); base == "" {