/
target.go
399 lines (364 loc) · 10 KB
/
target.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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
package project
import (
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
"github.com/easeway/langx.go/errors"
"github.com/easeway/langx.go/mapper"
)
// Target defines a build target
type Target struct {
Name string `map:"name"`
Desc string `map:"description"`
Before []string `map:"before"`
After []string `map:"after"`
ExecDriver string `map:"exec-driver"`
WorkDir string `map:"workdir"`
Watches []string `map:"watches"`
Always bool `map:"always"`
Artifacts []string `map:"artifacts"`
Ext map[string]interface{} `map:"*"`
// Runtime fields
Project *Project `map:"-"`
File *File `map:"-"`
Command bool `map:"-"`
Exec bool `map:"-"`
Args []string `map:"-"`
Depends TargetNameMap `map:"-"`
Activates TargetNameMap `map:"-"`
}
// TargetNameMap is targets mapping by name
type TargetNameMap map[string]*Target
// Settings applies to targets
type Settings map[string]interface{}
// WatchItem contains information the target watches
type WatchItem struct {
// Path is relative path to the project root
Path string
// ModTime is the modification time of the item
ModTime time.Time
}
// WatchList is list of watched items
type WatchList []*WatchItem
// Initialize prepare fields in target
func (t *Target) Initialize(name string, project *Project) {
t.Name = name
t.Project = project
t.Depends = make(TargetNameMap)
t.Activates = make(TargetNameMap)
}
// IsTransit indicates the targets doesn't have actual work to do
func (t *Target) IsTransit() bool {
return t.ExecDriver == "" &&
!t.Exec &&
len(t.Ext) == 0 &&
len(t.Watches) == 0 &&
len(t.Artifacts) == 0
}
// GetExt maps Ext to provided value
func (t *Target) GetExt(v interface{}) error {
if t.Ext != nil {
return mapper.Map(v, t.Ext)
}
return nil
}
// Errorf formats an error related to the target
func (t *Target) Errorf(format string, args ...interface{}) error {
args = append([]interface{}{t.Name, t.File.Source}, args...)
return fmt.Errorf("%s(%s): "+format, args...)
}
// AddDep adds a dependency with corresponding activates
func (t *Target) AddDep(dep *Target) {
t.Depends[dep.Name] = dep
dep.Activates[t.Name] = t
}
// GetSettings extracts the value from settings stack
func (t *Target) GetSettings(name string, v interface{}) (err error) {
err = t.Project.GetSettingsIn(name, v)
if err == nil {
err = t.File.Local.GetBy(name, v)
}
return
}
// GetSettingsWithExt extracts the value from Ext and settings stack
func (t *Target) GetSettingsWithExt(name string, v interface{}) (err error) {
if err = t.GetSettings(name, v); err == nil && t.Ext != nil {
err = mapper.Map(v, t.Ext)
}
return
}
// CommonSettings retrieve common settings from target local and project
func (t *Target) CommonSettings() (settings CommonSettings, err error) {
if err = t.Project.GetSettings(&settings); err == nil {
err = t.File.Local.Get(&settings)
}
return
}
// ProjectPath translate a source relative path to project relative path
func (t *Target) ProjectPath(path string) string {
// must use "/" as this path is a relative path inside project
// not platform specific path
// the "absolute" path is relative to project root
if strings.HasPrefix(path, "/") {
return strings.Trim(path, "/")
}
return RelPath(t.File.Source, path)
}
// BaseDir returns the project relative path relative to file defining the target
func (t *Target) BaseDir(dirs ...string) string {
dirs = append([]string{filepath.Dir(t.File.Source)}, dirs...)
return filepath.Join(dirs...)
}
// WorkingDir returns the project relative working dir for executing the target
func (t *Target) WorkingDir(dirs ...string) string {
dirs = append([]string{t.ProjectPath(t.WorkDir)}, dirs...)
return filepath.Join(dirs...)
}
// BuildWatchList collects current state of all watched items
func (t *Target) BuildWatchList() (list WatchList) {
files := make(map[string]*WatchItem)
excludes := make(map[string]*WatchItem)
for _, pattern := range t.Watches {
dict := files
if strings.HasPrefix(pattern, "!") {
dict = excludes
pattern = pattern[1:]
}
paths, err := t.Project.Glob(t.ProjectPath(pattern))
if err != nil {
continue
}
for _, path := range paths {
fullpath := filepath.Join(t.Project.BaseDir, path)
st, err := os.Stat(fullpath)
if err != nil {
continue
}
if st.IsDir() {
filepath.Walk(fullpath, func(relpath string, st os.FileInfo, err error) error {
if err == nil {
relpath = path + relpath[len(fullpath):]
if !st.IsDir() {
dict[relpath] = &WatchItem{Path: relpath, ModTime: st.ModTime()}
}
}
return nil
})
} else {
dict[path] = &WatchItem{Path: path, ModTime: st.ModTime()}
}
}
}
for path := range excludes {
delete(files, path)
}
names := make([]string, 0, len(files))
for name := range files {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
list = append(list, files[name])
}
return
}
// Add adds a target to name map
func (m TargetNameMap) Add(t *Target) error {
if target, exists := m[t.Name]; exists {
return t.Errorf("target name duplicated in %s", target.File.Source)
}
m[t.Name] = t
return nil
}
// CompleteName resolve pattern as a single name
func (m TargetNameMap) CompleteName(name string) ([]string, error) {
var out []string
if strings.HasPrefix(name, "/") {
if len(name) <= 1 || !strings.HasSuffix(name, "/") {
return nil, fmt.Errorf("incomplete regexp: %s", name)
}
rexStr := name[1 : len(name)-1]
rex, err := regexp.Compile(rexStr)
if err != nil {
return nil, fmt.Errorf("invalid regexp: %s: %v", rexStr, err)
}
for n := range m {
if rex.MatchString(n) {
out = append(out, n)
}
}
} else if strings.ContainsAny(name, "*?\\[") {
for n := range m {
if match, err := filepath.Match(name, n); err != nil {
return nil, fmt.Errorf("malformed pattern: %s: %v", name, err)
} else if match {
out = append(out, n)
}
}
} else {
out = append(out, name)
}
return out, nil
}
// CompleteNames resolves pattern in name list
func (m TargetNameMap) CompleteNames(in []string, errs *errors.AggregatedError) (out []string) {
for _, name := range in {
completed, err := m.CompleteName(name)
if errs.Add(err) {
continue
}
out = append(out, completed...)
}
return
}
// BuildDeps builds direct depends and activates
func (m TargetNameMap) BuildDeps() error {
errs := &errors.AggregatedError{}
for _, t := range m {
names := m.CompleteNames(t.Before, errs)
if t.Command && len(names) > 0 {
errs.Add(t.Errorf("before not allowed in commands"))
continue
}
// convert before to after in target
for _, name := range names {
dest, ok := m[name]
if !ok {
errs.Add(t.Errorf("before %s which is not defined", name))
} else {
dest.AddDep(t)
}
}
names = m.CompleteNames(t.After, errs)
// add depends for all after
for _, name := range names {
dest, ok := m[name]
if !ok {
errs.Add(t.Errorf("after %s which is not defined", name))
} else if dest.Command {
errs.Add(t.Errorf("dependency on command %s not allowed", name))
} else {
t.AddDep(dest)
}
}
}
return errs.Aggregate()
}
// CheckCyclicDeps detects cycles in depenencies
func (m TargetNameMap) CheckCyclicDeps() error {
errs := &errors.AggregatedError{}
unresolved := make(TargetNameMap)
allDeps := make(map[string]TargetNameMap)
// build direct dependencies
for _, t := range m {
unresolved[t.Name] = t
deps := make(TargetNameMap)
allDeps[t.Name] = deps
for name, dep := range t.Depends {
deps[name] = dep
}
}
// merge indirect dependencies
for len(unresolved) > 0 {
var t *Target
for _, t = range unresolved {
break
}
m.resolveDeps(t, unresolved, allDeps, errs)
}
return errs.Aggregate()
}
func (m TargetNameMap) resolveDeps(t *Target,
unresolved TargetNameMap, allDeps map[string]TargetNameMap,
errs *errors.AggregatedError) {
if unresolved[t.Name] != nil {
delete(unresolved, t.Name)
directDeps := make([]*Target, 0, len(allDeps[t.Name]))
for _, dep := range allDeps[t.Name] {
directDeps = append(directDeps, dep)
m.resolveDeps(dep, unresolved, allDeps, errs)
}
for _, dep := range directDeps {
for _, indirect := range allDeps[dep.Name] {
allDeps[t.Name][indirect.Name] = indirect
}
}
for _, dep := range allDeps[t.Name] {
if dep.Name == t.Name {
errs.Add(t.Errorf("cyclic dependency %s(%s)",
dep.Name, dep.File.Source))
}
}
}
}
// Get maps settings into provided variable
func (s Settings) Get(v interface{}) error {
if s != nil {
return mapper.Map(v, s)
}
return nil
}
// GetBy maps settings into provided variable by specified key
func (s Settings) GetBy(name string, v interface{}) error {
if s == nil {
return nil
}
if val, exists := s[name]; exists {
return mapper.Map(v, val)
}
return nil
}
// Merge merges settings s1 into s
func (s Settings) Merge(s1 Settings) error {
if s1 == nil {
return nil
}
return mapper.Map(s, s1)
}
// MergeFlat merges settings from a flat key/value map
// The key in flat map can be splitted by "." for a more complicated hierarchy
func (s Settings) MergeFlat(flat map[string]interface{}) error {
for key, val := range flat {
valDict, isValDict := val.(map[string]interface{})
paths := strings.Split(key, ".")
dict := s
for n, path := range paths {
sub, ok := dict[path].(map[string]interface{})
if n+1 == len(paths) {
if isValDict && ok {
if err := mapper.Map(sub, valDict); err != nil {
return err
}
} else {
dict[path] = val
}
} else {
if !ok {
sub = make(Settings)
dict[path] = sub
}
dict = sub
}
}
}
return nil
}
// IsEmpty indicates the watch list is empty
func (w WatchList) IsEmpty() bool {
return len(w) == 0
}
// String formats the watch list as a string
func (w WatchList) String() string {
if w.IsEmpty() {
return ""
}
str := ""
for _, item := range w {
str += fmt.Sprintf("%s %d\n", item.Path, item.ModTime.Unix())
}
return str
}