-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
316 lines (282 loc) · 7.4 KB
/
main.go
File metadata and controls
316 lines (282 loc) · 7.4 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
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
package main
import (
"fmt"
"os"
"os/signal"
"path"
"regexp"
"strconv"
"strings"
"syscall"
"text/template"
"time"
"github.com/Masterminds/sprig/v3"
"github.com/fatih/color"
"github.com/mattn/go-shellwords"
"gopkg.in/yaml.v2"
)
type rule struct {
Pattern string `yaml:"pattern"`
Message string `yaml:"message"`
vars map[string]string // named capture groups from regex + default variables like INPUT_CMD
}
type config struct {
GlobalVarsNamedGroups []string `yaml:"global_vars_named_groups"`
Rules []rule `yaml:"rules"`
}
func skipUserInput() bool {
skipEnv := os.Getenv("HOLUP_SKIP_USER_INPUT")
if skipEnv == "true" || skipEnv == "1" {
return true
}
// epoch time in seconds
skipUntil := os.Getenv("HOLUP_SKIP_USER_INPUT_UNTIL")
if skipUntil != "" {
skipUntilInt, err := strconv.ParseInt(skipUntil, 10, 64)
if err != nil {
fmt.Printf("failed to parse HOLUP_SKIP_USER_INPUT_UNTIL: %v\n", err)
return false
}
if time.Now().Unix() < skipUntilInt {
return true
}
}
return false
}
func main() {
inputCmd := getinputCmd()
go exitOnSignal()
if !skipUserInput() {
cfg, err := getConfig()
if err != nil {
panic("failed to load config: " + err.Error())
}
rule := getMatchingRule(inputCmd, cfg.Rules)
if rule != nil {
message, err := renderMessage(*rule)
if err != nil {
fmt.Printf("failed to render message: %v", err)
os.Exit(1)
}
input, err := getUserConfirmation(message)
if err != nil {
fmt.Printf("encountered error, aborting the execution: %v", err)
os.Exit(1)
}
if !input {
fmt.Println("aborting...")
os.Exit(0)
}
}
}
debugLog("executing command: %s", strings.Join(inputCmd, " "))
if len(inputCmd) > 1 {
output, err := runCommand(inputCmd, true)
if err != nil {
fmt.Fprint(os.Stderr, output)
fmt.Println(err)
os.Exit(1)
}
fmt.Println(output)
}
}
func getinputCmd() []string {
return os.Args[1:]
}
func exitOnSignal() {
sigc := make(chan os.Signal, 1)
signal.Notify(sigc,
syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT)
s := <-sigc
broadcastSignalToRunningCommands(s)
fmt.Printf("%v signal received, aborting", s)
os.Exit(1)
}
func getUserConfirmation(message string) (input bool, err error) {
message += "\n[y/n]: "
fmt.Print(message)
for {
var input string
_, err := fmt.Scanln(&input)
if err != nil {
return false, fmt.Errorf("failed to read user input: %w", err)
}
if strings.HasPrefix(input, "y") || strings.HasPrefix(input, "Y") {
return true, nil
}
if strings.HasPrefix(input, "n") || strings.HasPrefix(input, "N") {
return false, nil
}
}
}
func templateExecFn(cmd string) string {
cmdParts, err := shellwords.Parse(cmd)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to parse command '%s': %v\n", cmd, err)
return "<error>"
}
output, err := runCommand(cmdParts, false)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to run command '%s': %v: %v\n", cmd, err, output)
return "<error>"
}
return strings.Trim(output, "\n")
}
// List of supported colors - BlackString, RedString, GreenString, YellowString, BlueString, MagentaString, CyanString, WhiteString, HiBlack, HiRed, HiGreen, HiYellow, HiBlue, HiMagenta, HiCyan, HiWhite, HiBlackString, HiRedString, HiGreenString, HiYellowString, HiBlueString, HiMagentaString, HiCyanString, HiWhiteString
func templateColorFn(colorName string, text string) string {
switch strings.ToLower(colorName) {
case "black":
return color.BlackString(text)
case "red":
return color.RedString(text)
case "green":
return color.GreenString(text)
case "yellow":
return color.YellowString(text)
case "blue":
return color.BlueString(text)
case "magenta":
return color.MagentaString(text)
case "cyan":
return color.CyanString(text)
case "white":
return color.WhiteString(text)
case "hiblack":
return color.HiBlackString(text)
case "hired":
return color.HiRedString(text)
case "higreen":
return color.HiGreenString(text)
case "hiyellow":
return color.HiYellowString(text)
case "hiblue":
return color.HiBlueString(text)
case "himagenta":
return color.HiMagentaString(text)
case "hicyan":
return color.HiCyanString(text)
case "hiwhite":
return color.HiWhiteString(text)
default:
return text
}
}
func renderMessage(rule rule) (string, error) {
if rule.Message == "" {
return "", nil
}
messageTemplate, err := template.New("message").
Funcs(sprig.FuncMap()). // spig functions
Funcs(template.FuncMap{ //custom functions
"exec": templateExecFn,
"color": templateColorFn,
},
).
Parse(rule.Message)
if err != nil {
return "", fmt.Errorf("failed to parse message template: %w", err)
}
debugLog("rendering message template: %s with vars: %v", rule.Message, rule.vars)
var renderedMessage strings.Builder
err = messageTemplate.Execute(&renderedMessage, rule.vars)
if err != nil {
return "", fmt.Errorf("failed to execute message template: %w", err)
}
return renderedMessage.String(), nil
}
var debugLogEnabled = os.Getenv("HOLUP_DEBUG") == "true"
func debugLog(format string, a ...interface{}) {
if debugLogEnabled {
fmt.Printf("[DEBUG] "+format+"\n", a...)
}
}
// returns the first matching rule, or nil if no rule matches
func getMatchingRule(cmdArgs []string, rules []rule) *rule {
command := strings.Join(cmdArgs, " ")
for i := range rules {
rule := &rules[i]
if rule.Pattern != "" {
regexp, err := regexp.Compile(rule.Pattern)
if err != nil {
fmt.Printf("[WARN] holup failed to compile regex \"%s\": %v", rule.Pattern, err)
continue
}
if regexp.MatchString(command) {
match := regexp.FindStringSubmatch(command)
for i, name := range regexp.SubexpNames() {
if i != 0 && name != "" {
rule.vars[name] = match[i]
}
}
return rule
}
}
}
return nil
}
func getConfig() (config, error) {
configFile := os.Getenv("HOLUP_CONFIG")
if configFile == "" {
homeDir, err := os.UserHomeDir()
if err != nil {
debugLog("failed to get user home dir: %v", err)
homeDir = ""
}
configFile = path.Join(homeDir, ".holup", "config.yaml")
configFile = os.ExpandEnv(configFile)
}
var cfg config
file, err := os.ReadFile(configFile)
if err != nil {
return cfg, err
}
err = yaml.Unmarshal(file, &cfg)
if err != nil {
return cfg, err
}
inputCmd := getinputCmd()
var globalVars map[string]string = make(map[string]string)
for _, r := range cfg.GlobalVarsNamedGroups {
regexp, err := regexp.Compile(r)
if err != nil {
fmt.Printf("failed compiling global regexp: %v", err)
continue
}
appendMap(globalVars, getNamedGroupValues(*regexp, strings.Join(inputCmd, " ")))
}
debugLog("global vars from regexp '%v': %v", cfg.GlobalVarsNamedGroups, globalVars)
for i := range cfg.Rules {
if cfg.Rules[i].vars == nil {
cfg.Rules[i].vars = map[string]string{}
}
cfg.Rules[i].vars["INPUT_CMD"] = strings.Join(inputCmd, " ")
if len(globalVars) > 0 {
for k, v := range globalVars {
cfg.Rules[i].vars[k] = v
}
}
}
return cfg, nil
}
func getNamedGroupValues(regexp regexp.Regexp, input string) map[string]string {
var output = make(map[string]string)
match := regexp.FindStringSubmatch(input)
if match == nil {
return output
}
for i, name := range regexp.SubexpNames() {
if i != 0 && name != "" && i < len(match) {
output[name] = match[i]
}
}
return output
}
func appendMap(m1, m2 map[string]string) map[string]string {
for k, v := range m2 {
m1[k] = v
}
return m1
}