/
cmd.go
454 lines (405 loc) · 11.2 KB
/
cmd.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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
/*
Copyright 2018 Comcast Cable Communications Management, LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"bytes"
"errors"
"fmt"
"os"
"path"
"path/filepath"
"sort"
"strings"
"github.com/comcast/tsb/loadfiles"
)
type Executor struct {
startDir string
configRepo string
cmds []string
at string
}
type Done struct{}
func (d Done) Error() string { return "Done" }
func (e *Executor) HasArg() bool {
return len(e.cmds) != 0
}
func (e *Executor) PopArg() string {
if len(e.cmds) == 0 {
return ""
}
arg := e.cmds[0]
e.cmds = e.cmds[1:]
return arg
}
func (e *Executor) Execute() error {
if !e.HasArg() {
return Done{}
}
if e.startDir == `` {
e.startDir, _ = os.Getwd()
}
cmd := e.PopArg()
if verbose {
fmt.Fprintf(os.Stderr, "Performing %s.\n", cmd)
}
switch cmd {
case `fetch`:
cfg, err := e.Config(e.at)
if err != nil {
return err
}
return cfg.Repos.Fetch(e.Dir())
case `build`, `prebuild`:
cfg, err := e.Config(e.at)
if err != nil {
return err
}
err = cfg.Repos.Prepare(e.Dir())
if err != nil {
return err
}
for name, repo := range cfg.Repos {
if cfg.Patches[name] != nil {
for _, patch_item := range cfg.Patches[name] {
chg := patch_item.Change
if chg.Node != "" {
if repo.BuildStrategy == BuildStrategyMerge {
err = repo.Merge(e.Dir(), name, chg.Node)
} else { // default to cherry
err = repo.Cherry(e.Dir(), name, chg.Node)
if verbose {
fmt.Fprintf(os.Stderr, "build-strategy for '%s' fallback to 'cherry'.\n", name)
}
}
if err != nil {
return fmt.Errorf("Unable to apply %s to %s: "+chg.Node, name, err.Error())
}
} else if patch_item.Sub != nil {
if len(patch_item.Sub.Changesets) > 0 {
for _, changeset := range patch_item.Sub.Changesets {
if repo.BuildStrategy == BuildStrategyCherry {
err = repo.Cherry(e.Dir(), name, changeset.Node)
} else if repo.BuildStrategy == BuildStrategyMerge {
err = repo.Merge(e.Dir(), name, changeset.Node)
} else {
return fmt.Errorf("Unrecognized build strategy %s in repo yaml file", repo.BuildStrategy)
}
if err != nil {
return fmt.Errorf("Unable to apply %s to %s: "+changeset.Node, name, err.Error())
}
}
}
} else {
return errors.New(`Unrecognized format in patches yaml file`)
}
}
}
}
if cmd == `build` {
for _, service := range cfg.Compose.ServiceNames() {
b, err := run(`sudo`, `docker-compose`, `-f`, path.Join(e.Dir(), `docker-compose.yml`), `build`, `--pull`, `--no-cache`, `--force-rm`, service)
if err != nil {
return errors.New(`Unable to create build image ` + service + `: ` + err.Error() + "\n" + string(b))
}
b, err = run(`sudo`, `docker-compose`, `-f`, path.Join(e.Dir(), `docker-compose.yml`), `run`, `--rm`, service)
if err != nil {
return errors.New(`Failed to build ` + service + `: ` + err.Error() + "\n" + string(b))
}
}
}
return nil
case `update`:
if e.at != `` {
return errors.New("Cannot update from alternate revision.")
}
cfg, err := e.Config(``)
if err != nil {
return err
}
err = cfg.Repos.Update(e.Dir())
if err != nil {
return err
}
for name, _ := range cfg.Patches {
g := gitRepo(path.Join(e.Dir(), `src`, name))
for sub_ind, patch_item := range cfg.Patches[name] {
if patch_item.Sub != nil {
b, err := g.git(`log`, `origin/`+cfg.Repos[name].Branch+`..`+patch_item.Sub.Branch, ChangesetGitFormatArg, `--reverse`)
if err != nil {
return err
}
cslines := strings.Split(string(bytes.TrimSpace(b)), "\n")
changesets := make([]Changeset, len(cslines))
for i, csline := range cslines {
changesets[i] = NewChangeset(csline)
}
cfg.Patches[name][sub_ind].Sub.Changesets = changesets
}
}
}
return e.StoreConfig(cfg)
case `cherry`:
arg := e.PopArg()
if arg == `` {
return errors.New(`No argument provided to cherry.`)
}
if e.at != `` {
return errors.New("Cannot cherry from alternate revision.")
}
repo, changeset := ParseCherry(arg)
cfg, err := e.Config(``)
if err != nil {
return err
}
if repo == `` {
if len(cfg.Repos) != 1 {
return errors.New("You must supply repository to cherry when you do not have exactly one repository.")
}
for repo = range cfg.Repos {
/* Just use range to get the only repo name available. */
}
}
if _, ok := cfg.Repos[repo]; ok {
g := gitRepo(path.Join(e.Dir(), `src`, repo))
b, err := g.git(`log`, `-n1`, ChangesetGitFormatArg, changeset)
if err != nil {
return fmt.Errorf(`"%s" is not a valid changeset in "%s": %s`, changeset, repo, err.Error())
}
changeset = string(bytes.TrimSpace(b)) /* Set changeset to the output, in case a branch head or tag was passed in. */
} else {
return fmt.Errorf(`"%s" is not a valid repository.`, repo)
}
new_patch := new(Patch)
new_patch.Change = NewChangeset(changeset)
cfg.Patches[repo] = append(cfg.Patches[repo], *new_patch)
return e.StoreConfig(cfg)
case `subscribe`:
arg := e.PopArg()
if arg == `` {
return errors.New(`No argument provided to subscribe`)
}
if e.at != `` {
return errors.New(`Cannot subscribe from alternate revision`)
}
repo, branch := ParseCherry(arg)
cfg, err := e.Config(``)
if err != nil {
return err
}
if repo == `` {
if len(cfg.Repos) != 1 {
return errors.New("You must supply repository to subscribe when you do not have exactly one repository.")
}
for repo = range cfg.Repos {
}
}
if _, ok := cfg.Repos[repo]; ok {
g := gitRepo(path.Join(e.Dir(), `src`, repo))
all_branches, err := g.git(`branch`, `-a`)
if err != nil {
return err
}
if !strings.Contains(string(all_branches), " remotes/"+string(branch)+"\n") {
return fmt.Errorf("%s is not a branch in repository %s", branch, repo)
}
} else {
return fmt.Errorf(`"%s" is not a valid repository.`, repo)
}
new_sub := new(Subscription)
new_sub.Branch = branch
new_patch := new(Patch)
new_patch.Sub = new_sub
cfg.Patches[repo] = append(cfg.Patches[repo], *new_patch)
return e.StoreConfig(cfg)
case `ls-cherry`:
return e.ListPatches()
case `validate`:
return e.Validate()
case `patchdiff`:
return e.PatchDiff()
case `diff`:
detailed := true
return e.Diff(detailed)
case `changelog`:
detailed := false
return e.Diff(detailed)
case `verbose`, `-v`:
verbose = true
return nil
case `quiet`, `-q`:
verbose = false
return nil
case `cd`:
/* This isn't generally necessary, but allows the user to
* explictly use a directory that matches a command name.
*/
cmd = e.PopArg()
if cmd == `` {
return errors.New(`No argument provided to cd.`)
}
break
case `at`:
e.at = e.PopArg()
return nil
}
_, err := os.Stat(path.Join(e.startDir, cmd))
if err == nil {
e.configRepo = cmd
return nil
}
return errors.New(`Unknown command ` + cmd)
}
func (e *Executor) Dir() string {
dir := e.configRepo
/* Use working directory by default. */
if dir == `` {
dir, _ = os.Getwd()
}
return dir
}
func (e *Executor) Config(at string) (*Config, error) {
var cfg Config
var file loadfiles.File
if at == `` {
file = loadfiles.OsFile(e.Dir())
} else {
file = loadfiles.GitFile{
Repo: filepath.Join(e.Dir(), `.git`),
Rev: at,
}
}
err := loadfiles.Load(file, &cfg)
if err != nil {
return nil, err
}
return &cfg, nil
}
func (e *Executor) StoreConfig(cfg *Config) error {
return loadfiles.Store(loadfiles.OsFile(e.Dir()), cfg)
}
func (e *Executor) Validate() error {
cfg, err := e.Config(e.at)
if err != nil {
return err
}
fmt.Printf("Valid config: %v\n", *cfg)
return nil
}
func ParseCherry(arg string) (string, string) {
parts := strings.SplitN(arg, `:`, 2)
if len(parts) == 1 {
return ``, arg
}
return parts[0], parts[1]
}
func (e *Executor) ListPatches() error {
cfg, err := e.Config(e.at)
if err != nil {
return err
}
var repos []string
for repo := range cfg.Patches {
repos = append(repos, repo)
}
sort.Strings(repos)
for _, repo := range repos {
fmt.Printf("Patches for %s:\n", repo)
patch_items := cfg.Patches[repo]
g := gitRepo(path.Join(e.Dir(), `src`, repo))
for _, change_item := range patch_items {
chg := change_item.Change
if chg.Node != "" {
b, err := g.git(`log`, `-n1`, `--format=%s (%an) <%aI!%ae>`, chg.Node)
if err != nil {
fmt.Printf("\t%s: Failed to find commit; \"%v\"\n", chg.Node, err)
}
fmt.Printf("\t%s: %s\n", chg.Node, string(bytes.TrimSpace(b)))
} else if change_item.Sub != nil {
fmt.Printf("\tChangesets for subscription to %s:\n", change_item.Sub.Branch)
if len(change_item.Sub.Changesets) > 0 {
for _, changeset := range change_item.Sub.Changesets {
b, err := g.git(`log`, `-n1`, `--format=%s (%an) <%aI!ae>`, changeset.Node)
if err != nil {
fmt.Printf("\t\t%s: Failed to find commit; \"%v\"\n", changeset.Node, err)
} else {
fmt.Printf("\t\t%s: %s\n", changeset.Node, string(bytes.TrimSpace(b)))
}
}
}
} else {
return errors.New("Unrecognized format in patches yaml")
}
}
}
return nil
}
func (e *Executor) PatchDiff() error {
g := gitRepo(".")
b, _ := g.git(`log`, `-n1`, `--format=%s (%an)`)
fmt.Printf("Differences from previous TSB repo Commit:\n")
fmt.Printf("\t Commit Message: %s\n", string(b))
b, err := g.git(`diff`, `HEAD^`, `HEAD`, `--format=%s`, `-U0`, `patches.yml`)
if err != nil {
fmt.Printf("err: %s", err)
return nil
}
changes := strings.Split(string(b), "\n")
var removals []string
var additions []string
for _, line := range changes {
if strings.HasPrefix(line, "-- ") {
// patch removed
removals = append(removals, strings.TrimPrefix(line, "-- "))
}
if strings.HasPrefix(line, "+- ") {
// patch added
additions = append(additions, strings.TrimPrefix(line, "+- "))
}
}
cfg, err := e.Config(e.at)
if err != nil {
return err
}
var repos []string
for repo := range cfg.Patches {
repos = append(repos, repo)
}
sort.Strings(repos)
fmt.Printf("Removals: \n")
for _, removal := range removals {
for _, repo := range repos {
g := gitRepo(path.Join(e.Dir(), `src`, repo))
msg, err := g.git(`log`, `-n1`, `--format=%s (%an)`, removal)
if err == nil {
fmt.Printf("\t%s: %s - %s \n", repo, removal, msg)
break
}
}
}
fmt.Printf("Additions: \n")
for _, addition := range additions {
for _, repo := range repos {
g := gitRepo(path.Join(e.Dir(), `src`, repo))
msg, err := g.git(`log`, `-n1`, `--format=%s (%an)`, addition)
if err == nil {
fmt.Printf("\t%s: %s - %s \n", repo, addition, msg)
break
}
}
}
fmt.Printf("\n")
return nil
}
func (e *Executor) Diff(detailed bool) error {
return Diff(e.PopArg(), detailed)
}