diff --git a/load.go b/load.go index 1568968..5373025 100644 --- a/load.go +++ b/load.go @@ -45,7 +45,7 @@ func ConfigLoad(pb proto.Message, argname string, protoname string) error { return ErrEmpty // file is empty } - // Unmarshal() + // Unmarshal() if err = prototext.Unmarshal(data, pb); err != nil { return err } diff --git a/save.go b/save.go index 35c5bab..b035e7c 100644 --- a/save.go +++ b/save.go @@ -1,7 +1,47 @@ package config -// functions to import and export the protobuf -// data to and from config files +import ( + "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 { if _, base := filepath.Split(fullname); base == "" {