Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
751 lines (660 loc) · 25.7 KB
/
Copy pathmain.go
File metadata and controls
751 lines (660 loc) · 25.7 KB
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
package main
import (
"context"
"errors"
"flag"
"fmt"
"os"
"runtime"
"sort"
"strings"
"dagger.io/dagger"
"github.com/pablogore/kit-logger/pkg/logger"
"github.com/pablogore/shipwright/internal/app"
"github.com/pablogore/shipwright/internal/config"
"github.com/pablogore/shipwright/internal/interfaces"
"github.com/pablogore/shipwright/internal/pipelines/shared"
"github.com/pablogore/shipwright/internal/workflow/engine"
"github.com/pablogore/shipwright/internal/workflow/graph"
"github.com/pablogore/shipwright/internal/workflow/manifest"
"github.com/pablogore/shipwright/internal/workflow/providers"
)
// defaultWorkflowManifestPath is --workflow's registered default (design.md
// D-N: "Default .shipwright/workflow.yaml").
const defaultWorkflowManifestPath = ".shipwright/workflow.yaml"
// CLI identity constants — presented in the --help usage line, --version
// output, and structured startup log messages.
const (
cliName = "shipwright"
versionLogMessage = "Shipwright version"
initLogMessage = "Shipwright initialized successfully"
)
// CLI represents the command line interface for the application.
type CLI struct {
app *app.App
yamlConfig *config.YAMLConfig
}
// NewCLI creates a new CLI instance.
func NewCLI() *CLI {
return &CLI{}
}
// Run executes the CLI with the given arguments.
func (c *CLI) Run(args []string) error {
ctx := context.Background()
// Parse command line flags
flags, err := c.parseFlags(args)
if err != nil {
return fmt.Errorf("failed to parse command line arguments: %w", err)
}
// Handle version flag
if flags.version {
c.showVersion()
return nil
}
// Handle health check flag
if flags.health {
return c.runHealthChecks(ctx, flags)
}
// Load configuration
cfg, err := config.NewConfigurationWrapper()
if err != nil {
return fmt.Errorf("failed to load configuration: %w", err)
}
// Load YAML configuration if specified and file exists
// The config file is optional - if it doesn't exist, we use defaults
if flags.configFile != "" {
// Check if file exists before trying to load it
if _, err := os.Stat(flags.configFile); err == nil {
var yamlCfg *config.YAMLConfig
yamlCfg, err = c.loadYAMLConfig(ctx, cfg, flags.configFile)
if err != nil {
return fmt.Errorf("failed to load YAML configuration: %w", err)
}
c.yamlConfig = yamlCfg
} else if flags.configFile != ".shipwright.yml" {
// File doesn't exist - this is OK, we'll use defaults.
// Only warn if the user explicitly specified --config.
logger.L().WarnContext(ctx, "Configuration file not found, using defaults",
"config_file", flags.configFile)
}
}
// Override configuration with CLI flags
c.overrideConfig(cfg, flags)
// Initialize the application
err = app.Initialize(ctx, cfg)
if err != nil {
return fmt.Errorf("failed to initialize application: %w", err)
}
defer app.Reset()
// Log successful initialization using go-kit-logger
logger.L().InfoContext(ctx, initLogMessage,
"workflow", flags.workflow,
"environment", flags.env,
"verbose", flags.verbose)
// Get the application instance
c.app = app.NewApp(app.GetContainer())
// The manifest-driven entrypoint (design.md D-N) is now the CLI's sole
// dispatch path — the legacy --pipeline preset registry, its factory
// functions, and every flag that only made sense against a named
// preset (--pipeline, --list-pipelines, --only-build, --only-test,
// --skip-push) were deleted in this work unit (tasks.md 11.3/11.4),
// which is why --step/--list-steps no longer need a mode switch: they
// always target the manifest now (runWorkflowCLI handles both). A
// missing/unreadable manifest fails closed naming the expected path
// (tasks.md 9.1) — there is no other path left to fall back to.
return c.runWorkflowCLI(ctx, flags)
}
// Flags represents the command line flags.
type Flags struct {
coverage float64
branch string
env string
executor string
gitAuth string
gitRef string
health bool
listSteps bool
local bool
step string
verbose bool
version bool
configFile string
// workflow is --workflow's path value — the manifest path for the
// sole CLI entrypoint (design.md D-N). Defaults to
// defaultWorkflowManifestPath when not explicitly passed.
workflow string
}
// parseFlags parses command line arguments.
// Returns parsed flags and an error if flag parsing fails.
func (c *CLI) parseFlags(args []string) (*Flags, error) {
flagSet := flag.NewFlagSet(cliName, flag.ContinueOnError)
defaultGitAuth := "ssh"
if os.Getenv("CI_JOB_TOKEN") != "" {
defaultGitAuth = "https"
}
flags := &Flags{}
flagSet.Float64Var(&flags.coverage, "coverage", 90, "Minimum coverage percentage required (in: 90 for 90%)")
flagSet.StringVar(&flags.branch, "branch", "develop", "Branch name")
flagSet.StringVar(&flags.env, "env", "dev", "Environment: dev, staging, prod")
flagSet.StringVar(&flags.executor, "executor", "", "Executor to use: native, docker (empty for auto-detection)")
flagSet.BoolVar(&flags.verbose, "verbose", false, "Verbose mode")
flagSet.StringVar(&flags.gitRef, "git-ref", "main", "Branch name (default: main)")
flagSet.StringVar(&flags.step, "step", "", "Workflow step to execute — the needs-transitive closure of this step id")
flagSet.StringVar(&flags.gitAuth, "git-auth", defaultGitAuth, "Git authentication method: ssh or https")
flagSet.BoolVar(&flags.listSteps, "list-steps", false, "List available workflow steps")
flagSet.StringVar(&flags.configFile, "config", ".shipwright.yml", "Configuration file path")
flagSet.BoolVar(&flags.version, "version", false, "Show version information")
flagSet.BoolVar(&flags.local, "local", false, "Run pipeline locally without Docker")
flagSet.BoolVar(&flags.health, "health", false, "Run health checks for Dagger, registry, and Git")
flagSet.StringVar(&flags.workflow, "workflow", defaultWorkflowManifestPath,
"Path to a declarative workflow manifest — the CLI's sole entrypoint (design.md D-N). "+
"--step/--list-steps target this manifest")
if err := flagSet.Parse(args); err != nil {
return nil, fmt.Errorf("failed to parse flags: %w", err)
}
return flags, nil
}
// overrideConfig overrides configuration with CLI flags.
func (c *CLI) overrideConfig(cfg interfaces.Configuration, flags *Flags) {
// Override configuration values with CLI flags
if flags.coverage != 90 {
cfg.Set("pipeline.coverage", flags.coverage)
}
if flags.env != "dev" {
cfg.Set("environment", flags.env)
}
if flags.verbose {
cfg.Set("pipeline.verbose", true)
}
if flags.gitRef != "main" {
cfg.Set("git.ref", flags.gitRef)
}
if flags.gitAuth != "ssh" {
cfg.Set("git.protocol", flags.gitAuth)
}
}
// loadYAMLConfig loads and applies YAML configuration
// Returns the parsed YAMLConfig for later use
func (c *CLI) loadYAMLConfig(ctx context.Context, cfg interfaces.Configuration, configFile string) (*config.YAMLConfig, error) {
parser := config.NewYAMLParser()
// Parse YAML file
yamlConfig, err := parser.ParseFile(configFile)
if err != nil {
return nil, fmt.Errorf("failed to parse YAML file: %w", err)
}
// Validate configuration
if err := parser.ValidateConfig(yamlConfig); err != nil {
return nil, fmt.Errorf("invalid YAML configuration: %w", err)
}
// Apply to main configuration
if err := parser.ApplyToConfiguration(yamlConfig, cfg); err != nil {
return nil, fmt.Errorf("failed to apply YAML configuration: %w", err)
}
logger.L().InfoContext(ctx, "Loaded configuration from file",
"config_file", configFile,
"pipeline", yamlConfig.Pipeline.Name,
"steps", yamlConfig.Pipeline.Steps)
return yamlConfig, nil
}
// workflowStepInfo is one manifest step's --list-steps report line
// (design.md D-N: "--list-steps retargeted to list manifest step ids with
// capability and resolved provider").
type workflowStepInfo struct {
StepID string
Capability string
ProviderName string
ProviderModule string
ProviderVersion string
}
// runWorkflowCLI is the manifest-driven entrypoint's dispatcher (design.md
// D-N). It parses+builds the manifest's graph first, unconditionally — a
// missing/invalid manifest fails closed here, before --list-steps or
// --step are even inspected (tasks.md 9.1), and this function never calls
// into any legacy --pipeline code path (tasks.md 9.5).
func (c *CLI) runWorkflowCLI(ctx context.Context, flags *Flags) error {
m, g, err := loadWorkflowManifest(flags.workflow)
if err != nil {
return err
}
if flags.listSteps {
return c.listWorkflowSteps(ctx, m)
}
if err := manifest.ValidateExecutable(m); err != nil {
return fmt.Errorf("workflow: %w", err)
}
runGraph, err := selectWorkflowGraph(g, flags.step)
if err != nil {
return err
}
return c.executeWorkflow(ctx, m, runGraph, flags)
}
// loadWorkflowManifest runs stages 1-3 (manifest.ParseFile) and stage 5
// (graph.Build) of the fixed seven-stage validation pipeline (design.md
// D-H) against path. manifest.ParseFile's own error already names the
// exact path it failed to open/parse (internal/workflow/manifest/parse.go:
// "manifest: open %s: %w") — this function adds no fallback of its own and
// performs no implicit legacy --pipeline behavior on failure (design.md
// D-N, tasks.md 9.1).
func loadWorkflowManifest(path string) (*manifest.Manifest, *graph.Graph, error) {
m, err := manifest.ParseFile(path)
if err != nil {
return nil, nil, fmt.Errorf("workflow: %w", err)
}
g, err := graph.Build(m.Spec.Steps)
if err != nil {
return nil, nil, fmt.Errorf("workflow: %w", err)
}
return m, g, nil
}
// selectWorkflowGraph returns g unchanged for a full workflow run
// (stepID == ""), or stepID's needs-transitive closure via engine.Closure
// when --step names a manifest step (design.md D-N: "--step <id>
// retargeted to a manifest step id ... executes the needs-transitive
// closure of <id> in topological order and stops"). This is the ONLY
// place main.go computes reachability — the actual algorithm lives in
// internal/workflow/engine/subgraph.go (WU8), per that package's own doc
// comment naming this wiring as Phase 9's job.
func selectWorkflowGraph(g *graph.Graph, stepID string) (*graph.Graph, error) {
if stepID == "" {
return g, nil
}
closure, err := engine.Closure(g, stepID)
if err != nil {
return nil, fmt.Errorf("workflow: %w", err)
}
return closure, nil
}
// listWorkflowSteps reports every manifest step's id, declared capability,
// and resolved provider name/version (design.md D-N). Providers are
// resolved against a nil Dagger client and an empty providers.Values map:
// resolution at listing time only needs to prove a step's uses.provider/
// uses.module is registered and version-supported (internal/workflow/
// providers.checkWithSchema only rejects a with-field kind mismatch for
// fields actually present in the Values it is given — an empty map can
// never trigger one), never to actually run anything.
func (c *CLI) listWorkflowSteps(ctx context.Context, m *manifest.Manifest) error {
reg := providers.NewRegistry()
providers.RegisterDefaults(reg, nil)
// Plugins are wired here too, with a nil Dagger client, so --list-steps
// resolves against the SAME provider set an actual run does. Without
// this, a manifest step naming a plugin-contributed provider would be
// reported as unregistered by --list-steps while executing correctly —
// a listing that lies about the run.
return runWithPluginLifecycle(ctx, c.app, reg, nil, func() error {
return reportWorkflowSteps(ctx, m, reg)
})
}
// reportWorkflowSteps resolves and logs every step's provider. Split out of
// listWorkflowSteps so the plugin lifecycle wraps exactly the resolution and
// reporting work.
func reportWorkflowSteps(ctx context.Context, m *manifest.Manifest, reg *providers.Registry) error {
infos, err := resolveStepInfos(m.Spec.Steps, reg)
if err != nil {
return err
}
logger.L().InfoContext(ctx, "Available workflow steps",
"manifest", m.Metadata.Name,
"steps_count", len(infos))
for i, info := range infos {
logger.L().InfoContext(ctx, "Step information",
"index", i+1,
"step", info.StepID,
"capability", info.Capability,
"provider", info.ProviderName,
"provider_module", info.ProviderModule,
"provider_version", info.ProviderVersion)
}
return nil
}
// resolveStepInfos resolves every step's declared uses.provider/uses.module
// against reg — see listWorkflowSteps' doc comment for why an empty
// providers.Values map is always safe here.
func resolveStepInfos(steps []manifest.Step, reg *providers.Registry) ([]workflowStepInfo, error) {
infos := make([]workflowStepInfo, 0, len(steps))
for _, s := range steps {
ref := providers.Ref{Name: s.Uses.Provider, Module: s.Uses.Module, Version: s.Uses.Version}
if err := resolveCapabilityRef(reg, s.Capability, ref); err != nil {
return nil, fmt.Errorf("workflow: step %q: %w", s.ID, err)
}
infos = append(infos, workflowStepInfo{
StepID: s.ID,
Capability: s.Capability,
ProviderName: ref.Name,
ProviderModule: ref.Module,
ProviderVersion: ref.Version,
})
}
return infos, nil
}
// resolveCapabilityRef dispatches ref to the Resolve* method matching
// capability — manifest.ValidateStructure (stage 3, already run by
// manifest.ParseFile) rejects any capability outside the seven known
// values (runtime-toolchain-upgrade, design.md D-4b/D-8/D-9 adds
// runtime-inspect and runtime-upgrade), so the default case here is
// defensive only, never reachable through the normal parse -> list
// pipeline.
func resolveCapabilityRef(reg *providers.Registry, capability string, ref providers.Ref) error {
empty := providers.Values{}
switch capability {
case "build":
_, err := reg.ResolveBuilder(ref, empty)
return err
case "test":
_, err := reg.ResolveTester(ref, empty)
return err
case "artifact":
_, err := reg.ResolveArtifactor(ref, empty)
return err
case "deploy":
_, err := reg.ResolveDeployer(ref, empty)
return err
case "run":
_, err := reg.ResolveRunner(ref, empty)
return err
case "runtime-inspect":
_, err := reg.ResolveRuntimeInspector(ref, empty)
return err
case "runtime-upgrade":
_, err := reg.ResolveRuntimeUpgrader(ref, empty)
return err
default:
return fmt.Errorf("unknown capability %q", capability)
}
}
// executeWorkflow runs g's steps end-to-end (design.md D-N/D-K): a real
// Dagger client (via the app container — the same lazily-connected
// "daggerClient" component the legacy --pipeline path already uses),
// providers.RegisterDefaults' real in-repo capability implementations
// (WU3/WU7), the manifest's declared secrets/source/variables, and
// engine.Execute (WU8) for the wave-scheduled run itself. This is the
// wiring task.md 9.4 asks for — it does not reimplement any engine logic,
// it only assembles engine.Config and calls engine.Execute.
func (c *CLI) executeWorkflow(ctx context.Context, m *manifest.Manifest, g *graph.Graph, flags *Flags) error {
client, err := c.workflowDaggerClient()
if err != nil {
return err
}
reg := providers.NewRegistry()
providers.RegisterDefaults(reg, client)
return runWithPluginLifecycle(ctx, c.app, reg, client, func() error {
return c.runWorkflowEngine(ctx, m, g, flags, reg, client)
})
}
// pluginLifecycle is the plugin load/cleanup surface the workflow entrypoint
// depends on, satisfied by *app.App. Declaring it here (consumer-side) keeps
// runWithPluginLifecycle's deferred-cleanup contract unit-testable without a
// DI container or a live Dagger engine.
type pluginLifecycle interface {
LoadAndInitializePlugins(ctx context.Context, reg *providers.Registry, client *dagger.Client) error
CleanupPlugins(ctx context.Context) error
}
// runWithPluginLifecycle wires the configured plugins into reg, runs run, and
// always cleans the plugins up afterwards.
//
// Cleanup is deferred BEFORE the load error is checked on purpose: plugin
// loading initializes plugins one at a time, so a failure on the third plugin
// leaves the first two initialized and needing cleanup. Cleanup failure is
// logged, never propagated — it must not mask the workflow's real outcome.
func runWithPluginLifecycle(
ctx context.Context,
lc pluginLifecycle,
reg *providers.Registry,
client *dagger.Client,
run func() error,
) error {
defer func() {
if err := lc.CleanupPlugins(ctx); err != nil {
logger.L().WarnContext(ctx, "Plugin cleanup failed", "error", err)
}
}()
if err := lc.LoadAndInitializePlugins(ctx, reg, client); err != nil {
return fmt.Errorf("workflow: %w", err)
}
return run()
}
// runWorkflowEngine assembles engine.Config and calls engine.Execute. It runs
// inside runWithPluginLifecycle, so reg already carries both the in-repo
// providers (RegisterDefaults) and every provider the loaded plugins
// contributed.
func (c *CLI) runWorkflowEngine(
ctx context.Context,
m *manifest.Manifest,
g *graph.Graph,
flags *Flags,
reg *providers.Registry,
client *dagger.Client,
) error {
opts, err := engine.OptionsFromSpec(m.Spec.Execution)
if err != nil {
return fmt.Errorf("workflow: %w", err)
}
secrets, err := resolveWorkflowSecrets(client, m.Spec.Secrets)
if err != nil {
return fmt.Errorf("workflow: %w", err)
}
source, err := resolveWorkflowSource(ctx, client, m.Spec.Source, shared.CloneRepo)
if err != nil {
return fmt.Errorf("workflow: %w", err)
}
cfg := engine.Config{
Steps: m.Spec.Steps,
Graph: g,
Registry: reg,
Source: source,
Variables: m.Spec.Variables,
Secrets: secrets,
Predicates: map[string]string{"branch": flags.branch},
Options: opts,
}
logger.L().InfoContext(ctx, "Executing workflow",
"manifest", m.Metadata.Name,
"steps", len(g.Nodes))
res, err := engine.Execute(ctx, cfg)
reportWorkflowOutcomes(ctx, m, res)
if err != nil {
return fmt.Errorf("workflow: %w", err)
}
if res.Failed() {
return fmt.Errorf("workflow: steps failed: %v", res.Failures)
}
logger.L().InfoContext(ctx, "Workflow completed successfully", "manifest", m.Metadata.Name)
return nil
}
// reportWorkflowOutcomes logs every executed step's Duration, Provider,
// Capability, Output, and Diagnostics (design.md D6). Kept distinct from
// reportWorkflowSteps, which serves the read-only --list-steps path and
// takes no *engine.Result, so reusing it would couple that path to
// execution. Output is a structured slog field, never interpolated into
// the message string.
func reportWorkflowOutcomes(ctx context.Context, m *manifest.Manifest, res *engine.Result) {
logger.L().InfoContext(ctx, "Workflow step outcomes",
"manifest", m.Metadata.Name,
"steps_count", len(res.Outcomes))
for i, o := range res.Outcomes {
logger.L().InfoContext(ctx, "Step outcome",
"index", i+1,
"step", o.StepID,
"status", o.Status.String(),
"attempts", o.Attempts,
"duration", o.Duration.String(),
"provider", o.Provider.Name,
"provider_module", o.Provider.Module,
"provider_version", o.Provider.Version,
"capability", o.Capability,
"output", o.Output)
for _, d := range o.Diagnostics {
logger.L().InfoContext(ctx, "Step diagnostic",
"step", o.StepID,
"severity", d.Severity.String(),
"code", d.Code,
"message", d.Message)
}
}
}
// workflowDaggerClient acquires the app container's lazily-connected
// "daggerClient" component. Real execution genuinely needs a live Dagger
// engine, unlike loadWorkflowManifest/listWorkflowSteps above, which never
// touch it — listWorkflowSteps deliberately wires plugins with a nil client
// for exactly that reason.
func (c *CLI) workflowDaggerClient() (*dagger.Client, error) {
container := c.app.GetContainer()
client, err := container.Get("daggerClient")
if err != nil {
return nil, fmt.Errorf("workflow: failed to acquire Dagger client: %w", err)
}
daggerClient, ok := client.(*dagger.Client)
if !ok || daggerClient == nil {
return nil, errors.New("workflow: Dagger client unavailable")
}
return daggerClient, nil
}
// resolveWorkflowSecrets binds every spec.secrets entry to a *dagger.Secret
// via client.SetSecret, reading each one's plaintext value from its
// declared FromEnv environment variable (internal/pipelines/shared/
// docker.go's existing client.SetSecret pattern, reused here per
// manifest/schema.go's SecretSpec doc comment). Fails closed: every binding
// is validated with os.LookupEnv, in sorted name order, before any
// *dagger.Secret is created — an unset or empty-string FromEnv variable is
// an error, never a silently empty secret. The plaintext value never
// leaves this function as anything other than the argument to SetSecret —
// engine.Config.Secrets only ever holds the resulting *dagger.Secret
// handles (design.md D-L).
func resolveWorkflowSecrets(client *dagger.Client, secrets map[string]manifest.SecretSpec) (map[string]*dagger.Secret, error) {
if len(secrets) == 0 {
return nil, nil
}
names := make([]string, 0, len(secrets))
for name := range secrets {
names = append(names, name)
}
sort.Strings(names)
values := make(map[string]string, len(secrets))
var failures []string
for _, name := range names {
spec := secrets[name]
value, ok := os.LookupEnv(spec.FromEnv)
switch {
case !ok:
failures = append(failures, fmt.Sprintf("%s: environment variable %q is not set", name, spec.FromEnv))
case value == "":
failures = append(failures, fmt.Sprintf("%s: environment variable %q is empty", name, spec.FromEnv))
default:
values[name] = value
}
}
if len(failures) > 0 {
return nil, &SecretResolutionError{Failures: failures}
}
out := make(map[string]*dagger.Secret, len(secrets))
for _, name := range names {
out[name] = client.SetSecret(name, values[name])
}
return out, nil
}
// SecretResolutionError reports every spec.secrets binding that failed
// validation in resolveWorkflowSecrets, one message per Failures entry.
// Each message names only the secret and its FromEnv variable — never the
// plaintext value, which this error type must never carry.
type SecretResolutionError struct {
Failures []string
}
func (e *SecretResolutionError) Error() string {
return "secrets: binding failed: " + strings.Join(e.Failures, "; ")
}
// cloneRepoFunc is the signature shared.CloneRepo satisfies. Accepting
// this as a parameter lets tests inject a mock without requiring a real
// Dagger client or network access.
type cloneRepoFunc func(ctx context.Context, client *dagger.Client, opts shared.GitCloneOpts, protocol string) (*dagger.Directory, error)
// resolveWorkflowSource resolves the workflow's input source directory.
//
// When spec.Repo is non-empty, the clone protocol is detected from the URL
// prefix (git@ → SSH, anything else → HTTPS) and delegated to
// shared.CloneRepo. When spec.Repo is empty, the existing path-based local
// directory resolution is used unchanged.
func resolveWorkflowSource(ctx context.Context, client *dagger.Client, spec manifest.SourceSpec, cloneFn cloneRepoFunc) (*dagger.Directory, error) {
if spec.Repo != "" {
if spec.AuthSecretRef != "" {
return nil, fmt.Errorf("workflow: source.authSecretRef is not supported yet (got %q)", spec.AuthSecretRef)
}
if spec.Ref == "" {
return nil, errors.New("workflow: source.ref is required when source.repo is set")
}
protocol := "https"
if strings.HasPrefix(spec.Repo, "git@") || strings.HasPrefix(spec.Repo, "ssh://") {
protocol = "ssh"
}
opts := shared.GitCloneOpts{
Repo: spec.Repo,
Branch: spec.Ref,
Name: "workflow-source",
}
return cloneFn(ctx, client, opts, protocol)
}
path := spec.Path
if path == "" {
path = "."
}
// Exclude VCS metadata and language build-output directories, same
// convention as SetupStepHandler's own Host().Directory call
// (internal/app/step_handlers.go). Without this, a repo with a
// populated local build directory (e.g. Rust's target/, which can
// reach tens of GB and hundreds of thousands of files after running
// cargo natively) gets synced whole into every Dagger snapshot on
// every workflow run: it's never actually needed, since every
// provider that builds/compiles mounts its own Dagger cache volume
// at the equivalent in-container path instead of reusing this one,
// and syncing it wastes snapshot time at best. On this host, syncing
// ego-rs's 42GB/400k-file target/ directory reliably hit a
// virtiofs/copy_file_range ENOSPC failure in Dagger's snapshotter
// well before disk was actually full.
return client.Host().Directory(path, dagger.HostDirectoryOpts{
Exclude: []string{"**/.git", "**/node_modules", "**/.dagger-cache", "**/target"},
}), nil
}
// Version and build information - set at build time
var (
Version = "dev"
BuildTime = "unknown"
GitCommit = "unknown"
)
// showVersion displays version information
func (c *CLI) showVersion() {
logger.L().InfoContext(context.Background(), versionLogMessage,
"version", Version,
"go_version", runtime.Version(),
"os", runtime.GOOS,
"arch", runtime.GOARCH,
"build_time", BuildTime,
"git_commit", GitCommit)
}
// runHealthChecks executes health checks for all configured services
func (c *CLI) runHealthChecks(ctx context.Context, flags *Flags) error {
// Load configuration
cfg, err := config.NewConfigurationWrapper()
if err != nil {
return fmt.Errorf("failed to load configuration: %w", err)
}
// Load YAML configuration if specified and file exists
// The config file is optional - if it doesn't exist, we use defaults
if flags.configFile != "" {
// Check if file exists before trying to load it
if _, err := os.Stat(flags.configFile); err == nil {
var yamlCfg *config.YAMLConfig
yamlCfg, err = c.loadYAMLConfig(ctx, cfg, flags.configFile)
if err != nil {
return fmt.Errorf("failed to load YAML configuration: %w", err)
}
c.yamlConfig = yamlCfg
}
// If file doesn't exist, silently use defaults (no error)
}
logger.L().InfoContext(ctx, "Running health checks")
return app.RunHealthChecks(ctx, cfg)
}
func main() {
cli := NewCLI()
if err := cli.Run(os.Args[1:]); err != nil {
logger.L().ErrorContext(context.Background(), "CLI execution failed", "error", err)
os.Exit(1)
}
}