forked from kardianos/govendor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun.go
626 lines (564 loc) · 15.9 KB
/
run.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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
// imports for this file should not contain "os".
import (
"errors"
"flag"
"fmt"
"io"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
. "github.com/kardianos/govendor/context"
"github.com/kardianos/govendor/migrate"
)
var helpFull = `govendor: copy go packages locally. Uses vendor folder.
govendor init
Creates a vendor file if it does not exist.
govendor list [options] ( +status or import-path-filter )
List all dependencies and packages in folder tree.
Options:
-v verbose listing, show dependencies of each package
-no-status do not prefix status to list, package names only
govendor {add, update, remove} [options] ( +status or import-path-filter )
add - Copy one or more packages into the vendor folder.
update - Update one or more packages from GOPATH into the vendor folder.
remove - Remove one or more packages from the vendor folder.
Options:
-n dry run and print actions that would be taken
-tree copy package(s) and all sub-folders under each package
The following may be replaced with something else in the future.
-short if conflict, take short path
-long if conflict, take long path
govendor migrate [auto, godep, internal]
Change from a one schema to use the vendor folder. Default to auto detect.
govendor [fmt, build, install, clean, test, vet] ( +status or import-path-filter )
Run "go" commands using status filters.
$ govendor test +local
Expanding "..."
A package import path may be expanded to other paths that
show up in "govendor list" be ending the "import-path" with "...".
NOTE: this uses the import tree from "vendor list" and NOT the file system.
Flags
-n print actions but do not run them
-short chooses the shorter path in case of conflict
-long chooses the longer path in case of conflict
"import-path-filter" arguements:
May be a literal individual package:
github.com/user/supercool
github.com/user/supercool/anotherpkg
Match on any exising Go package that the project uses under "supercool"
github.com/user/supercool/...
Match the package "supercool" and also copy all sub-folders.
Will copy non-Go files and Go packages that aren't used.
github.com/user/supercool/^
Same as specifying:
-tree github.com/user/supercool
Status list used in "+<status>" arguments:
external - package does not share root path
vendor - vendor folder; copied locally
unused - the package has been copied locally, but isn't used
local - shares the root path and is not a vendor package
missing - referenced but not found in GOROOT or GOPATH
std - standard library package
program - package is a main package
---
outside - external + missing
all - all of the above status
Status can be referenced by their initial letters.
"st" == "std"
"e" == "external"
Status can be joined together with boolean AND and OR
govendor list +vendor,program +e --> (vendor AND program) OR external
Ignoring files with build tags:
The "vendor.json" file contains a string field named "ignore".
It may contain a space separated list of build tags to ignore when
listing and copying files. By default the init command adds the
the "test" tag to the ignore list.
If using go1.5, ensure you set GO15VENDOREXPERIMENT=1
Examples:
$ govendor list -no-status +local
$ govendor list +vend,prog +local,program
$ govendor list +local,^prog
`
var helpList = `govendor list [options] ( +status or import-path-filter )
List all dependencies and packages in folder tree.
Options:
-v verbose listing, show dependencies of each package
-no-status do not prefix status to list, package names only
Examples:
$ govendor list -no-status +local
$ govendor list +vend,prog +local,program
$ govendor list +local,^prog
`
var helpAdd = `govendor add [options] ( +status or import-path-filter )
Copy one or more packages into the vendor folder.
Options:
-n dry run and print actions that would be taken
-tree copy package(s) and all sub-folders under each package
The following may be replaced with something else in the future.
-short if conflict, take short path
-long if conflict, take long path
`
var helpUpdate = `govendor update [options] ( +status or import-path-filter )
Update one or more packages from GOPATH into the vendor folder.
Options:
-n dry run and print actions that would be taken
-tree copy package(s) and all sub-folders under each package
The following may be replaced with something else in the future.
-short if conflict, take short path
-long if conflict, take long path
`
var helpRemove = `govendor remove [options] ( +status or import-path-filter )
Remove one or more packages from the vendor folder.
Options:
-n dry run and print actions that would be taken
`
var helpFetch = `govendor fetch <TBD>
`
var helpMigrate = `govendor migrate [auto, godep, internal]
Change from a one schema to use the vendor folder. Default to auto detect.
`
var (
outside = []Status{
{Location: LocationExternal},
{Presence: PresenceMissing},
}
normal = []Status{
{Location: LocationExternal},
{Location: LocationVendor},
{Location: LocationLocal},
{Location: LocationNotFound},
}
all = []Status{
{Location: LocationStandard},
{Location: LocationExternal},
{Location: LocationVendor},
{Location: LocationLocal},
{Location: LocationNotFound},
}
)
func statusGroupFromList(list []Status, and, not bool) StatusGroup {
sg := StatusGroup{
Not: not,
And: and,
}
for _, s := range list {
sg.Status = append(sg.Status, s)
}
return sg
}
const notOp = "^"
func parseStatusGroup(statusString string) (sg StatusGroup, err error) {
ss := strings.Split(statusString, ",")
sg.And = true
for _, s := range ss {
st := Status{}
if strings.HasPrefix(s, notOp) {
st.Not = true
s = strings.TrimPrefix(s, notOp)
}
var list []Status
switch {
case strings.HasPrefix("external", s):
st.Location = LocationExternal
case strings.HasPrefix("vendor", s):
st.Location = LocationVendor
case strings.HasPrefix("unused", s):
st.Presence = PresenceUnsued
case strings.HasPrefix("missing", s):
st.Presence = PresenceMissing
case strings.HasPrefix("local", s):
st.Location = LocationLocal
case strings.HasPrefix("program", s):
st.Type = TypeProgram
case strings.HasPrefix("std", s):
st.Location = LocationStandard
case strings.HasPrefix("standard", s):
st.Location = LocationStandard
case strings.HasPrefix("all", s):
list = all
case strings.HasPrefix("normal", s):
list = normal
case strings.HasPrefix("outside", s):
list = outside
default:
err = fmt.Errorf("unknown status %q", s)
return
}
if len(list) == 0 {
sg.Status = append(sg.Status, st)
} else {
sg.Group = append(sg.Group, statusGroupFromList(list, false, st.Not))
}
}
return
}
type filterImport struct {
Import string
Added bool // Used to prevent imports from begin added twice.
}
func (f *filterImport) String() string {
return f.Import
}
type filter struct {
Status StatusGroup
Import []*filterImport
}
func (f filter) String() string {
return fmt.Sprintf("status %q, import: %q", f.Status, f.Import)
}
func (f filter) HasStatus(item StatusItem) bool {
return item.Status.MatchGroup(f.Status)
}
func (f filter) HasImport(item StatusItem) bool {
for _, imp := range f.Import {
if imp.Import == item.Local || imp.Import == item.Canonical {
imp.Added = true
return true
}
if strings.HasSuffix(imp.Import, "/...") {
base := strings.TrimSuffix(imp.Import, "/...")
if strings.HasPrefix(item.Local, base) || strings.HasPrefix(item.Canonical, base) {
imp.Added = true
return true
}
}
if strings.HasSuffix(imp.Import, "...") {
base := strings.TrimSuffix(imp.Import, "...")
if strings.HasPrefix(item.Local, base) || strings.HasPrefix(item.Canonical, base) {
imp.Added = true
return true
}
}
}
return false
}
func parseFilter(args []string) (filter, error) {
f := filter{
Import: make([]*filterImport, 0, len(args)),
}
for _, a := range args {
if len(a) == 0 {
continue
}
// Check if item is a status.
if a[0] == '+' {
sg, err := parseStatusGroup(a[1:])
if err != nil {
return f, err
}
f.Status.Group = append(f.Status.Group, sg)
} else {
f.Import = append(f.Import, &filterImport{Import: a})
}
}
return f, nil
}
func insertListToAllNot(sg *StatusGroup, list []Status) {
if len(sg.Group) == 0 {
allStatusNot := true
for _, s := range sg.Status {
if s.Not == false {
allStatusNot = false
break
}
}
if allStatusNot {
sg.Group = append(sg.Group, statusGroupFromList(list, false, false))
}
}
for i := range sg.Group {
insertListToAllNot(&sg.Group[i], list)
}
}
type HelpMessage byte
const (
MsgNone HelpMessage = iota
MsgFull
MsgList
MsgAdd
MsgUpdate
MsgRemove
MsgFetch
MsgMigrate
)
// run is isoloated from main and os.Args to help with testing.
// Shouldn't directly print to console, just write through w.
// TODO (DT): replace bool with const help type.
func run(w io.Writer, appArgs []string) (HelpMessage, error) {
if len(appArgs) == 1 {
return MsgFull, nil
}
cmd := appArgs[1]
switch cmd {
case "init":
ctx, err := NewContextWD(RootWD)
if err != nil {
return MsgNone, err
}
ctx.VendorFile.Ignore = "test" // Add default ignore rule.
err = ctx.WriteVendorFile()
if err != nil {
return MsgNone, err
}
err = os.MkdirAll(filepath.Join(ctx.RootDir, ctx.VendorFolder), 0777)
if err != nil {
return MsgNone, err
}
case "list":
listFlags := flag.NewFlagSet("list", flag.ContinueOnError)
verbose := listFlags.Bool("v", false, "verbose")
noStatus := listFlags.Bool("no-status", false, "do not show the status")
err := listFlags.Parse(appArgs[2:])
if err != nil {
return MsgList, err
}
args := listFlags.Args()
f, err := parseFilter(args)
if err != nil {
return MsgList, err
}
insertListToAllNot(&f.Status, normal)
// fmt.Printf("Status: %q\n", f.Status)
// Print all listed status.
ctx, err := NewContextWD(RootVendorOrWD)
if err != nil {
return checkNewContextError(err)
}
list, err := ctx.Status()
if err != nil {
return MsgNone, err
}
formatSame := "%[1]v %[2]s\n"
formatDifferent := "%[1]v %[2]s\n"
if *verbose {
formatDifferent = "%[1]v %[2]s ::%[3]s\n"
}
if *noStatus {
formatSame = "%[2]s\n"
formatDifferent = "%[2]s\n"
if *verbose {
formatDifferent = "%[2]s ::%[3]s\n"
}
}
for _, item := range list {
if f.HasStatus(item) == false {
continue
}
if len(f.Import) != 0 && f.HasImport(item) == false {
continue
}
if item.Local == item.Canonical {
fmt.Fprintf(w, formatSame, item.Status, item.Canonical)
} else {
fmt.Fprintf(w, formatDifferent, item.Status, item.Canonical, strings.TrimPrefix(item.Local, ctx.RootImportPath))
}
if *verbose {
for i, imp := range item.ImportedBy {
if i != len(item.ImportedBy)-1 {
fmt.Fprintf(w, " ├── %s\n", imp)
} else {
fmt.Fprintf(w, " └── %s\n", imp)
}
}
}
}
case "add", "update", "remove", "fetch":
msg := MsgFull
var mod Modify
switch cmd {
case "add":
msg = MsgAdd
mod = Add
case "update":
msg = MsgUpdate
mod = Update
case "remove":
msg = MsgRemove
mod = Remove
case "fetch":
msg = MsgFetch
// TODO: enable a code path that fetches recursivly on missing status.
mod = Fetch
}
listFlags := flag.NewFlagSet("mod", flag.ContinueOnError)
dryrun := listFlags.Bool("n", false, "dry-run")
short := listFlags.Bool("short", false, "choose the short path")
long := listFlags.Bool("long", false, "choose the long path")
tree := listFlags.Bool("tree", false, "copy all folders including and under selected folder")
err := listFlags.Parse(appArgs[2:])
if err != nil {
return msg, err
}
if *short && *long {
return MsgNone, errors.New("cannot select both long and short path")
}
args := listFlags.Args()
if len(args) == 0 {
return msg, errors.New("missing package or status")
}
f, err := parseFilter(args)
if err != nil {
return msg, err
}
ctx, err := NewContextWD(RootVendor)
if err != nil {
return checkNewContextError(err)
}
list, err := ctx.Status()
if err != nil {
return msg, err
}
addTree := func(s string) string {
if !*tree {
return s
}
if strings.HasSuffix(s, TreeSuffix) {
return s
}
return path.Join(s, TreeSuffix)
}
for _, item := range list {
if f.HasStatus(item) {
err = ctx.ModifyImport(addTree(item.Local), mod)
if err != nil {
// Skip these errors if from status.
if _, is := err.(ErrTreeChildren); is {
continue
}
if _, is := err.(ErrTreeParents); is {
continue
}
return MsgNone, err
}
}
if f.HasImport(item) {
err = ctx.ModifyImport(addTree(item.Local), mod)
if err != nil {
return MsgNone, err
}
}
}
// If import path was not added from list, then add in here.
for _, imp := range f.Import {
if imp.Added {
continue
}
importPath := strings.TrimSuffix(imp.Import, "...")
importPath = strings.TrimSuffix(importPath, "/")
err = ctx.ModifyImport(addTree(importPath), mod)
if err != nil {
return MsgNone, err
}
}
// Auto-resolve package conflicts.
conflicts := ctx.Check()
conflicts = ctx.ResolveAutoVendorFileOrigin(conflicts)
if *long {
conflicts = ResolveAutoLongestPath(conflicts)
}
if *short {
conflicts = ResolveAutoShortestPath(conflicts)
}
ctx.ResloveApply(conflicts)
// TODO: loop through conflicts to see if there are any remaining conflicts.
// Print out any here.
if *dryrun {
for _, op := range ctx.Operation {
if len(op.Dest) == 0 {
fmt.Fprintf(w, "Remove %q\n", op.Src)
} else {
fmt.Fprintf(w, "Copy %q -> %q\n", op.Src, op.Dest)
for _, ignore := range op.IgnoreFile {
fmt.Fprintf(w, "\tIgnore %q\n", ignore)
}
}
}
return MsgNone, nil
}
// Write out vendor file and do change.
err = ctx.WriteVendorFile()
if err != nil {
return MsgNone, err
}
err = ctx.Alter()
if err != nil {
return MsgNone, err
}
case "migrate":
args := appArgs[2:]
from := migrate.Auto
if len(args) > 0 {
switch args[0] {
case "auto":
from = migrate.Auto
case "gb":
from = migrate.Gb
case "godep":
from = migrate.Godep
case "internal":
from = migrate.Internal
default:
return MsgMigrate, fmt.Errorf("Unknown migrate command %q", args[0])
}
}
return MsgNone, migrate.MigrateWD(from)
case "fmt", "build", "install", "clean", "test", "vet":
return goCmd(cmd, appArgs[2:])
default:
return MsgFull, fmt.Errorf("Unknown command %q", cmd)
}
return MsgNone, nil
}
func goCmd(subcmd string, args []string) (HelpMessage, error) {
ctx, err := NewContextWD(RootVendorOrWD)
if err != nil {
return MsgNone, err
}
statusArgs := make([]string, 0, len(args))
otherArgs := make([]string, 1, len(args)+1)
otherArgs[0] = subcmd
for _, a := range args {
if a[0] == '+' {
statusArgs = append(statusArgs, a)
} else {
otherArgs = append(otherArgs, a)
}
}
f, err := parseFilter(statusArgs)
if err != nil {
return MsgNone, err
}
list, err := ctx.Status()
if err != nil {
return MsgNone, err
}
for _, item := range list {
if f.HasStatus(item) {
otherArgs = append(otherArgs, item.Local)
}
}
cmd := exec.Command("go", otherArgs...)
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
return MsgNone, cmd.Run()
}
func checkNewContextError(err error) (HelpMessage, error) {
// Diagnose error, show current value of 1.5vendor, suggest alter.
if err == nil {
return MsgNone, nil
}
if _, is := err.(ErrMissingVendorFile); is {
err = fmt.Errorf(`%v
Ensure the current folder or a parent folder contains a folder named "vendor".
If in doubt, run "govendor init" in the project root.
`, err)
return MsgNone, err
}
return MsgNone, err
}