-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
102 lines (84 loc) · 1.8 KB
/
parser.go
File metadata and controls
102 lines (84 loc) · 1.8 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
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
type EnvVar struct {
Key string
Value string
Line int
Comment string
}
type EnvFile struct {
Path string
Vars map[string]EnvVar
}
func ParseEnvFile(path string) (*EnvFile, error) {
file, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("failed to open file: %w", err)
}
defer file.Close()
envFile := &EnvFile{
Path: path,
Vars: make(map[string]EnvVar),
}
scanner := bufio.NewScanner(file)
lineNum := 0
for scanner.Scan() {
lineNum++
line := scanner.Text()
trimmed := strings.TrimSpace(line)
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
continue
}
key, value, comment := parseLine(line)
if key != "" {
envFile.Vars[key] = EnvVar{
Key: key,
Value: value,
Line: lineNum,
Comment: comment,
}
}
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("error reading file: %w", err)
}
return envFile, nil
}
func parseLine(line string) (key, value, comment string) {
parts := strings.SplitN(line, "=", 2)
if len(parts) != 2 {
return "", "", ""
}
key = strings.TrimSpace(parts[0])
valPart := parts[1]
commentIdx := strings.Index(valPart, "#")
if commentIdx != -1 && !isInsideQuotes(valPart, commentIdx) {
comment = strings.TrimSpace(valPart[commentIdx+1:])
valPart = valPart[:commentIdx]
}
value = strings.TrimSpace(valPart)
value = unquote(value)
return key, value, comment
}
func isInsideQuotes(s string, pos int) bool {
inQuote := false
for i := 0; i < pos && i < len(s); i++ {
if s[i] == '"' || s[i] == '\'' {
inQuote = !inQuote
}
}
return inQuote
}
func unquote(s string) string {
if len(s) >= 2 {
if (s[0] == '"' && s[len(s)-1] == '"') || (s[0] == '\'' && s[len(s)-1] == '\'') {
return s[1 : len(s)-1]
}
}
return s
}