/
main.go
186 lines (165 loc) · 4.27 KB
/
main.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
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
package main;
import (
"bufio"
"fmt"
"flag"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
)
import "github.com/kylelemons/go-gypsy/yaml"
type Config struct {
lineRules []*LineRule
}
type LineRule struct {
pattern string
patternRx *regexp.Regexp
message string
}
func main() {
defaultUrl := "https://raw.github.com/ijt/aphid/config/config.yaml"
defaultPrefix := " " + Bold + FgCyan + "[aphid]" + Reset
configUrl := flag.String("c", defaultUrl,
"URL of config file in YAML format")
prefix := flag.String("p", defaultPrefix, "Prefix for aphid messages")
strict := flag.Bool("s", false, "Be strict when parsing patterns")
flag.Parse()
config, err := parseConfig(fetch(*configUrl), *configUrl)
if err != nil {
log.Fatalln(err)
}
err = compileRegexes(config)
if err != nil && *strict {
os.Exit(1)
}
addHelp(bufio.NewReader(os.Stdin), config, *prefix)
}
// fetch gets the contents at a given URL. The URL can point to a local file.
// Errors terminate.
func fetch(url string) []byte {
// Make a client that can load files if given a file:// URL.
t := &http.Transport{}
t.RegisterProtocol("file", http.NewFileTransport(http.Dir("/")))
c := &http.Client{Transport: t}
// Download the config file from a well-known location.
resp, err := c.Get(url)
if err != nil {
log.Fatalln(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
return body
}
func parseConfig(body []byte, url string) (conf *Config, err error) {
defer func() {
if e := recover(); e != nil {
// Clear return value.
conf = nil
body := string(body)
if len(body) > 200 {
body = body[:200] + "..."
}
err = fmt.Errorf("Failed to parse config file at %s:\n\n%s",
url, body)
}
}()
// Parse the YAML file.
yamlFile := yaml.Config(string(body))
count, e := yamlFile.Count("line_rules")
if e != nil {
err = fmt.Errorf("Could not get line_rules config section.")
return
}
// Extract the line rules.
conf = &Config {}
conf.lineRules = make([]*LineRule, count)
for i, _ := range conf.lineRules {
pattern, e := yamlFile.Get(fmt.Sprintf("line_rules[%d].pattern", i))
if e != nil {
return nil, e
}
message, e := yamlFile.Get(fmt.Sprintf("line_rules[%d].message", i))
if e != nil {
return nil, e
}
conf.lineRules[i] = &LineRule{ pattern, nil, message }
}
return conf, nil
}
// compileRegexes tries to compile all the regexes in the config.
// If any of them fail, it returns the first error it found.
func compileRegexes(conf *Config) error {
retErr := error(nil)
for _, rule := range conf.lineRules {
rx, err := regexp.Compile(rule.pattern)
if err != nil {
log.Println(err)
if retErr != nil {
retErr = err
}
} else {
rule.patternRx = rx
}
}
return retErr
}
// addHelp reads lines from a reader and prints them to stdout. It interjects
// helpful messages when those lines match patterns given by the config.
func addHelp(reader *bufio.Reader, conf *Config, prefix string) {
for {
line, err := reader.ReadString('\n')
if err != nil {
break
}
if line == "" {
fmt.Fprintln(os.Stderr, "Line is null. Ending.")
os.Exit(1)
}
fmt.Print(line)
for _, rule := range(conf.lineRules) {
matched := rule.patternRx.MatchString(line)
if matched {
pat := rule.patternRx
res := []byte {}
matches := pat.FindAllStringSubmatchIndex(line, -1)
for _, submatchRange := range matches {
msg := rule.message + "\n"
res = pat.ExpandString(res, msg, line,
submatchRange)
}
fmt.Print(prefix, " ", string(res))
}
}
}
}
// https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/99MKtEkvQ2c
const (
Reset = "\x1b[0m"
Bold = "\x1b[1m"
Dim = "\x1b[2m"
Underscore = "\x1b[4m"
Blink = "\x1b[5m"
Reverse = "\x1b[7m"
Hidden = "\x1b[8m"
FgBlack = "\x1b[30m"
FgRed = "\x1b[31m"
FgGreen = "\x1b[32m"
FgYellow = "\x1b[33m"
FgBlue = "\x1b[34m"
FgMagenta = "\x1b[35m"
FgCyan = "\x1b[36m"
FgWhite = "\x1b[37m"
BgBlack = "\x1b[40m"
BgRed = "\x1b[41m"
BgGreen = "\x1b[42m"
BgYellow = "\x1b[43m"
BgBlue = "\x1b[44m"
BgMagenta = "\x1b[45m"
BgCyan = "\x1b[46m"
BgWhite = "\x1b[47m"
)