-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgow_config.go
94 lines (85 loc) · 1.68 KB
/
gow_config.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
package main
import (
"fmt"
"github.com/BurntSushi/toml"
"github.com/romanoff/fsmonitor"
"os"
"os/exec"
"path/filepath"
"strings"
)
type Config struct {
Rules map[string]rule
}
type rule struct {
Path string
Pattern string
Ignored_Folders string
Command string
watcher *fsmonitor.Watcher
}
func (self *rule) watch(name string) error {
if self.Path == "" {
path, err := os.Getwd()
if err != nil {
return err
}
self.Path = path
}
w, err := fsmonitor.NewWatcherWithSkipFolders(self.getIgnoredFolders())
self.watcher = w
if err != nil {
return err
}
err = w.Watch(self.Path)
if err != nil {
return err
}
go func(r rule) {
r.handleEvents()
}(*self)
return nil
}
func (self *rule) handleEvents() {
for {
select {
case event := <-self.watcher.Event:
filename := filepath.Base(event.Name)
for _, p := range self.getPatterns() {
match, _ := filepath.Match(p, filename)
if match {
if !event.IsCreate() {
self.Execute()
}
break
}
}
case err := <-self.watcher.Error:
fmt.Println(err)
}
}
}
func (self *rule) Execute() {
commands := strings.Split(self.Command, " ")
cmd := exec.Command(commands[0], commands[1:]...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
if err := cmd.Run(); err != nil {
fmt.Fprintln(os.Stderr, err)
}
}
func (self *rule) getPatterns() []string {
return strings.Split(self.Pattern, ",")
}
func (self *rule) getIgnoredFolders() []string {
return strings.Split(self.Ignored_Folders, ",")
}
func ReadConfig(content []byte) (*Config, error) {
conf := &Config{}
_, err := toml.Decode(string(content), &conf)
if err != nil {
return nil, err
}
return conf, nil
}