-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathini.go
More file actions
100 lines (90 loc) · 2.3 KB
/
Copy pathini.go
File metadata and controls
100 lines (90 loc) · 2.3 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
package main
import (
"bufio"
"io"
"os"
"strings"
)
// IniFile represents a simple parsed INI configuration.
type IniFile struct {
data map[string]map[string]string
}
// LoadIni reads an INI file into memory. Returns an empty struct if file is missing.
func LoadIni(filename string) *IniFile {
f, err := os.Open(filename)
if err != nil {
return newIniFile()
}
defer f.Close()
return ParseIni(f)
}
func newIniFile() *IniFile {
return &IniFile{data: make(map[string]map[string]string)}
}
// ParseIni reads INI data from an arbitrary source.
func ParseIni(r io.Reader) *IniFile {
ini := newIniFile()
scanner := bufio.NewScanner(r)
section := ""
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
section = line[1 : len(line)-1]
if ini.data[section] == nil {
ini.data[section] = make(map[string]string)
}
} else if idx := strings.Index(line, "="); idx != -1 {
key := strings.TrimSpace(line[:idx])
val := strings.TrimSpace(line[idx+1:])
if section != "" {
ini.data[section][key] = val
}
}
}
return ini
}
// Merge overlays settings from another IniFile. Values in 'other' overwrite existing ones.
func (ini *IniFile) Merge(other *IniFile) {
if other == nil {
return
}
for section, keys := range other.data {
if _, ok := ini.data[section]; !ok {
ini.data[section] = make(map[string]string)
}
for key, val := range keys {
ini.data[section][key] = val
}
}
}
// GetString safely retrieves a value or returns the default.
func (ini *IniFile) GetString(section, key, def string) string {
// First check environment variables for overrides (e.g. F4_PANEL_SHOW_HIDDEN_FILES)
envUpper := "F4_" + strings.ToUpper(section) + "_" + camelToSnake(key)
if val := os.Getenv(envUpper); val != "" {
return val
}
envLower := strings.ToLower(envUpper)
if val := os.Getenv(envLower); val != "" {
return val
}
if sec, ok := ini.data[section]; ok {
if val, ok := sec[key]; ok {
return val
}
}
return def
}
func camelToSnake(s string) string {
var res []rune
for i, r := range s {
if i > 0 && r >= 'A' && r <= 'Z' {
prev := res[len(res)-1]
if prev != '_' && !(prev >= 'A' && prev <= 'Z') {
res = append(res, '_')
}
}
res = append(res, r)
}
return strings.ToUpper(string(res))
}