110 lines
2.4 KiB
Go
110 lines
2.4 KiB
Go
package config
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"go.wit.com/log"
|
|
"google.golang.org/protobuf/encoding/protojson"
|
|
"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
|
|
}
|
|
|
|
s := prototext.Format(pb)
|
|
|
|
dir, name := filepath.Split(fullname)
|
|
if name == "" {
|
|
return fmt.Errorf("filename was blank")
|
|
}
|
|
err := os.MkdirAll(dir, os.ModePerm)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
log.Infof("ConfigSave() filename=%s %d\n", fullname, len(s))
|
|
return configWrite(fullname, []byte(s))
|
|
}
|
|
|
|
func ConfigSaveWithHeader(pb proto.Message, header string) error {
|
|
// get pb.Filename if it is there in the .proto file
|
|
fullname, ok := GetFilename(pb)
|
|
if !ok {
|
|
return ErrProtoFilename
|
|
}
|
|
|
|
dir, name := filepath.Split(fullname)
|
|
if name == "" {
|
|
return fmt.Errorf("filename was blank")
|
|
}
|
|
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
|
|
return err
|
|
}
|
|
|
|
var final error
|
|
if err := configTEXT(fullname, pb, header); err != nil {
|
|
final = err
|
|
}
|
|
|
|
if strings.HasSuffix(fullname, ".text") {
|
|
fullname = strings.TrimSuffix(fullname, ".text")
|
|
fullname += ".json"
|
|
if err := configJSON(fullname, pb); err != nil {
|
|
final = err
|
|
}
|
|
}
|
|
return final
|
|
}
|
|
|
|
func configTEXT(fullname string, pb proto.Message, header string) error {
|
|
s := prototext.Format(pb)
|
|
|
|
log.Infof("ConfigSave() filename=%s %d\n", fullname, len(s))
|
|
return configWrite(fullname, []byte(header+s))
|
|
}
|
|
|
|
func configJSON(fullname string, pb proto.Message) error {
|
|
data := protojson.Format(pb)
|
|
|
|
log.Infof("ConfigSave() filename=%s %d\n", fullname, len(data))
|
|
return configWrite(fullname, []byte(data))
|
|
}
|
|
|
|
func configWrite(fullname string, data []byte) error {
|
|
|
|
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
|
|
}
|
|
|
|
/*
|
|
func (e *Events) Save() {
|
|
var fullname string
|
|
base, _ := filepath.Split(argv.Config)
|
|
fullname = filepath.Join(base, "events.pb")
|
|
|
|
data, err := e.Marshal()
|
|
if err != nil {
|
|
log.Info("proto.Marshal() failed", err)
|
|
return
|
|
}
|
|
log.Info("proto.Marshal() worked len", len(data))
|
|
configWrite(fullname, data)
|
|
}
|
|
*/
|