blob: 14869b05cd6c91521505b74c6e100de829a4ef8f (
plain)
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
|
package testhelper
import (
"bufio"
"io"
"regexp"
"strings"
)
var cfgHeaderRegex = regexp.MustCompile(`^\[(.*?)\]$`)
// ConfigFile allows access to the different sections of a git config file
type ConfigFile map[string][]string
// ParseConfig will attempt to parse a config file into sections
func ParseConfig(src io.Reader) (ConfigFile, error) {
scanner := bufio.NewScanner(src)
currentSection := ""
parsed := map[string][]string{}
for scanner.Scan() {
line := scanner.Text()
matches := cfgHeaderRegex.FindStringSubmatch(line)
if len(matches) == 2 {
currentSection = matches[1]
continue
}
parsed[currentSection] = append(
parsed[currentSection],
strings.TrimSpace(line),
)
}
if err := scanner.Err(); err != nil {
return nil, err
}
return parsed, nil
}
var configPairRegex = regexp.MustCompile(`^(.*?) = (.*?)$`)
// GetValue will return the value for a configuration line int the specified
// section for the provided key
func (cf ConfigFile) GetValue(section, key string) (string, bool) {
pairs := cf[section]
for _, pair := range pairs {
matches := configPairRegex.FindStringSubmatch(pair)
if len(matches) != 3 {
continue
}
k, v := matches[1], matches[2]
if k == key {
return v, true
}
}
return "", false
}
|