Repository navigation
feat: Implement component workdir provisioning and CRUD commands - #1876
Conversation
a1806c0 to
4edac7d
Compare
|
Warning This PR exceeds the recommended limit of 1,000 lines.Large PRs are difficult to review and may be rejected due to their size. Please verify that this PR does not address multiple issues. |
Dependency Review✅ No vulnerabilities or license issues found.Scanned FilesNone |
📝 WalkthroughWalkthroughAdds a Component Workdir feature: CLI subcommand "workdir" (list/describe/show/clean), a workdir provisioner service with filesystem/hasher/path-filter abstractions and defaults, metadata persistence and cleanup APIs, Terraform execution override via WorkdirPathKey, new sentinel errors, tests, and docs. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
rect rgb(250,250,252)
participant CLI as Atmos CLI
participant WM as WorkdirManager (CLI)
participant Prov as workdir.Service
participant FS as FileSystem
participant H as Hasher
participant TF as Terraform exec
end
CLI->>WM: parse flags → build ConfigAndStacksInfo
CLI->>Prov: ProvisionWorkdir(ctx, atmosConfig, componentConfig)
Prov->>FS: MkdirAll(.workdir/terraform/<component>)
Prov->>FS: CopyDir(component_path → workdir)
Prov->>H: HashDir(workdir)
H-->>Prov: content_hash
Prov->>FS: WriteFile(.workdir-metadata.json)
Prov-->>CLI: set WorkdirPathKey in component config
CLI->>TF: start Terraform using WorkdirPathKey (override componentPath)
TF-->>CLI: terraform run completes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Disabled knowledge base sources:
📒 Files selected for processing (9)
🚧 Files skipped from review as they are similar to previous changes (6)
🧰 Additional context used📓 Path-based instructions (2)**/*.go📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)
Files:
**/*_test.go📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)
Files:
🧠 Learnings (45)📓 Common learnings📚 Learning: 2025-11-24T17:35:37.209ZApplied to files:
📚 Learning: 2025-05-23T19:51:47.091ZApplied to files:
📚 Learning: 2025-11-24T17:35:37.209ZApplied to files:
📚 Learning: 2025-12-26T06:31:02.244ZApplied to files:
📚 Learning: 2025-11-24T17:35:37.209ZApplied to files:
📚 Learning: 2024-11-02T15:35:09.958ZApplied to files:
📚 Learning: 2025-12-26T06:31:02.244ZApplied to files:
📚 Learning: 2025-11-24T17:35:37.209ZApplied to files:
📚 Learning: 2025-12-26T06:31:02.244ZApplied to files:
📚 Learning: 2025-11-24T17:35:37.209ZApplied to files:
📚 Learning: 2024-12-25T20:28:47.526ZApplied to files:
📚 Learning: 2025-11-24T17:35:37.209ZApplied to files:
📚 Learning: 2025-05-23T19:51:47.091ZApplied to files:
📚 Learning: 2025-12-26T06:31:02.244ZApplied to files:
📚 Learning: 2024-10-27T04:54:32.397ZApplied to files:
📚 Learning: 2024-10-27T04:28:40.966ZApplied to files:
📚 Learning: 2025-05-23T19:51:47.091ZApplied to files:
📚 Learning: 2024-10-28T01:51:30.811ZApplied to files:
📚 Learning: 2024-11-12T03:16:02.910ZApplied to files:
📚 Learning: 2025-12-13T06:10:13.688ZApplied to files:
📚 Learning: 2024-12-07T16:16:13.038ZApplied to files:
📚 Learning: 2025-12-13T06:10:25.156ZApplied to files:
📚 Learning: 2025-10-10T23:51:36.597ZApplied to files:
📚 Learning: 2025-09-08T01:25:44.958ZApplied to files:
📚 Learning: 2025-11-11T03:47:45.878ZApplied to files:
📚 Learning: 2024-12-25T20:28:19.618ZApplied to files:
📚 Learning: 2024-12-02T21:26:32.337ZApplied to files:
📚 Learning: 2025-03-18T12:26:25.329ZApplied to files:
📚 Learning: 2025-12-10T18:32:51.237ZApplied to files:
📚 Learning: 2025-08-15T14:43:41.030ZApplied to files:
📚 Learning: 2024-10-27T04:41:49.199ZApplied to files:
📚 Learning: 2025-12-21T04:10:29.030ZApplied to files:
📚 Learning: 2025-09-08T01:25:44.958ZApplied to files:
📚 Learning: 2025-09-08T01:25:44.958ZApplied to files:
📚 Learning: 2025-12-26T06:31:02.244ZApplied to files:
📚 Learning: 2025-11-24T17:35:37.209ZApplied to files:
📚 Learning: 2024-11-24T19:13:10.287ZApplied to files:
📚 Learning: 2025-01-25T04:01:58.095ZApplied to files:
📚 Learning: 2025-12-26T06:31:02.244ZApplied to files:
📚 Learning: 2025-04-26T15:54:10.506ZApplied to files:
📚 Learning: 2025-11-24T17:35:37.209ZApplied to files:
📚 Learning: 2025-05-23T19:51:47.091ZApplied to files:
📚 Learning: 2025-11-11T03:47:59.576ZApplied to files:
📚 Learning: 2025-01-09T22:27:25.538ZApplied to files:
🧬 Code graph analysis (3)pkg/provisioner/workdir/integration_test.go (4)
pkg/provisioner/workdir/clean.go (7)
tests/cli_workdir_test.go (1)
⏰ Context from checks skipped due to timeout of 900000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
🔇 Additional comments (24)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
📝 WalkthroughWalkthroughIntroduces a workdir provisioner system that creates isolated per-component Terraform working directories with JIT source vendoring, caching, and metadata management. Adds CLI subcommands for listing, describing, showing, and cleaning workdirs, plus provisioner hooks that run before terraform init to populate workdir contents from remote or local sources. Changes
Sequence DiagramsequenceDiagram
participant CLI as Atmos CLI
participant Provisioner as ProvisionWorkdir
participant Cache as Cache
participant Downloader as Downloader
participant FileSystem as FileSystem
participant Terraform as Terraform
CLI->>Provisioner: ProvisionWorkdir(componentConfig)
Provisioner->>Provisioner: Check if activation needed
alt Source metadata or workdir enabled
Provisioner->>FileSystem: Create workdir directory
FileSystem-->>Provisioner: workdir path
alt Remote source
Provisioner->>Cache: GenerateKey(source)
Cache-->>Provisioner: cache key
Provisioner->>Cache: Get(key)
alt Cache hit
Cache-->>Provisioner: CacheEntry
Provisioner->>FileSystem: Copy from cache path
else Cache miss
Provisioner->>Downloader: Download(source URI)
Downloader-->>Provisioner: Downloaded to temp
Provisioner->>Cache: Put(key, temp path)
Cache-->>Provisioner: Cached
Provisioner->>FileSystem: Copy from cache
end
else Local source
Provisioner->>FileSystem: Copy component directory
end
Provisioner->>FileSystem: HashDir(workdir)
FileSystem-->>Provisioner: content hash
Provisioner->>FileSystem: WriteFile(metadata.json)
FileSystem-->>Provisioner: Written
Provisioner-->>Terraform: _workdir_path in componentConfig
else Not activated
Provisioner-->>CLI: Skip (return nil)
end
CLI->>Terraform: Execute with overridden componentPath
Terraform->>Terraform: Use workdir path instead of component path
Terraform-->>CLI: Completed
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related PRs
Suggested labels
Suggested reviewers
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 8
🧹 Nitpick comments (14)
cmd/terraform/workdir/workdir_describe.go (1)
57-58: Usedata.Writefor pipeable output.Per coding guidelines, use
data.*for stdout output that should be pipeable, notfmt.Print.+ "github.com/cloudposse/atmos/pkg/data"// Output the manifest. - fmt.Print(manifest) + data.Write(manifest) return nilpkg/provisioner/workdir/workdir_test.go (1)
9-10: Remove no-op cleanup.
defer t.Cleanup(func() {})does nothing - it registers an empty cleanup function. Remove it.func TestExtractSourceConfig(t *testing.T) { - defer t.Cleanup(func() {}) - tests := []struct {pkg/provisioner/workdir/clean.go (1)
132-136: Error aggregation loses underlying errors.When multiple errors occur, only the count is reported. Consider including the first error as the cause for better debugging.
if len(errs) > 0 { return errUtils.Build(errUtils.ErrWorkdirClean). + WithCause(errs[0]). WithExplanation(fmt.Sprintf("%d error(s) occurred during cleanup", len(errs))). Err() }cmd/terraform/workdir/workdir_list.go (3)
36-43: Missing global flags parsing before config initialization.Per the established pattern, populate
ConfigAndStacksInfowith global flag values by callingflags.ParseGlobalFlags(cmd, v)beforeInitCliConfig. Without this, flags like--base-path,--config,--config-path, and--profilewill be ignored.v := viper.GetViper() format := v.GetString("format") + // Parse global flags into ConfigAndStacksInfo. + info, err := flags.ParseGlobalFlags(cmd, v) + if err != nil { + return errUtils.Build(errUtils.ErrWorkdirMetadata). + WithCause(err). + WithExplanation("Failed to parse global flags"). + Err() + } + // Initialize config. - atmosConfig, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, false) + atmosConfig, err := cfg.InitCliConfig(info, false)Based on learnings about InitCliConfig requiring populated ConfigAndStacksInfo.
64-86: Use data. utilities for pipeable output.*Per coding guidelines, JSON and YAML are pipeable data outputs and should use
data.WriteJSONanddata.WriteYAMLinstead offmt.Println/fmt.Print. This ensures consistent stream handling and masking.+import "github.com/cloudposse/atmos/pkg/data" + func printListJSON(workdirs []WorkdirInfo) error { - jsonData, err := json.MarshalIndent(workdirs, "", " ") - if err != nil { - return errUtils.Build(errUtils.ErrWorkdirMetadata). - WithCause(err). - WithExplanation("Failed to marshal workdirs to JSON"). - Err() - } - fmt.Println(string(jsonData)) - return nil + return data.WriteJSON(workdirs) } func printListYAML(workdirs []WorkdirInfo) error { - yamlData, err := yaml.Marshal(workdirs) - if err != nil { - return errUtils.Build(errUtils.ErrWorkdirMetadata). - WithCause(err). - WithExplanation("Failed to marshal workdirs to YAML"). - Err() - } - fmt.Print(string(yamlData)) - return nil + return data.WriteYAML(workdirs) }
88-129: Use ui. for human-readable messages.*Per guidelines, use
ui.Writelnor similar for human messages to stderr instead offmt.Fprintln(os.Stderr, ...). This ensures consistent formatting and theme application.+import "github.com/cloudposse/atmos/pkg/ui" + func printListTable(workdirs []WorkdirInfo) { if len(workdirs) == 0 { - fmt.Fprintln(os.Stderr, "No workdirs found") + ui.Writeln("No workdirs found") return } // ... table building ... - fmt.Fprintln(os.Stderr, t) + ui.Writeln(t.String()) }cmd/terraform/workdir/workdir_clean.go (2)
62-69: Missing global flags parsing before config initialization.Same as
workdir_list.go- populateConfigAndStacksInfoviaflags.ParseGlobalFlags(cmd, v)before callingInitCliConfigto respect global CLI flags.+ // Parse global flags. + info, err := flags.ParseGlobalFlags(cmd, v) + if err != nil { + return errUtils.Build(errUtils.ErrWorkdirClean). + WithCause(err). + WithExplanation("Failed to parse global flags"). + Err() + } + // Initialize config. - atmosConfig, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, false) + atmosConfig, err := cfg.InitCliConfig(info, false)
81-97: Use ui. for success messages.*Per guidelines, human-facing messages should use
ui.Successrather than directfmt.Fprintf(os.Stderr, ...).+import "github.com/cloudposse/atmos/pkg/ui" + func cleanAllWorkdirs(atmosConfig *schema.AtmosConfiguration) error { if err := workdirManager.CleanAllWorkdirs(atmosConfig); err != nil { return err } - fmt.Fprintf(os.Stderr, "%s All workdirs cleaned\n", theme.Styles.Checkmark.String()) + ui.Success("All workdirs cleaned") return nil } func cleanSpecificWorkdir(atmosConfig *schema.AtmosConfiguration, component, stack string) error { if err := workdirManager.CleanWorkdir(atmosConfig, component, stack); err != nil { return err } - fmt.Fprintf(os.Stderr, "%s Workdir cleaned for %s in %s\n", theme.Styles.Checkmark.String(), component, stack) + ui.Successf("Workdir cleaned for %s in %s", component, stack) return nil }cmd/terraform/workdir/workdir_helpers_test.go (2)
122-130: Use assert.ErrorIs for sentinel error checking.Per coding guidelines, always use
assert.ErrorIs()in tests, neverassert.Contains(err.Error(), ...)or justassert.Error()when checking for specific sentinel errors.func TestDefaultWorkdirManager_GetWorkdirInfo_NotFound(t *testing.T) { tmpDir := t.TempDir() manager := NewDefaultWorkdirManager() atmosConfig := &schema.AtmosConfiguration{BasePath: tmpDir} _, err := manager.GetWorkdirInfo(atmosConfig, "vpc", "dev") - assert.Error(t, err) + require.Error(t, err) + assert.ErrorIs(t, err, errUtils.ErrWorkdirMetadata) }You'll need to import
errUtils "github.com/cloudposse/atmos/errors"and verify the correct sentinel error.
189-197: Use assert.ErrorIs for sentinel error checking.Same as above - use
assert.ErrorIswith the appropriate sentinel error for consistent error verification.func TestDefaultWorkdirManager_CleanWorkdir_NotFound(t *testing.T) { tmpDir := t.TempDir() manager := NewDefaultWorkdirManager() atmosConfig := &schema.AtmosConfiguration{BasePath: tmpDir} err := manager.CleanWorkdir(atmosConfig, "vpc", "dev") - assert.Error(t, err) + require.Error(t, err) + assert.ErrorIs(t, err, errUtils.ErrWorkdirClean) }pkg/provisioner/workdir/cache.go (2)
315-327: Compile regexes once at package level.
regexp.MustCompileis called on every invocation. For frequently called functions, pre-compile at package scope.+var ( + semverRegex = regexp.MustCompile(`^v?\d+\.\d+\.\d+(-[a-zA-Z0-9.]+)?$`) + commitSHARegex = regexp.MustCompile(`^[0-9a-f]{7,40}$`) +) + // isSemver checks if a string looks like a semantic version. func isSemver(s string) bool { - // Match v1.2.3, 1.2.3, v1.2.3-rc1, etc. - re := regexp.MustCompile(`^v?\d+\.\d+\.\d+(-[a-zA-Z0-9.]+)?$`) - return re.MatchString(s) + return semverRegex.MatchString(s) } // isCommitSHA checks if a string looks like a git commit SHA. func isCommitSHA(s string) bool { - // Full SHA is 40 hex chars, short SHA is 7+. - re := regexp.MustCompile(`^[0-9a-f]{7,40}$`) - return re.MatchString(strings.ToLower(s)) + return commitSHARegex.MatchString(strings.ToLower(s)) }
296-299: Guard against short keys to prevent panic.
key[:2]will panic if key length is less than 2. WhileGenerateKeyalways produces 64-char hashes, defensive coding is advisable.func (c *DefaultCache) contentPath(key string) string { - // Use first 2 chars of hash as subdirectory for sharding. - return filepath.Join(c.basePath, "blobs", key[:2], key, "content") + // Use first 2 chars of hash as subdirectory for sharding. + prefix := key + if len(key) >= 2 { + prefix = key[:2] + } + return filepath.Join(c.basePath, "blobs", prefix, key, "content") }cmd/terraform/workdir/workdir_helpers.go (1)
258-270: Consider sync protection for global manager.The global
workdirManagervariable lacks synchronization. While typically set once during test setup, concurrent access could race. Anatomic.Valueorsync.Oncepattern would be safer.pkg/provisioner/workdir/workdir.go (1)
529-537: Usestrings.Containsinstead of manual loop.This reimplements
strings.Contains. Simpler and clearer to use the standard library.// containsParam checks if the URI contains a specific parameter. func containsParam(uri, param string) bool { - for i := 0; i <= len(uri)-len(param); i++ { - if uri[i:i+len(param)] == param { - return true - } - } - return false + return strings.Contains(uri, param) }
There was a problem hiding this comment.
Actionable comments posted: 5
♻️ Duplicate comments (8)
website/blog/2025-12-12-component-workdir-isolation.mdx (2)
148-148: Add hyphen to compound modifier.Change "go-getter supported" to "go-getter-supported" when used as a compound adjective.
127-135: Correct the clean command examples.The documented clean commands reference flags that don't match the actual implementation:
atmos terraform clean --allshould beatmos terraform workdir clean --all(new workdir subcommand)atmos terraform clean --cachedoesn't exist in the current implementationThe first example
atmos terraform clean vpc -s devis the traditional component-level clean.Update the examples to reflect the new workdir-specific commands introduced in this PR.
cmd/terraform/workdir/workdir_describe.go (1)
42-49: Pass global flags to InitCliConfig.This duplicates the issue flagged in previous review - global flags like
--base-pathare ignored when passing empty struct.pkg/provisioner/workdir/workdir.go (3)
203-204: Silently ignoring hash error.This was flagged in a previous review. The error from
HashDiris being discarded.
223-230:s.cache.Path("")returns empty string.This was flagged in a previous review. The temp directory path will be malformed.
311-312: Same hash error pattern.Same issue as line 204 - the error from
HashDiris silently ignored.pkg/provisioner/workdir/cache.go (2)
103-125: Data race: modifying entry under read lock.Line 123 mutates
entry.LastAccessedAtwhile holdingRLock. This was flagged in a previous review. Upgrade toLock()or remove the update.
416-421: Useio.EOFinstead of string comparison.This was flagged in a previous review. Replace
err.Error() == "EOF"witherr == io.EOF(orerrors.Is(err, io.EOF)).
🧹 Nitpick comments (9)
pkg/provisioner/workdir/downloader.go (1)
38-40: Consider enablingDisableSymlinksfor security.
DisableSymlinks: falseallows symlinks in downloaded content. This can be exploited via symlink attacks where malicious sources create symlinks pointing outside the destination. For defense-in-depth, consider setting this totrueunless symlink preservation is required.Mode: getter.ClientModeDir, - DisableSymlinks: false, + DisableSymlinks: true,cmd/terraform/workdir/workdir_clean.go (2)
86-86: Useui.*helpers instead of directfmt.Fprintfto stderr.Per coding guidelines, use
ui.Successfor human messages to stderr rather than direct stream access.- fmt.Fprintf(os.Stderr, "%s All workdirs cleaned\n", theme.Styles.Checkmark.String()) + ui.Success("All workdirs cleaned")
95-95: Same pattern - preferui.Successhere.- fmt.Fprintf(os.Stderr, "%s Workdir cleaned for %s in %s\n", theme.Styles.Checkmark.String(), component, stack) + ui.Successf("Workdir cleaned for %s in %s", component, stack)cmd/terraform/workdir/workdir_helpers_test.go (1)
122-130: Consider usingassert.ErrorIsfor error verification.Per coding guidelines, prefer
assert.ErrorIs(err, expectedSentinel)over justassert.Error(t, err)to validate the specific error type._, err := manager.GetWorkdirInfo(atmosConfig, "vpc", "dev") - assert.Error(t, err) + assert.ErrorIs(t, err, errUtils.ErrWorkdirMetadata) // or appropriate sentinelcmd/terraform/workdir/workdir_show.go (1)
69-69: Preferui.*for stderr output.Per guidelines, use
ui.Write*helpers rather than directfmt.Fprintfto stderr.pkg/provisioner/workdir/workdir_test.go (1)
9-11: Remove unnecessary empty cleanup.
defer t.Cleanup(func() {})does nothing and can be removed.func TestExtractSourceConfig(t *testing.T) { - defer t.Cleanup(func() {}) - tests := []struct {pkg/provisioner/workdir/clean.go (1)
14-44: Solid cleanup implementation.The error handling with context is well done. One consideration: this uses
os.Stat/os.RemoveAlldirectly while theServicetype uses theFileSysteminterface. For consistency and testability, you might consider either making this aServicemethod or accepting aFileSystemparameter. Not blocking though.pkg/provisioner/workdir/workdir.go (1)
519-537: Consider usingstrings.Containsfor simplicity.The manual character/substring search works but
strings.Containswould be more idiomatic.+import "strings" + // containsQuery checks if the URI contains a query string. func containsQuery(uri string) bool { - for _, c := range uri { - if c == '?' { - return true - } - } - return false + return strings.Contains(uri, "?") } // containsParam checks if the URI contains a specific parameter. func containsParam(uri, param string) bool { - for i := 0; i <= len(uri)-len(param); i++ { - if uri[i:i+len(param)] == param { - return true - } - } - return false + return strings.Contains(uri, param) }pkg/provisioner/workdir/cache.go (1)
315-327: Pre-compile regexes for better performance.
isSemverandisCommitSHAcompile their regexes on every call. These should be package-level variables.+var ( + semverRegex = regexp.MustCompile(`^v?\d+\.\d+\.\d+(-[a-zA-Z0-9.]+)?$`) + commitSHARegex = regexp.MustCompile(`^[0-9a-f]{7,40}$`) +) + // isSemver checks if a string looks like a semantic version. func isSemver(s string) bool { - // Match v1.2.3, 1.2.3, v1.2.3-rc1, etc. - re := regexp.MustCompile(`^v?\d+\.\d+\.\d+(-[a-zA-Z0-9.]+)?$`) - return re.MatchString(s) + return semverRegex.MatchString(s) } // isCommitSHA checks if a string looks like a git commit SHA. func isCommitSHA(s string) bool { - // Full SHA is 40 hex chars, short SHA is 7+. - re := regexp.MustCompile(`^[0-9a-f]{7,40}$`) - return re.MatchString(strings.ToLower(s)) + return commitSHARegex.MatchString(strings.ToLower(s)) }
|
💥 This pull request now has conflicts. Could you fix it Erik Osterman (Cloud Posse) (@osterman)? 🙏 |
0b67480 to
acabfb4
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (11)
cmd/terraform/workdir/workdir_clean.go (1)
62-70: Global flags handling is now correct.The
buildConfigAndStacksInfohelper properly parses global flags before callingInitCliConfig, addressing the concern from past reviews.cmd/terraform/workdir/workdir.go (1)
15-19: Verifyworkdir.SetAtmosConfigis called in root.go.Per past review and established patterns (version, devcontainer, themeCmd, backend),
SetAtmosConfigmust be called incmd/root.goafterInitCliConfigto initialize the package-level pointer. OtherwiseatmosConfigPtrwill be nil when used in perf.Track calls.#!/bin/bash # Verify workdir.SetAtmosConfig is called in root.go rg -n "workdir.*SetAtmosConfig\|workdir\.SetAtmosConfig" cmd/root.gocmd/terraform/workdir/workdir_describe.go (1)
41-49: Global flags handling is now correct.The
buildConfigAndStacksInfohelper properly addresses the past review concern about ignoring global flags.cmd/terraform/workdir/workdir_show.go (1)
44-52: Global flags handling is now correct.The
buildConfigAndStacksInfohelper properly addresses the past review concern about ignoring global flags.pkg/provisioner/workdir/clean.go (1)
133-138: Error aggregation properly preserves individual errors.The current implementation uses
errors.Join(errs...)which correctly preserves all individual error details in the cause chain, addressing the previous review concern.pkg/provisioner/workdir/workdir.go (2)
204-207: Hash error handling is properly implemented.The function now captures the hash error and logs a warning, addressing the previous review concern about silently ignoring hash failures.
227-233: Cache base path properly retrieved.The function now uses
s.cache.BasePath()method to get the cache directory, addressing the previous review concern about usingPath("").pkg/provisioner/workdir/cache.go (4)
46-68: Thread-safe initialization properly implemented.The function now uses
sync.Onceto ensure basePath initialization happens exactly once, addressing the previous race condition concern.
98-130: Lock upgrade properly implemented.The method now uses write lock to safely update LastAccessedAt, addressing the previous data race concern.
362-407: Symlink handling properly implemented.The function now explicitly checks for symlinks and handles them correctly, addressing the previous review concern.
453-455: EOF check is idiomatic.Direct comparison with
io.EOFis the standard Go pattern for this sentinel error. Usingerrors.Iswould work but adds no value here sinceio.EOFis a simple sentinel.
🧹 Nitpick comments (11)
internal/exec/terraform_shell.go (1)
63-77: Use static error sentinel for wrapping.The provisioner integration logic is sound. One adjustment needed per coding guidelines: use static errors from
errors/errors.goinstead of dynamic error strings.+ errUtils "github.com/cloudposse/atmos/errors"Then at line 70:
- return fmt.Errorf("provisioner execution failed: %w", err) + return fmt.Errorf(errUtils.ErrWrapFormat, errUtils.ErrWorkdirProvision, err)This ensures consistent error handling using the newly added
ErrWorkdirProvisionsentinel.cmd/terraform/workdir/workdir_list.go (4)
72-72: Replacefmt.Printlnwith appropriate output function.Per coding guidelines,
fmt.Printlnshould not be used. For data output to stdout, use the appropriatedata.*output function.
84-84: Replacefmt.Printwith appropriate output function.Same guideline applies here for YAML data output.
88-92: Replacefmt.Fprintln(os.Stderr, ...)withui.*function.Per coding guidelines, UI output to stderr should use
ui.*functions rather than directfmt.Fprintln.
128-128: Replacefmt.Fprintln(os.Stderr, t)withui.*function.Table output is UI and should use the appropriate
ui.*function.cmd/terraform/workdir/workdir_clean.go (2)
87-87: Replacefmt.Fprintf(os.Stderr, ...)withui.*function.Per coding guidelines, UI output should use
ui.*functions rather than directfmt.Fprintf.
96-96: Replacefmt.Fprintf(os.Stderr, ...)withui.*function.Same guideline applies for the specific workdir cleaned message.
cmd/terraform/workdir/workdir_describe.go (1)
58-58: Replacefmt.Printwith appropriate data output function.Per coding guidelines, data outputs should use
data.*functions rather thanfmt.Print.cmd/terraform/workdir/workdir_show.go (2)
69-69: Replacefmt.Fprintf(os.Stderr, ...)withui.*function.Per coding guidelines, UI output to stderr should use
ui.*functions.
105-105: Replacefmt.Fprintf(os.Stderr, ...)withui.*function.Same guideline applies for the table output.
pkg/provisioner/workdir/workdir_test.go (1)
10-10: Remove unnecessary empty cleanup.The empty
t.Cleanup(func() {})serves no purpose and can be removed.func TestExtractSourceConfig(t *testing.T) { - defer t.Cleanup(func() {}) - tests := []struct {
|
💥 This pull request now has conflicts. Could you fix it Erik Osterman (Cloud Posse) (@osterman)? 🙏 |
00cd2d0 to
daaa163
Compare
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (6)
internal/exec/terraform_shell.go (1)
63-77: Consider using errUtils.Build for error wrapping.The provisioner integration looks solid - timeout is reasonable, workdir path override logic is clean, and logging provides good visibility. However, per coding guidelines, errors should be wrapped using errUtils.Build for consistency across the codebase.
Optional refactor for consistency:
err = provisioner.ExecuteProvisioners(ctx, provisioner.HookEvent(beforeTerraformInitEvent), atmosConfig, info.ComponentSection, info.AuthContext) if err != nil { - return fmt.Errorf("provisioner execution failed: %w", err) + return errUtils.Build(errUtils.ErrProvisionerFailed). + WithCause(err). + WithContext("hook_event", beforeTerraformInitEvent). + Err() }The existing code works fine; this just aligns with the broader error handling pattern.
pkg/provisioner/workdir/workdir_test.go (1)
9-11: Remove the no-op cleanup call.
defer t.Cleanup(func() {})does nothing. Remove it or replace with actual cleanup logic if needed.func TestExtractSourceConfig(t *testing.T) { - defer t.Cleanup(func() {}) - tests := []struct {pkg/provisioner/workdir/workdir.go (1)
529-551: Consider usingstringspackage for simpler checks.These manual string scanning functions work correctly, but
strings.Containswould be more idiomatic and readable.+import "strings" + // containsRef checks if the URI already contains a ref parameter. func containsRef(uri string) bool { - return containsParam(uri, "ref=") + return strings.Contains(uri, "ref=") } // containsQuery checks if the URI contains a query string. func containsQuery(uri string) bool { - for _, c := range uri { - if c == '?' { - return true - } - } - return false + return strings.Contains(uri, "?") } - -// containsParam checks if the URI contains a specific parameter. -func containsParam(uri, param string) bool { - for i := 0; i <= len(uri)-len(param); i++ { - if uri[i:i+len(param)] == param { - return true - } - } - return false -}pkg/provisioner/workdir/clean.go (1)
19-22: Consider resolving absolute paths before deletion.Based on learnings, when deleting directories, resolving absolute paths using
filepath.Absis recommended. This provides safer deletion semantics and clearer logging.func CleanWorkdir(atmosConfig *schema.AtmosConfiguration, component string) error { defer perf.Track(atmosConfig, "workdir.CleanWorkdir")() basePath := atmosConfig.BasePath if basePath == "" { basePath = "." } - workdirPath := filepath.Join(basePath, WorkdirPath, "terraform", component) + workdirPath, err := filepath.Abs(filepath.Join(basePath, WorkdirPath, "terraform", component)) + if err != nil { + return errUtils.Build(errUtils.ErrWorkdirClean). + WithCause(err). + WithExplanation("failed to resolve absolute workdir path"). + WithContext("component", component). + Err() + }Based on learnings, absolute paths are preferred when deleting directories.
Also applies to: 51-54
pkg/provisioner/workdir/fs.go (1)
141-153: Consider checking Close error.While uncommon, Close can fail (e.g., on NFS). The error is currently ignored.
func (h *DefaultHasher) HashFile(path string) (string, error) { defer perf.Track(nil, "workdir.DefaultHasher.HashFile")() file, err := os.Open(path) if err != nil { return "", err } - defer file.Close() + defer func() { + _ = file.Close() + }() hash := sha256.New()This explicitly ignores the error, making it clear the decision is intentional.
cmd/terraform/workdir/workdir_helpers.go (1)
243-256: Consider wrapping errors for consistency.While this private helper is called from methods that add their own context, wrapping errors here would provide more detailed information about what failed during metadata reading.
Apply this diff to add error context:
func readWorkdirMetadata(path string) (*provWorkdir.WorkdirMetadata, error) { data, err := os.ReadFile(path) if err != nil { - return nil, err + return nil, errUtils.Build(errUtils.ErrWorkdirMetadata). + WithCause(err). + WithContext("path", path). + Err() } var metadata provWorkdir.WorkdirMetadata if err := json.Unmarshal(data, &metadata); err != nil { - return nil, err + return nil, errUtils.Build(errUtils.ErrWorkdirMetadata). + WithCause(err). + WithExplanation("Failed to parse metadata JSON"). + WithContext("path", path). + Err() } return &metadata, nil }As per coding guidelines, all errors should be wrapped using errUtils.Build for consistency, even in private helpers.
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #1876 +/- ##
==========================================
- Coverage 73.58% 73.55% -0.03%
==========================================
Files 634 643 +9
Lines 59027 59723 +696
==========================================
+ Hits 43433 43930 +497
- Misses 12605 12783 +178
- Partials 2989 3010 +21
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
pkg/provisioner/workdir/integration_test.go (1)
60-61: Remove unused gomock controller.The controller is created but never used since this test exercises the real filesystem.
🔎 Proposed fix
- ctrl := gomock.NewController(t) - defer ctrl.Finish() - // Create temp directories.
🧹 Nitpick comments (10)
website/src/data/roadmap.js (1)
280-280: Consider mentioning the CLI commands.The PR introduces new CLI commands (
atmos terraform workdirwith subcommands list, describe, show, clean). For consistency with other milestones that mention their CLI commands (e.g., line 196: "atmos list stacks"), consider including this in the description or label.Example enhancement
- { label: 'Component workdir provisioning', status: 'shipped', quarter: 'q4-2025', pr: 1876, description: 'Isolated working directories for each component instance, eliminating conflicts when multiple instances share the same component source.', benefits: 'Enables concurrent component execution and just-in-time vendoring. Multiple component instances no longer conflict by overwriting each other in the same directory.' }, + { label: 'Component workdir provisioning', status: 'shipped', quarter: 'q4-2025', pr: 1876, description: 'Isolated working directories for each component instance with `atmos terraform workdir` commands to manage them—eliminating conflicts when multiple instances share the same component source.', benefits: 'Enables concurrent component execution and just-in-time vendoring. Multiple component instances no longer conflict by overwriting each other in the same directory. Use list, describe, show, and clean subcommands to inspect and manage workdirs.' },internal/exec/stack_processor_process_stacks_helpers.go (1)
74-74: Add a godoc comment for the new field.The
ComponentProvisionfield is exported but lacks documentation. Add a brief comment explaining its purpose and contents.Suggested addition
+ // ComponentProvision holds provisioning configuration for the component (e.g., workdir settings). ComponentProvision map[string]anyinternal/exec/terraform.go (2)
408-411: Consider adding debug logging for consistency.The workdir path override logic is correct, but unlike the similar block in
terraform_shell.go(lines 77-80), this doesn't log the override. Consider adding debug logging for consistency:🔎 Proposed enhancement
// Check if workdir provisioner set a workdir path - if so, use it instead of the component path. if workdirPath, ok := info.ComponentSection[provWorkdir.WorkdirPathKey].(string); ok && workdirPath != "" { componentPath = workdirPath + log.Debug("Using workdir path after provisioner execution", "workdirPath", workdirPath) }
515-518: Same suggestion: add debug logging for consistency.This override block in the init case follows the same pattern as the one above. The same logging suggestion applies here for consistency with
terraform_shell.go.🔎 Proposed enhancement
// Check if workdir provisioner set a workdir path - if so, use it instead of the component path. if workdirPath, ok := info.ComponentSection[provWorkdir.WorkdirPathKey].(string); ok && workdirPath != "" { componentPath = workdirPath + log.Debug("Using workdir path in init case", "workdirPath", workdirPath) }cmd/terraform/workdir/workdir.go (2)
15-19: Missing perf.Track call in SetAtmosConfig.Per coding guidelines, all public functions should include
defer perf.Track(...)(). Since this is a simple setter andatmosConfigPtrisn't available yet, you could usenilfor the config parameter.🔎 Suggested fix
+import ( + "github.com/cloudposse/atmos/pkg/perf" + ... +) // SetAtmosConfig sets the Atmos configuration for the workdir command. // This is called from root.go after atmosConfig is initialized. func SetAtmosConfig(config *schema.AtmosConfiguration) { + defer perf.Track(nil, "workdir.SetAtmosConfig")() + atmosConfigPtr = config }
36-39: Missing perf.Track call in GetWorkdirCommand.Same as above—public function should have performance tracking.
🔎 Suggested fix
// GetWorkdirCommand returns the workdir command for parent registration. func GetWorkdirCommand() *cobra.Command { + defer perf.Track(nil, "workdir.GetWorkdirCommand")() + return workdirCmd }cmd/terraform/workdir/workdir_show.go (1)
100-107: Consider extracting the StyleFunc for reuse.This styling pattern (cyan first column, padding) appears in multiple workdir commands. Could be a shared helper, but that's optional polish.
cmd/terraform/workdir/workdir_describe_test.go (1)
24-32: Consider expanding minimal structural tests.These tests only assert non-nil but don't validate actual behavior. For instance,
TestDescribeCmd_Argscould verifycobra.ExactArgs(1)is configured (which you already do inTestDescribeCmd_ArgsValidation). These are fine as-is since they provide basic smoke coverage.pkg/provisioner/workdir/clean.go (1)
94-102: Silent no-op when no options provided.When
opts.Allis false andopts.Componentis empty, the function returnsnilwithout any action or feedback. This is reasonable behavior, though a debug log might help troubleshooting.pkg/provisioner/workdir/fs.go (1)
46-52: Minor edge case in Exists.
Existsreturnsfalsefor any error, not just "not exists". Permission errors would also returnfalse. This is typically fine for the workdir use case, but worth noting.
|
Warning Release Documentation RequiredThis PR is labeled
|
|
These changes were released in v1.203.0-rc.3. |
|
Closes #225 |
what
WorkdirProvisioneratmos terraform workdirCLI commands: list, describe, show, cleanwhy
Multiple component instances targeting the same component caused conflicts due to shared working directories. Workdir provisioning isolates each component execution to a dedicated directory (
.workdir/terraform/<stack>-<component>/), enabling parallel execution and preventing state/artifact interference.references
Summary by CodeRabbit
New Features
Documentation
Schema
Tests
✏️ Tip: You can customize this high-level summary in your review settings.