-
Notifications
You must be signed in to change notification settings - Fork 0
/
pumpkin.go
73 lines (61 loc) · 1.43 KB
/
pumpkin.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
package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"os/exec"
"regexp"
"strings"
)
type Pumpkin struct {
Regex *regexp.Regexp
Pattern string `json:"pattern"`
Commands []string `json:"commands"`
}
func NewPumpkinFromFile(filename string) Pumpkin {
bytes, err := ioutil.ReadFile(filename)
check(err)
return NewPumpkin(bytes)
}
func NewPumpkin(bytes []byte) Pumpkin {
var pumpkin Pumpkin
err := json.Unmarshal(bytes, &pumpkin)
check(err)
pumpkin.Regex = regexp.MustCompile(pumpkin.Pattern)
return pumpkin
}
func (p Pumpkin) Validate() (bool, string) {
if len(p.Commands) <= 0 {
return false, "commands cannot be blank"
}
return true, ""
}
func (p Pumpkin) Carve(filename string, output chan Message) {
if p.Check(filename) {
p.Process(output)
}
}
func (p Pumpkin) Check(filename string) bool {
return p.Regex.MatchString(filename)
}
func (p Pumpkin) Process(output chan Message) {
var stdout, stderr bytes.Buffer
output <- Message{Color: yellow, Content: "---------------"}
for _, command := range p.Commands {
args := strings.Split(command, " ")
cmd := exec.Command(args[0], args[1:]...)
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
msg := &Message{Color: green, Content: stdout.String()}
if msg.IsAvailable() {
output <- Message{Color: yellow, Content: command}
}
if err != nil {
msg.Color = red
output <- *msg
msg.Content = stderr.String()
}
output <- *msg
}
}