summaryrefslogtreecommitdiff
path: root/load.go
blob: 87831fc6f21336d928af1de08f023894975dcb91 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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
}