forked from sourcegraph/srclib
/
store_cmds.go
1192 lines (1053 loc) · 31.4 KB
/
store_cmds.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
package src
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"code.google.com/p/rog-go/parallel"
"golang.org/x/tools/godoc/vfs"
"sort"
"sourcegraph.com/sourcegraph/go-flags"
"sourcegraph.com/sourcegraph/go-sourcegraph/sourcegraph"
"sourcegraph.com/sourcegraph/rwvfs"
"sourcegraph.com/sourcegraph/srclib/config"
"sourcegraph.com/sourcegraph/srclib/graph"
"sourcegraph.com/sourcegraph/srclib/grapher"
"sourcegraph.com/sourcegraph/srclib/plan"
"sourcegraph.com/sourcegraph/srclib/store"
"sourcegraph.com/sourcegraph/srclib/unit"
)
func init() {
storeC, err := CLI.AddCommand("store",
"graph store commands",
"",
&storeCmd,
)
if err != nil {
log.Fatal(err)
}
lrepo, _ := openLocalRepo()
if lrepo != nil && lrepo.RootDir != "" {
absDir, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
relDir, err := filepath.Rel(absDir, lrepo.RootDir)
if err == nil {
SetOptionDefaultValue(storeC.Group, "root", filepath.Join(relDir, store.SrclibStoreDir))
}
}
InitStoreCmds(storeC)
}
func InitStoreCmds(c *flags.Command) {
importC, err := c.AddCommand("import",
"import data",
`The import command imports data (from .srclib-cache) into the store.`,
&storeImportCmd,
)
if err != nil {
log.Fatal(err)
}
setDefaultRepoURIOpt(importC)
setDefaultCommitIDOpt(importC)
_, err = c.AddCommand("indexes",
"list indexes",
"The indexes command lists all of a store's indexes that match the specified criteria.",
&storeIndexesCmd,
)
if err != nil {
log.Fatal(err)
}
_, err = c.AddCommand("index",
"build indexes",
"The index command builds indexes that match the specified index criteria. Built indexes are printed to stdout.",
&storeIndexCmd,
)
if err != nil {
log.Fatal(err)
}
_, err = c.AddCommand("repos",
"list repos",
"The repos command lists all repos that match a filter.",
&storeReposCmd,
)
if err != nil {
log.Fatal(err)
}
_, err = c.AddCommand("versions",
"list versions",
"The versions command lists all versions that match a filter.",
&storeVersionsCmd,
)
if err != nil {
log.Fatal(err)
}
_, err = c.AddCommand("units",
"list units",
"The units command lists all units that match a filter.",
&storeUnitsCmd,
)
if err != nil {
log.Fatal(err)
}
defsC, err := c.AddCommand("defs",
"list defs",
"The defs command lists all defs that match a filter.",
&storeDefsCmd,
)
if err != nil {
log.Fatal(err)
}
defsC.Aliases = []string{"def"}
_, err = c.AddCommand("refs",
"list refs",
"The refs command lists all refs that match a filter.",
&storeRefsCmd,
)
if err != nil {
log.Fatal(err)
}
}
// OpenStore is called by all of the store subcommands to open the
// store.
var OpenStore func() (interface{}, error) = storeCmd.store
type StoreCmd struct {
Type string `short:"t" long:"type" description:"the (multi-)repo store type to use (RepoStore, MultiRepoStore, etc.)" default:"RepoStore"`
Root string `short:"r" long:"root" description:"the root of the store (repo clone dir for RepoStore, global path for MultiRepoStore, etc.)" default:".srclib-store"`
Config string `long:"config" description:"(rarely used) JSON-encoded config for extra config, specific to each store type"`
}
var storeCmd StoreCmd
func (c *StoreCmd) Execute(args []string) error { return nil }
// store returns the store specified by StoreCmd's Type and Root
// options.
func (c *StoreCmd) store() (interface{}, error) {
fs := rwvfs.OS(c.Root)
type createParents interface {
CreateParentDirs(bool)
}
if fs, ok := fs.(createParents); ok {
fs.CreateParentDirs(true)
}
switch c.Type {
case "RepoStore":
return store.NewFSRepoStore(fs), nil
case "MultiRepoStore":
return store.NewFSMultiRepoStore(rwvfs.Walkable(fs), nil), nil
default:
return nil, fmt.Errorf("unrecognized store --type value: %q (valid values are RepoStore, MultiRepoStore)", c.Type)
}
}
type StoreImportCmd struct {
ImportOpt
Quiet bool `short:"q" long:"quiet" description:"silence all output"`
Sample bool `long:"sample" description:"(sample data) import sample data, not .srclib-cache data"`
SampleDefs int `long:"sample-defs" description:"(sample data) number of sample defs to import" default:"100"`
SampleRefs int `long:"sample-refs" description:"(sample data) number of sample refs to import" default:"100"`
SampleImportOnly bool `long:"sample-import-only" description:"(sample data) only import, don't demonstrate listing data"`
RemoteBuildData bool `long:"remote-build-data" description:"import remote build data (not the local .srclib-cache build data)"`
}
var storeImportCmd StoreImportCmd
func (c *StoreImportCmd) Execute(args []string) error {
start := time.Now()
s, err := OpenStore()
if err != nil {
return err
}
if c.Sample {
return c.sample(s)
}
bdfs, label, err := getBuildDataFS(!c.RemoteBuildData, c.Repo, c.CommitID)
if err != nil {
return err
}
if GlobalOpt.Verbose {
log.Printf("# Importing build data for %s (commit %s) from %s", c.Repo, c.CommitID, label)
}
if err := Import(bdfs, s, c.ImportOpt); err != nil {
return err
}
if !c.Quiet {
log.Printf("# Import completed in %s.", time.Since(start))
}
return nil
}
type ImportOpt struct {
DryRun bool `short:"n" long:"dry-run" description:"print what would be done but don't do anything"`
NoIndex bool `long:"no-index" description:"don't build indexes (indexes inside a single source unit are always built)"`
Repo string `long:"repo" description:"only import for this repo"`
Unit string `long:"unit" description:"only import source units with this name"`
UnitType string `long:"unit-type" description:"only import source units with this type"`
CommitID string `long:"commit" description:"commit ID of commit whose data to import"`
Verbose bool
}
// Import imports build data into a RepoStore or MultiRepoStore.
func Import(buildDataFS vfs.FileSystem, stor interface{}, opt ImportOpt) error {
// Traverse the build data directory for this repo and commit to
// create the makefile that lists the targets (which are the data
// files we will import).
treeConfig, err := config.ReadCached(buildDataFS)
if err != nil {
return err
}
mf, err := plan.CreateMakefile(".", nil, "", treeConfig, plan.Options{NoCache: true})
if err != nil {
return err
}
var (
mu sync.Mutex
hasIndexableData bool
)
par := parallel.NewRun(10)
for _, rule_ := range mf.Rules {
rule := rule_
if opt.Unit != "" || opt.UnitType != "" {
type ruleForSourceUnit interface {
SourceUnit() *unit.SourceUnit
}
if rule, ok := rule.(ruleForSourceUnit); ok {
u := rule.SourceUnit()
if (opt.Unit != "" && u.Name != opt.Unit) || (opt.UnitType != "" && u.Type != opt.UnitType) {
continue
}
} else {
// Skip all non-source-unit rules if --unit or
// --unit-type are specified.
continue
}
}
par.Do(func() error {
switch rule := rule.(type) {
case *grapher.GraphUnitRule:
var data graph.Output
if err := readJSONFileFS(buildDataFS, rule.Target(), &data); err != nil {
if os.IsNotExist(err) {
log.Printf("Warning: no build data for unit %s %s.", rule.Unit.Type, rule.Unit.Name)
return nil
}
return err
}
if opt.DryRun || GlobalOpt.Verbose {
log.Printf("# Importing graph data (%d defs, %d refs, %d docs, %d anns) for unit %s %s", len(data.Defs), len(data.Refs), len(data.Docs), len(data.Anns), rule.Unit.Type, rule.Unit.Name)
if opt.DryRun {
return nil
}
}
// HACK: Transfer docs to [def].Docs.
docsByPath := make(map[string]*graph.Doc, len(data.Docs))
for _, doc := range data.Docs {
docsByPath[doc.Path] = doc
}
for _, def := range data.Defs {
if doc, present := docsByPath[def.Path]; present {
def.Docs = append(def.Docs, graph.DefDoc{Format: doc.Format, Data: doc.Data})
}
}
switch imp := stor.(type) {
case store.RepoImporter:
if err := imp.Import(opt.CommitID, rule.Unit, data); err != nil {
return err
}
case store.MultiRepoImporter:
if err := imp.Import(opt.Repo, opt.CommitID, rule.Unit, data); err != nil {
return err
}
default:
return fmt.Errorf("store (type %T) does not implement importing", stor)
}
mu.Lock()
hasIndexableData = true
mu.Unlock()
}
return nil
})
}
if err := par.Wait(); err != nil {
return err
}
if hasIndexableData && !opt.NoIndex {
if GlobalOpt.Verbose {
log.Printf("# Building indexes")
}
switch s := stor.(type) {
case store.RepoIndexer:
if err := s.Index(opt.CommitID); err != nil {
return err
}
case store.MultiRepoIndexer:
if err := s.Index(opt.Repo, opt.CommitID); err != nil {
return err
}
}
}
return nil
}
// sample imports sample data (when the --sample option is given).
func (c *StoreImportCmd) sample(s interface{}) error {
dataString := []byte(`"abcdabcdabcdabcdabcdcdabcdabcdabcdabcdabcdabcdabcdabcdcdabcdabcdabcdabcdabcdabcdabcdabcdcdabcdabcdabcdabcdabcdabcdabcdabcdcdabcdabcdabcdabcdabcdabcdabcdabcdcdabcdabcdabcdabcdabcdabcdabcdabcdcdabcdabcdabcdabcdabcdabcdabcdabcdcdabcdabcdabcd"`)
makeGraphData := func(numDefs, numRefs int) *graph.Output {
defs := make([]graph.Def, numDefs)
refs := make([]graph.Ref, numRefs)
data := graph.Output{
Defs: make([]*graph.Def, numDefs),
Refs: make([]*graph.Ref, numRefs),
}
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < numDefs; i++ {
defs[i] = graph.Def{
DefKey: graph.DefKey{Path: fmt.Sprintf("def-path-%d", i)},
Name: fmt.Sprintf("def-name-%d", i),
Kind: "mykind",
DefStart: uint32((i % 53) * 37),
DefEnd: uint32((i%53)*37 + (i % 20)),
File: fmt.Sprintf("dir%d/subdir%d/subsubdir%d/file-%d.foo", i%5, i%3, i%7, i%11),
Exported: i%5 == 0,
Local: i%3 == 0,
Data: dataString,
}
}
}()
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < numRefs; i++ {
refs[i] = graph.Ref{
DefPath: fmt.Sprintf("ref-path-%d", i%179),
Def: i%5 == 0,
Start: uint32((i % 51) * 39),
End: uint32((i%51)*37 + (int(i) % 18)),
File: fmt.Sprintf("dir%d/subdir%d/subsubdir%d/file-%d.foo", i%3, i%5, i%7, i%11),
}
if i%3 == 0 {
refs[i].DefUnit = fmt.Sprintf("def-unit-%d", i%5)
refs[i].DefUnitType = fmt.Sprintf("def-unit-type-%d", i%4)
if i%7 == 0 {
refs[i].DefRepo = fmt.Sprintf("def-repo-%d", i%7)
}
}
}
}()
wg.Add(1)
go func() {
defer wg.Done()
for i := range defs {
data.Defs[i] = &defs[i]
}
for i := range refs {
data.Refs[i] = &refs[i]
}
}()
wg.Wait()
return &data
}
start := time.Now()
log.Printf("Making sample data (%d defs, %d refs)", c.SampleDefs, c.SampleRefs)
data := makeGraphData(c.SampleDefs, c.SampleRefs)
unit := &unit.SourceUnit{Type: "MyUnitType", Name: "MyUnit"}
files := map[string]struct{}{}
for _, def := range data.Defs {
files[def.File] = struct{}{}
}
for _, ref := range data.Refs {
files[ref.File] = struct{}{}
}
for f := range files {
unit.Files = append(unit.Files, f)
}
if d := time.Since(start); d > time.Millisecond*250 {
log.Printf("Done making sample data (took %s).", d)
}
// Find some sample objects to query for down below.
ref2 := data.Refs[len(data.Refs)/2+1]
ref3 := data.Refs[len(data.Refs)/3+1]
def2 := data.Defs[len(data.Defs)/2+1]
def3 := data.Defs[len(data.Defs)/3+1]
// Find a ref that has the Unit/UnitType filled in.
var (
refDef4 graph.RefDefKey
foundRefDef4 bool
)
for _, ref := range data.Refs[len(data.Refs)/2:] {
if ref.DefUnit != "" && ref.DefUnitType != "" {
refDef4 = ref.RefDefKey()
foundRefDef4 = true
break
}
}
size, err := store.Codec.NewEncoder(ioutil.Discard).Encode(data)
if err != nil {
return err
}
log.Printf("Encoded data is %s", bytesString(size))
if c.CommitID == "" {
c.CommitID = strings.Repeat("f", 40)
}
log.Printf("Importing %d defs and %d refs into the source unit %+v at commit %s", len(data.Defs), len(data.Refs), unit.ID2(), c.CommitID)
start = time.Now()
switch imp := s.(type) {
case store.RepoImporter:
c.Repo = ""
if err := imp.Import(c.CommitID, unit, *data); err != nil {
return err
}
case store.MultiRepoImporter:
if c.Repo == "" {
c.Repo = "example.com/my/repo"
}
log.Printf(" - repo %s", c.Repo)
if err := imp.Import(c.Repo, c.CommitID, unit, *data); err != nil {
return err
}
default:
return fmt.Errorf("store (type %T) does not implement importing", s)
}
log.Printf("Import took %s (~%s per def/ref)", time.Since(start), time.Duration(int64(time.Since(start))/int64(len(data.Defs)+len(data.Refs))))
start = time.Now()
if !c.NoIndex {
switch s := s.(type) {
case store.RepoIndexer:
if err := s.Index(c.CommitID); err != nil {
return err
}
case store.MultiRepoIndexer:
if err := s.Index(c.Repo, c.CommitID); err != nil {
return err
}
}
}
log.Printf("Index took %s (~%s per def/ref)", time.Since(start), time.Duration(int64(time.Since(start))/int64(len(data.Defs)+len(data.Refs))))
if c.SampleImportOnly {
return nil
}
log.Println()
log.Printf("Running some commands to list sample data...")
runCmd := func(args ...string) error {
start := time.Now()
var b bytes.Buffer
c := exec.Command(args[0], args[1:]...)
c.Stdout = &b
c.Stderr = &b
log.Println()
log.Println(strings.Join(c.Args, " "))
if err := c.Run(); err != nil {
return fmt.Errorf("command %v failed\n\noutput was:\n%s", c.Args, b.String())
}
if GlobalOpt.Verbose {
log.Println(b.String())
} else {
log.Printf("-> printed %d lines of output (run with `%s -v` to view)", bytes.Count(b.Bytes(), []byte{'\n'}), os.Args[0])
}
log.Printf("-> took %s", time.Since(start))
return nil
}
prog := os.Args[0]
storeCmdArgs := func(subcmd, repo string, args ...string) []string {
x := []string{prog, "store", subcmd}
if repo != "" {
x = append(x, "--repo", repo)
}
x = append(x, "--commit", c.CommitID)
x = append(x, args...)
return x
}
if err := runCmd(storeCmdArgs("versions", c.Repo)...); err != nil {
return err
}
if err := runCmd(storeCmdArgs("units", c.Repo)...); err != nil {
return err
}
if err := runCmd(storeCmdArgs("units", c.Repo, "--file", def2.File)...); err != nil {
return err
}
if err := runCmd(storeCmdArgs("units", c.Repo, "--file", ref2.File)...); err != nil {
return err
}
if err := runCmd(storeCmdArgs("defs", c.Repo, "--file", def3.File)...); err != nil {
return err
}
if err := runCmd(storeCmdArgs("defs", c.Repo, "--query", def3.Name[:len(def3.Name)-2])...); err != nil {
return err
}
if err := runCmd(storeCmdArgs("refs", c.Repo, "--file", ref3.File)...); err != nil {
return err
}
if foundRefDef4 {
if err := runCmd(storeCmdArgs("refs", c.Repo, "--def-unit-type", refDef4.DefUnitType, "--def-unit", refDef4.DefUnit, "--def-path", refDef4.DefPath)...); err != nil {
return err
}
}
return nil
}
// countingWriter wraps an io.Writer, counting the number of bytes
// written.
type countingWriter struct {
io.Writer
n uint64
}
func (cr *countingWriter) Write(p []byte) (n int, err error) {
n, err = cr.Writer.Write(p)
cr.n += uint64(n)
return
}
type storeIndexCriteria struct {
Repo string `long:"repo" description:"only indexes for this repo"`
CommitID string `long:"commit" description:"only indexes for this commit ID"`
UnitType string `long:"unit-type" description:"only indexes for this source unit type"`
Unit string `long:"unit" description:"only indexes for this source unit name"`
Name string `long:"name" description:"only indexes whose name contains this substring"`
Type string `long:"type" description:"only indexes whose Go type contains this substring"`
NoSourceUnit bool `long:"no-unit" description:"skip indexes for specific source units"`
Stale bool `long:"stale" description:"only stale indexes"`
NotStale bool `long:"not-stale" description:"only non-stale indexes"`
ReposLimit int `long:"repos-limit" description:"only indexes from this many repos (0=all)"`
ReposOffset int `long:"repos-offset" description:"only indexes after skipping this many repos"`
}
func (c storeIndexCriteria) IndexCriteria() store.IndexCriteria {
crit := store.IndexCriteria{
Repo: c.Repo,
CommitID: c.CommitID,
Name: c.Name,
Type: c.Type,
}
if c.Stale && c.NotStale {
log.Fatal("must specify exactly one of --stale and --not-stale")
}
if c.Stale {
t := true
crit.Stale = &t
}
if c.NotStale {
f := false
crit.Stale = &f
}
if c.NoSourceUnit {
crit.Unit = store.NoSourceUnit
}
if c.UnitType != "" || c.Unit != "" {
crit.Unit = &unit.ID2{Type: c.UnitType, Name: c.Unit}
if crit.Unit.Type == "" || crit.Unit.Name == "" {
log.Fatal("must specify either both or neither of --unit-type and --unit (to filter by source unit)")
}
}
crit.ReposLimit = c.ReposLimit
crit.ReposOffset = c.ReposOffset
return crit
}
// doStoreIndexesCmd is invoked by both StoreIndexesCmd.Execute and
// StoreBuildIndexesCmd.Execute.
func doStoreIndexesCmd(crit store.IndexCriteria, opt storeIndexOptions, f func(interface{}, store.IndexCriteria, chan<- store.IndexStatus) ([]store.IndexStatus, error)) error {
if opt.Parallel != 1 {
log.Printf("NOTE: Index parallelism is %d. Output will printed as it is available, not necessarily ordered and grouped by repo, source unit, etc.", opt.Parallel)
}
store.MaxIndexParallel = opt.Parallel
printIndex := func(x store.IndexStatus) error {
if !opt.Print {
return nil
}
return x.Fprint(os.Stderr)
}
s, err := OpenStore()
if err != nil {
return err
}
hasError := false
done := make(chan struct{})
indexChan := make(chan store.IndexStatus)
switch opt.Output {
case "json":
go func() {
for x := range indexChan {
PrintJSON(x, "")
if err := printIndex(x); err != nil {
log.Fatal(err)
}
}
done <- struct{}{}
}()
case "text":
_, isMultiRepo := s.(store.MultiRepoStore)
var repoTab string
if isMultiRepo {
repoTab = "\t"
}
go func() {
var lastRepo, lastCommitID string
var lastUnit *unit.ID2
for x := range indexChan {
if isMultiRepo {
if x.Repo != lastRepo {
if lastRepo != "" {
fmt.Println()
}
fmt.Println(x.Repo)
}
}
if x.CommitID != lastCommitID {
fmt.Print(repoTab, x.CommitID, "\n")
}
if x.Unit != lastUnit && x.Unit != nil {
if x.Repo == lastRepo && x.CommitID == lastCommitID {
fmt.Println()
}
fmt.Print(repoTab, "\t", x.Unit.Name, " ", x.Unit.Type, "\n")
}
if x.Unit != nil {
fmt.Print("\t")
}
fmt.Print(repoTab, "\t")
fmt.Printf("%s (%s) ", x.Name, x.Type)
if x.Stale {
fmt.Print("STALE ")
}
if x.Size != 0 {
fmt.Print(bytesString(uint64(x.Size)), " ")
}
if x.Error != "" {
fmt.Printf("(ERROR: %s) ", x.Error)
hasError = true
}
if x.BuildError != "" {
fmt.Printf("(BUILD ERROR: %s) ", x.BuildError)
hasError = true
}
if x.BuildDuration != 0 {
fmt.Printf("- build took %s ", x.BuildDuration)
}
fmt.Println()
if err := printIndex(x); err != nil {
log.Fatal(err)
}
lastRepo = x.Repo
lastCommitID = x.CommitID
lastUnit = x.Unit
}
done <- struct{}{}
}()
default:
return fmt.Errorf("unexpected --output value: %q", opt.Output)
}
_, err = f(s, crit, indexChan)
defer func() {
close(indexChan)
<-done
}()
if err != nil {
return err
}
if hasError {
return errors.New("\nindex listing or index building errors occurred (see above)")
}
return nil
}
type storeIndexOptions struct {
Output string `short:"o" long:"output" description:"output format (text|json)" default:"text"`
Parallel int `short:"p" long:"parallel" description:"parallelism (may produce out-of-order output)" default:"1"`
Print bool `long:"print" description:"(debug) print representation of index"`
}
type StoreIndexesCmd struct {
storeIndexCriteria
storeIndexOptions
}
var storeIndexesCmd StoreIndexesCmd
func (c *StoreIndexesCmd) Execute(args []string) error {
return doStoreIndexesCmd(c.IndexCriteria(), c.storeIndexOptions, store.Indexes)
}
type StoreIndexCmd struct {
storeIndexCriteria
storeIndexOptions
}
var storeIndexCmd StoreIndexCmd
func (c *StoreIndexCmd) Execute(args []string) error {
return doStoreIndexesCmd(c.IndexCriteria(), c.storeIndexOptions, store.BuildIndexes)
}
type StoreReposCmd struct {
IDContains string `short:"i" long:"id-contains" description:"filter to repos whose ID contains this substring"`
}
func (c *StoreReposCmd) filters() []store.RepoFilter {
var fs []store.RepoFilter
if c.IDContains != "" {
fs = append(fs, store.RepoFilterFunc(func(repo string) bool { return strings.Contains(repo, c.IDContains) }))
}
return fs
}
var storeReposCmd StoreReposCmd
func (c *StoreReposCmd) Execute(args []string) error {
s, err := OpenStore()
if err != nil {
return err
}
mrs, ok := s.(store.MultiRepoStore)
if !ok {
return fmt.Errorf("store (type %T) does not implement listing repositories", s)
}
repos, err := mrs.Repos(c.filters()...)
if err != nil {
return err
}
for _, repo := range repos {
fmt.Println(repo)
}
return nil
}
type StoreVersionsCmd struct {
Repo string `long:"repo"`
CommitIDPrefix string `long:"commit" description:"commit ID prefix"`
RepoCommitIDs string `long:"repo-commits" description:"comma-separated list of repo@commitID specifiers"`
}
func (c *StoreVersionsCmd) filters() []store.VersionFilter {
var fs []store.VersionFilter
if c.Repo != "" {
fs = append(fs, store.ByRepos(c.Repo))
}
if c.CommitIDPrefix != "" {
fs = append(fs, store.VersionFilterFunc(func(version *store.Version) bool {
return strings.HasPrefix(version.CommitID, c.CommitIDPrefix)
}))
}
if c.RepoCommitIDs != "" {
fs = append(fs, makeRepoCommitIDsFilter(c.RepoCommitIDs))
}
return fs
}
var storeVersionsCmd StoreVersionsCmd
func (c *StoreVersionsCmd) Execute(args []string) error {
s, err := OpenStore()
if err != nil {
return err
}
rs, ok := s.(store.RepoStore)
if !ok {
return fmt.Errorf("store (type %T) does not implement listing versions", s)
}
versions, err := rs.Versions(c.filters()...)
if err != nil {
return err
}
for _, version := range versions {
if version.Repo != "" {
fmt.Print(version.Repo, "\t")
}
fmt.Println(version.CommitID)
}
return nil
}
type StoreUnitsCmd struct {
Type string `long:"type" `
Name string `long:"name"`
CommitID string `long:"commit"`
Repo string `long:"repo"`
RepoCommitIDs string `long:"repo-commits" description:"comma-separated list of repo@commitID specifiers"`
File string `long:"file" description:"filter by units whose Files list contains this file"`
}
func (c *StoreUnitsCmd) filters() []store.UnitFilter {
var fs []store.UnitFilter
if c.Type != "" && c.Name != "" {
fs = append(fs, store.ByUnits(unit.ID2{Type: c.Type, Name: c.Name}))
}
if (c.Type != "" && c.Name == "") || (c.Type == "" && c.Name != "") {
log.Fatal("must specify either both or neither of --type and --name (to filter by source unit)")
}
if c.CommitID != "" {
fs = append(fs, store.ByCommitIDs(c.CommitID))
}
if c.Repo != "" {
fs = append(fs, store.ByRepos(c.Repo))
}
if c.RepoCommitIDs != "" {
fs = append(fs, makeRepoCommitIDsFilter(c.RepoCommitIDs))
}
if c.File != "" {
fs = append(fs, store.ByFiles(path.Clean(c.File)))
}
return fs
}
var storeUnitsCmd StoreUnitsCmd
func (c *StoreUnitsCmd) Execute(args []string) error {
s, err := OpenStore()
if err != nil {
return err
}
ts, ok := s.(store.TreeStore)
if !ok {
return fmt.Errorf("store (type %T) does not implement listing source units", s)
}
units, err := ts.Units(c.filters()...)
if err != nil {
return err
}
PrintJSON(units, " ")
return nil
}
type StoreDefsCmd struct {
Repo string `long:"repo"`
Path string `long:"path"`
UnitType string `long:"unit-type" `
Unit string `long:"unit"`
File string `long:"file"`
CommitID string `long:"commit"`
RepoCommitIDs string `long:"repo-commits" description:"comma-separated list of repo@commitID specifiers"`
Query string `long:"query"`
Limit int `short:"n" long:"limit" description:"max results to return (0 for all)"`
Offset int `long:"offset" description:"results offset (0 to start with first results)"`
// If Filter is non-nil, it is applied along with the above
// filters.
Filter store.DefFilter
}
func (c *StoreDefsCmd) filters() []store.DefFilter {
var fs []store.DefFilter
if c.UnitType != "" && c.Unit != "" {
fs = append(fs, store.ByUnits(unit.ID2{Type: c.UnitType, Name: c.Unit}))
}
if (c.UnitType != "" && c.Unit == "") || (c.UnitType == "" && c.Unit != "") {
log.Fatal("must specify either both or neither of --unit-type and --unit (to filter by source unit)")
}
if c.CommitID != "" {
fs = append(fs, store.ByCommitIDs(c.CommitID))
}
if c.Repo != "" {
fs = append(fs, store.ByRepos(c.Repo))
}
if c.RepoCommitIDs != "" {
fs = append(fs, makeRepoCommitIDsFilter(c.RepoCommitIDs))
}
if c.Path != "" {
fs = append(fs, store.ByDefPath(c.Path))
}
if c.File != "" {
fs = append(fs, store.ByFiles(path.Clean(c.File)))
}
if c.Query != "" {
fs = append(fs, store.ByDefQuery(c.Query))
}
if c.Filter != nil {
fs = append(fs, c.Filter)
}
if c.Limit != 0 || c.Offset != 0 {
fs = append(fs, store.Limit(c.Limit, c.Offset))
}
return fs
}
var storeDefsCmd StoreDefsCmd
func (c *StoreDefsCmd) Execute(args []string) error {
defs, err := c.Get()
if err != nil {
return err
}
PrintJSON(defs, " ")
return nil
}
func (c *StoreDefsCmd) Get() ([]*graph.Def, error) {
s, err := OpenStore()
if err != nil {
return nil, err
}
us, ok := s.(store.UnitStore)
if !ok {
return nil, fmt.Errorf("store (type %T) does not implement listing defs", s)
}
defs, err := us.Defs(c.filters()...)
if err != nil {
return nil, err
}
return defs, nil
}
type StoreRefsCmd struct {
Repo string `long:"repo"`
UnitType string `long:"unit-type" `
Unit string `long:"unit"`
File string `long:"file"`
CommitID string `long:"commit"`
RepoCommitIDs string `long:"repo-commits" description:"comma-separated list of repo@commitID specifiers"`
Start uint32 `long:"start"`
End uint32 `long:"end"`
DefRepo string `long:"def-repo"`