-
Notifications
You must be signed in to change notification settings - Fork 28
/
main.go
1313 lines (1123 loc) · 29 KB
/
main.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 main
import (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"text/tabwriter"
homedir "github.com/mitchellh/go-homedir"
cli "github.com/urfave/cli"
rw "github.com/whyrusleeping/gx-go/rewrite"
gx "github.com/whyrusleeping/gx/gxutil"
. "github.com/whyrusleeping/stump"
)
var vendorDir = filepath.Join("vendor", "gx", "ipfs")
var cwd string
// for go packages, extra info
type GoInfo struct {
DvcsImport string `json:"dvcsimport,omitempty"`
// GoVersion sets a compiler version requirement, users will be warned if installing
// a package using an unsupported compiler
GoVersion string `json:"goversion,omitempty"`
}
type Package struct {
gx.PackageBase
Gx GoInfo `json:"gx,omitempty"`
}
func LoadPackageFile(name string) (*Package, error) {
fi, err := os.Open(name)
if err != nil {
return nil, err
}
var pkg Package
err = json.NewDecoder(fi).Decode(&pkg)
if err != nil {
return nil, err
}
return &pkg, nil
}
func main() {
app := cli.NewApp()
app.Name = "gx-go"
app.Author = "whyrusleeping"
app.Usage = "gx extensions for golang"
app.Version = "1.9.0"
app.Flags = []cli.Flag{
cli.BoolFlag{
Name: "verbose",
Usage: "turn on verbose output",
},
}
app.Before = func(c *cli.Context) error {
Verbose = c.Bool("verbose")
return nil
}
mcwd, err := os.Getwd()
if err != nil {
Fatal("failed to get cwd:", err)
}
lcwd, err := filepath.EvalSymlinks(mcwd)
if err != nil {
Fatal("failed to resolve symlinks of cdw:", err)
}
cwd = lcwd
app.Commands = []cli.Command{
DepMapCommand,
HookCommand,
ImportCommand,
PathCommand,
RewriteCommand,
rewriteUndoAlias,
UpdateCommand,
DvcsDepsCommand,
LinkCommand,
LockGenCommand,
DevCopyCommand,
// Go tool compat:
GetCommand,
}
if err := app.Run(os.Args); err != nil {
Fatal("Error: " + err.Error())
}
}
var DepMapCommand = cli.Command{
Name: "dep-map",
Usage: "prints out a json dep map for usage by 'import --map'",
Action: func(c *cli.Context) error {
pkg, err := LoadPackageFile(gx.PkgFileName)
if err != nil {
return err
}
m := make(map[string]string)
err = buildMap(pkg, m)
if err != nil {
return err
}
out, err := json.MarshalIndent(m, "", " ")
if err != nil {
return err
}
os.Stdout.Write(out)
return nil
},
}
var LockGenCommand = cli.Command{
Name: "lock-gen",
Usage: "Generate a lock file",
Flags: []cli.Flag{
cli.BoolFlag{
Name: "ignore-conflicts",
Usage: "Does not error on conflicting import in sub-packages",
},
},
Action: func(c *cli.Context) error {
ignoreConflict := c.Bool("ignore-conflicts")
pkg, err := LoadPackageFile(gx.PkgFileName)
if err != nil {
return err
}
done := make(map[string]bool)
lockFile := gx.LockFile{
LockVersion: gx.LockVersion,
}
lockFile.Language = pkg.Language
lockFile.Deps = make(map[string]map[string]gx.Lock)
lockFile.Deps[pkg.Language] = make(map[string]gx.Lock)
if err := genLockDeps(pkg, lockFile.Deps[pkg.Language], done, ignoreConflict); err != nil {
return err
}
m, err := json.MarshalIndent(lockFile, "", " ")
if err != nil {
return err
}
_, err = os.Stdout.Write(m)
return err
},
}
var HookCommand = cli.Command{
Name: "hook",
Usage: "go specific hooks to be called by the gx tool",
Subcommands: []cli.Command{
postImportCommand,
reqCheckCommand,
installLocHookCommand,
postInitHookCommand,
postUpdateHookCommand,
postInstallHookCommand,
preTestHookCommand,
postTestHookCommand,
testHookCommand,
},
Action: func(c *cli.Context) error { return nil },
}
var ImportCommand = cli.Command{
Name: "import",
Usage: "import a go package and all its depencies into gx",
Description: `imports a given go package and all of its dependencies into gx
producing a package.json for each, and outputting a package hash
for each.`,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "rewrite",
Usage: "rewrite import paths to use vendored packages",
},
cli.BoolFlag{
Name: "yesall",
Usage: "assume defaults for all options",
},
cli.BoolFlag{
Name: "tmpdir",
Usage: "create and use a temporary directory for the GOPATH",
},
cli.StringFlag{
Name: "map",
Usage: "json document mapping imports to prexisting hashes",
},
},
Action: func(c *cli.Context) error {
var mapping map[string]string
preset := c.String("map")
if preset != "" {
err := loadMap(&mapping, preset)
if err != nil {
return err
}
}
var gopath string
if c.Bool("tmpdir") {
dir, err := ioutil.TempDir("", "gx-go-import")
if err != nil {
return fmt.Errorf("creating temp dir: %s", err)
}
err = os.Setenv("GOPATH", dir)
if err != nil {
return fmt.Errorf("setting GOPATH: %s", err)
}
Log("setting GOPATH to", dir)
gopath = dir
} else {
gp, err := getGoPath()
if err != nil {
return fmt.Errorf("couldnt determine gopath: %s", err)
}
gopath = gp
}
importer, err := NewImporter(c.Bool("rewrite"), gopath, mapping)
if err != nil {
return err
}
importer.yesall = c.Bool("yesall")
if !c.Args().Present() {
return fmt.Errorf("must specify a package name")
}
pkg := c.Args().First()
Log("vendoring package %s", pkg)
_, err = importer.GxPublishGoPackage(pkg)
if err != nil {
return err
}
return nil
},
}
var UpdateCommand = cli.Command{
Name: "update",
Usage: "update a packages imports to a new path",
ArgsUsage: "[old import] [new import]",
Action: func(c *cli.Context) error {
if len(c.Args()) < 2 {
return fmt.Errorf("must specify current and new import names")
}
oldimp := c.Args()[0]
newimp := c.Args()[1]
err := doUpdate(cwd, oldimp, newimp)
if err != nil {
return err
}
return nil
},
}
var rewriteUndoAlias = cli.Command{
Name: "uw",
Action: func(c *cli.Context) error {
return fullRewrite(true)
},
}
var RewriteCommand = cli.Command{
Name: "rewrite",
Usage: "temporary hack to evade causality",
ArgsUsage: "[optional package name]",
Aliases: []string{"rw"},
Flags: []cli.Flag{
cli.BoolFlag{
Name: "undo",
Usage: "rewrite import paths back to dvcs",
},
cli.BoolFlag{
Name: "dry-run",
Usage: "print out mapping without touching files",
},
cli.StringFlag{
Name: "pkgdir",
Usage: "alternative location of the package directory",
},
cli.BoolFlag{
Name: "fix",
Usage: "more error tolerant version of '--undo'",
},
},
Action: func(c *cli.Context) error {
root, err := gx.GetPackageRoot()
if err != nil {
return err
}
if c.Bool("fix") {
return fixImports(root)
}
pkg, err := LoadPackageFile(filepath.Join(root, gx.PkgFileName))
if err != nil {
return err
}
pkgdir := filepath.Join(root, vendorDir)
if pdopt := c.String("pkgdir"); pdopt != "" {
pkgdir = pdopt
}
VLog(" - building rewrite mapping")
mapping := make(map[string]string)
if !c.Args().Present() {
err = buildRewriteMapping(pkg, pkgdir, mapping, c.Bool("undo"))
if err != nil {
return fmt.Errorf("build of rewrite mapping failed:\n%s", err)
}
} else {
for _, arg := range c.Args() {
dep := pkg.FindDep(arg)
if dep == nil {
return fmt.Errorf("%s not found", arg)
}
pkg, err := loadDep(dep, pkgdir)
if err != nil {
return err
}
addRewriteForDep(dep, pkg, mapping, c.Bool("undo"), true)
}
}
VLog(" - rewrite mapping complete")
if c.Bool("dry-run") {
tabPrintSortedMap(nil, mapping)
return nil
}
err = doRewrite(pkg, root, mapping)
if err != nil {
return err
}
return nil
},
}
var DvcsDepsCommand = cli.Command{
Name: "dvcs-deps",
Usage: "display all dvcs deps",
Action: func(c *cli.Context) error {
i, err := NewImporter(false, os.Getenv("GOPATH"), nil)
if err != nil {
return err
}
relp, err := getImportPath(cwd)
if err != nil {
return err
}
deps, err := i.DepsToVendorForPackage(relp)
if err != nil {
return err
}
sort.Strings(deps)
for _, d := range deps {
fmt.Println(d)
}
return nil
},
}
func getImportPath(pkgpath string) (string, error) {
pkg, err := LoadPackageFile(filepath.Join(pkgpath, gx.PkgFileName))
if err != nil {
return "", err
}
return pkg.Gx.DvcsImport, nil
}
var PathCommand = cli.Command{
Name: "path",
Usage: "prints the import path of the current package within GOPATH",
Action: func(c *cli.Context) error {
rel, err := getImportPath(cwd)
if err != nil {
return err
}
fmt.Println(rel)
return nil
},
}
func goGetPackage(path string) error {
cmd := exec.Command("go", "get", "-d", path)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Run()
return nil
}
func gxGetPackage(hash string) error {
srcdir, err := gx.InstallPath("go", "", true)
if err != nil {
return err
}
gxdir := filepath.Join(srcdir, "gx", "ipfs", hash)
gxget := exec.Command("gx", "get", hash, "-o", gxdir)
gxget.Stdout = os.Stderr
gxget.Stderr = os.Stderr
if err = gxget.Run(); err != nil {
return fmt.Errorf("error during gx get: %s", err)
}
return nil
}
func fixImports(path string) error {
fixmap := make(map[string]string)
gopath := os.Getenv("GOPATH")
rwf := func(imp string) string {
if strings.HasPrefix(imp, "gx/ipfs/") {
parts := strings.Split(imp, "/")
canon := strings.Join(parts[:4], "/")
rest := strings.Join(parts[4:], "/")
if rest != "" {
rest = "/" + rest
}
if base, ok := fixmap[canon]; ok {
return base + rest
}
var pkg Package
err := gx.FindPackageInDir(&pkg, filepath.Join(gopath, "src", canon))
if err != nil {
hash := parts[2]
err = gxGetPackage(hash)
if err != nil {
VLog(err)
return imp
}
err := gx.FindPackageInDir(&pkg, filepath.Join(gopath, "src", canon))
if err != nil {
VLog(err)
return imp
}
}
if pkg.Gx.DvcsImport != "" {
fixmap[imp] = pkg.Gx.DvcsImport
return pkg.Gx.DvcsImport + rest
}
fmt.Printf("Package %s has no dvcs import set!\n", imp)
}
return imp
}
filter := func(s string) bool {
return strings.HasSuffix(s, ".go")
}
return rw.RewriteImports(path, rwf, filter)
}
var GetCommand = cli.Command{
Name: "get",
Usage: "gx-ified `go get`",
Action: func(c *cli.Context) error {
pkgpath := c.Args().First()
if err := goGetPackage(pkgpath); err != nil {
return err
}
gpath, err := getGoPath()
if err != nil {
return err
}
pkgdir := filepath.Join(gpath, "src", pkgpath)
cmd := exec.Command("gx", "install")
cmd.Dir = pkgdir
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return err
}
var pkg Package
if err := gx.LoadPackageFile(&pkg, filepath.Join(pkgdir, "package.json")); err != nil {
return err
}
depsdir := filepath.Join(pkgdir, vendorDir)
rwmapping := make(map[string]string)
if err := buildRewriteMapping(&pkg, depsdir, rwmapping, false); err != nil {
return err
}
if err := doRewrite(&pkg, pkgdir, rwmapping); err != nil {
return err
}
return nil
},
}
func prompt(text, def string) (string, error) {
scan := bufio.NewScanner(os.Stdin)
fmt.Printf("%s (default: '%s') ", text, def)
for scan.Scan() {
if scan.Text() != "" {
return scan.Text(), nil
}
return def, nil
}
return "", scan.Err()
}
func yesNoPrompt(prompt string, def bool) bool {
opts := "[y/N]"
if def {
opts = "[Y/n]"
}
fmt.Printf("%s %s ", prompt, opts)
scan := bufio.NewScanner(os.Stdin)
for scan.Scan() {
val := strings.ToLower(scan.Text())
switch val {
case "":
return def
case "y":
return true
case "n":
return false
default:
fmt.Println("please type 'y' or 'n'")
}
}
panic("unexpected termination of stdin")
}
var postImportCommand = cli.Command{
Name: "post-import",
Usage: "hook called after importing a new go package",
Action: func(c *cli.Context) error {
if !c.Args().Present() {
Fatal("no package specified")
}
dephash := c.Args().First()
pkg, err := LoadPackageFile(gx.PkgFileName)
if err != nil {
return err
}
err = postImportHook(pkg, dephash)
if err != nil {
return err
}
return nil
},
}
var reqCheckCommand = cli.Command{
Name: "req-check",
Usage: "hook called to check if requirements of a package are met",
Action: func(c *cli.Context) error {
if !c.Args().Present() {
Fatal("no package specified")
}
pkgpath := c.Args().First()
err := reqCheckHook(pkgpath)
if err != nil {
return err
}
return nil
},
}
var postInitHookCommand = cli.Command{
Name: "post-init",
Usage: "hook called to perform go specific package initialization",
Action: func(c *cli.Context) error {
var dir string
if c.Args().Present() {
dir = c.Args().First()
} else {
dir = cwd
}
pkgpath := filepath.Join(dir, gx.PkgFileName)
pkg, err := LoadPackageFile(pkgpath)
if err != nil {
return err
}
imp, _ := packagesGoImport(dir)
if imp != "" {
pkg.Gx.DvcsImport = imp
}
err = gx.SavePackageFile(pkg, pkgpath)
if err != nil {
return err
}
return nil
},
}
var postInstallHookCommand = cli.Command{
Name: "post-install",
Usage: "post install hook for newly installed go packages",
Flags: []cli.Flag{
cli.BoolFlag{
Name: "global",
Usage: "specifies whether or not the install was global",
},
cli.StringFlag{
Name: "override-deps",
Usage: "path of a package used to override dependency versions (intended to be used with the link command)",
},
},
Action: func(c *cli.Context) error {
if !c.Args().Present() {
return fmt.Errorf("must specify path to newly installed package")
}
npkg := c.Args().First()
// update sub-package refs here
// ex:
// if this package is 'github.com/X/Y' replace all imports
// matching 'github.com/X/Y*' with 'gx/<hash>/name*'
var pkg Package
err := gx.FindPackageInDir(&pkg, npkg)
if err != nil {
return fmt.Errorf("find package failed: %s", err)
}
dir := filepath.Join(npkg, pkg.Name)
// build rewrite mapping from parent package if
// this call is made on one in the vendor directory
var reldir string
if strings.Contains(npkg, "vendor/gx/ipfs") {
reldir = strings.Split(npkg, "vendor/gx/ipfs")[0]
reldir = filepath.Join(reldir, "vendor", "gx", "ipfs")
} else {
reldir = dir
}
var depsPkg *Package
var depsPkgDir string
if depsPkgDir = c.String("override-deps"); depsPkgDir != "" {
err := gx.FindPackageInDir(&depsPkg, depsPkgDir)
if err != nil {
return fmt.Errorf("find deps package in %s failed : %s", depsPkgDir, err)
}
}
mapping := make(map[string]string)
err = buildRewriteMapping(&pkg, reldir, mapping, false)
if err != nil {
return fmt.Errorf("building rewrite mapping failed for package %s: %s", pkg.Name, err)
}
if depsPkg != nil {
// Use the dependency versions of `depsPkg` in case of a mismatch
// with the versions in `pkg`.
depsRewriteMap := make(map[string]string)
err = buildRewriteMapping(depsPkg, depsPkgDir, depsRewriteMap, false)
if err != nil {
return fmt.Errorf("building rewrite mapping failed for package %s: %s", depsPkg.Name, err)
// TODO: All the dependencies of the deps package need to be fetched. Should we call
// `gx install --global`?
}
// Iterate the `rewriteMap` indexed by the DVCS imports (since `undo`
// is false) and replace them with dependencies found in the
// `depsRewriteMap` if the gx import paths don't match (that is,
// if their versions are different).
var replacedImports []string
for dvcsImport, gxImportPath := range mapping {
depsGxImportPath, exists := depsRewriteMap[dvcsImport]
if exists && gxImportPath != depsGxImportPath {
mapping[dvcsImport] = depsGxImportPath
replacedImports = append(replacedImports, dvcsImport)
}
}
if len(replacedImports) > 0 {
fmt.Printf("Replaced %d entries in the rewrite map:\n", len(replacedImports))
for _, dvcsImport := range replacedImports {
fmt.Printf(" %s\n", dvcsImport)
}
}
// TODO: This should be handled by the `VLog` function.
// (At the moment this is called from `gx-go link` which doesn't
// have access to the global `Verbose` flag to check whether to
// include the `--verbose` argument or not.)
}
hash := filepath.Base(npkg)
newimp := "gx/ipfs/" + hash + "/" + pkg.Name
mapping[pkg.Gx.DvcsImport] = newimp
err = doRewrite(&pkg, dir, mapping)
if err != nil {
return fmt.Errorf("rewrite failed: %s", err)
}
return nil
},
}
func doRewrite(pkg *Package, cwd string, mapping map[string]string) error {
rwm := func(in string) string {
m, ok := mapping[in]
if ok {
return m
}
for k, v := range mapping {
if strings.HasPrefix(in, k+"/") {
nmapping := strings.Replace(in, k, v, 1)
mapping[in] = nmapping
return nmapping
}
}
mapping[in] = in
return in
}
filter := func(s string) bool {
return strings.HasSuffix(s, ".go")
}
VLog(" - rewriting imports")
err := rw.RewriteImports(cwd, rwm, filter)
if err != nil {
return err
}
VLog(" - finished!")
return nil
}
var installLocHookCommand = cli.Command{
Name: "install-path",
Usage: "prints out install path",
Flags: []cli.Flag{
cli.BoolFlag{
Name: "global",
Usage: "print global install directory",
},
},
Action: func(c *cli.Context) error {
if c.Bool("global") {
gpath, err := getGoPath()
if err != nil {
return fmt.Errorf("GOPATH not set")
}
fmt.Println(filepath.Join(gpath, "src"))
return nil
} else {
cwd, err := os.Getwd()
if err != nil {
return fmt.Errorf("install-path cwd: %s", err)
}
fmt.Println(filepath.Join(cwd, "vendor"))
return nil
}
},
}
var postUpdateHookCommand = cli.Command{
Name: "post-update",
Usage: "rewrite go package imports to new versions",
Action: func(c *cli.Context) error {
if len(c.Args()) < 2 {
Fatal("must specify two arguments")
}
before := "gx/ipfs/" + c.Args()[0]
after := "gx/ipfs/" + c.Args()[1]
err := doUpdate(cwd, before, after)
if err != nil {
return err
}
return nil
},
}
var testHookCommand = cli.Command{
Name: "test",
SkipFlagParsing: true,
Action: func(c *cli.Context) error {
args := []string{"test"}
args = append(args, c.Args()...)
cmd := exec.Command("go", args...)
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
return cmd.Run()
},
}
var preTestHookCommand = cli.Command{
Name: "pre-test",
Usage: "",
Action: func(c *cli.Context) error {
return fullRewrite(false)
},
}
var postTestHookCommand = cli.Command{
Name: "post-test",
Usage: "",
Action: func(c *cli.Context) error {
return fullRewrite(true)
},
}
var DevCopyCommand = cli.Command{
Name: "devcopy",
Usage: "Create a development copy of the given package",
Action: func(c *cli.Context) error {
// gx install --local
// gx-go rewrite --undo
// symlink <hash> -> dvcs path
Log("creating local copy of deps")
cmd := exec.Command("gx", "install", "--local")
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
if err := cmd.Run(); err != nil {
return err
}
Log("change imports to dvcs")
cmd = exec.Command("gx-go", "rewrite", "--undo")
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
if err := cmd.Run(); err != nil {
return err
}
pkg, err := LoadPackageFile(gx.PkgFileName)
if err != nil {
return err
}
return devCopySymlinking(filepath.Join(cwd, "vendor"), pkg, make(map[string]bool))
},
}
func genLockDeps(pkg *Package, deps map[string]gx.Lock, done map[string]bool, ignoreConflict bool) error {
for _, dep := range pkg.Dependencies {
if done[dep.Hash] {
continue
}
done[dep.Hash] = true
var cpkg Package
err := gx.LoadPackage(&cpkg, pkg.Language, dep.Hash)
if err != nil {
if os.IsNotExist(err) {
VLog("LoadPackage error: ", err)
return fmt.Errorf("package %s (%s) not found", dep.Name, dep.Hash)
}
return err
}
ref := fmt.Sprintf("/ipfs/%s/%s", dep.Hash, dep.Name)
if d, found := deps[cpkg.Gx.DvcsImport]; found {
if !ignoreConflict && ref != d.Ref {
return fmt.Errorf("Found a duplicate import %s for package %s", cpkg.Gx.DvcsImport, pkg.Name)
}
} else {
deps[cpkg.Gx.DvcsImport] = gx.Lock{
Ref: ref,
}
}
if err := genLockDeps(&cpkg, deps, done, ignoreConflict); err != nil {
return err
}
}
return nil
}
func devCopySymlinking(root string, pkg *Package, done map[string]bool) error {
for _, dep := range pkg.Dependencies {
if done[dep.Hash] {
continue
}
done[dep.Hash] = true
var cpkg Package
err := gx.LoadPackage(&cpkg, pkg.Language, dep.Hash)
if err != nil {
if os.IsNotExist(err) {
VLog("LoadPackage error: ", err)
return fmt.Errorf("package %s (%s) not found", dep.Name, dep.Hash)
}
return err
}
frompath := filepath.Join(root, "gx", "ipfs", dep.Hash, dep.Name)
cmd := exec.Command("gx-go", "rewrite", "--undo")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = frompath
if err := cmd.Run(); err != nil {
return err
}
topath := filepath.Join(root, cpkg.Gx.DvcsImport)
dir := filepath.Dir(topath)
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
if err := os.Symlink(frompath, topath); err != nil {
return err
}
if err := devCopySymlinking(root, &cpkg, done); err != nil {
return err
}
}
return nil
}
func fullRewrite(undo bool) error {
root, err := gx.GetPackageRoot()
if err != nil {
return err
}
pkg, err := LoadPackageFile(filepath.Join(root, gx.PkgFileName))
if err != nil {
return err
}
pkgdir := filepath.Join(root, vendorDir)
mapping := make(map[string]string)
err = buildRewriteMapping(pkg, pkgdir, mapping, undo)
if err != nil {
return fmt.Errorf("build of rewrite mapping failed:\n%s", err)