-
Notifications
You must be signed in to change notification settings - Fork 386
/
main.go
2846 lines (2614 loc) · 85.2 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"
"bytes"
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
_ "net/http/pprof" // enable pprof handlers on net/http listener
"net/url"
"os"
"os/signal"
"os/user"
"path"
"path/filepath"
"regexp"
"runtime"
"runtime/debug"
"strconv"
"strings"
"syscall"
"text/tabwriter"
"time"
"github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/joho/godotenv"
"github.com/moby/buildkit/client"
_ "github.com/moby/buildkit/client/connhelper/dockercontainer" // Load "docker-container://" helper.
"github.com/moby/buildkit/client/llb"
"github.com/moby/buildkit/session"
"github.com/moby/buildkit/session/auth/authprovider"
"github.com/moby/buildkit/session/localhost/localhostprovider"
"github.com/moby/buildkit/session/sshforward/sshprovider"
"github.com/moby/buildkit/util/entitlements"
specs "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"golang.org/x/sync/errgroup"
"golang.org/x/sync/semaphore"
"golang.org/x/term"
"github.com/earthly/earthly/analytics"
"github.com/earthly/earthly/ast"
"github.com/earthly/earthly/autocomplete"
"github.com/earthly/earthly/buildcontext"
"github.com/earthly/earthly/buildcontext/provider"
"github.com/earthly/earthly/builder"
"github.com/earthly/earthly/buildkitd"
"github.com/earthly/earthly/cleanup"
"github.com/earthly/earthly/config"
"github.com/earthly/earthly/conslogging"
debuggercommon "github.com/earthly/earthly/debugger/common"
"github.com/earthly/earthly/debugger/terminal"
"github.com/earthly/earthly/docker2earthly"
"github.com/earthly/earthly/domain"
"github.com/earthly/earthly/earthfile2llb"
"github.com/earthly/earthly/secretsclient"
"github.com/earthly/earthly/states"
"github.com/earthly/earthly/util/cliutil"
"github.com/earthly/earthly/util/fileutil"
"github.com/earthly/earthly/util/llbutil"
"github.com/earthly/earthly/util/termutil"
"github.com/earthly/earthly/variables"
)
var dotEnvPath = ".env"
type earthlyApp struct {
cliApp *cli.App
console conslogging.ConsoleLogger
cfg *config.Config
sessionID string
commandName string
cliFlags
}
type cliFlags struct {
platformsStr cli.StringSlice
buildArgs cli.StringSlice
secrets cli.StringSlice
secretFiles cli.StringSlice
artifactMode bool
imageMode bool
pull bool
push bool
ci bool
noOutput bool
noCache bool
pruneAll bool
pruneReset bool
buildkitdSettings buildkitd.Settings
allowPrivileged bool
enableProfiler bool
buildkitHost string
buildkitdImage string
remoteCache string
maxRemoteCache bool
saveInlineCache bool
useInlineCache bool
configPath string
gitUsernameOverride string
gitPasswordOverride string
interactiveDebugging bool
sshAuthSock string
verbose bool
debug bool
homebrewSource string
bootstrapNoBuildkit bool
bootstrapWithAutocomplete bool
email string
token string
password string
disableNewLine bool
secretFile string
secretStdin bool
apiServer string
writePermission bool
registrationPublicKey string
dockerfilePath string
earthfilePath string
earthfileFinalImage string
expiry string
termsConditionsPrivacy bool
authToken string
noFakeDep bool
enableSourceMap bool
configDryRun bool
strict bool
conversionParllelism int
debuggerHost string
certPath string
keyPath string
}
var (
// DefaultBuildkitdImage is the default buildkitd image to use.
DefaultBuildkitdImage string
// Version is the version of this CLI app.
Version string
// GitSha contains the git sha used to build this app
GitSha string
)
func profhandler() {
addr := "127.0.0.1:6060"
fmt.Printf("listening for pprof on %s\n", addr)
http.ListenAndServe(addr, nil)
}
func main() {
startTime := time.Now()
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
defer func() {
signal.Stop(c)
cancel()
}()
go func() {
receivedSignal := false
for sig := range c {
cancel()
if receivedSignal {
// This is the second time we have received a signal. Quit immediately.
fmt.Printf("Received second signal %s. Forcing exit.\n", sig.String())
os.Exit(9)
}
receivedSignal = true
fmt.Printf("Received signal %s. Cleaning up before exiting...\n", sig.String())
go func() {
// Wait for 30 seconds before forcing an exit.
time.Sleep(30 * time.Second)
fmt.Printf("Timed out cleaning up. Forcing exit.\n")
os.Exit(9)
}()
}
}()
// Occasional spurious warnings show up - these are coming from imported libraries. Discard them.
logrus.StandardLogger().Out = ioutil.Discard
// Load .env into current global env's. This is mainly for applying Earthly settings.
// Separate call is made for build args and secrets.
if fileutil.FileExists(dotEnvPath) {
err := godotenv.Load(dotEnvPath)
if err != nil {
fmt.Printf("Error loading dot-env file %s: %s\n", dotEnvPath, err.Error())
os.Exit(1)
}
}
colorMode := conslogging.AutoColor
_, forceColor := os.LookupEnv("FORCE_COLOR")
if forceColor {
colorMode = conslogging.ForceColor
color.NoColor = false
}
_, noColor := os.LookupEnv("NO_COLOR")
if noColor {
colorMode = conslogging.NoColor
color.NoColor = true
}
padding := conslogging.DefaultPadding
customPadding, ok := os.LookupEnv("EARTHLY_TARGET_PADDING")
if ok {
targetPadding, err := strconv.Atoi(customPadding)
if err == nil {
padding = targetPadding
}
}
_, fullTarget := os.LookupEnv("EARTHLY_FULL_TARGET")
if fullTarget {
padding = conslogging.NoPadding
}
app := newEarthlyApp(ctx, conslogging.Current(colorMode, padding, false))
app.autoComplete()
exitCode := app.run(ctx, os.Args)
// app.cfg will be nil when a user runs `earthly --version`;
// however in all other regular commands app.cfg will be set in app.Before
if app.cfg != nil && !app.cfg.Global.DisableAnalytics {
ctxTimeout, cancel := context.WithTimeout(ctx, time.Millisecond*500)
defer cancel()
displayErrors := app.verbose
analytics.CollectAnalytics(ctxTimeout, app.apiServer, displayErrors, Version, getPlatform(), GitSha, app.commandName, exitCode, time.Since(startTime))
}
os.Exit(exitCode)
}
func getVersionPlatform() string {
var isRelease = regexp.MustCompile(`^v[0-9]+\.[0-9]+\.[0-9]+$`)
v := Version
if !isRelease.MatchString(Version) {
v = fmt.Sprintf("%s-%s", Version, GitSha)
}
return fmt.Sprintf("%s %s", v, getPlatform())
}
func getPlatform() string {
return fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)
}
func getBinaryName() string {
if len(os.Args) == 0 {
return "earthly"
}
binPath := os.Args[0] // can't use os.Executable() here; because it will give us earthly if executed via the earth symlink
baseName := path.Base(binPath)
return baseName
}
func newEarthlyApp(ctx context.Context, console conslogging.ConsoleLogger) *earthlyApp {
sessionIDBytes := make([]byte, 64)
_, err := rand.Read(sessionIDBytes)
if err != nil {
panic(err)
}
app := &earthlyApp{
cliApp: cli.NewApp(),
console: console,
sessionID: base64.StdEncoding.EncodeToString(sessionIDBytes),
cliFlags: cliFlags{
buildkitdSettings: buildkitd.Settings{},
},
}
earthly := getBinaryName()
app.cliApp.Usage = "A build automation tool for the container era"
app.cliApp.UsageText = "\t" + earthly + " [options] <target-ref>\n" +
"\n" +
" \t" + earthly + " [options] --image <target-ref>\n" +
"\n" +
" \t" + earthly + " [options] --artifact <artifact-ref> [<dest-path>]\n" +
"\n" +
" \t" + earthly + " [options] command [command options]\n" +
"\n" +
"Executes Earthly builds. For more information see https://docs.earthly.dev/earthly-command.\n" +
"To get started with using Earthly, check out the getting started guide at https://docs.earthly.dev/guides/basics."
app.cliApp.UseShortOptionHandling = true
app.cliApp.Action = app.actionBuild
app.cliApp.Version = getVersionPlatform()
app.cliApp.Flags = []cli.Flag{
&cli.StringSliceFlag{
Name: "platform",
EnvVars: []string{"EARTHLY_PLATFORMS"},
Usage: "Specify the target platform to build for *experimental*",
Value: &app.platformsStr,
},
&cli.StringSliceFlag{
Name: "build-arg",
EnvVars: []string{"EARTHLY_BUILD_ARGS"},
Usage: "A build arg override, specified as <key>=[<value>]",
Value: &app.buildArgs,
},
&cli.StringSliceFlag{
Name: "secret",
Aliases: []string{"s"},
EnvVars: []string{"EARTHLY_SECRETS"},
Usage: "A secret override, specified as <key>=[<value>]",
Value: &app.secrets,
},
&cli.StringSliceFlag{
Name: "secret-file",
EnvVars: []string{"EARTHLY_SECRET_FILES"},
Usage: "A secret override, specified as <key>=<path>",
Value: &app.secretFiles,
},
&cli.BoolFlag{
Name: "artifact",
Aliases: []string{"a"},
Usage: "Output only specified artifact",
Destination: &app.artifactMode,
},
&cli.BoolFlag{
Name: "image",
Usage: "Output only docker image of the specified target",
Destination: &app.imageMode,
},
&cli.BoolFlag{
Name: "pull",
EnvVars: []string{"EARTHLY_PULL"},
Usage: "Force pull any referenced Docker images",
Destination: &app.pull,
},
&cli.BoolFlag{
Name: "push",
EnvVars: []string{"EARTHLY_PUSH"},
Usage: "Push docker images and execute RUN --push commands",
Destination: &app.push,
},
&cli.BoolFlag{
Name: "ci",
EnvVars: []string{"EARTHLY_CI"},
Usage: wrap("Execute in CI mode (implies --use-inline-cache --save-inline-cache --no-output --strict)", "*experimental*"),
Destination: &app.ci,
},
&cli.BoolFlag{
Name: "no-output",
EnvVars: []string{"EARTHLY_NO_OUTPUT"},
Usage: wrap("Do not output artifacts or images", "(using --push is still allowed)"),
Destination: &app.noOutput,
},
&cli.BoolFlag{
Name: "no-cache",
EnvVars: []string{"EARTHLY_NO_CACHE"},
Usage: "Do not use cache while building",
Destination: &app.noCache,
},
&cli.StringFlag{
Name: "config",
Value: defaultConfigPath(),
EnvVars: []string{"EARTHLY_CONFIG"},
Usage: "Path to config file",
Destination: &app.configPath,
},
&cli.StringFlag{
Name: "ssh-auth-sock",
Value: os.Getenv("SSH_AUTH_SOCK"),
EnvVars: []string{"EARTHLY_SSH_AUTH_SOCK"},
Usage: wrap("The SSH auth socket to use for ssh-agent forwarding", ""),
Destination: &app.sshAuthSock,
},
&cli.StringFlag{
Name: "auth-token",
EnvVars: []string{"EARTHLY_TOKEN"},
Usage: "Force Earthly account login to authenticate with supplied token",
Destination: &app.authToken,
},
&cli.StringFlag{
Name: "git-username",
EnvVars: []string{"GIT_USERNAME"},
Usage: "The git username to use for git HTTPS authentication",
Destination: &app.gitUsernameOverride,
},
&cli.StringFlag{
Name: "git-password",
EnvVars: []string{"GIT_PASSWORD"},
Usage: "The git password to use for git HTTPS authentication",
Destination: &app.gitPasswordOverride,
},
&cli.StringFlag{
Name: "git-url-instead-of",
Value: "",
EnvVars: []string{"GIT_URL_INSTEAD_OF"},
Usage: wrap("Rewrite git URLs of a certain pattern. Similar to git-config url.", "<base>.insteadOf (https://git-scm.com/docs/git-config#Documentation/git-config.txt-urlltbasegtinsteadOf).", "Multiple values can be separated by commas. Format: <base>=<instead-of>[,...]. ", "For example: 'https://github.com/=git@github.com:'"),
Destination: &app.buildkitdSettings.GitURLInsteadOf,
},
&cli.BoolFlag{
Name: "allow-privileged",
Aliases: []string{"P"},
EnvVars: []string{"EARTHLY_ALLOW_PRIVILEGED"},
Usage: "Allow build to use the --privileged flag in RUN commands",
Destination: &app.allowPrivileged,
},
&cli.BoolFlag{
Name: "profiler",
EnvVars: []string{"EARTHLY_PROFILER"},
Usage: "Enable the profiler",
Destination: &app.enableProfiler,
Hidden: true, // Dev purposes only.
},
&cli.StringFlag{
Name: "buildkit-host",
Value: buildkitd.DockerAddress,
EnvVars: []string{"EARTHLY_BUILDKIT_HOST"},
Usage: wrap("The URL to use for connecting to a buildkit host. ", "If empty, earthly will attempt to start a buildkitd instance via docker run"),
Destination: &app.buildkitHost,
},
&cli.StringFlag{
Name: "debugger-host",
EnvVars: []string{"EARTHLY_DEBUGGER_HOST"},
Usage: wrap("The URL to use for connecting to a debugger host. ", "If empty, earthly uses the default debugger port, combined with the desired buildkit host."),
Destination: &app.debuggerHost,
Hidden: true,
},
&cli.StringFlag{
Name: "tlscert",
Value: "./certs/earthly_cert.pem",
EnvVars: []string{"EARTHLY_TLS_CERT"},
Usage: wrap("The path to the client TLS cert", "If relative, will be interpreted as relative to the ~/.earthly folder."),
Destination: &app.certPath,
Hidden: true,
},
&cli.StringFlag{
Name: "tlskey",
Value: "./certs/earthly_key.pem",
EnvVars: []string{"EARTHLY_TLS_KEY"},
Usage: wrap("The path to the client TLS key.", "If relative, will be interpreted as relative to the ~/.earthly folder."),
Destination: &app.keyPath,
Hidden: true,
},
&cli.IntFlag{
Name: "buildkit-cache-size-mb",
Value: 10000,
EnvVars: []string{"EARTHLY_BUILDKIT_CACHE_SIZE_MB"},
Usage: "The total size of the buildkit cache, in MB",
Destination: &app.buildkitdSettings.CacheSizeMb,
},
&cli.StringFlag{
Name: "buildkit-image",
Value: DefaultBuildkitdImage,
EnvVars: []string{"EARTHLY_BUILDKIT_IMAGE"},
Usage: "The docker image to use for the buildkit daemon",
Destination: &app.buildkitdImage,
},
&cli.StringFlag{
Name: "remote-cache",
EnvVars: []string{"EARTHLY_REMOTE_CACHE"},
Usage: "A remote docker image tag use as explicit cache *experimental*",
Destination: &app.remoteCache,
},
&cli.BoolFlag{
Name: "max-remote-cache",
EnvVars: []string{"EARTHLY_MAX_REMOTE_CACHE"},
Usage: "Saves all intermediate images too in the remove cache *experimental*",
Destination: &app.maxRemoteCache,
},
&cli.BoolFlag{
Name: "save-inline-cache",
EnvVars: []string{"EARTHLY_SAVE_INLINE_CACHE"},
Usage: "Enable cache inlining when pushing images *experimental*",
Destination: &app.saveInlineCache,
},
&cli.BoolFlag{
Name: "use-inline-cache",
EnvVars: []string{"EARTHLY_USE_INLINE_CACHE"},
Usage: wrap("Attempt to use any inline cache that may have been previously pushed ", "uses image tags referenced by SAVE IMAGE --push or SAVE IMAGE --cache-from", "*experimental*"),
Destination: &app.useInlineCache,
},
&cli.BoolFlag{
Name: "interactive",
Aliases: []string{"i"},
EnvVars: []string{"EARTHLY_INTERACTIVE"},
Usage: "Enable interactive debugging",
Destination: &app.interactiveDebugging,
},
&cli.BoolFlag{
Name: "verbose",
Aliases: []string{"V"},
EnvVars: []string{"EARTHLY_VERBOSE"},
Usage: "Enable verbose logging",
Destination: &app.verbose,
},
&cli.BoolFlag{
Name: "debug",
Aliases: []string{"D"},
EnvVars: []string{"EARTHLY_DEBUG"},
Usage: "Enable debug mode. This flag also turns on the debug mode of buildkitd, which may cause it to restart",
Destination: &app.debug,
Hidden: true, // For development purposes only.
},
&cli.StringFlag{
Name: "server",
Value: "https://api.earthly.dev",
EnvVars: []string{"EARTHLY_SERVER"},
Usage: "API server override for dev purposes",
Destination: &app.apiServer,
Hidden: true, // Internal.
},
&cli.BoolFlag{
Name: "no-fake-dep",
EnvVars: []string{"EARTHLY_NO_FAKE_DEP"},
Usage: "Internal feature flag for fake-dep",
Destination: &app.noFakeDep,
Hidden: true, // Internal.
},
&cli.BoolFlag{
Name: "strict",
EnvVars: []string{"EARTHLY_STRICT"},
Usage: "Disallow usage of features that may create unreproduceable builds",
Destination: &app.strict,
},
&cli.IntFlag{
Name: "conversion-parallelism",
EnvVars: []string{"EARTHLY_CONVERSION_PARALLELISM"},
Usage: "Set the conversion parallelism, which speeds up the use of IF, WITH DOCKER --load, FROM DOCKERFILE and others. A value of 0 disables the feature *experimental*",
Destination: &app.conversionParllelism,
},
}
app.cliApp.Commands = []*cli.Command{
{
Name: "bootstrap",
Usage: "Bootstraps earthly installation including shell autocompletion and buildkit image download",
Description: "Bootstraps earthly installation including shell autocompletion and buildkit image download",
Action: app.actionBootstrap,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "source",
Usage: "Output source file (for use in homebrew install)",
Hidden: true, // only meant for use with homebrew formula
Destination: &app.homebrewSource,
},
&cli.BoolFlag{
Name: "no-buildkit",
Usage: "Do not bootstrap buildkit",
Destination: &app.bootstrapNoBuildkit,
},
&cli.BoolFlag{
Name: "with-autocomplete",
Usage: "Add earthly autocompletions",
Destination: &app.bootstrapWithAutocomplete,
},
},
},
{
Name: "docker",
Usage: "Build a Dockerfile without converting to an Earthfile",
Description: "Builds a dockerfile",
Hidden: true, // Experimental.
Action: app.actionDocker,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "dockerfile",
Usage: "Path to dockerfile input, or - for stdin",
Value: "Dockerfile",
Destination: &app.dockerfilePath,
},
&cli.StringFlag{
Name: "tag",
Usage: "Name and tag for the built image; formatted as 'name:tag'",
Destination: &app.earthfileFinalImage,
},
},
},
{
Name: "docker2earthly",
Usage: "Convert a Dockerfile into Earthfile",
Description: "Converts an existing dockerfile into an Earthfile",
Hidden: true, // Experimental.
Action: app.actionDocker2Earthly,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "dockerfile",
Usage: "Path to dockerfile input, or - for stdin",
Value: "Dockerfile",
Destination: &app.dockerfilePath,
},
&cli.StringFlag{
Name: "earthfile",
Usage: "Path to earthfile output, or - for stdout",
Value: "Earthfile",
Destination: &app.earthfilePath,
},
&cli.StringFlag{
Name: "tag",
Usage: "Name and tag for the built image; formatted as 'name:tag'",
Destination: &app.earthfileFinalImage,
},
},
},
{
Name: "org",
Usage: "Earthly organization administration *experimental*",
Subcommands: []*cli.Command{
{
Name: "create",
Usage: "Create a new organization",
UsageText: "earthly [options] org create <org-name>",
Action: app.actionOrgCreate,
},
{
Name: "list",
Usage: "List organizations you belong to",
UsageText: "earthly [options] org list",
Action: app.actionOrgList,
},
{
Name: "list-permissions",
Usage: "List permissions and membership of an organization",
UsageText: "earthly [options] org list-permissions <org-name>",
Action: app.actionOrgListPermissions,
},
{
Name: "invite",
Usage: "Invite accounts to your organization",
UsageText: "earthly [options] org invite [options] <path> <email> [<email> ...]",
Action: app.actionOrgInvite,
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "write",
Usage: "Grant write permissions in addition to read",
Destination: &app.writePermission,
},
},
},
{
Name: "revoke",
Usage: "Remove accounts from your organization",
UsageText: "earthly [options] org revoke <path> <email> [<email> ...]",
Action: app.actionOrgRevoke,
},
},
},
{
Name: "secrets",
Usage: "Earthly secrets",
Description: "Manage cloud secrets *experimental*",
Subcommands: []*cli.Command{
{
Name: "set",
Usage: "Stores a secret in the secrets store",
UsageText: "earthly [options] secrets set <path> <value>\n" +
" earthly [options] secrets set --file <local-path> <path>\n" +
" earthly [options] secrets set --file <local-path> <path>",
Action: app.actionSecretsSet,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "file",
Aliases: []string{"f"},
Usage: "Stores secret stored in file",
Destination: &app.secretFile,
},
&cli.BoolFlag{
Name: "stdin",
Aliases: []string{"i"},
Usage: "Stores secret read from stdin",
Destination: &app.secretStdin,
},
},
},
{
Name: "get",
Action: app.actionSecretsGet,
Usage: "Retrieve a secret from the secrets store",
UsageText: "earthly [options] secrets get [options] <path>",
Flags: []cli.Flag{
&cli.BoolFlag{
Aliases: []string{"n"},
Usage: "Disable newline at the end of the secret",
Destination: &app.disableNewLine,
},
},
},
{
Name: "ls",
Usage: "List secrets in the secrets store",
UsageText: "earthly [options] secrets ls [<path>]",
Action: app.actionSecretsList,
},
{
Name: "rm",
Usage: "Removes a secret from the secrets store",
UsageText: "earthly [options] secrets rm <path>",
Action: app.actionSecretsRemove,
},
},
},
{
Name: "account",
Usage: "Create or manage an Earthly account *experimental*",
Subcommands: []*cli.Command{
{
Name: "register",
Usage: "Register for an Earthly account",
Description: "Register for an Earthly account",
UsageText: "first, request a token with:\n" +
" earthly [options] account register --email <email>\n" +
"\n" +
" then check your email to retrieve the token, then continue by running:\n" +
" earthly [options] account register --email <email> --token <token> [options]",
Action: app.actionRegister,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "email",
Usage: "Email address",
Destination: &app.email,
},
&cli.StringFlag{
Name: "token",
Usage: "Email verification token",
Destination: &app.token,
},
&cli.StringFlag{
Name: "password",
EnvVars: []string{"EARTHLY_PASSWORD"},
Usage: "Specify password on the command line instead of interactively being asked",
Destination: &app.password,
},
&cli.StringFlag{
Name: "public-key",
EnvVars: []string{"EARTHLY_PUBLIC_KEY"},
Usage: "Path to public key to register",
Destination: &app.registrationPublicKey,
},
&cli.BoolFlag{
Name: "accept-terms-of-service-privacy",
EnvVars: []string{"EARTHLY_ACCEPT_TERMS_OF_SERVICE_PRIVACY"},
Usage: "Accept the Terms & Conditions, and Privacy Policy",
Destination: &app.termsConditionsPrivacy,
},
},
},
{
Name: "login",
Usage: "Login to an Earthly account",
Description: "Login to an Earthly account",
UsageText: "earthly [options] account login\n" +
" earthly [options] account login --email <email>\n" +
" earthly [options] account login --email <email> --password <password>\n" +
" earthly [options] account login --token <token>\n",
Action: app.actionAccountLogin,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "email",
Usage: "Email address",
Destination: &app.email,
},
&cli.StringFlag{
Name: "token",
Usage: "Authentication token",
Destination: &app.token,
},
&cli.StringFlag{
Name: "password",
EnvVars: []string{"EARTHLY_PASSWORD"},
Usage: "Specify password on the command line instead of interactively being asked",
Destination: &app.password,
},
},
},
{
Name: "logout",
Usage: "Logout of an Earthly account",
Description: "Logout of an Earthly account; this has no effect for ssh-based authentication",
Action: app.actionAccountLogout,
},
{
Name: "list-keys",
Usage: "List associated public keys used for authentication",
UsageText: "earthly [options] account list-keys",
Action: app.actionAccountListKeys,
},
{
Name: "add-key",
Usage: "Associate a new public key with your account",
UsageText: "earthly [options] add-key [<key>]",
Action: app.actionAccountAddKey,
},
{
Name: "remove-key",
Usage: "Removes an existing public key from your account",
UsageText: "earthly [options] remove-key <key>",
Action: app.actionAccountRemoveKey,
},
{
Name: "list-tokens",
Usage: "List associated tokens used for authentication",
UsageText: "earthly [options] account list-tokens",
Action: app.actionAccountListTokens,
},
{
Name: "create-token",
Usage: "Create a new authentication token for your account",
UsageText: "earthly [options] account create-token [options] <token name>",
Action: app.actionAccountCreateToken,
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "write",
Usage: "Grant write permissions in addition to read",
Destination: &app.writePermission,
},
&cli.StringFlag{
Name: "expiry",
Usage: "Set token expiry date in the form YYYY-MM-DD or never (default 1year)",
Destination: &app.expiry,
},
},
},
{
Name: "remove-token",
Usage: "Remove an authentication token from your account",
UsageText: "earthly [options] account remove-token <token>",
Action: app.actionAccountRemoveToken,
},
},
},
{
Name: "debug",
Usage: "Print debug information about an Earthfile",
Description: "Print debug information about an Earthfile",
ArgsUsage: "[<path>]",
Hidden: true, // Dev purposes only.
Subcommands: []*cli.Command{
{
Name: "ast",
Usage: "Output the AST",
UsageText: "earthly [options] debug ast",
Action: app.actionDebugAst,
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "source-map",
Usage: "Enable outputting inline sourcemap",
Destination: &app.enableSourceMap,
},
},
},
},
},
{
Name: "prune",
Usage: "Prune Earthly build cache",
Description: "Prune Earthly build cache",
Action: app.actionPrune,
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "all",
Aliases: []string{"a"},
EnvVars: []string{"EARTHLY_PRUNE_ALL"},
Usage: "Prune all cache",
Destination: &app.pruneAll,
},
&cli.BoolFlag{
Name: "reset",
EnvVars: []string{"EARTHLY_PRUNE_RESET"},
Usage: "Reset cache entirely by wiping cache dir",
Destination: &app.pruneReset,
},
},
},
{
Name: "config",
Usage: "Edits your Earthly configuration file",
Action: app.actionConfig,
UsageText: `This command takes a path, and a value and sets it in your configuration file.
As the configuration file is YAML, the key must be a valid key within the file. You can specify sub-keys by using "." to separate levels.
If the sub-key you wish to use has a "." in it, you can quote that subsection, like this: git."github.com".
Values must be valid YAML, and also be deserializable into the key you wish to assign them to.
This means you can set higher level objects using a compact style, or single values with simple values.
Only one key/value can be set per invocation.
To get help with a specific key, do "config [key] --help". Or, visit https://docs.earthly.dev/earthly-config for more details.`,
Description: `Set your cache size:
config global.cache_size_mb 1234
Set additional buildkit args, using a YAML array:
config global.buildkit_additional_args ['userns', '--host']
Set a key containing a period:
config git."example.com".password hunter2
Set up a whole custom git repository for a server called example.com, using a single-line YAML literal:
* which stores git repos under /var/git/repos/name-of-repo.git
* allows access over ssh
* using port 2222
* sets the username to git
* is recognized to earthly as example.com/name-of-repo
config git "{example: {pattern: 'example.com/([^/]+)', substitute: 'ssh://git@example.com:2222/var/git/repos/\$1.git', auth: ssh}}"
`,
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "dry-run",
Usage: "Print the changed config file to the console instead of writing it out",
Destination: &app.configDryRun,
},
},
},
}
app.cliApp.Before = app.before
return app
}
func wrap(s ...string) string {
return strings.Join(s, "\n\t")
}
func (app *earthlyApp) before(context *cli.Context) error {
if app.enableProfiler {
go profhandler()
}
if app.verbose {
app.console = app.console.WithVerbose(true)
}
if context.IsSet("config") {
app.console.Printf("loading config values from %q\n", app.configPath)
}
var yamlData []byte
var err error
if app.configPath != "" {
yamlData, err = config.ReadConfigFile(app.configPath, context.IsSet("config"))
if err != nil {
return errors.Wrapf(err, "read config")
}
}
app.cfg, err = config.ParseConfigFile(yamlData)
if err != nil {
return errors.Wrapf(err, "failed to parse %s", app.configPath)
}
if app.cfg.Git == nil {
app.cfg.Git = map[string]config.GitConfig{}
}
err = app.processDeprecatedCommandOptions(context, app.cfg)
if err != nil {
return err
}
// command line option overrides the config which overrides the default value
if !context.IsSet("buildkit-image") && app.cfg.Global.BuildkitImage != "" {
app.buildkitdImage = app.cfg.Global.BuildkitImage
}
var addrs addresses
switch app.cfg.Global.BuildkitScheme {
case "tcp":
addrs, err = app.getAddressesForTCP(context)
if err != nil {
return err
}
app.handleTLSCertificateSettings(context)
case "docker-container":
addrs, err = app.getAddressesOriginal()
if err != nil {
return err
}
default:
return fmt.Errorf("%s is not a valid buildkit scheme", app.cfg.Global.BuildkitScheme)
}
app.debuggerHost = addrs.debugger
app.buildkitdSettings.AdditionalArgs = app.cfg.Global.BuildkitAdditionalArgs
app.buildkitdSettings.AdditionalConfig = app.cfg.Global.BuildkitAdditionalConfig
app.buildkitdSettings.Timeout = time.Duration(app.cfg.Global.BuildkitRestartTimeoutS) * time.Second
app.buildkitdSettings.Debug = app.debug
app.buildkitdSettings.BuildkitAddress = addrs.buildkit
app.buildkitdSettings.DebuggerAddress = app.debuggerHost
app.buildkitdSettings.LocalRegistryAddress = addrs.localRegistry
app.buildkitdSettings.UseTCP = app.cfg.Global.BuildkitScheme == "tcp"
app.buildkitdSettings.UseTLS = app.cfg.Global.TLSEnabled