Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions completions.go
Original file line number Diff line number Diff line change
Expand Up @@ -289,8 +289,11 @@ func (c *Command) initCompleteCmd(args []string) {
fmt.Fprintf(out, ":%d\n", directive)

// Print some helpful info to stderr for the user to understand.
// Output from stderr must be ignored by the completion script.
fmt.Fprintf(finalCmd.ErrOrStderr(), "Completion ended with directive: %s\n", directive.string())
// Output from stderr must be ignored by the completion script,
// so skip it when stderr was redirected to the stdout the script reads.
if errOut := finalCmd.ErrOrStderr(); errOut != os.Stdout {
fmt.Fprintf(errOut, "Completion ended with directive: %s\n", directive.string())
}
},
}
c.AddCommand(completeCmd)
Expand Down
44 changes: 44 additions & 0 deletions completions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4127,3 +4127,47 @@ func TestCompletionDoesNotMutateOsArgs(t *testing.T) {
t.Errorf("os.Args[2] was mutated: expected %q, got %q", "x", os.Args[2])
}
}

func TestCompletionInfoNotPrintedWhenStderrIsStdout(t *testing.T) {
rootCmd := &Command{
Use: "root",
ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
return []string{"one", "two"}, ShellCompDirectiveDefault
},
Run: emptyRun,
}

reader, writer, err := os.Pipe()
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
defer reader.Close()
defer writer.Close()
realStdout := os.Stdout
os.Stdout = writer
defer func() { os.Stdout = realStdout }()

// Send stderr to the same stdout the shell script reads, as in issue #1287.
rootCmd.SetOut(os.Stdout)
rootCmd.SetErr(os.Stdout)
rootCmd.SetArgs([]string{ShellCompNoDescRequestCmd, ""})
if err := rootCmd.Execute(); err != nil {
t.Fatalf("Unexpected error: %v", err)
}
writer.Close()

output := new(bytes.Buffer)
if _, err := output.ReadFrom(reader); err != nil {
t.Fatalf("Unexpected error: %v", err)
}

expected := strings.Join([]string{
"one",
"two",
":0",
}, "\n") + "\n"

if output.String() != expected {
t.Errorf("expected: %q, got: %q", expected, output.String())
}
}
Loading