Skip to content

use correct context in After function with subcommand#2108

Merged
dearchap merged 2 commits intourfave:mainfrom
bystones:fix_2098
Apr 24, 2025
Merged

use correct context in After function with subcommand#2108
dearchap merged 2 commits intourfave:mainfrom
bystones:fix_2098

Conversation

@bystones
Copy link
Contributor

What type of PR is this?

bugfix

What this PR does / why we need it:

Fixes #2098

Special notes for your reviewer:

This still passes with the new test from #2107.
Instead of returning the context we could also use a pointer to a context, but that looks very strange.

Testing

Added unit test.

Release Notes

Command.After now uses the correct context (as set by Command.Before) even when subcommands are involved

@dearchap
Copy link
Contributor

@bystones This is a really elegant solution. Thanks. Here is a sequence I want to test

  1. Main command -> run
  2. Main command -> Before
  3. subcommand -> run
  4. subcommand -> Before adds key
  5. subcommnd -> Action has key
  6. subcommand -> After has key
  7. Main command -> After : does this have key ? Do we want to have it ?

When adding values to a context in a Before function that value is not
present in the After function when a subcommand was run. Without the
subcommand the value is present.

This fixes that be returning the new context from the subcommand and
changing the context in the calling function. Defer'd function now pick
up the new context.

Fixes urfave#2098
@bystones
Copy link
Contributor Author

@dearchap I changed the test to check the values in the context at more places, hopefully that covers what you have in mind.

Main command -> After : does this have key ? Do we want to have it ?

Generally speaking my answer would be that the context values added in a child should not go upwards to the parent. But this is already happening with Flag.Actions, see the newly added test TestCommand_Run_FlagActionContext (which passes with and without the bugfix). So we should either declare that as a bug as well or allow the same thing with Command.After.

@bystones bystones requested a review from dearchap April 23, 2025 21:11
@bystones
Copy link
Contributor Author

Added a new commit with your suggested changes.

@dearchap dearchap merged commit c6c5804 into urfave:main Apr 24, 2025
10 checks passed
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.

v3: context value added in Before missing in After when subcommands are involved

2 participants