summaryrefslogtreecommitdiff
path: root/config.go
diff options
context:
space:
mode:
Diffstat (limited to 'config.go')
-rw-r--r--config.go107
1 files changed, 107 insertions, 0 deletions
diff --git a/config.go b/config.go
new file mode 100644
index 0000000..afbb159
--- /dev/null
+++ b/config.go
@@ -0,0 +1,107 @@
+package main
+
+// functions to import and export the protobuf
+// data to and from config files
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+
+ "go.wit.com/log"
+ "google.golang.org/protobuf/proto"
+)
+
+func (m *Portmaps) ConfigSave() error {
+ if m == nil {
+ return fmt.Errorf("ConfigSave() nil")
+ }
+ s := m.FormatTEXT()
+ log.Info("proto.Marshal() worked len", len(s))
+ configWrite([]byte(s))
+ return nil
+}
+
+func (m *Portmaps) ConfigLoad() error {
+ if m == nil {
+ return errors.New("It's not safe to run ConfigLoad() on a nil ?")
+ }
+ if os.Getenv("CLOUD_HOME") == "" {
+ homeDir, _ := os.UserHomeDir()
+ fullpath := filepath.Join(homeDir, ".config/cloud")
+ os.Setenv("CLOUD_HOME", fullpath)
+ }
+
+ var data []byte
+ var err error
+ if data, err = loadFile("gus.text"); err != nil {
+ // something went wrong loading the file
+ return err
+ }
+
+ if data != nil {
+ if err = proto.Unmarshal(data, m); err != nil {
+ log.Warn("broken gus.text config file", "gus.text")
+ return err
+ }
+ return nil
+ }
+
+ log.Log(INFO, "gus.ConfigLoad() has", m.Len(), "port mappings")
+ return nil
+}
+
+func loadFile(filename string) ([]byte, error) {
+ homeDir, err := os.UserHomeDir()
+ p := filepath.Join(homeDir, ".config/cloud")
+ fullname := filepath.Join(p, filename)
+ data, err := os.ReadFile(fullname)
+ if errors.Is(err, os.ErrNotExist) {
+ // if file does not exist, just return nil. this
+ return nil, nil
+ }
+ if err != nil {
+ // log.Info("open config file :", err)
+ return nil, err
+ }
+ return data, nil
+}
+
+func (m *Portmaps) loadFile(fname string) ([]byte, error) {
+ fullname := filepath.Join(os.Getenv("CLOUD_HOME"), fname)
+
+ data, err := os.ReadFile(fullname)
+ if err != nil {
+ // log.Info("open config file :", err)
+ return nil, err
+ }
+ return data, nil
+}
+
+func configWrite(data []byte) error {
+ homeDir, err := os.UserHomeDir()
+ p := filepath.Join(homeDir, ".config/cloud")
+ fname := filepath.Join(p, "gus.text")
+ cfgfile, err := os.OpenFile(fname, 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(fname string, data []byte) error {
+ fullname := filepath.Join(os.Getenv("CLOUD_HOME"), fname)
+
+ 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
+}