forked from perkeep/perkeep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
make.go
1212 lines (1102 loc) · 34.2 KB
/
make.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
// +build ignore
/*
Copyright 2013 The Perkeep Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// This program builds Perkeep.
//
// $ go run make.go
//
// See the BUILDING file.
//
// The output binaries go into the ./bin/ directory (under the
// Perkeep root, where make.go is)
package main
import (
"archive/zip"
"bytes"
"crypto/sha256"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
pathpkg "path"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"time"
)
var haveSQLite = checkHaveSQLite()
var (
embedResources = flag.Bool("embed_static", true, "Whether to embed resources needed by the UI such as images, css, and javascript.")
sqlFlag = flag.String("sqlite", "false", "Whether you want SQLite in your build: true, false, or auto.")
race = flag.Bool("race", false, "Build race-detector version of binaries (they will run slowly)")
verbose = flag.Bool("v", strings.Contains(os.Getenv("CAMLI_DEBUG_X"), "makego"), "Verbose mode")
targets = flag.String("targets", "", "Optional comma-separated list of targets (i.e go packages) to build and install. '*' builds everything. Empty builds defaults for this platform. Example: perkeep.org/server/perkeepd,perkeep.org/cmd/pk-put")
quiet = flag.Bool("quiet", false, "Don't print anything unless there's a failure.")
buildARCH = flag.String("arch", runtime.GOARCH, "Architecture to build for.")
buildOS = flag.String("os", runtime.GOOS, "Operating system to build for.")
buildARM = flag.String("arm", "7", "ARM version to use if building for ARM. Note that this version applies even if the host arch is ARM too (and possibly of a different version).")
stampVersion = flag.Bool("stampversion", true, "Stamp version into buildinfo.GitInfo")
website = flag.Bool("website", false, "Just build the website.")
camnetdns = flag.Bool("camnetdns", false, "Just build perkeep.org/server/camnetdns.")
static = flag.Bool("static", false, "Build a static binary, so it can run in an empty container.")
buildWebUI = flag.Bool("buildWebUI", false, "Rebuild the JS code of the web UI instead of fetching it from perkeep.org.")
)
var (
// pkRoot is the Perkeep project root
pkRoot string
binDir string // $GOBIN or $GOPATH/bin, based on user setting or default Go value.
// gopherjsGoroot should be specified through the env var
// CAMLI_GOPHERJS_GOROOT when the user's using go tip, because gopherjs only
// builds with Go 1.12.
gopherjsGoroot string
)
func main() {
log.SetFlags(0)
flag.Parse()
if *buildARCH == "386" && *buildOS == "darwin" {
if ok, _ := strconv.ParseBool(os.Getenv("CAMLI_FORCE_OSARCH")); !ok {
log.Fatalf("You're trying to build a 32-bit binary for a Mac. That is almost always a mistake.\nTo do it anyway, set env CAMLI_FORCE_OSARCH=1 and run again.\n")
}
}
if *website && *camnetdns {
log.Fatal("-camnetdns and -website are mutually exclusive")
}
failIfCamlistoreOrgDir()
verifyGoVersion()
verifyPerkeepRoot()
version := getVersion()
gitRev := getGitVersion()
sql := withSQLite()
if *verbose {
log.Printf("Perkeep version = %q, git = %q", version, gitRev)
log.Printf("SQLite included: %v", sql)
log.Printf("Project source: %s", pkRoot)
log.Printf("Output binaries: %s", actualBinDir())
}
buildAll := false
targs := []string{
"perkeep.org/dev/devcam",
"perkeep.org/cmd/pk-get",
"perkeep.org/cmd/pk-put",
"perkeep.org/cmd/pk",
"perkeep.org/cmd/pk-deploy",
"perkeep.org/server/perkeepd",
"perkeep.org/app/hello",
"perkeep.org/app/publisher",
"perkeep.org/app/scanningcabinet",
"perkeep.org/app/scanningcabinet/scancab",
}
switch *targets {
case "*":
buildAll = true
case "":
// Add pk-mount to default build targets on OSes that support FUSE.
switch *buildOS {
case "linux", "darwin":
targs = append(targs, "perkeep.org/cmd/pk-mount")
}
default:
if *website {
log.Fatal("-targets and -website are mutually exclusive")
}
if *camnetdns {
log.Fatal("-targets and -camnetdns are mutually exclusive")
}
if t := strings.Split(*targets, ","); len(t) != 0 {
targs = t
}
}
if *website || *camnetdns {
buildAll = false
if *website {
targs = []string{"perkeep.org/website/pk-web"}
} else if *camnetdns {
targs = []string{"perkeep.org/server/camnetdns"}
}
}
withPerkeepd := stringListContains(targs, "perkeep.org/server/perkeepd")
withPublisher := stringListContains(targs, "perkeep.org/app/publisher")
if err := doUI(withPerkeepd, withPublisher); err != nil {
log.Fatal(err)
}
if *embedResources && withPerkeepd {
doEmbed()
}
tags := []string{"purego"} // for cznic/zappy
if *static {
tags = append(tags, "netgo")
}
if sql {
// used by go-sqlite to use system sqlite libraries
tags = append(tags, "libsqlite3")
// used by perkeep to switch behavior to sqlite for tests
// and some underlying libraries
tags = append(tags, "with_sqlite")
}
if *embedResources {
tags = append(tags, "with_embed")
}
baseArgs := []string{"install", "-v"}
if *race {
baseArgs = append(baseArgs, "-race")
}
if *verbose {
log.Printf("version to stamp is %q, %q", version, gitRev)
}
var ldFlags string
if *static {
ldFlags = "-w -d -linkmode internal"
}
if *stampVersion {
if ldFlags != "" {
ldFlags += " "
}
ldFlags += "-X \"perkeep.org/pkg/buildinfo.GitInfo=" + gitRev + "\""
ldFlags += "-X \"perkeep.org/pkg/buildinfo.Version=" + version + "\""
}
if ldFlags != "" {
baseArgs = append(baseArgs, "--ldflags="+ldFlags)
}
baseArgs = append(baseArgs, "--tags="+strings.Join(tags, " "))
// First install command: build just the final binaries, installed to a GOBIN
// under <perkeep_root>/bin:
args := append(baseArgs, targs...)
if buildAll {
args = append(args,
"perkeep.org/app/...",
"perkeep.org/pkg/...",
"perkeep.org/server/...",
"perkeep.org/internal/...",
)
}
cmd := exec.Command("go", args...)
cmd.Env = cleanGoEnv()
if *static {
cmd.Env = append(cmd.Env, "CGO_ENABLED=0")
}
if *verbose {
log.Printf("Running go %q with Env %q", args, cmd.Env)
}
var output bytes.Buffer
if *quiet {
cmd.Stdout = &output
cmd.Stderr = &output
} else {
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
}
if *verbose {
log.Printf("Running go install of main binaries with args %s", cmd.Args)
}
if err := cmd.Run(); err != nil {
log.Fatalf("Error building main binaries: %v\n%s", err, output.String())
}
if !*quiet {
log.Printf("Success. Binaries are in %s", actualBinDir())
}
}
func actualBinDir() string {
cmd := exec.Command("go", "list", "-f", "{{.Target}}", "perkeep.org/cmd/pk")
cmd.Env = cleanGoEnv()
cmd.Stderr = os.Stderr
out, err := cmd.Output()
if err != nil {
log.Fatalf("Could not run go list to guess install dir: %v, %v", err, out)
}
return filepath.Dir(strings.TrimSpace(string(out)))
}
func baseDirName(sql bool) string {
buildBaseDir := "build-gopath"
if !sql {
buildBaseDir += "-nosqlite"
}
// We don't even consider whether we're cross-compiling. As long as we
// build for ARM, we do it in its own versioned dir.
if *buildARCH == "arm" {
buildBaseDir += "-armv" + *buildARM
}
return buildBaseDir
}
const (
publisherJS = "app/publisher/publisher.js"
gopherjsUI = "server/perkeepd/ui/goui.js"
gopherjsUIURL = "https://storage.googleapis.com/perkeep-release/gopherjs/goui.js"
publisherJSURL = "https://storage.googleapis.com/perkeep-release/gopherjs/publisher.js"
)
func buildGopherjs() error {
// if gopherjs binary already exists, record its modtime, so we can reset it later.
// See explanation below.
outBin := hostExeName(filepath.Join(binDir, "gopherjs"))
fi, err := os.Stat(outBin)
if err != nil && !os.IsNotExist(err) {
return err
}
modtime := time.Now()
var hashBefore string
if err == nil {
modtime = fi.ModTime()
hashBefore = hashsum(outBin)
}
goBin := "go"
if gopherjsGoroot != "" {
goBin = hostExeName(filepath.Join(gopherjsGoroot, "bin", "go"))
}
src := filepath.Join(pkRoot, filepath.FromSlash("vendor/github.com/gopherjs/gopherjs"))
cmd := exec.Command(goBin, "install", "-v")
cmd.Dir = src
cmd.Env = os.Environ()
// forcing GOOS and GOARCH to prevent cross-compiling, as gopherjs will run on the
// current (host) platform.
cmd.Env = append(cmd.Env, "GOOS="+runtime.GOOS)
cmd.Env = append(cmd.Env, "GOARCH="+runtime.GOARCH)
if gopherjsGoroot != "" {
cmd.Env = append(cmd.Env, "GOROOT="+gopherjsGoroot)
}
cmd.Env = append(cmd.Env, "GO111MODULE=off")
var buf bytes.Buffer
cmd.Stderr = &buf
if err := cmd.Run(); err != nil {
return fmt.Errorf("error while building gopherjs: %v, %v", err, buf.String())
}
if *verbose {
fmt.Println(buf.String())
}
hashAfter := hashsum(outBin)
if hashAfter != hashBefore {
log.Printf("gopherjs rebuilt at %v", outBin)
return nil
}
// even if the source hasn't changed, apparently goinstall still at least bumps
// the modtime. Which means, 'gopherjs install' would then always rebuild its
// output too, even if no source changed since last time. We want to avoid that
// (because then parts of Perkeep get unnecessarily rebuilt too and yada yada), so
// we reset the modtime of gopherjs if the binary is the same as the previous time
// it was built.
return os.Chtimes(outBin, modtime, modtime)
}
func hashsum(filename string) string {
h := sha256.New()
f, err := os.Open(filename)
if err != nil {
log.Fatalf("could not compute SHA256 of %v: %v", filename, err)
}
defer f.Close()
if _, err := io.Copy(h, f); err != nil {
log.Fatalf("could not compute SHA256 of %v: %v", filename, err)
}
return string(h.Sum(nil))
}
// genSearchTypes duplicates some of the perkeep.org/pkg/search types into
// perkeep.org/app/publisher/js/zsearch.go , because it's too costly (in output
// file size) for now to import the search pkg into gopherjs.
func genSearchTypes() error {
sourceFile := filepath.Join(pkRoot, filepath.FromSlash("pkg/search/describe.go"))
outputFile := filepath.Join(pkRoot, filepath.FromSlash("app/publisher/js/zsearch.go"))
fi1, err := os.Stat(sourceFile)
if err != nil {
return err
}
fi2, err := os.Stat(outputFile)
if err != nil && !os.IsNotExist(err) {
return err
}
if err == nil && fi2.ModTime().After(fi1.ModTime()) {
return nil
}
cmd := exec.Command("go", "generate", "-tags=js", "-v", "perkeep.org/app/publisher/js")
if out, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("go generate for publisher js error: %v, %v", err, string(out))
}
log.Printf("generated %v", outputFile)
return nil
}
func genPublisherJS() error {
if err := genSearchTypes(); err != nil {
return err
}
output := filepath.Join(pkRoot, filepath.FromSlash(publisherJS))
pkg := "perkeep.org/app/publisher/js"
return genJS(pkg, output)
}
func genWebUIJS() error {
output := filepath.Join(pkRoot, filepath.FromSlash(gopherjsUI))
pkg := "perkeep.org/server/perkeepd/ui/goui"
return genJS(pkg, output)
}
func goPathBinDir() (string, error) {
cmd := exec.Command("go", "env", "GOPATH")
out, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("could not get GOPATH: %v, %s", err, out)
}
paths := filepath.SplitList(strings.TrimSpace(string(out)))
if len(paths) < 1 {
return "", errors.New("no GOPATH")
}
return filepath.Join(paths[0], "bin"), nil
}
func genJS(pkg, output string) error {
// We want to use 'gopherjs install', and not 'gopherjs build', as the former is
// smarter and only rebuilds the output if needed. However, 'install' writes the
// output to GOPATH/bin, and not GOBIN. (https://github.com/gopherjs/gopherjs/issues/494)
// This means we have to be somewhat careful with naming our source pkg since gopherjs
// derives its output name from it.
// TODO(mpl): maybe rename the source pkg directories mentioned above.
if err := runGopherJS(pkg); err != nil {
return err
}
// TODO(mpl): set GOBIN, and remove all below, once
// https://github.com/gopherjs/gopherjs/issues/494 is fixed
binDir, err := goPathBinDir()
if err != nil {
return err
}
jsout := filepath.Join(binDir, filepath.Base(pkg)+".js")
fi1, err1 := os.Stat(output)
if err1 != nil && !os.IsNotExist(err1) {
return err1
}
fi2, err2 := os.Stat(jsout)
if err2 != nil && !os.IsNotExist(err2) {
return err2
}
if err1 == nil && fi1.ModTime().After(fi2.ModTime()) {
// output exists and is already up to date, nothing to do
return nil
}
data, err := ioutil.ReadFile(jsout)
if err != nil {
return err
}
return ioutil.WriteFile(output, data, 0600)
}
func runGopherJS(pkg string) error {
gopherjsBin := hostExeName(filepath.Join(binDir, "gopherjs"))
args := []string{"install", pkg, "-v", "--tags", "nocgo noReactBundle"}
if *embedResources {
// when embedding for "production", use -m to minify the javascript output
args = append(args, "-m")
}
cmd := exec.Command(gopherjsBin, args...)
cmd.Env = os.Environ()
// Pretend we're on linux regardless of the actual host, because recommended
// hack to work around https://github.com/gopherjs/gopherjs/issues/511
cmd.Env = append(cmd.Env, "GOOS=linux")
if gopherjsGoroot != "" {
cmd.Env = append(cmd.Env, "GOROOT="+gopherjsGoroot)
}
cmd.Env = append(cmd.Env, "GO111MODULE=off")
var buf bytes.Buffer
cmd.Stderr = &buf
err := cmd.Run()
if err != nil {
return fmt.Errorf("gopherjs for %v error: %v, %v", pkg, err, buf.String())
}
if *verbose {
fmt.Println(buf.String())
}
return nil
}
// genWebUIReact runs go generate on the gopherjs code of the web UI, which
// invokes reactGen on the Go React components. This generates the boilerplate
// code, in gen_*_reactGen.go files, required to complete those components.
func genWebUIReact() error {
args := []string{"generate", "-v", "perkeep.org/server/perkeepd/ui/goui/..."}
path := strings.Join([]string{
binDir,
os.Getenv("PATH"),
}, string(os.PathListSeparator))
cmd := exec.Command("go", args...)
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, "PATH="+path)
var buf bytes.Buffer
cmd.Stderr = &buf
cmd.Env = append(os.Environ(), "GO111MODULE=off")
err := cmd.Run()
if err != nil {
return fmt.Errorf("go generate for web UI error: %v, %v", err, buf.String())
}
if *verbose {
fmt.Println(buf.String())
}
return nil
}
// makeJS builds and runs the gopherjs command on perkeep.org/app/publisher/js
// and perkeep.org/server/perkeepd/ui/goui
func makeJS(doWebUI, doPublisher bool) error {
if err := buildGopherjs(); err != nil {
return fmt.Errorf("error building gopherjs: %v", err)
}
if doPublisher {
if err := genPublisherJS(); err != nil {
return err
}
}
if doWebUI {
if err := genWebUIJS(); err != nil {
return err
}
}
return nil
}
func fetchAllJS(doWebUI, doPublisher bool) error {
if doPublisher {
if err := fetchJS(publisherJSURL, filepath.FromSlash(publisherJS)); err != nil {
return err
}
}
if doWebUI {
if err := fetchJS(gopherjsUIURL, filepath.FromSlash(gopherjsUI)); err != nil {
return err
}
}
return nil
}
// fetchJS gets the javascript resource at jsURL and writes it to jsOnDisk.
// Since said resource can be quite large, it first fetches the hashsum contained
// in the file at jsURL+".sha256", and if we already have the file on disk, with a
// matching hashsum, it does not actually fetch jsURL. If it does, it checks that
// the newly written file does match the hashsum.
func fetchJS(jsURL, jsOnDisk string) error {
var currentSum string
_, err := os.Stat(jsOnDisk)
if err != nil {
if !os.IsNotExist(err) {
return err
}
} else {
// If yes, compute its hash
h := sha256.New()
f, err := os.Open(jsOnDisk)
if err != nil {
return err
}
defer f.Close()
if _, err := io.Copy(h, f); err != nil {
return err
}
currentSum = fmt.Sprintf("%x", h.Sum(nil))
}
// fetch the hash of the remote
resp, err := http.Get(jsURL + ".sha256")
if err != nil {
return err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
upstreamSum := strings.TrimSuffix(string(data), "\n")
if currentSum != "" &&
currentSum == upstreamSum {
// We already have the latest version
return nil
}
resp, err = http.Get(jsURL)
if err != nil {
return err
}
defer resp.Body.Close()
js := filepath.Join(pkRoot, filepath.FromSlash(jsOnDisk))
f, err := os.Create(js)
if err != nil {
return err
}
h := sha256.New()
mr := io.MultiWriter(f, h)
if _, err := io.Copy(mr, resp.Body); err != nil {
f.Close()
return err
}
if err := f.Close(); err != nil {
return err
}
sum := fmt.Sprintf("%x", h.Sum(nil))
if upstreamSum != sum {
return fmt.Errorf("checksum mismatch for %q: got %q, want %q", jsURL, sum, upstreamSum)
}
return nil
}
func doUI(withPerkeepd, withPublisher bool) error {
if !withPerkeepd && !withPublisher {
return nil
}
if !*buildWebUI {
return fetchAllJS(withPerkeepd, withPublisher)
}
if os.Getenv("GO111MODULE") != "off" {
fmt.Println("Cannot rebuild web UI with go modules enabled, as it is not supported by GopherJS. Now rebuilding with GO111MODULE=off.")
}
if err := buildReactGen(); err != nil {
return err
}
if withPerkeepd {
if err := genWebUIReact(); err != nil {
return err
}
}
// gopherjs has to run before doEmbed since we need all the javascript
// to be generated before embedding happens.
return makeJS(withPerkeepd, withPublisher)
}
// Create an environment variable of the form key=value.
func envPair(key, value string) string {
return fmt.Sprintf("%s=%s", key, value)
}
// TODO(mpl): we probably can get rid of cleanGoEnv now that "last in wins" for
// duplicates in Env.
// cleanGoEnv returns a copy of the current environment with any variable listed
// in others removed. Also, when cross-compiling, it removes GOBIN and sets GOOS
// and GOARCH, and GOARM as needed.
func cleanGoEnv(others ...string) (clean []string) {
excl := make([]string, len(others))
for i, v := range others {
excl[i] = v + "="
}
Env:
for _, env := range os.Environ() {
for _, v := range excl {
if strings.HasPrefix(env, v) {
continue Env
}
}
// remove GOBIN if we're cross-compiling
if strings.HasPrefix(env, "GOBIN=") &&
(*buildOS != runtime.GOOS || *buildARCH != runtime.GOARCH) {
continue
}
// We skip these two as well, otherwise they'd take precedence over the
// ones appended below.
if *buildOS != runtime.GOOS && strings.HasPrefix(env, "GOOS=") {
continue
}
if *buildARCH != runtime.GOARCH && strings.HasPrefix(env, "GOARCH=") {
continue
}
// If we're building for ARM (regardless of cross-compiling or not), we reset GOARM
if *buildARCH == "arm" && strings.HasPrefix(env, "GOARM=") {
continue
}
clean = append(clean, env)
}
if *buildOS != runtime.GOOS {
clean = append(clean, envPair("GOOS", *buildOS))
}
if *buildARCH != runtime.GOARCH {
clean = append(clean, envPair("GOARCH", *buildARCH))
}
// If we're building for ARM (regardless of cross-compiling or not), we reset GOARM
if *buildARCH == "arm" {
clean = append(clean, envPair("GOARM", *buildARM))
}
return
}
func stringListContains(strs []string, str string) bool {
for _, s := range strs {
if s == str {
return true
}
}
return false
}
// fullSrcPath returns the full path concatenation
// of pkRoot with fromSrc.
func fullSrcPath(fromSrc string) string {
return filepath.Join(pkRoot, filepath.FromSlash(fromSrc))
}
func genEmbeds() error {
cmdName := hostExeName(filepath.Join(binDir, "genfileembed"))
for _, embeds := range []string{
"server/perkeepd/ui",
"pkg/server",
"clients/web/embed/fontawesome",
"clients/web/embed/keepy",
"clients/web/embed/leaflet",
"clients/web/embed/less",
"clients/web/embed/opensans",
"clients/web/embed/react",
"app/publisher",
"app/scanningcabinet/ui",
} {
embeds := fullSrcPath(embeds)
args := []string{"-build-tags=with_embed"}
args = append(args, embeds)
cmd := exec.Command(cmdName, args...)
cmd.Stdout = os.Stdout
var buf bytes.Buffer
cmd.Stderr = &buf
if *verbose {
log.Printf("Running %s %s", cmdName, embeds)
}
if err := cmd.Run(); err != nil {
os.Stderr.Write(buf.Bytes())
return fmt.Errorf("error running %s %s: %v", cmdName, embeds, err)
}
if *verbose {
fmt.Println(buf.String())
}
}
return nil
}
func buildGenfileembed() error {
return buildBin("perkeep.org/pkg/fileembed/genfileembed", false)
}
func buildReactGen() error {
return buildBin("perkeep.org/vendor/myitcv.io/react/cmd/reactGen", true)
}
func buildDevcam() error {
return buildBin("perkeep.org/dev/devcam", false)
}
func buildBin(pkg string, forceModulesOff bool) error {
pkgBase := pathpkg.Base(pkg)
args := []string{"install", "-v"}
args = append(args,
filepath.FromSlash(pkg),
)
cmd := exec.Command("go", args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if *verbose {
log.Printf("Running go with args %s", args)
}
if forceModulesOff {
cmd.Env = append(os.Environ(), "GO111MODULE=off")
}
if err := cmd.Run(); err != nil {
return fmt.Errorf("Error building %v: %v", pkgBase, err)
}
if *verbose {
log.Printf("%v installed in %s", pkgBase, actualBinDir())
}
return nil
}
// getVersion returns the version of Perkeep found in a VERSION file at the root.
func getVersion() string {
slurp, err := ioutil.ReadFile(filepath.Join(pkRoot, "VERSION"))
v := strings.TrimSpace(string(slurp))
if err != nil && !os.IsNotExist(err) {
log.Fatal(err)
}
if v == "" {
return "unknown"
}
return v
}
var gitVersionRx = regexp.MustCompile(`\b\d\d\d\d-\d\d-\d\d-[0-9a-f]{10,10}\b`)
// getGitVersion returns the git version of the git repo at pkRoot as a
// string of the form "yyyy-mm-dd-xxxxxxx", with an optional trailing
// '+' if there are any local uncommitted modifications to the tree.
func getGitVersion() string {
if _, err := exec.LookPath("git"); err != nil {
return ""
}
if _, err := os.Stat(filepath.Join(pkRoot, ".git")); os.IsNotExist(err) {
return ""
}
cmd := exec.Command("git", "rev-list", "--max-count=1", "--pretty=format:'%ad-%h'",
"--date=short", "--abbrev=10", "HEAD")
cmd.Dir = pkRoot
out, err := cmd.Output()
if err != nil {
log.Fatalf("Error running git rev-list in %s: %v", pkRoot, err)
}
v := strings.TrimSpace(string(out))
if m := gitVersionRx.FindStringSubmatch(v); m != nil {
v = m[0]
} else {
panic("Failed to find git version in " + v)
}
cmd = exec.Command("git", "diff", "--exit-code")
cmd.Dir = pkRoot
if err := cmd.Run(); err != nil {
v += "+"
}
return v
}
// verifyPerkeepRoot sets pkRoot and crashes if dir isn't the Perkeep root directory.
func verifyPerkeepRoot() {
var err error
pkRoot, err = os.Getwd()
if err != nil {
log.Fatalf("Failed to get current directory: %v", err)
}
testFile := filepath.Join(pkRoot, "pkg", "blob", "ref.go")
if _, err := os.Stat(testFile); err != nil {
log.Fatalf("make.go must be run from the Perkeep src root directory (where make.go is). Current working directory is %s", pkRoot)
}
// we can't rely on perkeep.org/cmd/pk with modules on as we have no assurance
// the current dir is $GOPATH/src/perkeep.org, so we use ./cmd/pk instead.
cmd := exec.Command("go", "list", "-f", "{{.Target}}", "./cmd/pk")
if os.Getenv("GO111MODULE") == "off" || *buildWebUI {
// if we're building the webUI we need to be in "legacy" GOPATH mode, so in
// $GOPATH/src/perkeep.org
if err := validateDirInGOPATH(pkRoot); err != nil {
log.Fatalf("We're running in GO111MODULE=off mode, either because you set it, or because you want to build the Web UI, so we need to be in a GOPATH, but: %v", err)
}
cmd = exec.Command("go", "list", "-f", "{{.Target}}", "perkeep.org/cmd/pk")
}
cmd.Stderr = os.Stderr
out, err := cmd.Output()
if err != nil {
log.Fatalf("Could not run go list to find install dir: %v, %s", err, out)
}
binDir = filepath.Dir(strings.TrimSpace(string(out)))
}
func validateDirInGOPATH(dir string) error {
fi, err := os.Lstat(dir)
if err != nil {
return err
}
gopathEnv, err := exec.Command("go", "env", "GOPATH").Output()
if err != nil {
return fmt.Errorf("error finding GOPATH: %v", err)
}
gopaths := filepath.SplitList(strings.TrimSpace(string(gopathEnv)))
if len(gopaths) == 0 {
return fmt.Errorf("failed to find your GOPATH: go env GOPATH returned nothing")
}
var validOpts []string
for _, gopath := range gopaths {
validDir := filepath.Join(gopath, "src", "perkeep.org")
validOpts = append(validOpts, validDir)
fi2, err := os.Lstat(validDir)
if os.IsNotExist(err) {
continue
}
if err != nil {
return err
}
if os.SameFile(fi, fi2) {
// In a valid directory.
return nil
}
}
if len(validOpts) == 1 {
return fmt.Errorf("make.go cannot be run from %s; it must be in a valid GOPATH. Move the directory containing make.go to %s", dir, validOpts[0])
} else {
return fmt.Errorf("make.go cannot be run from %s; it must be in a valid GOPATH. Move the directory containing make.go to one of %q", dir, validOpts)
}
}
const (
goVersionMinor = 13
gopherJSGoMinor = 12
)
var validVersionRx = regexp.MustCompile(`go version go1\.(\d+)`)
// verifyGoVersion runs "go version" and parses the output. If the version is
// acceptable a check for gopherjs versions are also done. If problems
// are found a message is logged and we abort.
func verifyGoVersion() {
_, err := exec.LookPath("go")
if err != nil {
log.Fatalf("Go doesn't appear to be installed ('go' isn't in your PATH). Install Go 1.%d or newer.", goVersionMinor)
}
out, err := exec.Command("go", "version").Output()
if err != nil {
log.Fatalf("Error checking Go version with the 'go' command: %v", err)
}
version := string(out)
// Handle non-versioned binaries
// ex: "go version devel +c26fac8 Thu Feb 15 21:41:39 2018 +0000 linux/amd64"
if strings.HasPrefix(version, "go version devel ") {
verifyGopherjsGoroot(" devel")
return
}
m := validVersionRx.FindStringSubmatch(version)
if m == nil {
log.Fatalf("Unexpected output while checking 'go version': %q", version)
}
minorVersion, err := strconv.Atoi(m[1])
if err != nil {
log.Fatalf("Unexpected error while parsing version string %q: %v", m[1], err)
}
if minorVersion < goVersionMinor {
log.Fatalf("Your version of Go (%s) is too old. Perkeep requires Go 1.%d or later.", string(out), goVersionMinor)
}
if *website || *camnetdns {
return
}
if minorVersion != gopherJSGoMinor {
verifyGopherjsGoroot(fmt.Sprintf("1.%d", minorVersion))
}
}
func verifyGopherjsGoroot(goFound string) {
if !*buildWebUI {
return
}
gopherjsGoroot = os.Getenv("CAMLI_GOPHERJS_GOROOT")
goBin := hostExeName(filepath.Join(gopherjsGoroot, "bin", "go"))
if gopherjsGoroot == "" {
goInHomeDir, err := findGopherJSGoroot()
if err != nil {
log.Fatalf("Error while looking for a go1.%d dir in %v: %v", gopherJSGoMinor, homeDir(), err)
}
if goInHomeDir == "" {
log.Fatalf("You're using go%s != go1.%d, which GopherJS requires, and it was not found in %v. You need to specify a go1.%d root in CAMLI_GOPHERJS_GOROOT for building GopherJS.", goFound, gopherJSGoMinor, homeDir(), gopherJSGoMinor)
}
gopherjsGoroot = filepath.Join(homeDir(), goInHomeDir)
goBin = hostExeName(filepath.Join(gopherjsGoroot, "bin", "go"))
log.Printf("You're using go%s != go1.%d, which GopherJS requires, and CAMLI_GOPHERJS_GOROOT was not provided, so defaulting to %v for building GopherJS instead.", goFound, gopherJSGoMinor, goBin)
}
if _, err := os.Stat(goBin); err != nil {
if !os.IsNotExist(err) {
log.Fatal(err)
}
log.Fatalf("%v not found. You need to specify a go1.%d root in CAMLI_GOPHERJS_GOROOT for building GopherJS", goBin, gopherJSGoMinor)
}
}
// findGopherJSGoroot tries to find a go1.gopherJSGoMinor.* go root in the home
// directory. It returns the empty string and no error if none was found.
func findGopherJSGoroot() (string, error) {
dir, err := os.Open(homeDir())
if err != nil {
return "", err
}
defer dir.Close()
names, err := dir.Readdirnames(-1)
if err != nil {
return "", err
}
goVersion := fmt.Sprintf("go1.%d", gopherJSGoMinor)
for _, name := range names {
if strings.HasPrefix(name, goVersion) {
return name, nil
}
}
return "", nil
}
func withSQLite() bool {
cross := runtime.GOOS != *buildOS || runtime.GOARCH != *buildARCH
var sql bool
var err error
if *sqlFlag == "auto" {
sql = !cross && haveSQLite
} else {
sql, err = strconv.ParseBool(*sqlFlag)
if err != nil {
log.Fatalf("Bad boolean --sql flag %q", *sqlFlag)
}
}
if cross && sql {
log.Fatalf("SQLite isn't available when cross-compiling to another OS. Set --sqlite=false.")
}
if sql && !haveSQLite {
// TODO(lindner): fix these docs.
log.Printf("SQLite not found. Either install it, or run make.go with --sqlite=false See https://code.google.com/p/camlistore/wiki/SQLite")
switch runtime.GOOS {
case "darwin":
log.Printf("On OS X, run 'brew install sqlite3 pkg-config'. Get brew from http://mxcl.github.io/homebrew/")
case "linux":
log.Printf("On Linux, run 'sudo apt-get install libsqlite3-dev' or equivalent.")
case "windows":