/
main.go
281 lines (255 loc) · 5.16 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
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
package main
import (
"encoding/json"
"fmt"
"github.com/ronbu/fsevents"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
)
var _ = fmt.Fscan
const (
stateFile = "/.made.json"
madeFile = "/Madefile"
)
type files map[string]time.Time
type changes map[string]bool
func main() {
if len(os.Args) > 2 {
fmt.Fprintln(os.Stderr, "Usage:", os.Args[0], "[root]")
os.Exit(1)
}
root, err := os.Getwd()
check(err)
if len(os.Args) == 2 {
root = os.Args[1]
}
excs, _, _ := Made(root)
// c := make(chan os.Signal, 1)
// signal.Notify(c, os.Interrupt)
// go func() {
// <-c
// stop <- true
// }()
for exc := range excs {
if exc.Err != nil {
fmt.Fprint(os.Stderr, exc.String())
} else {
fmt.Print(exc.String())
}
}
}
func mapFiles(root string) (fs files) {
fs = make(files)
filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
check(err)
if path != root {
relPath, err := filepath.Rel(root, path)
check(err)
fs[relPath] = info.ModTime()
}
return nil
})
return
}
func writeState(root string, files files) {
b, err := json.Marshal(files)
check(err)
ioutil.WriteFile(root+stateFile, b, 0777)
}
func compareFileMaps(from, to files) (compared changes) {
cTo := make(files)
compared = make(changes)
for k, v := range to {
cTo[k] = v
}
for fk, fv := range from {
tv, ok := to[fk]
// fmt.Println(fk, tv, fv)
if ok {
delete(cTo, fk)
if tv.After(fv) {
compared[fk] = true
}
} else {
compared[fk] = false
}
}
for k, _ := range cTo {
compared[k] = true
}
return
}
func getChanged(root string) (init bool, changed changes) {
from := make(files)
changed = make(changes)
to := mapFiles(root)
b, err := ioutil.ReadFile(root + stateFile)
if os.IsNotExist(err) {
for k := range to {
changed[k] = true
}
writeState(root, to)
return
}
check(err)
check(json.Unmarshal(b, &from))
writeState(root, to)
return init, compareFileMaps(from, to)
}
func run(root string, cmd string) Execution {
sh := "/usr/local/bin/fish"
c := exec.Command(sh, "-c", cmd)
// c.Stderr = os.Stderr
// c.Stdout = os.Stdout
c.Dir = root
output, err := c.CombinedOutput()
return Execution{
Cmd: cmd,
Err: err,
Output: output}
}
// %f - whole filepath
// %d - dirname of path
// %b - basename of file
// %B - basename without extension
// %e - extension of file
func replaceForEach(name, arg string) (string, bool) {
li := -1
found := false
for i := 0; i > li; {
li = i
if i = strings.Index(arg, "%"); i > -1 {
ext := filepath.Ext(name)
if len(ext) > 1 {
ext = ext[1:] // strip
}
base := filepath.Base(name)
m := map[rune]string{
'f': name,
'd': filepath.Dir(name),
'b': base,
'B': strings.TrimSuffix(base, filepath.Ext(name)),
'e': ext,
}
i++
r := rune(arg[i])
insert, ok := m[r]
if ok {
found = true
arg = strings.Replace(arg, "%"+string(r), insert, -1)
// println(arg, insert, strings.TrimSuffix("dir/a.a", filepath.Ext("dir/a.a")))
}
} else {
break
}
}
return arg, found
}
func filterCmds(change, madeFile string) (cmds []string) {
regex := regexp.MustCompile(`<\|(.+?)\|>`)
for _, rule := range strings.Split(madeFile, "\n") {
matched := false
ms := regex.FindAllStringSubmatchIndex(rule, -1)
for _, sm := range ms {
glob := rule[sm[2]:sm[3]]
if matched, _ = filepath.Match(glob, change); matched {
break
}
}
if !matched {
continue
}
cmd, isForeach := replaceForEach(change, rule)
if isForeach {
cmd = regex.ReplaceAllString(cmd, change)
} else {
cmd = regex.ReplaceAllString(cmd, "$1")
}
cmds = append(cmds, cmd)
}
return
}
func Made(root string) (chan Execution, chan bool, error) {
excs := make(chan Execution)
stop := make(chan bool)
change := make(chan string)
ch := fsevents.WatchPaths([]string{root})
_, initChanges := getChanged(root)
go func() {
go func() {
<-stop
fsevents.Unwatch(ch)
}()
for c, _ := range initChanges {
change <- c
}
// println("--- new init")
for pes := range ch {
for _, pe := range pes {
if pe.Flags != fsevents.FlagItemRemoved {
relPath, err := filepath.Rel(root, pe.Path)
check(err)
// fmt.Println(pe)
change <- relPath
}
}
}
close(change)
}()
go func() {
for change := range change {
mf, err := ioutil.ReadFile(root + madeFile)
if err != nil {
return
}
cmds := filterCmds(change, string(mf))
for _, c := range cmds {
excs <- run(root, c)
}
}
close(excs)
}()
return excs, stop, nil
}
func listAll(dir string) (files []string) {
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
check(err)
if path != dir {
relPath, err := filepath.Rel(dir, path)
check(err)
files = append(files, relPath)
}
return nil
})
return files
}
func check(err error) {
if err != nil {
panic(err)
}
}
type Execution struct {
Cmd string
Err error
Output []byte
}
func (e *Execution) String() string {
output := string(e.Output)
str := "Executed: "
if e.Err != nil {
str = "Failed to Execute: "
}
str += e.Cmd
if e.Err != nil {
str += "\n\t" + e.Err.Error()
}
if output != "" {
str += "\n\t" + output
}
return str
}