-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdiscover.go
More file actions
86 lines (78 loc) · 2.2 KB
/
Copy pathdiscover.go
File metadata and controls
86 lines (78 loc) · 2.2 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
package env
import (
"os"
"path/filepath"
"strings"
)
// Candidate represents a discovered .env file with its derived environment.
type Candidate struct {
File string
Env string
}
// Discover finds .env files in the current directory.
// It excludes template files like .env.example, .env.sample, etc.
func Discover() []Candidate {
entries, err := os.ReadDir(".")
if err != nil {
return nil
}
// Template files to exclude (not real secrets)
excludeFiles := map[string]bool{
".env.example": true, // Template files
".env.sample": true,
".env.template": true,
}
var candidates []Candidate
for _, entry := range entries {
name := entry.Name()
if strings.HasPrefix(name, ".env") && !excludeFiles[name] && !entry.IsDir() {
candidates = append(candidates, Candidate{
File: name,
Env: DeriveEnvFromFile(name),
})
}
}
return candidates
}
// envAliases maps common framework-specific env file suffixes and shorthand
// names to standard vault environment names.
var envAliases = map[string]string{
"local": "development",
"dev": "development",
"prod": "production",
"stage": "staging",
"stg": "staging",
"development.local": "development",
"production.local": "production",
"staging.local": "staging",
"test.local": "development",
"dev.local": "development",
"prod.local": "production",
"stage.local": "staging",
}
// NormalizeEnvName maps shorthand or framework-specific environment names
// to their canonical vault environment names.
func NormalizeEnvName(name string) string {
name = strings.ToLower(strings.TrimSpace(name))
if mapped, ok := envAliases[name]; ok {
return mapped
}
return name
}
// DeriveEnvFromFile derives the environment name from a filename.
// Examples:
// - ".env" -> "development"
// - ".env.local" -> "development"
// - ".env.production" -> "production"
// - ".env.staging" -> "staging"
func DeriveEnvFromFile(file string) string {
base := filepath.Base(file)
if base == ".env" {
return "development"
}
if strings.HasPrefix(base, ".env.") {
suffix := strings.TrimPrefix(base, ".env.")
return NormalizeEnvName(suffix)
}
return "development"
}