Skip to content

Commit 40909df

Browse files
fix: use root Writer in completion subcommand and add write error test
The completion subcommand was using cmd.Writer which defaults to os.Stdout instead of the root command's configured Writer. Also fix inverted assertion in TestCompletionShell and add TestCompletionShellWriteError to cover the Writer error path. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent 018710f commit 40909df

File tree

2 files changed

+31
-5
lines changed

2 files changed

+31
-5
lines changed

completion.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ func buildShellCompletionSubcommand(shell string, render renderCompletion, appNa
8282
if err != nil {
8383
return Exit(err, 1)
8484
}
85-
_, err = cmd.Writer.Write([]byte(completionScript))
85+
_, err = cmd.Root().Writer.Write([]byte(completionScript))
8686
if err != nil {
8787
return Exit(err, 1)
8888
}

completion_test.go

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -110,10 +110,7 @@ func TestCompletionShell(t *testing.T) {
110110
r := require.New(t)
111111

112112
r.NoError(cmd.Run(buildTestContext(t), []string{"foo", completionCommandName, k}))
113-
r.Containsf(
114-
k, out.String(),
115-
"Expected output to contain shell name %[1]q", k,
116-
)
113+
r.NotEmpty(out.String(), "Expected non-empty completion output for shell %q", k)
117114
})
118115
}
119116
}
@@ -273,3 +270,32 @@ func TestCompletionShellRenderError(t *testing.T) {
273270
err := cmd.Run(buildTestContext(t), []string{"foo", completionCommandName, unknownShellName})
274271
assert.ErrorContains(t, err, "cant do completion")
275272
}
273+
274+
type mockWriter struct {
275+
err error
276+
}
277+
278+
func (mw *mockWriter) Write(p []byte) (int, error) {
279+
if mw.err != nil {
280+
return 0, mw.err
281+
}
282+
return len(p), nil
283+
}
284+
285+
func TestCompletionShellWriteError(t *testing.T) {
286+
shellName := "mock-shell"
287+
shellCompletions[shellName] = func(c *Command, appName string) (string, error) {
288+
return "something", nil
289+
}
290+
defer func() {
291+
delete(shellCompletions, shellName)
292+
}()
293+
294+
cmd := &Command{
295+
EnableShellCompletion: true,
296+
Writer: &mockWriter{err: fmt.Errorf("writer error")},
297+
}
298+
299+
err := cmd.Run(buildTestContext(t), []string{"foo", completionCommandName, shellName})
300+
assert.ErrorContains(t, err, "writer error")
301+
}

0 commit comments

Comments
 (0)