-
Notifications
You must be signed in to change notification settings - Fork 0
/
ranger.go
296 lines (237 loc) · 6.78 KB
/
ranger.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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
package main
import (
"flag"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
)
type stringmap map[string][]string
func (s *stringmap) String() string {
return fmt.Sprintf("%s", *s)
}
func (s *stringmap) Set(value string) error {
kv := strings.Split(value, ":")
(*s)[kv[0]] = strings.Split(kv[1], ",")
return nil
}
type Ranger struct {
structure string
filters stringmap
root string
unique bool
command []string
}
func getCleanStructure(r Ranger) (string, bool) {
cleanStructure := filepath.Clean(r.structure)
isAbs := filepath.IsAbs(cleanStructure)
if isAbs == false {
cleanStructure = filepath.Join(r.root, cleanStructure)
if filepath.IsAbs(r.root) {
isAbs = true
}
}
return cleanStructure, isAbs
}
func makeGlob(splitStructure []string, isAbs bool, filters map[string]string) string {
globSlice := make([]string, 0)
for _, el := range splitStructure {
if el == "" {
continue
}
//re := regexp.MustCompile("^@[^{}]*")
//re := regexp.MustCompile("@{[^{}]*}")
if strings.HasPrefix(el, "@") == false {
globSlice = append(globSlice, el)
continue
}
filter, ok := filters[el]
if ok == true {
globSlice = append(globSlice, filter)
} else {
globSlice = append(globSlice, "*")
}
}
glob := filepath.Join(globSlice...)
if isAbs {
glob = "/" + glob
}
glob = filepath.FromSlash(glob)
return glob
}
func makeGlobs(r Ranger) []string {
cleanStructure, isAbs := getCleanStructure(r)
splitStructure := strings.Split(filepath.ToSlash(cleanStructure), "/")
totalFilters := 1
for _, v := range r.filters {
totalFilters *= len(v)
}
unrolledFilters := make([]map[string]string, totalFilters)
for i := 0; i < totalFilters; i++ {
unrolledFilters[i] = make(map[string]string)
}
for k, v := range r.filters {
ncopies := totalFilters / len(v)
for i := 0; i < totalFilters; i++ {
unrolledFilters[i][k] = v[i/ncopies]
}
}
globs := make([]string, 0)
for _, filters := range unrolledFilters {
glob := makeGlob(splitStructure, isAbs, filters)
globs = append(globs, glob)
}
return globs
}
func runGlobs(globs []string) []string {
allRes := make([]string, 0)
for _, glob := range globs {
res, _ := filepath.Glob(glob)
for _, el := range res {
allRes = append(allRes, el)
}
}
return allRes
}
func makeCommands(r Ranger, globRes []string) [][]string {
cleanStructure, _ := getCleanStructure(r)
splitStructure := strings.Split(filepath.ToSlash(cleanStructure), "/")
commands := make([][]string, len(globRes))
for i, globPath := range globRes {
splitPath := strings.Split(filepath.ToSlash(globPath), "/")
vars := make(map[string]string)
for i, el := range splitPath {
if len(splitStructure) <= i {
break
}
if strings.HasPrefix(splitStructure[i], "@") == false {
continue
}
vars[splitStructure[i]] = el
}
command := make([]string, 0)
for _, el := range r.command {
arg := el
outArg := arg
for k, v := range vars {
absSlice := make([]string, 0)
for i, p := range splitStructure {
absSlice = append(absSlice, splitPath[i])
if p == k {
break
}
}
absPath := filepath.Join(absSlice...)
if filepath.IsAbs(globPath) {
absPath = "/" + absPath
}
if r.root != "" {
absPath, _ = filepath.Rel(r.root, absPath)
}
re := regexp.MustCompile("@" + k)
outArg = re.ReplaceAllString(outArg, absPath)
re = regexp.MustCompile("@@{" + k[1:] + "}")
outArg = re.ReplaceAllString(outArg, absPath)
re = regexp.MustCompile("@{" + k[1:] + "/.*/.*}")
matches := re.FindAllString(outArg, -1)
for _, match := range matches {
splitMatch := strings.Split(match[2:len(match)-1], "/")
if len(splitMatch) != 3 {
continue
}
subRe := regexp.MustCompile(splitMatch[1])
subsArg := subRe.ReplaceAllString(v, splitMatch[2])
subRe = regexp.MustCompile(match)
outArg = subRe.ReplaceAllString(outArg, subsArg)
}
re = regexp.MustCompile("@{" + k[1:] + "}")
outArg = re.ReplaceAllString(outArg, v)
re = regexp.MustCompile(k)
outArg = re.ReplaceAllString(outArg, v)
}
command = append(command, outArg)
}
commands[i] = command
}
if r.unique {
commandMap := make(map[string][]string)
for _, command := range commands {
commandMap[strings.Join(command, " ")] = command
}
commands = make([][]string, len(commandMap))
i := 0
for _, command := range commandMap {
commands[i] = command
i++
}
}
return commands
}
func main() {
// TODO COMMANDS:
// take, take-nth, take-rand
// count (count is like unique + echo, but it also shows the numerosity)
// tabulate
// TODO FEATURES:
// parallelization
// laziness (for this and the previous, use channels and have goroutines consume)
root := flag.String("root", "", "Path relative to which `structure` is evaluated.")
unique := flag.Bool("unique", false, "Only call `command` once for a unique combination of arguments.")
structure := flag.String("structure", "", "Path-like string describing the directory structure being visited. Variables can be defined by prepending @ to a name, e.g. /some/directory/@subdir/@filename.")
debug := flag.Bool("debug", false, "Output debug info.")
echo := flag.Bool("echo", false, "Only show commands, do not execute them.")
log := flag.Bool("log", false, "Show commands while executing.")
filters := make(stringmap)
flag.Var(&filters, "filter", "Filters acting on variables defined in `structure`. A filter is given as variable_name:glob_pattern, e.g. -filter @filename:*.txt.")
flag.Usage = func() {
fmt.Printf("Program: ranger 0.1\n")
fmt.Printf("Author: Luca Antiga, Orobix\n")
fmt.Printf("Usage: ranger [-root path] [-structure path] [-filter filter] [-filter filter] [-unique] [-debug] [-log] [-echo] command\n")
fmt.Printf("Example: ranger -root /home/joe/data -structure @department/@expenses -filter @department:*ENG -filter @expenses:2016*.tab sed -e 's/\\t/, /g' < @@expenses > out/@{expenses/tab/csv}\n")
flag.PrintDefaults()
}
flag.Parse()
ranger := Ranger{
structure: *structure,
filters: filters,
root: *root,
unique: *unique,
command: flag.Args()}
if len(flag.Args()) == 0 {
flag.Usage()
return
}
if *debug {
fmt.Println("Ranger:", ranger)
}
globs := makeGlobs(ranger)
if *debug {
fmt.Println("Globs:", globs)
}
globRes := runGlobs(globs)
if *debug {
fmt.Println("GlobRes:", globRes)
}
commands := makeCommands(ranger, globRes)
if *debug {
fmt.Println("Commands:", commands)
}
for _, command := range commands {
if *debug {
fmt.Println("Running:", strings.Join(command, " "))
}
if *echo {
fmt.Println(strings.Join(command, " "))
continue
}
if *log {
fmt.Println(strings.Join(command, " "))
}
cmd := exec.Command(command[0], command[1:]...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Run()
}
}