This repository was archived by the owner on Jul 8, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenv.go
More file actions
72 lines (58 loc) · 1.73 KB
/
Copy pathenv.go
File metadata and controls
72 lines (58 loc) · 1.73 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
package main
import (
"bufio"
"io"
"os"
"path/filepath"
"strings"
)
// parseDotEnv reads simple KEY=VALUE lines, skipping blanks and #-comments.
func parseDotEnv(r io.Reader) map[string]string {
values := map[string]string{}
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
key, value, ok := strings.Cut(line, "=")
if !ok {
continue
}
values[strings.TrimSpace(key)] = strings.Trim(strings.TrimSpace(value), `"'`)
}
return values
}
// loadDotEnv reads .env next to the running binary. `go run` builds to a throwaway
// temp path, so it falls back to the working directory when that lookup misses.
// Missing file is not an error — it just yields no overrides.
func loadDotEnv() map[string]string {
if exe, err := os.Executable(); err == nil {
if values, ok := readDotEnv(filepath.Join(filepath.Dir(exe), ".env")); ok {
return values
}
}
if values, ok := readDotEnv(".env"); ok {
return values
}
return map[string]string{}
}
func readDotEnv(path string) (map[string]string, bool) {
file, err := os.Open(path) //nolint:gosec // path is always one of two fixed local candidates, not user input
if err != nil {
return nil, false
}
defer func() { _ = file.Close() }()
return parseDotEnv(file), true
}
// configDefault resolves in priority order: real env var, then .env-next-to-binary, then fallback.
// Whatever this returns is only a flag default — an explicit CLI flag still wins at parse time.
func configDefault(dotenv map[string]string, envVar, fallback string) string {
if v := os.Getenv(envVar); v != "" {
return v
}
if v, ok := dotenv[envVar]; ok && v != "" {
return v
}
return fallback
}