pbconfig/load.go

71 lines
1.5 KiB
Go

package config
// functions to import and export the protobuf
// data to and from config files
import (
"errors"
"os"
"path/filepath"
"go.wit.com/log"
"google.golang.org/protobuf/encoding/prototext"
"google.golang.org/protobuf/proto"
)
/*
// loads a file from ~/.config/<argname>/
func Load(argname string) ([]byte, string) {
}
*/
var ErrEmpty error = log.Errorf("file was empty")
// returns:
// - Full path to the config file. usually: ~/.config/<argname>
// - []byte : the contents of the file
// - error on read
func ConfigLoad(pb proto.Message, argname string, protoname string) error {
var data []byte
var fullname string
homeDir, err := os.UserHomeDir()
if err != nil {
return err
}
fullname = filepath.Join(homeDir, ".config", argname, protoname+".text")
if data, err = loadFile(fullname); err != nil {
log.Warn("config file failed to load", err)
// set pb.Filename that was attempted
SetFilename(pb, fullname)
return err
}
// don't even bother with Marshal()
if data == nil {
return ErrEmpty // file is empty
}
// Unmarshal()
if err = prototext.Unmarshal(data, pb); err != nil {
return err
}
log.Infof("ConfigLoad() arg=%s, proto=%s\n", argname, protoname)
return nil
}
func loadFile(fullname string) ([]byte, error) {
data, err := os.ReadFile(fullname)
if errors.Is(err, os.ErrNotExist) {
// if file does not exist, just return nil. this
return nil, err
}
if err != nil {
// log.Info("open config file :", err)
return nil, err
}
return data, nil
}