Debian Codegraph @

config.go

raw symbols SCIP
1 package main
2
3 import (
4 "bufio"
5 "fmt"
6 "io"
7 "os"
8 "strings"
9 "time"
10
11 "github.com/kballard/go-shellquote"
12 flag "github.com/ogier/pflag"
13 )
14
15 type Config struct {
16 command []string
17 source string
18 regexes []string
19 globs []string
20 inverseRegexes []string
21 inverseGlobs []string
22 subSymbol string
23 startService bool
24 shutdownTimeout time.Duration
25 onlyFiles bool
26 onlyDirs bool
27 allFiles bool
28 }
29
30 func (c *Config) registerFlags(f *flag.FlagSet) {
31 f.VarP(newMultiString(nil, &c.regexes), "regex", "r", `
32 A regular expression to match filenames. (May be repeated.)`)
33 f.VarP(newMultiString(nil, &c.inverseRegexes), "inverse-regex", "R", `
34 A regular expression to exclude matching filenames.
35 (May be repeated.)`)
36 f.VarP(newMultiString(nil, &c.globs), "glob", "g", `
37 A shell glob expression to match filenames. (May be repeated.)`)
38 f.VarP(newMultiString(nil, &c.inverseGlobs), "inverse-glob", "G", `
39 A shell glob expression to exclude matching filenames.
40 (May be repeated.)`)
41 f.StringVar(&c.subSymbol, "substitute", defaultSubSymbol, `
42 The substitution symbol that is replaced with the filename
43 in a command.`)
44 f.BoolVarP(&c.startService, "start-service", "s", false, `
45 Indicates that the command is a long-running process to be
46 restarted on matching changes.`)
47 f.DurationVarP(&c.shutdownTimeout, "shutdown-timeout", "t", 500*time.Millisecond, `
48 Allow services this long to shut down.`)
49 f.BoolVar(&c.onlyFiles, "only-files", false, `
50 Only match files (not directories).`)
51 f.BoolVar(&c.onlyDirs, "only-dirs", false, `
52 Only match directories (not files).`)
53 f.BoolVar(&c.allFiles, "all", false, `
54 Include normally ignored files (VCS and editor special files).`)
55 }
56
57 // ReadConfigs reads configurations from either a file or, as a special case,
58 // stdin if "-" is given for path.
59 func ReadConfigs(path string) ([]*Config, error) {
60 var r io.Reader
61 name := path
62 if path == "-" {
63 r = os.Stdin
64 name = "standard input"
65 } else {
66 f, err := os.Open(flagConf)
67 if err != nil {
68 return nil, err
69 }
70 defer f.Close()
71 r = f
72 }
73 return readConfigsFromReader(r, name)
74 }
75
76 func readConfigsFromReader(r io.Reader, name string) ([]*Config, error) {
77 scanner := bufio.NewScanner(r)
78 lineNo := 0
79 var configs []*Config
80 parseFile:
81 for scanner.Scan() {
82 lineNo++
83 // Skip empty lines and comments (lines starting with #).
84 trimmed := strings.TrimSpace(scanner.Text())
85 if len(trimmed) == 0 || strings.HasPrefix(trimmed, "#") {
86 continue
87 }
88
89 // Found a command line; begin parsing it
90 errorf := fmt.Sprintf("error on line %d of %s: %%s", lineNo, name)
91
92 c := &Config{}
93 c.source = fmt.Sprintf("%s, line %d", name, lineNo)
94
95 line := scanner.Text()
96 parts, err := shellquote.Split(line)
97
98 // Loop while the input line ends with \ or an unfinished quoted string
99 for err != nil {
100 if err == shellquote.UnterminatedEscapeError {
101 // Strip the trailing backslash
102 line = line[:len(line)-1]
103 }
104 if !scanner.Scan() {
105 if scanner.Err() != nil {
106 // Error reading the file, not EOF, so return that
107 break parseFile
108 }
109 // EOF, return the most recent error with the line where the command started
110 return nil, fmt.Errorf(errorf, err)
111 }
112 // append the next line and parse again
113 lineNo++
114 line += "\n" + scanner.Text()
115 parts, err = shellquote.Split(line)
116 }
117
118 flags := flag.NewFlagSet("", flag.ContinueOnError)
119 flags.SetOutput(io.Discard)
120 c.registerFlags(flags)
121 if err := flags.Parse(parts); err != nil {
122 return nil, fmt.Errorf(errorf, err)
123 }
124 c.command = flags.Args()
125 configs = append(configs, c)
126 }
127 if err := scanner.Err(); err != nil {
128 return nil, fmt.Errorf("error reading config from %s: %s", name, err)
129 }
130 return configs, nil
131 }
132
133 // A multiString is a flag.Getter which collects repeated string flags.
134 type multiString struct {
135 vals *[]string
136 set bool // If false, then vals contains the defaults.
137 }
138
139 func newMultiString(vals []string, p *[]string) *multiString {
140 *p = vals
141 return &multiString{vals: p}
142 }
143
144 func (s *multiString) Set(val string) error {
145 if s.set {
146 *s.vals = append(*s.vals, val)
147 } else {
148 *s.vals = []string{val}
149 s.set = true
150 }
151 return nil
152 }
153
154 func (s *multiString) Get() interface{} {
155 return s.vals
156 }
157
158 func (s *multiString) String() string {
159 return fmt.Sprintf("[%s]", strings.Join(*s.vals, " "))
160 }