Skip to content

Commit 2b87c28

Browse files
aledbfclaude
andcommitted
refactor(go): thread context, fix hook/write-path bugs, drop stutter
Dave Cheney-style review follow-ups (Plan A). A1 — thread context.Context to the I/O boundary so the SIGINT/SIGTERM context built in root.go actually cancels work. Previously docker.Client, ComposeClient, oci push and host lifecycle exec each dropped or manufactured context.Background(), so a long `docker build`/registry push could not be cancelled with Ctrl-C. ctx is now the first argument of Client.Run/Build/Tag/ Detect*, ComposeClient.Run/Config/Build/Up, oci.PushArtifact/ PushCollectionMetadata, docker.UpdateRemoteUserUID and lifecycle.RunInitializeCommand (host exec via exec.CommandContext). The ctx field is removed from upRunner/buildRunner (no longer stored in a struct). A2 — parallel (object-syntax) lifecycle hooks aggregated failures by stringifying each error, destroying the *CommandError chain and leaving the errors.As branch in run_user_commands unreachable. Aggregate with errors.Join over %w-wrapped errors instead; add a regression test. A3 — check errors on write paths that previously reported success on corruption: feature tarball extraction (io.Copy/Create/MkdirAll/Chmod), the collection tar writer (explicit tw.Close/file.Close), the compose override temp dirs (new overrideDirFor helper) and the temp build Dockerfile WriteFile. A4 — drop package-name stutter and Get-prefixes: config.DevContainerConfig->DevContainer, BuildConfig->Build, ConfigNotFoundError->NotFoundError; log.Log->Logger, LogLevel->Level, MapLogLevel->ParseLevel; features.FeatureSet->Set, FeaturesConfig->Config, FeatureAdvisory->Advisory (+ ResolveID/ClassifyID/StripVersionFromID/ SourceType/WithAdvisory); docker.DockerAPI->API, ToImageName, EnsureFinalStageName; product.Config->Info, Get; and the pure getters (Dimensions/LockfilePath/SemanticTags/Dockerfile/BuildContext/ DockerComposeFilePaths, GetSafeID->safeID). No behavior change. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent cf26c31 commit 2b87c28

87 files changed

Lines changed: 708 additions & 650 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎internal/cli/build.go‎

Lines changed: 30 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,7 @@ func newBuildCmd() *cobra.Command {
9595
// buildRunner carries the dependencies shared across the `build` flow so they
9696
// don't have to be threaded through every helper by hand.
9797
type buildRunner struct {
98-
ctx context.Context
99-
log log.Log
98+
log log.Logger
10099
docker *docker.Client
101100
engine *docker.EngineClient
102101
opts *buildOpts
@@ -151,7 +150,7 @@ func runBuild(ctx context.Context, out Output, opts *buildOpts) error {
151150
// Setup logger
152151
logger := log.New(log.Options{
153152
Version: cliVersion(),
154-
Level: log.MapLogLevel(opts.logLevel),
153+
Level: log.ParseLevel(opts.logLevel),
155154
Format: opts.logFormat,
156155
Writer: os.Stderr,
157156
})
@@ -181,12 +180,12 @@ func runBuild(ctx context.Context, out Output, opts *buildOpts) error {
181180
}
182181
defer engine.Close()
183182

184-
run := &buildRunner{ctx: ctx, log: logger, docker: dockerClient, engine: engine, opts: opts}
183+
run := &buildRunner{log: logger, docker: dockerClient, engine: engine, opts: opts}
185184

186185
// Detect BuildKit
187186
var useBuildx bool
188187
if opts.buildkit != "never" {
189-
bk := dockerClient.DetectBuildKit()
188+
bk := dockerClient.DetectBuildKit(ctx)
190189
useBuildx = bk.Available
191190
}
192191

@@ -214,12 +213,12 @@ func runBuild(ctx context.Context, out Output, opts *buildOpts) error {
214213
var imageNameResult []string
215214

216215
if cfg.IsDockerfileConfig() {
217-
imageNameResult, err = run.buildDockerfile(cfg, loadResult, useBuildx)
216+
imageNameResult, err = run.buildDockerfile(ctx, cfg, loadResult, useBuildx)
218217
} else if cfg.IsComposeConfig() {
219-
imageNameResult, err = run.buildCompose(cfg, useBuildx)
218+
imageNameResult, err = run.buildCompose(ctx, cfg, useBuildx)
220219
} else {
221220
// Image-based config
222-
imageNameResult, err = run.buildImage(cfg, loadResult, useBuildx)
221+
imageNameResult, err = run.buildImage(ctx, cfg, loadResult, useBuildx)
223222
}
224223

225224
if err != nil {
@@ -237,10 +236,10 @@ func runBuild(ctx context.Context, out Output, opts *buildOpts) error {
237236
})
238237
}
239238

240-
func (r *buildRunner) buildDockerfile(cfg *config.DevContainerConfig, loadResult *config.LoadResult, useBuildx bool) ([]string, error) {
241-
ctx, logger, dockerClient, engine, opts := r.ctx, r.log, r.docker, r.engine, r.opts
239+
func (r *buildRunner) buildDockerfile(ctx context.Context, cfg *config.DevContainer, loadResult *config.LoadResult, useBuildx bool) ([]string, error) {
240+
logger, dockerClient, engine, opts := r.log, r.docker, r.engine, r.opts
242241
// Read Dockerfile
243-
dockerfilePath := cfg.GetDockerfile()
242+
dockerfilePath := cfg.Dockerfile()
244243
if dockerfilePath == "" {
245244
return nil, fmt.Errorf("no Dockerfile specified")
246245
}
@@ -263,7 +262,7 @@ func (r *buildRunner) buildDockerfile(cfg *config.DevContainerConfig, loadResult
263262
stageName = cfg.Build.Target
264263
} else {
265264
var modifiedContent string
266-
stageName, modifiedContent = docker.EnsureDockerfileHasFinalStageName(string(content), "dev_container_auto_added_stage_label")
265+
stageName, modifiedContent = docker.EnsureFinalStageName(string(content), "dev_container_auto_added_stage_label")
267266
if modifiedContent != "" {
268267
// Write modified Dockerfile to temp location
269268
tmpDockerfile := dockerfilePath + ".devcontainer.build"
@@ -303,8 +302,8 @@ func (r *buildRunner) buildDockerfile(cfg *config.DevContainerConfig, loadResult
303302

304303
// Build context
305304
contextPath := configDir
306-
if cfg.GetBuildContext() != "" {
307-
contextPath = filepath.Join(configDir, cfg.GetBuildContext())
305+
if cfg.BuildContext() != "" {
306+
contextPath = filepath.Join(configDir, cfg.BuildContext())
308307
}
309308

310309
// Build args from config
@@ -366,7 +365,7 @@ func (r *buildRunner) buildDockerfile(cfg *config.DevContainerConfig, loadResult
366365
Secrets: buildSecrets,
367366
}
368367

369-
result, err := dockerClient.Build(buildOpts)
368+
result, err := dockerClient.Build(ctx, buildOpts)
370369
if err != nil {
371370
return nil, err
372371
}
@@ -404,8 +403,8 @@ func (r *buildRunner) buildDockerfile(cfg *config.DevContainerConfig, loadResult
404403
return imageNames, nil
405404
}
406405

407-
func (r *buildRunner) buildImage(cfg *config.DevContainerConfig, loadResult *config.LoadResult, useBuildx bool) ([]string, error) {
408-
ctx, logger, dockerClient, engine, opts := r.ctx, r.log, r.docker, r.engine, r.opts
406+
func (r *buildRunner) buildImage(ctx context.Context, cfg *config.DevContainer, loadResult *config.LoadResult, useBuildx bool) ([]string, error) {
407+
logger, dockerClient, engine, opts := r.log, r.docker, r.engine, r.opts
409408
if cfg.Image == "" {
410409
return nil, fmt.Errorf("no image specified in devcontainer.json")
411410
}
@@ -414,7 +413,7 @@ func (r *buildRunner) buildImage(cfg *config.DevContainerConfig, loadResult *con
414413
// surface immediately instead of after an expensive pull.
415414
if len(cfg.Features) > 0 {
416415
for id := range cfg.Features {
417-
srcType := features.ClassifyFeatureID(id)
416+
srcType := features.ClassifyID(id)
418417
if srcType == features.SourceLegacyShorthand {
419418
name := id
420419
if idx := strings.LastIndex(id, ":"); idx > 0 {
@@ -521,7 +520,7 @@ func (r *buildRunner) buildImage(cfg *config.DevContainerConfig, loadResult *con
521520
authEnv, authCleanup := bridgeBuildAuth(logger, "", featureImageNames, opts.cacheFrom, opts.cacheTo)
522521
defer authCleanup()
523522

524-
result, buildErr := dockerClient.Build(docker.BuildOptions{
523+
result, buildErr := dockerClient.Build(ctx, docker.BuildOptions{
525524
Dockerfile: dfPath,
526525
ContextPath: tmpDir,
527526
Tags: featureImageNames,
@@ -560,7 +559,7 @@ func (r *buildRunner) buildImage(cfg *config.DevContainerConfig, loadResult *con
560559
return nil, fmt.Errorf("write temp Dockerfile: %w", err)
561560
}
562561

563-
result, buildErr := dockerClient.Build(docker.BuildOptions{
562+
result, buildErr := dockerClient.Build(ctx, docker.BuildOptions{
564563
Dockerfile: dfPath,
565564
ContextPath: tmpDir,
566565
Tags: imageNames,
@@ -572,7 +571,7 @@ func (r *buildRunner) buildImage(cfg *config.DevContainerConfig, loadResult *con
572571
}
573572
if result.ExitCode != 0 {
574573
for _, name := range opts.imageNames {
575-
if tagErr := dockerClient.Tag(cfg.Image, name); tagErr != nil {
574+
if tagErr := dockerClient.Tag(ctx, cfg.Image, name); tagErr != nil {
576575
return nil, fmt.Errorf("failed to build and tag image %q: %w", name, tagErr)
577576
}
578577
}
@@ -591,7 +590,7 @@ func (r *buildRunner) buildImage(cfg *config.DevContainerConfig, loadResult *con
591590
// (string or array). It applies only to the build of the user's Dockerfile; the
592591
// feature layers take the flag values alone (matching TS containerFeatures, which
593592
// uses additionalCacheFroms only).
594-
func cacheFromForDockerfileBuild(flagCacheFrom []string, cfg *config.DevContainerConfig) []string {
593+
func cacheFromForDockerfileBuild(flagCacheFrom []string, cfg *config.DevContainer) []string {
595594
if cfg == nil || cfg.Build == nil || len(cfg.Build.CacheFrom) == 0 {
596595
return flagCacheFrom
597596
}
@@ -601,14 +600,14 @@ func cacheFromForDockerfileBuild(flagCacheFrom []string, cfg *config.DevContaine
601600
return combined
602601
}
603602

604-
func buildArgsFromConfig(cfg *config.DevContainerConfig) map[string]string {
603+
func buildArgsFromConfig(cfg *config.DevContainer) map[string]string {
605604
if cfg.Build == nil || cfg.Build.Args == nil {
606605
return map[string]string{}
607606
}
608607
return cfg.Build.Args
609608
}
610609

611-
func dockerfileBuildMetadataEntries(cfg *config.DevContainerConfig, baseLabels map[string]string, logger log.Log) []imagemeta.Entry {
610+
func dockerfileBuildMetadataEntries(cfg *config.DevContainer, baseLabels map[string]string, logger log.Logger) []imagemeta.Entry {
612611
metadata := []imagemeta.Entry{}
613612
if len(baseLabels) > 0 {
614613
metadata = append(metadata, imagemeta.ReadMetadataFromLabels(baseLabels, logger)...)
@@ -627,7 +626,7 @@ func resolvePath(p string) string {
627626
return filepath.Join(cwd, p)
628627
}
629628

630-
func buildOptionsFromConfig(cfg *config.DevContainerConfig) []string {
629+
func buildOptionsFromConfig(cfg *config.DevContainer) []string {
631630
if cfg.Build == nil || len(cfg.Build.Options) == 0 {
632631
return nil
633632
}
@@ -669,14 +668,14 @@ func isUserFacingBuildError(err error) bool {
669668
return strings.HasPrefix(msg, legacyFeaturePrefix)
670669
}
671670

672-
func (r *buildRunner) buildCompose(cfg *config.DevContainerConfig, useBuildx bool) ([]string, error) {
673-
ctx, logger, dockerClient, engine, opts := r.ctx, r.log, r.docker, r.engine, r.opts
671+
func (r *buildRunner) buildCompose(ctx context.Context, cfg *config.DevContainer, useBuildx bool) ([]string, error) {
672+
logger, dockerClient, engine, opts := r.log, r.docker, r.engine, r.opts
674673
if cfg.Service == "" {
675674
return nil, fmt.Errorf("dockerComposeFile config requires 'service' property")
676675
}
677676

678677
env := osEnvMap()
679-
composeFiles, err := config.GetDockerComposeFilePaths(cfg, env, filepath.Dir(cfg.ConfigFilePath))
678+
composeFiles, err := config.DockerComposeFilePaths(cfg, env, filepath.Dir(cfg.ConfigFilePath))
680679
if err != nil {
681680
return nil, fmt.Errorf("resolve compose files: %w", err)
682681
}
@@ -686,7 +685,7 @@ func (r *buildRunner) buildCompose(cfg *config.DevContainerConfig, useBuildx boo
686685
return nil, fmt.Errorf("compose client: %w", err)
687686
}
688687

689-
composeConfig, err := composeClient.Config(composeFiles, "")
688+
composeConfig, err := composeClient.Config(ctx, composeFiles, "")
690689
if err != nil {
691690
return nil, fmt.Errorf("compose config: %w", err)
692691
}
@@ -706,7 +705,7 @@ func (r *buildRunner) buildCompose(cfg *config.DevContainerConfig, useBuildx boo
706705

707706
if hasBuild {
708707
logger.Write(fmt.Sprintf("Building compose service %s...", cfg.Service), log.LevelInfo)
709-
buildErr := composeClient.Build(composeFiles, "", []string{"--project-name", projectName}, []string{cfg.Service}, opts.noCache)
708+
buildErr := composeClient.Build(ctx, composeFiles, "", []string{"--project-name", projectName}, []string{cfg.Service}, opts.noCache)
710709
if buildErr != nil {
711710
return nil, fmt.Errorf("compose build: %w", buildErr)
712711
}
@@ -763,7 +762,7 @@ func (r *buildRunner) buildCompose(cfg *config.DevContainerConfig, useBuildx boo
763762
return nil, fmt.Errorf("write temp Dockerfile: %w", err)
764763
}
765764

766-
result, buildErr := dockerClient.Build(docker.BuildOptions{
765+
result, buildErr := dockerClient.Build(ctx, docker.BuildOptions{
767766
Dockerfile: dfPath,
768767
ContextPath: tmpDir,
769768
Tags: opts.imageNames,

‎internal/cli/build_auth.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import (
1414
// func. It returns (nil, no-op) when there is nothing to bridge, leaving the
1515
// build's ambient auth untouched. Errors are swallowed (best-effort): a build
1616
// that would have worked anonymously must not fail because auth bridging did.
17-
func bridgeBuildAuth(logger log.Log, baseImage string, tags, cacheFrom []string, cacheTo string) (env []string, cleanup func()) {
17+
func bridgeBuildAuth(logger log.Logger, baseImage string, tags, cacheFrom []string, cacheTo string) (env []string, cleanup func()) {
1818
noop := func() {}
1919
regs := collectBuildRegistries(baseImage, tags, cacheFrom, cacheTo)
2020
if len(regs) == 0 {

‎internal/cli/build_cachefrom_test.go‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,18 +11,18 @@ import (
1111
// devcontainer.json build.cacheFrom: flag values first, then config values, in
1212
// order — matching TS singleContainer (additionalCacheFroms, then config.build.cacheFrom).
1313
func TestCacheFromForDockerfileBuild(t *testing.T) {
14-
cfgWith := func(cf ...string) *config.DevContainerConfig {
15-
return &config.DevContainerConfig{Build: &config.BuildConfig{CacheFrom: config.StringOrStrings(cf)}}
14+
cfgWith := func(cf ...string) *config.DevContainer {
15+
return &config.DevContainer{Build: &config.Build{CacheFrom: config.StringOrStrings(cf)}}
1616
}
1717

1818
cases := []struct {
1919
name string
2020
flag []string
21-
cfg *config.DevContainerConfig
21+
cfg *config.DevContainer
2222
want []string
2323
}{
2424
{"nil cfg → flag only", []string{"a"}, nil, []string{"a"}},
25-
{"no build block → flag only", []string{"a"}, &config.DevContainerConfig{}, []string{"a"}},
25+
{"no build block → flag only", []string{"a"}, &config.DevContainer{}, []string{"a"}},
2626
{"empty config cacheFrom → flag only", []string{"a"}, cfgWith(), []string{"a"}},
2727
{"flag then config (order)", []string{"flag1", "flag2"}, cfgWith("cfg1", "cfg2"), []string{"flag1", "flag2", "cfg1", "cfg2"}},
2828
{"no flag, config only", nil, cfgWith("cfg1"), []string{"cfg1"}},
@@ -43,7 +43,7 @@ func TestCacheFromForDockerfileBuild(t *testing.T) {
4343
// still passes verbatim for the feature layers).
4444
func TestCacheFromForDockerfileBuildDoesNotMutateFlag(t *testing.T) {
4545
flag := []string{"flag1"}
46-
cfg := &config.DevContainerConfig{Build: &config.BuildConfig{CacheFrom: config.StringOrStrings{"cfg1"}}}
46+
cfg := &config.DevContainer{Build: &config.Build{CacheFrom: config.StringOrStrings{"cfg1"}}}
4747
_ = cacheFromForDockerfileBuild(flag, cfg)
4848
if len(flag) != 1 || flag[0] != "flag1" {
4949
t.Fatalf("flag slice mutated: %v", flag)

‎internal/cli/build_compose_path_test.go‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package cli
22

33
import (
4-
"context"
54
"io"
65
"strings"
76
"testing"
@@ -38,7 +37,6 @@ func TestBuildComposePathWiring(t *testing.T) {
3837
for _, tt := range tests {
3938
t.Run(tt.name, func(t *testing.T) {
4039
r := &buildRunner{
41-
ctx: context.Background(),
4240
log: log.New(log.Options{Writer: io.Discard}),
4341
opts: &buildOpts{
4442
// Force the `docker compose` (v2) probe to fail hermetically,
@@ -47,13 +45,13 @@ func TestBuildComposePathWiring(t *testing.T) {
4745
dockerComposePath: tt.dockerComposePath,
4846
},
4947
}
50-
cfg := &config.DevContainerConfig{
48+
cfg := &config.DevContainer{
5149
ConfigFilePath: "/tmp/devcontainer.json",
5250
Service: "app",
5351
DockerComposeFile: config.StringOrStrings{"docker-compose.yml"},
5452
}
5553

56-
_, err := r.buildCompose(cfg, false)
54+
_, err := r.buildCompose(t.Context(), cfg, false)
5755
if err == nil {
5856
t.Fatal("expected compose-client detection error, got nil")
5957
}

‎internal/cli/cache_key.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,10 +45,10 @@ func computeCacheKey(result *config.LoadResult, env map[string]string) (string,
4545
if err != nil {
4646
return "", err
4747
}
48-
in := cacheKeyInput{Config: cfgJSON, Context: cfg.GetBuildContext()}
48+
in := cacheKeyInput{Config: cfgJSON, Context: cfg.BuildContext()}
4949

5050
configDir := filepath.Dir(cfg.ConfigFilePath)
51-
if df := cfg.GetDockerfile(); df != "" {
51+
if df := cfg.Dockerfile(); df != "" {
5252
if content, rerr := os.ReadFile(filepath.Join(configDir, df)); rerr == nil {
5353
in.Dockerfile = string(content)
5454
}

‎internal/cli/cache_key_test.go‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import (
1010
)
1111

1212
func imageResult(image, cfgPath string) *config.LoadResult {
13-
return &config.LoadResult{Config: &config.DevContainerConfig{Image: image, ConfigFilePath: cfgPath}}
13+
return &config.LoadResult{Config: &config.DevContainer{Image: image, ConfigFilePath: cfgPath}}
1414
}
1515

1616
func TestComputeCacheKeyFormatAndDeterminism(t *testing.T) {
@@ -58,9 +58,9 @@ func TestComputeCacheKeyIncludesDockerfile(t *testing.T) {
5858
if err := os.WriteFile(dfPath, []byte("FROM ubuntu:22.04\nRUN echo v1\n"), 0o644); err != nil {
5959
t.Fatal(err)
6060
}
61-
r := &config.LoadResult{Config: &config.DevContainerConfig{
61+
r := &config.LoadResult{Config: &config.DevContainer{
6262
ConfigFilePath: cfgPath,
63-
Build: &config.BuildConfig{Dockerfile: "Dockerfile"},
63+
Build: &config.Build{Dockerfile: "Dockerfile"},
6464
}}
6565
k1, err := computeCacheKey(r, nil)
6666
if err != nil {

‎internal/cli/check.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ func newCheckCmd() *cobra.Command {
4141
}
4242

4343
func runCheck(ctx context.Context, out Output, opts *checkOpts) error {
44-
env := &doctor.Env{DockerPath: opts.dockerPath, CLIVersion: product.GetConfig().Version}
44+
env := &doctor.Env{DockerPath: opts.dockerPath, CLIVersion: product.Get().Version}
4545
report := doctor.Run(ctx, env)
4646

4747
// Persist best-effort: a diagnostics run must not fail because state could
@@ -97,7 +97,7 @@ func newSetupCmd() *cobra.Command {
9797
}
9898

9999
func runSetup(ctx context.Context, out Output, opts *setupOpts) error {
100-
env := &doctor.Env{DockerPath: opts.dockerPath, CLIVersion: product.GetConfig().Version}
100+
env := &doctor.Env{DockerPath: opts.dockerPath, CLIVersion: product.Get().Version}
101101
report := doctor.Run(ctx, env)
102102
actions := doctor.Setup(ctx, env, report, opts.dryRun)
103103

‎internal/cli/cli_test.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ func TestComposeServiceConfig(t *testing.T) {
183183

184184
func TestConfigToMetadataEntry_IncludesMountsAndUIDSetting(t *testing.T) {
185185
trueValue := true
186-
cfg := &config.DevContainerConfig{
186+
cfg := &config.DevContainer{
187187
UpdateRemoteUserUID: &trueValue,
188188
Mounts: []config.MountOrString{
189189
mountString("type=volume,target=/data"),
@@ -212,7 +212,7 @@ func TestConfigToMetadataEntry_IncludesMountsAndUIDSetting(t *testing.T) {
212212
}
213213

214214
func TestDockerfileBuildMetadataEntries_PreservesBaseAndConfigMetadata(t *testing.T) {
215-
cfg := &config.DevContainerConfig{
215+
cfg := &config.DevContainer{
216216
PostCreateCommand: lifecycleCommand("touch /tmp/postCreateCommand.testmarker"),
217217
PostStartCommand: lifecycleCommand("touch /tmp/postStartCommand.testmarker"),
218218
PostAttachCommand: lifecycleCommand("touch /tmp/postAttachCommand.testmarker"),

0 commit comments

Comments
 (0)