summaryrefslogtreecommitdiff
path: root/init.go
blob: 03b6e89bd1de71d3e99397bd55cb045c6779b1a4 (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
71
72
73
74
75
76
77
78
79
80
81
82
package ENV

import (
	"os"
	"path/filepath"
	"strings"
)

// this is an experiment at this point to
// see how this turns out
// normally called by "argv" (go.wit.com/lib/protobuf/argvpb)
func Init(appname, version, buildtime string, fromargv []string, goodFunc func(string), badFunc func(string, error)) {
	APPNAME = appname
	VERSION = version
	BUILDTIME = buildtime
	argv = fromargv
	goodExit = goodFunc
	badExit = badFunc

	if envPB != nil {
		// log.Info("Init() already ran")
		return
	}
	envPB = NewKeys()
	envPB.Init = true

	loadAppENV()

	SetGlobal("lib/ENV", "APPNAME", APPNAME)
	SetGlobal("lib/ENV", "VERSION", VERSION)
	SetGlobal("lib/ENV", "BUILDTIME", BUILDTIME)
}

// if it exists, loads ~/.config/<appname>/<appname>.ENV
func loadAppENV() error {
	saveMu.Lock()
	saveMu.Unlock()
	configDir, err := os.UserConfigDir()
	if err != nil {
		return err
	}

	envPB.Filename = filepath.Join(configDir, APPNAME, APPNAME+".ENV")
	// log.Info("envPB.Filename", envPB.Filename)

	data, err := os.ReadFile(envPB.Filename)
	if err != nil {
		return err
	}

	parseENV(string(data))
	return err
}

func InitValid() bool {
	if envPB == nil {
		// todo: track that the application did not init
		envPB = NewKeys()
		return false
	}
	return envPB.Init
}

func parseENV(data string) {
	// log.Info("loadENV()", filename)
	for _, line := range strings.Split(data, "\n") {
		line = strings.TrimSpace(line)
		if line == "" {
			continue
		}
		parts := strings.Split(line, "=")
		if len(parts) != 2 {
			// log.Info("INVALID LINE:", i, line)
			continue
		}
		c := new(Key)
		c.Var = parts[0]
		c.Value = parts[1]
		envPB.Append(c)
		// log.Printf("ENV LINE: (%v)\n", c)
	}
}