/
config.go
243 lines (204 loc) · 5.12 KB
/
config.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
// (c) 2012 Alexander Solovyov
// under terms of ISC license
package gostatic
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/bmatcuk/doublestar/v4"
)
// Command is a command belonging to a Rule. For example, `markdown', `directorify'.
type Command string
// CommandList is a slice of Commands.
type CommandList []Command
// Rule is a collection of a slice of dependencies, with a slice of commands in the
// form of a CommandList.
type Rule struct {
Deps []string
Commands CommandList
}
type RuleMap map[string]([]*Rule)
// SiteConfig contains the data for a complete parsed site configuration file.
type SiteConfig struct {
Templates []string
Base string
Source string
Output string
Rules RuleMap
Other map[string]string
changedAt time.Time
}
// NewSiteConfig parses the given `path' file to a *SiteConfig. Will return a nil
// pointer plus the non-nil error if the parsing has failed.
func NewSiteConfig(path string) (*SiteConfig, error) {
source, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
stat, err := os.Stat(path)
if err != nil {
return nil, err
}
basepath, _ := filepath.Split(path)
cfg := &SiteConfig{
Rules: make(RuleMap),
Other: make(map[string]string),
Base: basepath,
changedAt: stat.ModTime(),
}
indent := 0
level := 0
prefix := regexp.MustCompile("^[ \t]*")
comment := regexp.MustCompile(`(^|[^\\])#`)
var current *Rule
for i, line := range strings.Split(string(source), "\n") {
// check indent
indnew := len(prefix.FindString(line))
switch {
case indnew > indent:
level++
case indnew < indent:
level--
}
indent = indnew
// remove useless stuff from line
line = line[indent:]
commentloc := comment.FindIndex([]byte(line))
if commentloc != nil {
line = line[:commentloc[0]]
}
line = strings.Replace(line, "\\#", "#", -1)
line = strings.TrimSpace(line)
if len(line) == 0 {
continue
}
// is this a constant declaration?
if level == 0 && strings.Index(line, "=") != -1 {
cfg.ParseVariable(basepath, line)
continue
}
// not a constant, then a Rule start?
if level == 0 {
current = cfg.ParseRule(line)
continue
}
if level == 1 {
if current == nil {
return nil, fmt.Errorf("indent without rules, line %d", i+1)
}
current.ParseCommand(cfg, line)
continue
}
return nil, fmt.Errorf("unhandled situation on line %d: %s",
i+1, line)
}
return cfg, nil
}
// *** Parsing methods
var VarRe = regexp.MustCompile(`\$\(([^\)]+)\)`)
func (cfg *SiteConfig) SubVars(s string) string {
return VarRe.ReplaceAllStringFunc(s, func(m string) string {
name := VarRe.FindStringSubmatch(m)[1]
switch name {
case "TEMPLATES":
return strings.Join(cfg.Templates, ", ")
case "SOURCE":
return cfg.Source
case "OUTPUT":
return cfg.Output
default:
return cfg.Other[Capitalize(name)]
}
})
}
func (cfg *SiteConfig) ParseVariable(base string, line string) {
bits := TrimSplitN(line, "=", 2)
name := bits[0]
value := cfg.SubVars(bits[1])
switch name {
case "TEMPLATES":
templates := strings.Split(value, " ")
for _, template := range templates {
path := filepath.Join(base, template)
isDir, err := IsDir(path)
if err != nil {
errexit(fmt.Errorf("template does not exist: %s", err))
}
if isDir {
files, _ := filepath.Glob(filepath.Join(path, "*.tmpl"))
for _, fn := range files {
cfg.Templates = append(cfg.Templates, fn)
}
} else {
cfg.Templates = append(cfg.Templates, path)
}
}
case "SOURCE":
cfg.Source = filepath.Join(base, value)
case "OUTPUT":
cfg.Output = filepath.Join(base, value)
default:
cfg.Other[Capitalize(name)] = value
}
}
func (cfg *SiteConfig) ParseRule(line string) *Rule {
bits := TrimSplitN(line, ":", 2)
if len(bits) != 2 {
errexit(fmt.Errorf("Cannot parse rule, ':' not found in '%s'", line))
}
deps := NonEmptySplit(cfg.SubVars(bits[1]), " ")
rule := &Rule{
Deps: deps,
Commands: make(CommandList, 0),
}
if _, ok := cfg.Rules[bits[0]]; !ok {
cfg.Rules[bits[0]] = make([]*Rule, 0)
}
cfg.Rules[bits[0]] = append(cfg.Rules[bits[0]], rule)
return rule
}
func (rule *Rule) ParseCommand(cfg *SiteConfig, line string) {
line = cfg.SubVars(line)
rule.Commands = append(rule.Commands, Command(line))
}
// *** Traversing methods
func (cmd Command) Matches(prefix Command) bool {
return cmd == prefix || strings.HasPrefix(string(cmd), string(prefix)+" ")
}
func (rule *Rule) IsDep(page *Page) bool {
for _, dep := range rule.Deps {
matches, err := doublestar.Match(dep, page.Source)
if err == nil && matches {
return true
}
}
return false
}
func (rules RuleMap) MatchedRules(path string) (string, []*Rule) {
if rules[path] != nil {
return path, rules[path]
}
_, name := filepath.Split(path)
if rules[name] != nil {
return name, rules[name]
}
for pat, subset := range rules {
matched, err := doublestar.Match(pat, path)
errhandle(err)
if matched {
return pat, subset
}
}
for pat, subset := range rules {
matched, err := doublestar.Match(pat, name)
errhandle(err)
if matched {
return pat, subset
}
}
return "", nil
}