Skip to content

inherit Reader/Writer/ErrWriter from parent on subcommand setup#2329

Open
c-tonneslan wants to merge 1 commit into
urfave:mainfrom
c-tonneslan:fix/inherit-parent-writer-to-subcommand
Open

inherit Reader/Writer/ErrWriter from parent on subcommand setup#2329
c-tonneslan wants to merge 1 commit into
urfave:mainfrom
c-tonneslan:fix/inherit-parent-writer-to-subcommand

Conversation

@c-tonneslan
Copy link
Copy Markdown
Contributor

Fixes #2325.

`setupDefaults` runs once per command. The first time it runs for a subcommand it would observe a nil `Writer` and pin it to `os.Stdout`, which meant a `Writer` set on the root never reached the subcommand's `Action` via `c.Writer`. Same problem for `Reader` and `ErrWriter`.

```go
root := &cli.Command{
Name: "demo",
Writer: &buf,
Commands: []*cli.Command{{
Name: "sub",
Action: func(_ context.Context, c *cli.Command) error {
fmt.Fprintln(c.Writer, "from sub") // wrote to os.Stdout, not buf
return nil
},
}},
}
```

Walk to `cmd.parent` before defaulting: if the parent already has a non-nil `Reader` / `Writer` / `ErrWriter`, inherit it; otherwise fall back to the `os.*` defaults exactly as before. Root commands (no parent) keep their existing behavior.

Added `TestSubcommandInheritsRootWriters` to lock in the regression for both Writer and ErrWriter.

setupDefaults runs once per command. The first time it runs for a
subcommand it would observe a nil Writer and pin it to os.Stdout,
which meant a Writer set on the root never reached the subcommand's
Action via c.Writer. Same problem for Reader and ErrWriter.

Walk to cmd.parent before defaulting: if the parent already has a
non-nil Reader/Writer/ErrWriter, inherit it; otherwise fall back to
the os.* defaults exactly as before. Root commands (cmd.parent == nil)
keep their existing behavior.

Fixes urfave#2325.

Signed-off-by: Charlie Tonneslan <cst0520@gmail.com>
@c-tonneslan c-tonneslan requested a review from a team as a code owner May 16, 2026 19:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Root Command.Writer doesn't propagate to subcommand Actions

1 participant