-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathutils.go
122 lines (106 loc) · 2.29 KB
/
utils.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
package main
import (
"fmt"
"os"
"os/exec"
"strings"
"path/filepath"
"time"
"github.com/bmatcuk/doublestar/v4"
"github.com/fsnotify/fsnotify"
"github.com/google/shlex"
)
func expandVars(cmd string, event fsnotify.Event) string {
base := filepath.Base(event.Name)
dir := filepath.Dir(event.Name)
abs, err := filepath.Abs(event.Name)
if err != nil {
fmt.Fprintf(logger, "watcher: error getting absolute path of %q: %s\n", event.Name, err.Error())
}
return os.Expand(cmd, func(key string) string {
switch key {
case "FILE":
return abs
case "FILE_BASE":
return base
case "FILE_DIR":
return dir
case "FILE_EXT":
return filepath.Ext(event.Name)
case "EVENT_TYPE":
return event.Op.String()
case "EVENT_TIME":
return time.Now().Format(time.RFC3339)
case "PWD":
wd, err := os.Getwd()
if err != nil {
fmt.Fprintf(logger, "watcher: error getting current working directory: %s\n", err.Error())
}
return wd
case "TIMESTAMP":
return fmt.Sprintf("%d", time.Now().Unix())
default:
return os.Getenv(key)
}
})
}
func parseCommand(cmdTemplate string, event fsnotify.Event) *exec.Cmd {
expanded := expandVars(cmdTemplate, event)
expanded = strings.TrimSpace(expanded)
if expanded == "" {
return nil
}
parts, err := shlex.Split(expanded)
if err != nil || len(parts) == 0 {
return nil
}
if len(parts) == 1 {
return exec.Command(parts[0])
}
return exec.Command(parts[0], parts[1:]...)
}
func wrapCmd(cmd *exec.Cmd) *exec.Cmd {
if cmd != nil {
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
}
return cmd
}
func matchesPattern(path, pattern string) bool {
matched, err := doublestar.Match(pattern, path)
if err != nil {
fmt.Fprintf(logger, "watcher: error matching pattern %q: %s\n", pattern, err.Error())
return false
}
return matched
}
var excludedFolders = []string{
"node_modules",
"vendor",
".git",
".svn",
".hg",
".bzr",
".vscode",
"_vendor",
"godeps",
"dist",
"thirdparty",
"bin",
"__pycache__",
".cache",
"obj",
"testdata",
"examples",
"tmp",
"build",
}
func validPath(path string) bool {
_, err := os.Stat(path)
return err == nil
}
// fatalf prints a formatted error message to stderr and exits with status code 1
func fatalf(msg string, args ...interface{}) {
fmt.Fprintf(os.Stderr, msg, args...)
os.Exit(1)
}