This repository has been archived by the owner on Sep 9, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
ensure.go
854 lines (711 loc) · 27.1 KB
/
ensure.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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
// Copyright 2016 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
import (
"context"
"flag"
"fmt"
"go/build"
"log"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"github.com/golang/dep"
"github.com/golang/dep/gps"
"github.com/golang/dep/gps/paths"
"github.com/golang/dep/gps/pkgtree"
"github.com/golang/dep/gps/verify"
"github.com/pkg/errors"
)
const ensureShortHelp = `Ensure a dependency is safely vendored in the project`
const ensureLongHelp = `
Project spec:
<import path>[:alt source URL][@<constraint>]
Ensure gets a project into a complete, reproducible, and likely compilable state:
* All imports are fulfilled
* All rules in Gopkg.toml are respected
* Gopkg.lock records immutable versions for all dependencies
* vendor/ is populated according to Gopkg.lock
Ensure has fast techniques to determine that some of these steps may be
unnecessary. If that determination is made, ensure may skip some steps. Flags
may be passed to bypass these checks; -vendor-only will allow an out-of-date
Gopkg.lock to populate vendor/, and -no-vendor will update Gopkg.lock (if
needed), but never touch vendor/.
The effect of passing project spec arguments varies slightly depending on the
combination of flags that are passed.
Examples:
dep ensure Populate vendor from existing Gopkg.toml and Gopkg.lock
dep ensure -add github.com/pkg/foo Introduce a named dependency at its newest version
dep ensure -add github.com/pkg/foo@^1.0.1 Introduce a named dependency with a particular constraint
For more detailed usage examples, see dep ensure -examples.
`
const ensureExamples = `
dep ensure
Solve the project's dependency graph, and place all dependencies in the
vendor folder. If a dependency is in the lock file, use the version
specified there. Otherwise, use the most recent version that can satisfy the
constraints in the manifest file.
dep ensure -vendor-only
Write vendor/ from an existing Gopkg.lock file, without first verifying that
the lock is in sync with imports and Gopkg.toml. (This may be useful for
e.g. strategically layering a Docker images)
dep ensure -add github.com/pkg/foo github.com/pkg/foo/bar
Introduce one or more dependencies, at their newest version, ensuring that
specific packages are present in Gopkg.lock and vendor/. Also, append a
corresponding constraint to Gopkg.toml.
Note: packages introduced in this way will disappear on the next "dep
ensure" if an import statement is not added first.
dep ensure -add github.com/pkg/foo/[email protected] bitbucket.org/pkg/bar/baz@master
Append version constraints to Gopkg.toml for one or more packages, if no
such rules already exist.
If the named packages are not already imported, also ensure they are present
in Gopkg.lock and vendor/. As in the preceding example, packages introduced
in this way will disappear on the next "dep ensure" if an import statement
is not added first.
dep ensure -add github.com/pkg/foo:git.internal.com/alt/foo
Specify an alternate location to treat as the upstream source for a dependency.
dep ensure -update github.com/pkg/foo github.com/pkg/bar
Update a list of dependencies to the latest versions allowed by Gopkg.toml,
ignoring any versions recorded in Gopkg.lock. Write the results to
Gopkg.lock and vendor/.
dep ensure -update
Update all dependencies to the latest versions allowed by Gopkg.toml,
ignoring any versions recorded in Gopkg.lock. Update the lock file with any
changes. (NOTE: Not recommended. Updating one/some dependencies at a time is
preferred.)
dep ensure -update -no-vendor
As above, but only modify Gopkg.lock; leave vendor/ unchanged.
dep ensure -no-vendor -dry-run
This fails with a non zero exit code if Gopkg.lock is not up to date with
the Gopkg.toml or the project imports. It can be useful to run this during
CI to check if Gopkg.lock is up to date.
`
var (
errUpdateArgsValidation = errors.New("update arguments validation failed")
errAddDepsFailed = errors.New("adding dependencies failed")
)
func (cmd *ensureCommand) Name() string { return "ensure" }
func (cmd *ensureCommand) Args() string {
return "[-update | -add] [-no-vendor | -vendor-only] [-dry-run] [-v] [<spec>...]"
}
func (cmd *ensureCommand) ShortHelp() string { return ensureShortHelp }
func (cmd *ensureCommand) LongHelp() string { return ensureLongHelp }
func (cmd *ensureCommand) Hidden() bool { return false }
func (cmd *ensureCommand) Register(fs *flag.FlagSet) {
fs.BoolVar(&cmd.examples, "examples", false, "print detailed usage examples")
fs.BoolVar(&cmd.update, "update", false, "update the named dependencies (or all, if none are named) in Gopkg.lock to the latest allowed by Gopkg.toml")
fs.BoolVar(&cmd.add, "add", false, "add new dependencies, or populate Gopkg.toml with constraints for existing dependencies")
fs.BoolVar(&cmd.vendorOnly, "vendor-only", false, "populate vendor/ from Gopkg.lock without updating it first")
fs.BoolVar(&cmd.noVendor, "no-vendor", false, "update Gopkg.lock (if needed), but do not update vendor/")
fs.BoolVar(&cmd.dryRun, "dry-run", false, "only report the changes that would be made")
}
type ensureCommand struct {
examples bool
update bool
add bool
noVendor bool
vendorOnly bool
dryRun bool
}
func (cmd *ensureCommand) Run(ctx *dep.Ctx, args []string) error {
if cmd.examples {
ctx.Err.Println(strings.TrimSpace(ensureExamples))
return nil
}
if err := cmd.validateFlags(); err != nil {
return err
}
p, err := ctx.LoadProject()
if err != nil {
return err
}
sm, err := ctx.SourceManager()
if err != nil {
return err
}
sm.UseDefaultSignalHandling()
defer sm.Release()
if err := dep.ValidateProjectRoots(ctx, p.Manifest, sm); err != nil {
return err
}
params := p.MakeParams()
if ctx.Verbose {
params.TraceLogger = ctx.Err
}
if cmd.vendorOnly {
return cmd.runVendorOnly(ctx, args, p, sm, params)
}
if fatal, err := checkErrors(params.RootPackageTree.Packages, p.Manifest.IgnoredPackages()); err != nil {
if fatal {
return err
} else if ctx.Verbose {
ctx.Out.Println(err)
}
}
if ineffs := p.FindIneffectualConstraints(sm); len(ineffs) > 0 {
ctx.Err.Printf("Warning: the following project(s) have [[constraint]] stanzas in %s:\n\n", dep.ManifestName)
for _, ineff := range ineffs {
ctx.Err.Println(" ✗ ", ineff)
}
// TODO(sdboyer) lazy wording, it does not mention ignores at all
ctx.Err.Printf("\nHowever, these projects are not direct dependencies of the current project:\n")
ctx.Err.Printf("they are not imported in any .go files, nor are they in the 'required' list in\n")
ctx.Err.Printf("%s. Dep only applies [[constraint]] rules to direct dependencies, so\n", dep.ManifestName)
ctx.Err.Printf("these rules will have no effect.\n\n")
ctx.Err.Printf("Either import/require packages from these projects so that they become direct\n")
ctx.Err.Printf("dependencies, or convert each [[constraint]] to an [[override]] to enforce rules\n")
ctx.Err.Printf("on these projects, if they happen to be transitive dependencies.\n\n")
}
// Kick off vendor verification in the background. All of the remaining
// paths from here will need it, whether or not they end up solving.
go p.VerifyVendor()
if cmd.add {
return cmd.runAdd(ctx, args, p, sm, params)
} else if cmd.update {
return cmd.runUpdate(ctx, args, p, sm, params)
}
return cmd.runDefault(ctx, args, p, sm, params)
}
func (cmd *ensureCommand) validateFlags() error {
if cmd.add && cmd.update {
return errors.New("cannot pass both -add and -update")
}
if cmd.vendorOnly {
if cmd.update {
return errors.New("-vendor-only makes -update a no-op; cannot pass them together")
}
if cmd.add {
return errors.New("-vendor-only makes -add a no-op; cannot pass them together")
}
if cmd.noVendor {
// TODO(sdboyer) can't think of anything not snarky right now
return errors.New("really?")
}
}
return nil
}
func (cmd *ensureCommand) vendorBehavior() dep.VendorBehavior {
if cmd.noVendor {
return dep.VendorNever
}
return dep.VendorOnChanged
}
func (cmd *ensureCommand) runDefault(ctx *dep.Ctx, args []string, p *dep.Project, sm gps.SourceManager, params gps.SolveParameters) error {
// Bare ensure doesn't take any args.
if len(args) != 0 {
return errors.New("dep ensure only takes spec arguments with -add or -update")
}
if err := ctx.ValidateParams(sm, params); err != nil {
return err
}
var solve bool
lock := p.ChangedLock
if lock != nil {
lsat := verify.LockSatisfiesInputs(p.Lock, p.Manifest, params.RootPackageTree)
if !lsat.Satisfied() {
if ctx.Verbose {
ctx.Out.Printf("# Gopkg.lock is out of sync with Gopkg.toml and project imports:\n%s\n\n", sprintLockUnsat(lsat))
}
solve = true
} else if cmd.noVendor {
// The user said not to touch vendor/, so definitely nothing to do.
return nil
}
} else {
solve = true
}
if solve {
solver, err := gps.Prepare(params, sm)
if err != nil {
return errors.Wrap(err, "prepare solver")
}
solution, err := solver.Solve(context.TODO())
if err != nil {
return handleAllTheFailuresOfTheWorld(err)
}
lock = dep.LockFromSolution(solution, p.Manifest.PruneOptions)
}
dw, err := dep.NewDeltaWriter(p, lock, cmd.vendorBehavior())
if err != nil {
return err
}
if cmd.dryRun {
return dw.PrintPreparedActions(ctx.Out, ctx.Verbose)
}
var logger *log.Logger
if ctx.Verbose {
logger = ctx.Err
}
return errors.WithMessage(dw.Write(p.AbsRoot, sm, true, logger), "grouped write of manifest, lock and vendor")
}
func (cmd *ensureCommand) runVendorOnly(ctx *dep.Ctx, args []string, p *dep.Project, sm gps.SourceManager, params gps.SolveParameters) error {
if len(args) != 0 {
return errors.Errorf("dep ensure -vendor-only only populates vendor/ from %s; it takes no spec arguments", dep.LockName)
}
if p.Lock == nil {
return errors.Errorf("no %s exists from which to populate vendor/", dep.LockName)
}
// Pass the same lock as old and new so that the writer will observe no
// difference, and write out only ncessary vendor/ changes.
dw, err := dep.NewSafeWriter(nil, p.Lock, p.Lock, dep.VendorAlways, p.Manifest.PruneOptions, nil)
//dw, err := dep.NewDeltaWriter(p.Lock, p.Lock, p.Manifest.PruneOptions, filepath.Join(p.AbsRoot, "vendor"), dep.VendorAlways)
if err != nil {
return err
}
if cmd.dryRun {
return dw.PrintPreparedActions(ctx.Out, ctx.Verbose)
}
var logger *log.Logger
if ctx.Verbose {
logger = ctx.Err
}
return errors.WithMessage(dw.Write(p.AbsRoot, sm, true, logger), "grouped write of manifest, lock and vendor")
}
func (cmd *ensureCommand) runUpdate(ctx *dep.Ctx, args []string, p *dep.Project, sm gps.SourceManager, params gps.SolveParameters) error {
if p.Lock == nil {
return errors.Errorf("-update works by updating the versions recorded in %s, but %s does not exist", dep.LockName, dep.LockName)
}
if err := ctx.ValidateParams(sm, params); err != nil {
return err
}
// When -update is specified without args, allow every dependency to change
// versions, regardless of the lock file.
if len(args) == 0 {
params.ChangeAll = true
}
if err := validateUpdateArgs(ctx, args, p, sm, ¶ms); err != nil {
return err
}
// Re-prepare a solver now that our params are complete.
solver, err := gps.Prepare(params, sm)
if err != nil {
return errors.Wrap(err, "fastpath solver prepare")
}
solution, err := solver.Solve(context.TODO())
if err != nil {
// TODO(sdboyer) special handling for warning cases as described in spec
// - e.g., named projects did not upgrade even though newer versions
// were available.
return handleAllTheFailuresOfTheWorld(err)
}
dw, err := dep.NewDeltaWriter(p, dep.LockFromSolution(solution, p.Manifest.PruneOptions), cmd.vendorBehavior())
if err != nil {
return err
}
if cmd.dryRun {
return dw.PrintPreparedActions(ctx.Out, ctx.Verbose)
}
var logger *log.Logger
if ctx.Verbose {
logger = ctx.Err
}
return errors.Wrap(dw.Write(p.AbsRoot, sm, false, logger), "grouped write of manifest, lock and vendor")
}
func (cmd *ensureCommand) runAdd(ctx *dep.Ctx, args []string, p *dep.Project, sm gps.SourceManager, params gps.SolveParameters) error {
if len(args) == 0 {
return errors.New("must specify at least one project or package to -add")
}
if err := ctx.ValidateParams(sm, params); err != nil {
return err
}
// Compile unique sets of 1) all external packages imported or required, and
// 2) the project roots under which they fall.
exmap := make(map[string]bool)
if p.ChangedLock != nil {
for _, imp := range p.ChangedLock.InputImports() {
exmap[imp] = true
}
} else {
// We'll only hit this branch if Gopkg.lock did not exist.
rm, _ := p.RootPackageTree.ToReachMap(true, true, false, p.Manifest.IgnoredPackages())
for _, imp := range rm.FlattenFn(paths.IsStandardImportPath) {
exmap[imp] = true
}
for imp := range p.Manifest.RequiredPackages() {
exmap[imp] = true
}
}
// Note: these flags are only partially used by the latter parts of the
// algorithm; rather, it relies on inference. However, they remain in their
// entirety as future needs may make further use of them, being a handy,
// terse way of expressing the original context of the arg inputs.
type addType uint8
const (
// Straightforward case - this induces a temporary require, and thus
// a warning message about it being ephemeral.
isInManifest addType = 1 << iota
// If solving works, we'll pull this constraint from the in-memory
// manifest (where we recorded it earlier) and then append it to the
// manifest on disk.
isInImportsWithConstraint
// If solving works, we'll extract a constraint from the lock and
// append it into the manifest on disk, similar to init's behavior.
isInImportsNoConstraint
// This gets a message AND a hoist from the solution up into the
// manifest on disk.
isInNeither
)
type addInstruction struct {
id gps.ProjectIdentifier
ephReq map[string]bool
constraint gps.Constraint
typ addType
}
addInstructions := make(map[gps.ProjectRoot]addInstruction)
// A mutex for limited access to addInstructions by goroutines.
var mutex sync.Mutex
// Channel for receiving all the errors.
errCh := make(chan error, len(args))
var wg sync.WaitGroup
ctx.Out.Println("Fetching sources...")
for i, arg := range args {
wg.Add(1)
if ctx.Verbose {
ctx.Err.Printf("(%d/%d) %s\n", i+1, len(args), arg)
}
go func(arg string) {
defer wg.Done()
pc, path, err := getProjectConstraint(arg, sm)
if err != nil {
// TODO(sdboyer) ensure these errors are contextualized in a sensible way for -add
errCh <- err
return
}
// check if the the parsed path is the current root path
if strings.EqualFold(string(p.ImportRoot), string(pc.Ident.ProjectRoot)) {
errCh <- errors.New("cannot add current project to itself")
return
}
inManifest := p.Manifest.HasConstraintsOn(pc.Ident.ProjectRoot)
inImports := exmap[string(pc.Ident.ProjectRoot)]
if inManifest && inImports {
errCh <- errors.Errorf("nothing to -add, %s is already in %s and the project's direct imports or required list", pc.Ident.ProjectRoot, dep.ManifestName)
return
}
err = sm.SyncSourceFor(pc.Ident)
if err != nil {
errCh <- errors.Wrapf(err, "failed to fetch source for %s", pc.Ident.ProjectRoot)
return
}
someConstraint := !gps.IsAny(pc.Constraint) || pc.Ident.Source != ""
// Obtain a lock for addInstructions
mutex.Lock()
defer mutex.Unlock()
instr, has := addInstructions[pc.Ident.ProjectRoot]
if has {
// Multiple packages from the same project were specified as
// arguments; make sure they agree on declared constraints.
// TODO(sdboyer) until we have a general method for checking constraint equality, only allow one to declare
if someConstraint {
if !gps.IsAny(instr.constraint) || instr.id.Source != "" {
errCh <- errors.Errorf("can only specify rules once per project being added; rules were given at least twice for %s", pc.Ident.ProjectRoot)
return
}
instr.constraint = pc.Constraint
instr.id = pc.Ident
}
} else {
instr.ephReq = make(map[string]bool)
instr.constraint = pc.Constraint
instr.id = pc.Ident
}
if inManifest {
if someConstraint {
errCh <- errors.Errorf("%s already contains rules for %s, cannot specify a version constraint or alternate source", dep.ManifestName, path)
return
}
instr.ephReq[path] = true
instr.typ |= isInManifest
} else if inImports {
if !someConstraint {
if exmap[path] {
errCh <- errors.Errorf("%s is already imported or required, so -add is only valid with a constraint", path)
return
}
// No constraints, but the package isn't imported; require it.
// TODO(sdboyer) this case seems like it's getting overly specific and risks muddying the water more than it helps
instr.ephReq[path] = true
instr.typ |= isInImportsNoConstraint
} else {
// Don't require on this branch if the path was a ProjectRoot;
// most common here will be the user adding constraints to
// something they already imported, and if they specify the
// root, there's a good chance they don't actually want to
// require the project's root package, but are just trying to
// indicate which project should receive the constraints.
if !exmap[path] && string(pc.Ident.ProjectRoot) != path {
instr.ephReq[path] = true
}
instr.typ |= isInImportsWithConstraint
}
} else {
instr.typ |= isInNeither
instr.ephReq[path] = true
}
addInstructions[pc.Ident.ProjectRoot] = instr
}(arg)
}
wg.Wait()
close(errCh)
// Newline after printing the fetching source output.
ctx.Err.Println()
// Log all the errors.
if len(errCh) > 0 {
ctx.Err.Printf("Failed to add the dependencies:\n\n")
for err := range errCh {
ctx.Err.Println(" ✗", err.Error())
}
ctx.Err.Println()
return errAddDepsFailed
}
// We're now sure all of our add instructions are individually and mutually
// valid, so it's safe to begin modifying the input parameters.
for pr, instr := range addInstructions {
// The arg processing logic above only adds to the ephReq list if
// that package definitely needs to be on that list, so we don't
// need to check instr.typ here - if it's in instr.ephReq, it
// definitely needs to be added to the manifest's required list.
for path := range instr.ephReq {
p.Manifest.Required = append(p.Manifest.Required, path)
}
// Only two branches can possibly be adding rules, though the
// isInNeither case may or may not have an empty constraint.
if instr.typ&(isInNeither|isInImportsWithConstraint) != 0 {
p.Manifest.Constraints[pr] = gps.ProjectProperties{
Source: instr.id.Source,
Constraint: instr.constraint,
}
}
}
// Re-prepare a solver now that our params are complete.
solver, err := gps.Prepare(params, sm)
if err != nil {
return errors.Wrap(err, "fastpath solver prepare")
}
solution, err := solver.Solve(context.TODO())
if err != nil {
// TODO(sdboyer) detect if the failure was specifically about some of the -add arguments
return handleAllTheFailuresOfTheWorld(err)
}
// Prep post-actions and feedback from adds.
var reqlist []string
appender := dep.NewManifest()
for pr, instr := range addInstructions {
for path := range instr.ephReq {
reqlist = append(reqlist, path)
}
if instr.typ&isInManifest == 0 {
var pp gps.ProjectProperties
var found bool
for _, proj := range solution.Projects() {
// We compare just ProjectRoot instead of the whole
// ProjectIdentifier here because an empty source on the input side
// could have been converted into a source by the solver.
if proj.Ident().ProjectRoot == pr {
found = true
pp = getProjectPropertiesFromVersion(proj.Version())
break
}
}
if !found {
panic(fmt.Sprintf("unreachable: solution did not contain -add argument %s, but solver did not fail", pr))
}
pp.Source = instr.id.Source
if !gps.IsAny(instr.constraint) {
pp.Constraint = instr.constraint
}
appender.Constraints[pr] = pp
}
}
extra, err := appender.MarshalTOML()
if err != nil {
return errors.Wrap(err, "could not marshal manifest into TOML")
}
sort.Strings(reqlist)
dw, err := dep.NewDeltaWriter(p, dep.LockFromSolution(solution, p.Manifest.PruneOptions), cmd.vendorBehavior())
if err != nil {
return err
}
if cmd.dryRun {
return dw.PrintPreparedActions(ctx.Out, ctx.Verbose)
}
var logger *log.Logger
if ctx.Verbose {
logger = ctx.Err
}
if err := errors.Wrap(dw.Write(p.AbsRoot, sm, true, logger), "grouped write of manifest, lock and vendor"); err != nil {
return err
}
// FIXME(sdboyer) manifest writes ABSOLUTELY need verification - follow up!
f, err := os.OpenFile(filepath.Join(p.AbsRoot, dep.ManifestName), os.O_APPEND|os.O_WRONLY, 0666)
if err != nil {
return errors.Wrapf(err, "opening %s failed", dep.ManifestName)
}
if _, err := f.Write(extra); err != nil {
f.Close()
return errors.Wrapf(err, "writing to %s failed", dep.ManifestName)
}
switch len(reqlist) {
case 0:
// nothing to tell the user
case 1:
if cmd.noVendor {
ctx.Out.Printf("%q is not imported by your project, and has been temporarily added to %s.\n", reqlist[0], dep.LockName)
ctx.Out.Printf("If you run \"dep ensure\" again before actually importing it, it will disappear from %s. Running \"dep ensure -vendor-only\" is safe, and will guarantee it is present in vendor/.", dep.LockName)
} else {
ctx.Out.Printf("%q is not imported by your project, and has been temporarily added to %s and vendor/.\n", reqlist[0], dep.LockName)
ctx.Out.Printf("If you run \"dep ensure\" again before actually importing it, it will disappear from %s and vendor/.", dep.LockName)
}
default:
if cmd.noVendor {
ctx.Out.Printf("The following packages are not imported by your project, and have been temporarily added to %s:\n", dep.LockName)
ctx.Out.Printf("\t%s\n", strings.Join(reqlist, "\n\t"))
ctx.Out.Printf("If you run \"dep ensure\" again before actually importing them, they will disappear from %s. Running \"dep ensure -vendor-only\" is safe, and will guarantee they are present in vendor/.", dep.LockName)
} else {
ctx.Out.Printf("The following packages are not imported by your project, and have been temporarily added to %s and vendor/:\n", dep.LockName)
ctx.Out.Printf("\t%s\n", strings.Join(reqlist, "\n\t"))
ctx.Out.Printf("If you run \"dep ensure\" again before actually importing them, they will disappear from %s and vendor/.", dep.LockName)
}
}
return errors.Wrapf(f.Close(), "closing %s", dep.ManifestName)
}
func getProjectConstraint(arg string, sm gps.SourceManager) (gps.ProjectConstraint, string, error) {
emptyPC := gps.ProjectConstraint{
Constraint: gps.Any(), // default to any; avoids panics later
}
// try to split on '@'
// When there is no `@`, use any version
var versionStr string
atIndex := strings.Index(arg, "@")
if atIndex > 0 {
parts := strings.SplitN(arg, "@", 2)
arg = parts[0]
versionStr = parts[1]
}
// TODO: if we decide to keep equals.....
// split on colon if there is a network location
var source string
colonIndex := strings.Index(arg, ":")
if colonIndex > 0 {
parts := strings.SplitN(arg, ":", 2)
arg = parts[0]
source = parts[1]
}
pr, err := sm.DeduceProjectRoot(arg)
if err != nil {
return emptyPC, "", errors.Wrapf(err, "could not infer project root from dependency path: %s", arg) // this should go through to the user
}
pi := gps.ProjectIdentifier{ProjectRoot: pr, Source: source}
c, err := sm.InferConstraint(versionStr, pi)
if err != nil {
return emptyPC, "", err
}
return gps.ProjectConstraint{Ident: pi, Constraint: c}, arg, nil
}
func checkErrors(m map[string]pkgtree.PackageOrErr, ignore *pkgtree.IgnoredRuleset) (fatal bool, err error) {
var (
noGoErrors int
pkgtreeErrors = make(pkgtreeErrs, 0, len(m))
)
for ip, poe := range m {
if ignore.IsIgnored(ip) {
continue
}
if poe.Err != nil {
switch poe.Err.(type) {
case *build.NoGoError:
noGoErrors++
default:
pkgtreeErrors = append(pkgtreeErrors, poe.Err)
}
}
}
// If pkgtree was empty or all dirs lacked any Go code, return an error.
if len(m) == 0 || len(m) == noGoErrors {
return true, errors.New("no dirs contained any Go code")
}
// If all dirs contained build errors, return an error.
if len(m) == len(pkgtreeErrors) {
return true, errors.New("all dirs contained build errors")
}
// If all directories either had no Go files or caused a build error, return an error.
if len(m) == len(pkgtreeErrors)+noGoErrors {
return true, pkgtreeErrors
}
// If m contained some errors, return a warning with those errors.
if len(pkgtreeErrors) > 0 {
return false, pkgtreeErrors
}
return false, nil
}
type pkgtreeErrs []error
func (e pkgtreeErrs) Error() string {
errs := make([]string, 0, len(e))
for _, err := range e {
errs = append(errs, err.Error())
}
return fmt.Sprintf("found %d errors in the package tree:\n%s", len(e), strings.Join(errs, "\n"))
}
func validateUpdateArgs(ctx *dep.Ctx, args []string, p *dep.Project, sm gps.SourceManager, params *gps.SolveParameters) error {
// Channel for receiving all the valid arguments.
argsCh := make(chan string, len(args))
// Channel for receiving all the validation errors.
errCh := make(chan error, len(args))
var wg sync.WaitGroup
// Allow any of specified project versions to change, regardless of the lock
// file.
for _, arg := range args {
wg.Add(1)
go func(arg string) {
defer wg.Done()
// Ensure the provided path has a deducible project root.
pc, path, err := getProjectConstraint(arg, sm)
if err != nil {
// TODO(sdboyer) ensure these errors are contextualized in a sensible way for -update
errCh <- err
return
}
if path != string(pc.Ident.ProjectRoot) {
// TODO(sdboyer): does this really merit an abortive error?
errCh <- errors.Errorf("%s is not a project root, try %s instead", path, pc.Ident.ProjectRoot)
return
}
if !p.Lock.HasProjectWithRoot(pc.Ident.ProjectRoot) {
errCh <- errors.Errorf("%s is not present in %s, cannot -update it", pc.Ident.ProjectRoot, dep.LockName)
return
}
if pc.Ident.Source != "" {
errCh <- errors.Errorf("cannot specify alternate sources on -update (%s)", pc.Ident.Source)
return
}
if !gps.IsAny(pc.Constraint) {
// TODO(sdboyer) constraints should be allowed to allow solves that
// target particular versions while remaining within declared constraints.
errCh <- errors.Errorf("version constraint %s passed for %s, but -update follows constraints declared in %s, not CLI arguments", pc.Constraint, pc.Ident.ProjectRoot, dep.ManifestName)
return
}
// Valid argument.
argsCh <- arg
}(arg)
}
wg.Wait()
close(errCh)
close(argsCh)
// Log all the errors.
if len(errCh) > 0 {
ctx.Err.Printf("Invalid arguments passed to ensure -update:\n\n")
for err := range errCh {
ctx.Err.Println(" ✗", err.Error())
}
ctx.Err.Println()
return errUpdateArgsValidation
}
// Add all the valid arguments to solve params.
for arg := range argsCh {
params.ToChange = append(params.ToChange, gps.ProjectRoot(arg))
}
return nil
}