blob: ec683e19dd11c44fd3be8fb7de6c7e80fcd2b974 [file] [log] [blame]
Fumitoshi Ukai358c68a2015-06-08 13:12:55 +09001package main
2
3import (
4 "os/exec"
5 "path/filepath"
6 "strings"
7)
8
9var wildcardCache = make(map[string][]string)
10
11func wildcard(sw *ssvWriter, pat string) {
12 if useWildcardCache {
13 // TODO(ukai): make sure it didn't chdir?
14 if files, ok := wildcardCache[pat]; ok {
15 for _, file := range files {
16 sw.WriteString(file)
17 }
18 return
19 }
20 }
21 if strings.Contains(pat, "..") {
22 // For some reason, go's Glob normalizes
23 // foo/../bar to bar. We ask shell to expand
24 // a glob to avoid this.
25 cmdline := []string{"/bin/sh", "-c", "/bin/ls -d " + pat}
26 cmd := exec.Cmd{
27 Path: cmdline[0],
28 Args: cmdline,
29 }
30 // Ignore errors.
31 out, _ := cmd.Output()
32 if len(trimSpaceBytes(out)) > 0 {
33 out = formatCommandOutput(out)
34 sw.Write(out)
35 }
36 if useWildcardCache {
37 ws := newWordScanner(out)
38 var files []string
39 for ws.Scan() {
40 files = append(files, string(ws.Bytes()))
41 }
42 wildcardCache[pat] = files
43 }
44 return
45 }
46 files, err := filepath.Glob(pat)
47 if err != nil {
48 panic(err)
49 }
50 for _, file := range files {
51 sw.WriteString(file)
52 }
53 if useWildcardCache {
54 wildcardCache[pat] = files
55 }
56}