forked from golang/dep
/
status.go
1482 lines (1250 loc) · 39 KB
/
status.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
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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 (
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"sort"
"strings"
"sync"
"text/tabwriter"
"text/template"
"github.com/golang/dep"
"github.com/golang/dep/gps"
"github.com/golang/dep/gps/paths"
"github.com/golang/dep/gps/verify"
"github.com/pkg/errors"
)
const availableTemplateVariables = "ProjectRoot, Constraint, Version, Revision, Latest, and PackageCount."
const availableDefaultTemplateVariables = `.Projects[]{
.ProjectRoot,.Source,.Constraint,.PackageCount,.Packages[],
.PruneOpts,.Digest,.Locked{.Branch,.Revision,.Version},
.Latest{.Revision,.Version}
},
.Metadata{
.AnalyzerName,.AnalyzerVersion,.InputImports,.SolverName,
.SolverVersion
}`
const statusShortHelp = `Report the status of the project's dependencies`
const statusLongHelp = `
With no arguments, print the status of each dependency of the project.
PROJECT Import path
CONSTRAINT Version constraint, from the manifest
VERSION Version chosen, from the lock
REVISION VCS revision of the chosen version
LATEST Latest VCS revision available
PKGS USED Number of packages from this project that are actually used
You may use the -f flag to create a custom format for the output of the
dep status command. The available fields you can utilize are as follows:
` + availableTemplateVariables + `
Status returns exit code zero if all dependencies are in a "good state".
`
const statusExamples = `
dep status
Displays a table of the various dependencies in the project along with
their properties such as the constraints they are bound by and the
revision they are at.
dep status -detail
Displays a detailed table of the dependencies in the project including
the value of any source rules used and full list of packages used from
each project (instead of simply a count). Text wrapping may make this
output hard to read.
dep status -f='{{if eq .Constraint "master"}}{{.ProjectRoot}} {{end}}'
Displays the list of package names constrained on the master branch.
The -f flag allows you to use Go templates along with it's various
constructs for formating output data. Available flags are as follows:
` + availableTemplateVariables + `
dep status -detail -f='{{range $i, $p := .Projects}}{{if ne .Source "" -}}
{{- if $i}},{{end}}{{$p.ProjectRoot}}:{{$p.Source}}{{end}}{{end}}'
Displays the package name and source for each package with a source
rule defined, with a comma between each name-source pair.
When used with -detail, the -f flag applies the supplied Go templates
to the full output document, instead of to packages one at a time.
Available flags are as follows: ` + availableDefaultTemplateVariables + `
dep status -json
Displays the dependency information in JSON format as a list of
project objects. Each project object contains keys which correspond
to the table column names from the standard 'dep status' command.
Linux: dep status -dot | dot -T png | display
MacOS: dep status -dot | dot -T png | open -f -a /Applications/Preview.app
Windows: dep status -dot | dot -T png -o status.png; start status.png
Generates a visual representation of the dependency tree using GraphViz.
(Note: in order for this example to work you must first have graphviz
installed on your system)
`
const (
shortRev uint8 = iota
longRev
)
var (
errFailedUpdate = errors.New("failed to fetch updates")
errFailedListPkg = errors.New("failed to list packages")
errMultipleFailures = errors.New("multiple sources of failure")
errInputDigestMismatch = errors.New("input-digest mismatch")
)
func (cmd *statusCommand) Name() string { return "status" }
func (cmd *statusCommand) Args() string { return "[package...]" }
func (cmd *statusCommand) ShortHelp() string { return statusShortHelp }
func (cmd *statusCommand) LongHelp() string { return statusLongHelp }
func (cmd *statusCommand) Hidden() bool { return false }
func (cmd *statusCommand) Register(fs *flag.FlagSet) {
fs.BoolVar(&cmd.examples, "examples", false, "print detailed usage examples")
fs.BoolVar(&cmd.json, "json", false, "output in JSON format")
fs.StringVar(&cmd.template, "f", "", "output in text/template format")
fs.BoolVar(&cmd.lock, "lock", false, "output in the lock file format (assumes -detail)")
fs.BoolVar(&cmd.dot, "dot", false, "output the dependency graph in GraphViz format")
fs.BoolVar(&cmd.old, "old", false, "only show out-of-date dependencies")
fs.BoolVar(&cmd.missing, "missing", false, "only show missing dependencies")
fs.StringVar(&cmd.outFilePath, "out", "", "path to a file to which to write the output. Blank value will be ignored")
fs.BoolVar(&cmd.detail, "detail", false, "include more detail in the chosen format")
}
type statusCommand struct {
examples bool
json bool
template string
lock bool
output string
dot bool
old bool
missing bool
outFilePath string
detail bool
}
type outputter interface {
BasicHeader() error
BasicLine(*BasicStatus) error
BasicFooter() error
DetailHeader(*dep.SolveMeta) error
DetailLine(*DetailStatus) error
DetailFooter(*dep.SolveMeta) error
MissingHeader() error
MissingLine(*MissingStatus) error
MissingFooter() error
}
// Only a subset of the outputters should be able to output old statuses.
type oldOutputter interface {
OldHeader() error
OldLine(*OldStatus) error
OldFooter() error
}
type tableOutput struct{ w *tabwriter.Writer }
func (out *tableOutput) BasicHeader() error {
_, err := fmt.Fprintf(out.w, "PROJECT\tCONSTRAINT\tVERSION\tREVISION\tLATEST\tPKGS USED\n")
return err
}
func (out *tableOutput) BasicFooter() error {
return out.w.Flush()
}
func (out *tableOutput) BasicLine(bs *BasicStatus) error {
_, err := fmt.Fprintf(out.w,
"%s\t%s\t%s\t%s\t%s\t%d\t\n",
bs.ProjectRoot,
bs.getConsolidatedConstraint(),
formatVersion(bs.Version),
formatVersion(bs.Revision),
bs.getConsolidatedLatest(shortRev),
bs.PackageCount,
)
return err
}
func (out *tableOutput) DetailHeader(metadata *dep.SolveMeta) error {
_, err := fmt.Fprintf(out.w, "PROJECT\tSOURCE\tCONSTRAINT\tVERSION\tREVISION\tLATEST\tPKGS USED\n")
return err
}
func (out *tableOutput) DetailFooter(metadata *dep.SolveMeta) error {
return out.BasicFooter()
}
func (out *tableOutput) DetailLine(ds *DetailStatus) error {
_, err := fmt.Fprintf(out.w,
"%s\t%s\t%s\t%s\t%s\t%s\t[%s]\t\n",
ds.ProjectRoot,
ds.Source,
ds.getConsolidatedConstraint(),
formatVersion(ds.Version),
formatVersion(ds.Revision),
ds.getConsolidatedLatest(shortRev),
strings.Join(ds.Packages, ", "),
)
return err
}
func (out *tableOutput) MissingHeader() error {
_, err := fmt.Fprintln(out.w, "PROJECT\tMISSING PACKAGES")
return err
}
func (out *tableOutput) MissingLine(ms *MissingStatus) error {
_, err := fmt.Fprintf(out.w,
"%s\t%s\t\n",
ms.ProjectRoot,
ms.MissingPackages,
)
return err
}
func (out *tableOutput) MissingFooter() error {
return out.w.Flush()
}
func (out *tableOutput) OldHeader() error {
_, err := fmt.Fprintf(out.w, "PROJECT\tCONSTRAINT\tREVISION\tLATEST\n")
return err
}
func (out *tableOutput) OldLine(os *OldStatus) error {
_, err := fmt.Fprintf(out.w,
"%s\t%s\t%s\t%s\t\n",
os.ProjectRoot,
os.getConsolidatedConstraint(),
formatVersion(os.Revision),
os.getConsolidatedLatest(shortRev),
)
return err
}
func (out *tableOutput) OldFooter() error {
return out.w.Flush()
}
type jsonOutput struct {
w io.Writer
basic []*rawStatus
detail []rawDetailProject
missing []*MissingStatus
old []*rawOldStatus
}
func (out *jsonOutput) BasicHeader() error {
out.basic = []*rawStatus{}
return nil
}
func (out *jsonOutput) BasicFooter() error {
return json.NewEncoder(out.w).Encode(out.basic)
}
func (out *jsonOutput) BasicLine(bs *BasicStatus) error {
out.basic = append(out.basic, bs.marshalJSON())
return nil
}
func (out *jsonOutput) DetailHeader(metadata *dep.SolveMeta) error {
out.detail = []rawDetailProject{}
return nil
}
func (out *jsonOutput) DetailFooter(metadata *dep.SolveMeta) error {
doc := rawDetail{
Projects: out.detail,
Metadata: newRawMetadata(metadata),
}
return json.NewEncoder(out.w).Encode(doc)
}
func (out *jsonOutput) DetailLine(ds *DetailStatus) error {
out.detail = append(out.detail, *ds.marshalJSON())
return nil
}
func (out *jsonOutput) MissingHeader() error {
out.missing = []*MissingStatus{}
return nil
}
func (out *jsonOutput) MissingLine(ms *MissingStatus) error {
out.missing = append(out.missing, ms)
return nil
}
func (out *jsonOutput) MissingFooter() error {
return json.NewEncoder(out.w).Encode(out.missing)
}
func (out *jsonOutput) OldHeader() error {
out.old = []*rawOldStatus{}
return nil
}
func (out *jsonOutput) OldLine(os *OldStatus) error {
out.old = append(out.old, os.marshalJSON())
return nil
}
func (out *jsonOutput) OldFooter() error {
return json.NewEncoder(out.w).Encode(out.old)
}
type dotOutput struct {
w io.Writer
o string
g *graphviz
p *dep.Project
}
func (out *dotOutput) BasicHeader() error {
out.g = new(graphviz).New()
ptree := out.p.RootPackageTree
// TODO(sdboyer) should be true, true, false, out.p.Manifest.IgnoredPackages()
prm, _ := ptree.ToReachMap(true, false, false, nil)
out.g.createNode(string(out.p.ImportRoot), "", prm.FlattenFn(paths.IsStandardImportPath))
return nil
}
func (out *dotOutput) BasicFooter() error {
gvo := out.g.output("")
_, err := fmt.Fprintf(out.w, gvo.String())
return err
}
func (out *dotOutput) BasicLine(bs *BasicStatus) error {
out.g.createNode(bs.ProjectRoot, bs.getConsolidatedVersion(), bs.Children)
return nil
}
func (out *dotOutput) DetailHeader(metadata *dep.SolveMeta) error {
return out.BasicHeader()
}
func (out *dotOutput) DetailFooter(metadata *dep.SolveMeta) error {
return out.BasicFooter()
}
func (out *dotOutput) DetailLine(ds *DetailStatus) error {
return out.BasicLine(&ds.BasicStatus)
}
func (out *dotOutput) MissingHeader() error { return nil }
func (out *dotOutput) MissingLine(ms *MissingStatus) error { return nil }
func (out *dotOutput) MissingFooter() error { return nil }
type templateOutput struct {
w io.Writer
tmpl *template.Template
detail []rawDetailProject
}
func (out *templateOutput) BasicHeader() error { return nil }
func (out *templateOutput) BasicFooter() error { return nil }
func (out *templateOutput) BasicLine(bs *BasicStatus) error {
data := rawStatus{
ProjectRoot: bs.ProjectRoot,
Constraint: bs.getConsolidatedConstraint(),
Version: bs.getConsolidatedVersion(),
Revision: bs.Revision.String(),
Latest: bs.getConsolidatedLatest(shortRev),
PackageCount: bs.PackageCount,
}
return out.tmpl.Execute(out.w, data)
}
func (out *templateOutput) DetailHeader(metadata *dep.SolveMeta) error {
out.detail = []rawDetailProject{}
return nil
}
func (out *templateOutput) DetailFooter(metadata *dep.SolveMeta) error {
raw := rawDetail{
Projects: out.detail,
Metadata: newRawMetadata(metadata),
}
return out.tmpl.Execute(out.w, raw)
}
func (out *templateOutput) DetailLine(ds *DetailStatus) error {
data := rawDetailProject{
ProjectRoot: ds.ProjectRoot,
Constraint: ds.getConsolidatedConstraint(),
Locked: formatDetailVersion(ds.Version, ds.Revision),
Latest: formatDetailLatestVersion(ds.Latest, ds.hasError),
PruneOpts: ds.getPruneOpts(),
Digest: ds.Digest.String(),
PackageCount: ds.PackageCount,
Source: ds.Source,
Packages: ds.Packages,
}
out.detail = append(out.detail, data)
return nil
}
func (out *templateOutput) OldHeader() error { return nil }
func (out *templateOutput) OldFooter() error { return nil }
func (out *templateOutput) OldLine(os *OldStatus) error {
return out.tmpl.Execute(out.w, os)
}
func (out *templateOutput) MissingHeader() error { return nil }
func (out *templateOutput) MissingFooter() error { return nil }
func (out *templateOutput) MissingLine(ms *MissingStatus) error {
return out.tmpl.Execute(out.w, ms)
}
func (cmd *statusCommand) Run(ctx *dep.Ctx, args []string) error {
if cmd.examples {
ctx.Err.Println(strings.TrimSpace(statusExamples))
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
}
var buf bytes.Buffer
var out outputter
switch {
case cmd.missing:
return errors.Errorf("not implemented")
case cmd.json:
out = &jsonOutput{
w: &buf,
}
case cmd.dot:
out = &dotOutput{
p: p,
o: cmd.output,
w: &buf,
}
case cmd.template != "":
tmpl, err := parseStatusTemplate(cmd.template)
if err != nil {
return err
}
out = &templateOutput{
w: &buf,
tmpl: tmpl,
}
case cmd.lock:
tmpl, err := parseStatusTemplate(statusLockTemplate)
if err != nil {
return err
}
out = &templateOutput{
w: &buf,
tmpl: tmpl,
}
default:
out = &tableOutput{
w: tabwriter.NewWriter(&buf, 0, 4, 2, ' ', 0),
}
}
// Check if the lock file exists.
if p.Lock == nil {
return errors.Errorf("no Gopkg.lock found. Run `dep ensure` to generate lock file")
}
if cmd.old {
if _, ok := out.(oldOutputter); !ok {
return errors.Errorf("invalid output format used")
}
err = cmd.runOld(ctx, out.(oldOutputter), p, sm)
ctx.Out.Print(buf.String())
return err
}
_, errCount, runerr := cmd.runStatusAll(ctx, out, p, sm)
if runerr != nil {
switch runerr {
case errFailedUpdate:
// Print the help when in non-verbose mode
if !ctx.Verbose {
ctx.Out.Printf("The status of %d projects are unknown due to errors. Rerun with `-v` flag to see details.\n", errCount)
}
case errInputDigestMismatch:
ctx.Err.Printf("Gopkg.lock is out of sync with imports and/or Gopkg.toml. Run `dep check` for details.\n")
default:
return runerr
}
}
if cmd.outFilePath == "" {
// Print the status output
ctx.Out.Print(buf.String())
} else {
file, err := os.Create(cmd.outFilePath)
if err != nil {
return fmt.Errorf("error creating output file: %v", err)
}
defer file.Close()
if _, err := io.Copy(file, bytes.NewReader(buf.Bytes())); err != nil {
return fmt.Errorf("error writing output file: %v", err)
}
}
return runerr
}
func (cmd *statusCommand) validateFlags() error {
// Operating mode flags.
var opModes []string
if cmd.old {
opModes = append(opModes, "-old")
}
if cmd.missing {
opModes = append(opModes, "-missing")
}
if cmd.detail {
opModes = append(opModes, "-detail")
}
// Check if any other flags are passed with -dot.
if cmd.dot {
if cmd.template != "" {
return errors.New("cannot pass template string with -dot")
}
if cmd.json {
return errors.New("cannot pass multiple output format flags")
}
if len(opModes) > 0 {
return errors.New("-dot generates dependency graph; cannot pass other flags")
}
}
if cmd.lock {
if cmd.template != "" {
return errors.New("cannot pass template string with -lock")
}
if !cmd.detail {
cmd.detail = true
}
}
if len(opModes) > 1 {
// List the flags because which flags are for operation mode might not
// be apparent to the users.
return errors.Wrapf(errors.New("cannot pass multiple operating mode flags"), "%v", opModes)
}
return nil
}
// OldStatus contains information about all the out of date packages in a project.
type OldStatus struct {
ProjectRoot string
Constraint gps.Constraint
Revision gps.Revision
Latest gps.Version
}
type rawOldStatus struct {
ProjectRoot, Constraint, Revision, Latest string
}
func (os OldStatus) getConsolidatedConstraint() string {
var constraint string
if os.Constraint != nil {
if v, ok := os.Constraint.(gps.Version); ok {
constraint = formatVersion(v)
} else {
constraint = os.Constraint.String()
}
}
return constraint
}
func (os OldStatus) getConsolidatedLatest(revSize uint8) string {
latest := ""
if os.Latest != nil {
switch revSize {
case shortRev:
latest = formatVersion(os.Latest)
case longRev:
latest = os.Latest.String()
}
}
return latest
}
func (os OldStatus) marshalJSON() *rawOldStatus {
return &rawOldStatus{
ProjectRoot: os.ProjectRoot,
Constraint: os.getConsolidatedConstraint(),
Revision: string(os.Revision),
Latest: os.getConsolidatedLatest(longRev),
}
}
func (cmd *statusCommand) runOld(ctx *dep.Ctx, out oldOutputter, p *dep.Project, sm gps.SourceManager) error {
// While the network churns on ListVersions() requests, statically analyze
// code from the current project.
ptree := p.RootPackageTree
// Set up a solver in order to check the InputHash.
params := gps.SolveParameters{
ProjectAnalyzer: dep.Analyzer{},
RootDir: p.AbsRoot,
RootPackageTree: ptree,
Manifest: p.Manifest,
// Locks aren't a part of the input hash check, so we can omit it.
}
logger := ctx.Err
if ctx.Verbose {
params.TraceLogger = ctx.Err
} else {
logger = log.New(ioutil.Discard, "", 0)
}
// Check update for all the projects.
params.ChangeAll = true
solver, err := gps.Prepare(params, sm)
if err != nil {
return errors.Wrap(err, "fastpath solver prepare")
}
logger.Println("Solving dependency graph to determine which dependencies can be updated.")
solution, err := solver.Solve(context.TODO())
if err != nil {
return errors.Wrap(err, "runOld")
}
var oldStatuses []OldStatus
solutionProjects := solution.Projects()
for _, proj := range p.Lock.Projects() {
for _, sProj := range solutionProjects {
// Look for the same project in solution and lock.
if sProj.Ident().ProjectRoot != proj.Ident().ProjectRoot {
continue
}
// If revisions are not the same then it is old and we should display it.
latestRev, _, _ := gps.VersionComponentStrings(sProj.Version())
atRev, _, _ := gps.VersionComponentStrings(proj.Version())
if atRev == latestRev {
continue
}
var constraint gps.Constraint
// Getting Constraint.
if pp, has := p.Manifest.Ovr[proj.Ident().ProjectRoot]; has && pp.Constraint != nil {
// manifest has override for project.
constraint = pp.Constraint
} else if pp, has := p.Manifest.Constraints[proj.Ident().ProjectRoot]; has && pp.Constraint != nil {
// manifest has normal constraint.
constraint = pp.Constraint
} else {
// No constraint exists. No need to worry about displaying it.
continue
}
// Generate the old status data and append it.
os := OldStatus{
ProjectRoot: proj.Ident().String(),
Revision: gps.Revision(atRev),
Latest: gps.Revision(latestRev),
Constraint: constraint,
}
oldStatuses = append(oldStatuses, os)
}
}
out.OldHeader()
for _, ostat := range oldStatuses {
out.OldLine(&ostat)
}
out.OldFooter()
return nil
}
type rawStatus struct {
ProjectRoot string
Constraint string
Version string
Revision string
Latest string
PackageCount int
}
// rawDetail is is additional information used for the status when the
// -detail flag is specified
type rawDetail struct {
Projects []rawDetailProject
Metadata rawDetailMetadata
}
type rawDetailVersion struct {
Revision string `json:"Revision,omitempty"`
Version string `json:"Version,omitempty"`
Branch string `json:"Branch,omitempty"`
}
type rawDetailProject struct {
ProjectRoot string
Packages []string
Locked rawDetailVersion
Latest rawDetailVersion
PruneOpts string
Digest string
Source string `json:"Source,omitempty"`
Constraint string
PackageCount int
}
type rawDetailMetadata struct {
AnalyzerName string
AnalyzerVersion int
InputsDigest string // deprecated
InputImports []string
SolverName string
SolverVersion int
}
func newRawMetadata(metadata *dep.SolveMeta) rawDetailMetadata {
if metadata == nil {
return rawDetailMetadata{}
}
return rawDetailMetadata{
AnalyzerName: metadata.AnalyzerName,
AnalyzerVersion: metadata.AnalyzerVersion,
InputImports: metadata.InputImports,
SolverName: metadata.SolverName,
SolverVersion: metadata.SolverVersion,
}
}
// BasicStatus contains all the information reported about a single dependency
// in the summary/list status output mode.
type BasicStatus struct {
ProjectRoot string
Children []string
Constraint gps.Constraint
Version gps.UnpairedVersion
Revision gps.Revision
Latest gps.Version
PackageCount int
hasOverride bool
hasError bool
}
// DetailStatus contains all information reported about a single dependency
// in the detailed status output mode. The included information matches the
// information included about a a project in a lock file.
type DetailStatus struct {
BasicStatus
Packages []string
Source string
PruneOpts gps.PruneOptions
Digest verify.VersionedDigest
}
func (bs *BasicStatus) getConsolidatedConstraint() string {
var constraint string
if bs.Constraint != nil {
if v, ok := bs.Constraint.(gps.Version); ok {
constraint = formatVersion(v)
} else {
constraint = bs.Constraint.String()
}
}
if bs.hasOverride {
constraint += " (override)"
}
return constraint
}
func (bs *BasicStatus) getConsolidatedVersion() string {
version := formatVersion(bs.Revision)
if bs.Version != nil {
version = formatVersion(bs.Version)
}
return version
}
func (bs *BasicStatus) getConsolidatedLatest(revSize uint8) string {
latest := ""
if bs.Latest != nil {
switch revSize {
case shortRev:
latest = formatVersion(bs.Latest)
case longRev:
latest = bs.Latest.String()
}
}
if bs.hasError {
latest += "unknown"
}
return latest
}
func (ds *DetailStatus) getPruneOpts() string {
return (ds.PruneOpts & ^gps.PruneNestedVendorDirs).String()
}
func (bs *BasicStatus) marshalJSON() *rawStatus {
return &rawStatus{
ProjectRoot: bs.ProjectRoot,
Constraint: bs.getConsolidatedConstraint(),
Version: formatVersion(bs.Version),
Revision: string(bs.Revision),
Latest: bs.getConsolidatedLatest(longRev),
PackageCount: bs.PackageCount,
}
}
func (ds *DetailStatus) marshalJSON() *rawDetailProject {
rawStatus := ds.BasicStatus.marshalJSON()
return &rawDetailProject{
ProjectRoot: rawStatus.ProjectRoot,
Constraint: rawStatus.Constraint,
Locked: formatDetailVersion(ds.Version, ds.Revision),
Latest: formatDetailLatestVersion(ds.Latest, ds.hasError),
PruneOpts: ds.getPruneOpts(),
Digest: ds.Digest.String(),
Source: ds.Source,
Packages: ds.Packages,
PackageCount: ds.PackageCount,
}
}
// MissingStatus contains information about all the missing packages in a project.
type MissingStatus struct {
ProjectRoot string
MissingPackages []string
}
func (cmd *statusCommand) runStatusAll(ctx *dep.Ctx, out outputter, p *dep.Project, sm gps.SourceManager) (hasMissingPkgs bool, errCount int, err error) {
// While the network churns on ListVersions() requests, statically analyze
// code from the current project.
ptree := p.RootPackageTree
// Set up a solver in order to check the InputHash.
params := gps.SolveParameters{
ProjectAnalyzer: dep.Analyzer{},
RootDir: p.AbsRoot,
RootPackageTree: ptree,
Manifest: p.Manifest,
// Locks aren't a part of the input hash check, so we can omit it.
}
logger := ctx.Err
if ctx.Verbose {
params.TraceLogger = ctx.Err
} else {
logger = log.New(ioutil.Discard, "", 0)
}
if err := ctx.ValidateParams(sm, params); err != nil {
return false, 0, err
}
// Errors while collecting constraints should not fail the whole status run.
// It should count the error and tell the user about incomplete results.
cm, ccerrs := collectConstraints(ctx, p, sm)
if len(ccerrs) > 0 {
errCount += len(ccerrs)
}
// Get the project list and sort it so that the printed output users see is
// deterministically ordered. (This may be superfluous if the lock is always
// written in alpha order, but it doesn't hurt to double down.)
slp := p.Lock.Projects()
sort.Slice(slp, func(i, j int) bool {
return slp[i].Ident().Less(slp[j].Ident())
})
slcp := p.ChangedLock.Projects()
sort.Slice(slcp, func(i, j int) bool {
return slcp[i].Ident().Less(slcp[j].Ident())
})
lsat := verify.LockSatisfiesInputs(p.Lock, p.Manifest, params.RootPackageTree)
if lsat.Satisfied() {
// If the lock satisfies the inputs, we're guaranteed (barring manual
// meddling, about which we can do nothing) that the lock is a
// transitively complete picture of all deps. That eliminates the need
// for some checks.
logger.Println("Checking upstream projects:")
// DetailStatus channel to collect all the DetailStatus.
dsCh := make(chan *DetailStatus, len(slp))
// Error channels to collect different errors.
errListPkgCh := make(chan error, len(slp))
errListVerCh := make(chan error, len(slp))
var wg sync.WaitGroup
for i, proj := range slp {
wg.Add(1)
logger.Printf("(%d/%d) %s\n", i+1, len(slp), proj.Ident().ProjectRoot)
go func(proj verify.VerifiableProject) {
bs := BasicStatus{
ProjectRoot: string(proj.Ident().ProjectRoot),
PackageCount: len(proj.Packages()),
}
// Get children only for specific outputers
// in order to avoid slower status process.
switch out.(type) {
case *dotOutput:
ptr, err := sm.ListPackages(proj.Ident(), proj.Version())
if err != nil {
bs.hasError = true
errListPkgCh <- err
}
prm, _ := ptr.ToReachMap(true, true, false, p.Manifest.IgnoredPackages())
bs.Children = prm.FlattenFn(paths.IsStandardImportPath)
}
// Split apart the version from the lock into its constituent parts.
switch tv := proj.Version().(type) {
case gps.UnpairedVersion:
bs.Version = tv
case gps.Revision:
bs.Revision = tv
case gps.PairedVersion:
bs.Version = tv.Unpair()
bs.Revision = tv.Revision()
}
// Check if the manifest has an override for this project. If so,
// set that as the constraint.
if pp, has := p.Manifest.Ovr[proj.Ident().ProjectRoot]; has && pp.Constraint != nil {
bs.hasOverride = true
bs.Constraint = pp.Constraint
} else if pp, has := p.Manifest.Constraints[proj.Ident().ProjectRoot]; has && pp.Constraint != nil {
// If the manifest has a constraint then set that as the constraint.
bs.Constraint = pp.Constraint
} else {
bs.Constraint = gps.Any()
for _, c := range cm[bs.ProjectRoot] {
bs.Constraint = c.Constraint.Intersect(bs.Constraint)
}
}