-
Notifications
You must be signed in to change notification settings - Fork 10
/
configs.go
123 lines (101 loc) · 2.31 KB
/
configs.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
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"os"
"regexp"
"strings"
)
type Configs struct {
Directory string
Patterns []string
Command []string
}
var configfile = flag.String("config", ".wu.json", "Config file")
var directory = flag.String("dir", "", "Directory to watch")
var pattern = flag.String("pattern", "", "Patterns to filter filenames")
var saveconf = flag.Bool("save", false, "Save options to conf")
func init() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %s [options] [command]\n", os.Args[0])
flag.PrintDefaults()
}
}
func getConfigs() Configs {
flag.Parse()
conf := readConfigFile()
if dir := parseDirectory(); dir != "" {
conf.Directory = dir
}
if patterns := parsePatterns(); patterns != nil {
conf.Patterns = patterns
}
if command := parseCommand(); command != nil {
conf.Command = command
}
if *saveconf {
saveConfigFile(conf)
}
return conf
}
func readConfigFile() Configs {
file, err := os.Open(*configfile)
defer file.Close()
if err == nil {
log.Println("Reading options from", *configfile)
var conf Configs
if err := json.NewDecoder(file).Decode(&conf); err != nil {
log.Fatalln("Failed to parse config file:", err)
}
return conf
}
return Configs{".", []string{"*"}, []string{}}
}
func saveConfigFile(conf Configs) {
log.Println("Saving options to", *configfile)
file, err := os.Create(*configfile)
defer file.Close()
if err != nil {
log.Fatalln("Failed to open config file:", err)
}
if bytes, err := json.MarshalIndent(conf, "", " "); err == nil {
if _, err := file.Write(bytes); err != nil {
log.Fatalln("Failed to write config file:", err)
}
} else {
log.Fatalln("Failed to encode options:", err)
}
}
func parseDirectory() string {
dir := *directory
if info, err := os.Stat(dir); err == nil {
if !info.IsDir() {
log.Fatal(dir, "is not a directory")
}
}
return dir
}
func parsePatterns() []string {
pat := strings.Trim(*pattern, " ")
if pat == "" {
return nil
}
patternSep, _ := regexp.Compile("[,\\s]+")
patternMap := make(map[string]bool)
ret := []string{}
for _, part := range patternSep.Split(pat, -1) {
patternMap[part] = true
}
for part := range patternMap {
ret = append(ret, part)
}
return ret
}
func parseCommand() []string {
if flag.NArg() == 0 {
return nil
}
return flag.Args()
}