summaryrefslogtreecommitdiff
path: root/load.go
diff options
context:
space:
mode:
Diffstat (limited to 'load.go')
-rw-r--r--load.go63
1 files changed, 60 insertions, 3 deletions
diff --git a/load.go b/load.go
index 31e169a..1568968 100644
--- a/load.go
+++ b/load.go
@@ -1,14 +1,71 @@
package config
+// functions to import and export the protobuf
+// data to and from config files
+
import (
+ "errors"
"os"
- "strings"
- "unicode"
+ "path/filepath"
"go.wit.com/log"
- "golang.org/x/term"
+ "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)
+ // something went wrong loading the file
+ 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
+ }
+
+ // set pb.Filename if it is there in the .proto file
+ SetFilename(pb, fullname)
+
+ 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
+}