-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzuliprc.go
75 lines (63 loc) · 1.47 KB
/
zuliprc.go
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
package zulip
import (
"bufio"
"bytes"
"io"
"os"
"regexp"
"strings"
)
type (
// Zuliprc represents the content of a zuliprc file
// It is a map of sections, where each section is a map of key-value pairs
Zuliprc map[string]SectionData
// SectionData represents the key-value pairs of a section in a zuliprc file
SectionData struct {
Email string
APIKey string
Site string
}
)
func ParseZuliprc(file string) (Zuliprc, error) {
f, err := os.ReadFile(file)
if err != nil {
return nil, err
}
r := bytes.NewReader(f)
return parseZuliprcContent(r)
}
func parseZuliprcContent(b io.Reader) (Zuliprc, error) {
s := bufio.NewScanner(b)
rxSection := regexp.MustCompile(`\[(.*)\]`)
rxKeyVal := regexp.MustCompile(`(.*)=(.*)`)
currentSection := "unknown"
z := Zuliprc{}
for s.Scan() {
line := strings.TrimSpace(s.Text())
if line == "" {
continue
}
if rxSection.MatchString(line) {
section := rxSection.FindStringSubmatch(line)[1]
z[section] = SectionData{}
currentSection = strings.TrimSpace(section)
continue
}
if rxKeyVal.MatchString(line) {
kv := rxKeyVal.FindStringSubmatch(line)
key := kv[1]
val := kv[2]
sectionData := z[currentSection]
switch strings.TrimSpace(key) {
case "email":
sectionData.Email = strings.TrimSpace(val)
case "key":
sectionData.APIKey = strings.TrimSpace(val)
case "site":
sectionData.Site = strings.TrimSpace(val)
}
z[currentSection] = sectionData
}
}
return z, nil
}