Skip to content

Commit 3f5c111

Browse files
authored
refactor(env): Add a WithCancel option to the Env context (#43)
1 parent eaf900a commit 3f5c111

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

internal/app/azldev/env.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,20 @@ func (env *Env) Context() context.Context {
211211
return env.ctx
212212
}
213213

214+
// WithCancel returns a shallow copy of the [Env] with a child [context.Context]
215+
// derived from [context.WithCancel]. The returned [Env] shares all features
216+
// (FS, config, event listener, cmd factory, etc.) with the original but has an
217+
// independently cancellable context. The caller must call the returned
218+
// [context.CancelFunc] when done. Useful when performing parallel operations
219+
// that benefit from early cancellation on error.
220+
func (env *Env) WithCancel() (*Env, context.CancelFunc) {
221+
childCtx, cancel := context.WithCancel(env.ctx)
222+
childEnv := *env
223+
childEnv.ctx = childCtx
224+
225+
return &childEnv, cancel
226+
}
227+
214228
// ConfirmAutoResolution prompts the user to confirm auto-resolution of a problem. The provided
215229
// text is displayed to the user as explanation.
216230
func (env *Env) ConfirmAutoResolution(text string) bool {

internal/app/azldev/env_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,3 +115,20 @@ func TestEnvConstructionTime(t *testing.T) {
115115
// Make sure it appears to be a valid time that's before or at *now*.
116116
assert.LessOrEqual(t, testEnv.Env.ConstructionTime(), time.Now())
117117
}
118+
119+
func TestEnvWithCancel(t *testing.T) {
120+
testEnv := testutils.NewTestEnv(t)
121+
original := testEnv.Env
122+
123+
child, cancel := original.WithCancel()
124+
defer cancel()
125+
126+
// Child should share config and project dir with original.
127+
assert.Equal(t, original.ProjectDir(), child.ProjectDir())
128+
assert.Equal(t, original.Config(), child.Config())
129+
130+
// Cancelling the child should not cancel the original.
131+
cancel()
132+
require.Error(t, child.Err())
133+
assert.NoError(t, original.Err())
134+
}

0 commit comments

Comments
 (0)