Debian Codegraph @

utils.go

raw ◀ ▶
1 Debian patch touch this file
1 package gitconfig
2
3 import (
4 "strings"
5
6 "github.com/gobwas/glob"
7 )
8
9 // globMatch matches a string against a glob pattern.
10 // It uses the gobwas/glob package and supports:
11 // - single-asterisk (*) patterns for matching within a path component
12 // - double-asterisk (**) patterns for matching across path components
13 // - question mark (?) for single character matching
14 // - character classes [abc] and ranges [a-z]
15 //
16 // The pattern uses '/' as a path separator.
17 //
18 // Example:
19 //
20 // globMatch("feat/*", "feat/test") // returns (true, nil)
21 // globMatch("feat/**", "feat/foo/bar") // returns (true, nil)
22 //
23 // Returns:
24 // - (true, nil) if the string matches the pattern.
25 // - (false, nil) if the string does not match.
26 // - (false, error) if the pattern is invalid.
27 func globMatch(pattern, s string) (bool, error) {
•28 pattern = strings.ReplaceAll(pattern, "/**/", "/{**/,}")
29 if pattern, found := strings.CutPrefix(pattern, "**/"); found {
30 pattern = "{**/,}" + pattern
31 }
32
33 g, err := glob.Compile(pattern, '/')
34 if err != nil {
35 return false, err
36 }
37
38 return g.Match(s), nil
39 }
40
41 // splitKey splits a fully qualified gitconfig key into two or three parts.
42 // A valid key consists of either a section and a key separated by a dot
43 // or section, subsection and key, all separated by a dot. Note that
44 // the subsection might contain dots itself.
45 //
46 // Valid examples:
47 // - core.push
48 // - [email protected].
49 func splitKey(key string) (section, subsection, skey string) { //nolint:nonamedreturns
50 n := strings.Index(key, ".")
51 if n > 0 {
52 section = key[:n]
53 }
54
55 if m := strings.LastIndex(key, "."); n != m && m > 0 && len(key) > m+1 {
56 subsection = key[n+1 : m]
57 skey = key[m+1:]
58
59 return
60 }
61
62 skey = key[n+1:]
63
64 return
65 }
66
67 // canonicalizeKey normalizes a gitconfig key according to git rules.
68 //
69 // Canonicalization rules (per git-config):
70 // - Section names are converted to lowercase
71 // - Subsection names are kept as-is (case-sensitive per git spec)
72 // - Key names are converted to lowercase
73 //
74 // Returns an empty string if the key is invalid (missing section or key part).
75 //
76 // Examples:
77 //
78 // canonicalizeKey("Core.Push") returns "core.push"
79 // canonicalizeKey("remote.Origin.URL") returns "remote.Origin.url"
80 // canonicalizeKey("valid.key") returns "valid.key"
81 // canonicalizeKey("invalid") returns "" // missing key part
82 func canonicalizeKey(key string) string {
83 if key == "" {
84 // invalid key, return empty string
85 return ""
86 }
87
88 section, subsection, skey := splitKey(key)
89 // "Section names are case-insensitive.""
90 section = strings.ToLower(section)
91 // "Subsection names are case sensitive."
92 // "The variable names are case-insensitive."
93 skey = strings.ToLower(skey)
94
95 if section == "" || skey == "" {
96 // invalid key, return empty string
97 return ""
98 }
99
100 if subsection == "" {
101 return section + "." + skey
102 }
103
104 return section + "." + subsection + "." + skey
105 }
106
107 // trim removes leading and trailing whitespace from all strings in the slice.
108 // It modifies the slice in-place.
109 //
110 // This is a convenience function for cleaning up parsed lines.
111 func trim(s []string) {
112 for i, e := range s {
113 s[i] = strings.TrimSpace(e)
114 }
115 }
116
117 // parseLineForComment separates a line into content and comment parts.
118 //
119 // Parsing rules:
120 // - Searches for the first unquoted comment character (# or ;)
121 // - Ignores comment characters inside double-quoted strings
122 // - Trims whitespace from both content and comment
123 // - Removes surrounding double quotes from content
124 //
125 // The returned comment string does NOT include the delimiter character itself.
126 //
127 // Examples:
128 //
129 // parseLineForComment(`value # comment`) returns ("value", "comment")
130 // parseLineForComment(`"content # not-comment" # comment`) returns ("content # not-comment", "comment")
131 // parseLineForComment(`plain-value`) returns ("plain-value", "")
132 // parseLineForComment(`"quoted value"`) returns ("quoted value", "")
133 func parseLineForComment(line string) (string, string) {
134 line = strings.TrimSpace(line) // Trim whitespace from the line first
135 if !strings.HasPrefix(line, `"`) {
136 // no properly quoted value string, we shouldn't have ended up here.
137 if value, comment, found := strings.Cut(line, "#"); found {
138 return strings.TrimSpace(value), strings.TrimSpace(comment)
139 }
140 if value, comment, found := strings.Cut(line, ";"); found {
141 return strings.TrimSpace(value), strings.TrimSpace(comment)
142 }
143
144 // no comment found, return the line as is
145 return line, ""
146 }
147 commentStartIndex := -1 // Initialize to -1, indicating comment not found yet
148 inQuotes := false
149 foundComment := false // Flag to signal when to break the loop
150
151 // Iterate through the string to find the first unquoted comment character
152 for i, r := range line {
153 switch r {
154 case '"':
155 inQuotes = !inQuotes
156 case '#', ';':
157 if !inQuotes {
158 commentStartIndex = i
159 foundComment = true
160 }
161 }
162 if foundComment {
163 break // Exit the for loop
164 }
165 }
166
167 content := ""
168 comment := ""
169
170 // Determine initial content and comment parts based on index
171 var initialContent string
172 if commentStartIndex != -1 {
173 // Comment character was found
174 initialContent = line[:commentStartIndex]
175 // Extract comment text *after* the delimiter and trim whitespace
176 if commentStartIndex+1 <= len(line) { // Check index bounds
177 comment = strings.TrimSpace(line[commentStartIndex+1:])
178 } else {
179 comment = "" // Delimiter was the very last character
180 }
181 } else {
182 // No unquoted comment character found
183 initialContent = line
184 comment = ""
185 }
186
187 // Trim whitespace from the initial content part FIRST
188 trimmedContent := strings.TrimSpace(initialContent)
189 // Now, check for and remove surrounding quotes from the trimmed content
190 content = strings.Trim(trimmedContent, `"`)
191
192 // Return the processed content and the processed comment part
193 return content, comment
194 }