-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathdotenv.go
More file actions
232 lines (220 loc) · 6.18 KB
/
Copy pathdotenv.go
File metadata and controls
232 lines (220 loc) · 6.18 KB
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package main
import (
"log/slog"
"os"
"path/filepath"
"strings"
"reasonix/internal/config"
"reasonix/internal/fileutil"
)
// credentialsPath is the reasonix-owned global secrets file the settings panel
// writes API keys to — the same file `reasonix setup` writes and config.loadDotEnv
// reads, so a key set in the desktop app resolves for the CLI from any directory.
// Never a project .env: keys stay out of the user's project tree. Falls back to
// ~/.env only when the user config dir can't be resolved.
func credentialsPath() string {
if p := config.UserCredentialsPath(); p != "" {
return p
}
if home, err := os.UserHomeDir(); err == nil {
return filepath.Join(home, ".env")
}
return ".env"
}
// upsertDotEnv sets KEY=value in the global credentials file (replacing an
// existing KEY line, else appending), and applies it to the running process so a
// rebuild picks it up without a restart.
func upsertDotEnv(key, value string) error {
return upsertEnvFile(credentialsPath(), key, value)
}
func removeDotEnv(key string) error {
return removeEnvFile(credentialsPath(), key)
}
// upsertEnvFile merges KEY=value into a KEY=value file at path, preserving
// comments and unrelated lines, writing atomically via a sibling temp + rename.
func upsertEnvFile(path, key, value string) error {
key = strings.TrimSpace(key)
if key == "" {
return nil
}
var lines []string
if b, err := os.ReadFile(path); err == nil {
lines = strings.Split(strings.TrimRight(string(b), "\n"), "\n")
}
replaced := false
for i, ln := range lines {
t := strings.TrimSpace(ln)
if t == "" || strings.HasPrefix(t, "#") {
continue
}
if k, _, ok := strings.Cut(t, "="); ok && strings.TrimSpace(k) == key {
lines[i] = key + "=" + value
replaced = true
break
}
}
if !replaced {
lines = append(lines, key+"="+value)
}
out := strings.Join(lines, "\n") + "\n"
dir := filepath.Dir(path)
if dir != "" && dir != "." {
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
}
tmp, err := os.CreateTemp(dir, "credentials.*.tmp")
if err != nil {
return err
}
tmpPath := tmp.Name()
if _, err := tmp.WriteString(out); err != nil {
tmp.Close()
os.Remove(tmpPath)
return err
}
if err := tmp.Close(); err != nil {
os.Remove(tmpPath)
return err
}
if err := fileutil.ReplaceFile(tmpPath, path); err != nil {
os.Remove(tmpPath)
slog.Warn("dotenv: write failed", "path", path, "key", key, "err", err)
return err
}
slog.Debug("dotenv: upserted", "path", path, "key", key)
return os.Setenv(key, value)
}
func removeEnvFile(path, key string) error {
key = strings.TrimSpace(key)
if key == "" {
return nil
}
data, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
return os.Unsetenv(key)
}
return err
}
lines := strings.Split(strings.TrimRight(string(data), "\n"), "\n")
outLines := make([]string, 0, len(lines))
for _, ln := range lines {
t := strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(ln), "export "))
if t == "" || strings.HasPrefix(t, "#") {
outLines = append(outLines, ln)
continue
}
if k, _, ok := strings.Cut(t, "="); ok && strings.TrimSpace(k) == key {
continue
}
outLines = append(outLines, ln)
}
out := ""
if len(outLines) > 0 {
out = strings.Join(outLines, "\n") + "\n"
}
dir := filepath.Dir(path)
if dir != "" && dir != "." {
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
}
tmp, err := os.CreateTemp(dir, "credentials.*.tmp")
if err != nil {
return err
}
tmpPath := tmp.Name()
if _, err := tmp.WriteString(out); err != nil {
tmp.Close()
os.Remove(tmpPath)
return err
}
if err := tmp.Close(); err != nil {
os.Remove(tmpPath)
return err
}
if err := fileutil.ReplaceFile(tmpPath, path); err != nil {
os.Remove(tmpPath)
return err
}
return os.Unsetenv(key)
}
// envFileKeys returns the set of KEY names assigned in a KEY=value file, empty
// when the file is absent.
func envFileKeys(path string) map[string]bool {
keys := map[string]bool{}
data, err := os.ReadFile(path)
if err != nil {
return keys
}
for _, raw := range strings.Split(string(data), "\n") {
line := strings.TrimPrefix(strings.TrimSpace(raw), "export ")
if line == "" || strings.HasPrefix(line, "#") {
continue
}
if k, _, ok := strings.Cut(line, "="); ok {
keys[strings.TrimSpace(k)] = true
}
}
return keys
}
// promoteProviderKeysToCredentials copies any configured provider api_key_env that
// currently resolves (from a project .env, ~/.env, or the OS env) into the global
// credentials file when it isn't there yet, so a key set for one workspace follows
// the user across every project. Promoted keys are then stripped from ~/.env so the
// credentials file is the single source of truth; a project's own .env is
// user-owned and left untouched.
func promoteProviderKeysToCredentials(cfg *config.Config) {
credPath := credentialsPath()
have := envFileKeys(credPath)
for _, p := range cfg.Providers {
env := strings.TrimSpace(p.APIKeyEnv)
if env == "" || have[env] {
continue
}
val := os.Getenv(env)
if val == "" {
slog.Debug("promote: key not in env", "env", env)
continue
}
if err := upsertEnvFile(credPath, env, val); err != nil {
slog.Warn("promote: write failed", "env", env, "err", err)
continue
}
slog.Info("promote: key migrated to credentials", "env", env)
have[env] = true
removeHomeEnvKey(env)
}
}
// removeHomeEnvKey deletes a single KEY=value assignment from ~/.env (the legacy
// fallback the old migration wrote to), leaving every other line intact. No-op when
// ~/.env is absent or the credentials store resolves to ~/.env itself.
func removeHomeEnvKey(key string) {
home, err := os.UserHomeDir()
if err != nil {
return
}
path := filepath.Join(home, ".env")
if sameConfigPath(path, credentialsPath()) {
return
}
data, err := os.ReadFile(path)
if err != nil {
return
}
var kept []string
removed := false
for _, raw := range strings.Split(string(data), "\n") {
check := strings.TrimPrefix(strings.TrimSpace(raw), "export ")
if k, _, ok := strings.Cut(check, "="); ok && strings.TrimSpace(k) == key {
removed = true
continue
}
kept = append(kept, raw)
}
if !removed {
return
}
_ = os.WriteFile(path, []byte(strings.Join(kept, "\n")), 0o600)
}