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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
|
package env
import (
"os"
"os/user"
"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 {
// fmt.Println("Init() already ran")
return
}
envPB = NewKeys()
envPB.Init = true
envPB.HomeDir, _ = os.UserHomeDir()
loadAppENV()
SetGlobal("lib/env", "APPNAME", APPNAME)
SetGlobal("lib/env", "VERSION", VERSION)
SetGlobal("lib/env", "BUILDTIME", BUILDTIME)
usr, err := user.Current()
if err == nil {
SetGlobal("lib/env", "username", usr.Username)
}
homedir, err := os.UserHomeDir()
if err == nil {
SetGlobal("lib/env", "homedir", homedir)
}
}
// if it exists, loads ~/.config/<appname>/<appname>rc
func loadAppENV() error {
configDir, err := os.UserConfigDir()
if err != nil {
return err
}
{
// old way. deprecate in 2026
envPB.Filename = filepath.Join(configDir, APPNAME, APPNAME+".ENV")
data, err := os.ReadFile(envPB.Filename)
if err == nil {
parseENV(string(data))
}
}
envPB.Filename = filepath.Join(configDir, APPNAME, APPNAME+"rc")
data, err := os.ReadFile(envPB.Filename)
if err == nil {
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
}
// only allow super simple files
func parseENV(data string) {
var helptext string
// fmt.Println("loadENV()", filename)
for _, line := range strings.Split(data, "\n") {
line = strings.TrimSpace(line)
if line == "" {
// ignore empty lines
continue
}
if strings.HasPrefix(line, "#") {
// save notes & instructions from the config file
helptext += line + "\n"
continue
}
parts := strings.Split(line, "=")
if len(parts) != 2 {
// fmt.Println("INVALID LINE:", i, line)
continue
}
varname := parts[0]
varname = strings.TrimSpace(varname)
if varname == "" {
// ignore empty varname
continue
}
// check for duplicates here
found := envPB.FindByVar(varname)
if found != nil {
// varname alrady set
continue
}
value := parts[1]
value = strings.Trim(value, "'\"")
saveMu.Lock()
saveMu.Unlock()
c := new(Key)
c.Var = varname
c.Value = value
c.Help = helptext
helptext = ""
envPB.Append(c)
}
}
|