Allow running persistent run hooks of all parents (#2044)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Currently, only one of the persistent pre-runs and post-runs is executed. It is always the first one found in the parents chain, starting at this command. Expected behavior is to execute all parents' persistent pre-runs and post-runs. Dependent projects implemented various workarounds for this: - manually building persistent hook chains (in every hook). - applying some kind of monkey-patching on top of Cobra. This change eliminates the necessity for such workarounds by allowing to set a global variable EnableTraverseRunHooks. Tickets: - https://github.com/spf13/cobra/issues/216 - https://github.com/spf13/cobra/issues/252
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Signed-off-by: Volodymyr Khoroz <volodymyr.khoroz@foundries.io>
Diff stats
4 files+83 added−66 removed
- other:+83 added−66 removed
Provenance
- Commit
4cafa37- Tree
b0313b2- Author
vkhoroz <vkhoroz@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
5c962a2
4 files changed+83 added−66 removed
modified:site/content/user_guide.md+4 added
685 unmodified lines686 Inside subCmd PostRun with args: [arg1 arg2]687 Inside subCmd PersistentPostRun with args: [arg1 arg2]688 ```689 690+By default, only the first persistent hook found in the command chain is executed.691+That is why in the above output, the `rootCmd PersistentPostRun` was not called for a child command.692+Set `EnableTraverseRunHooks` global variable to `true` if you want to execute all parents' persistent hooks.693+694 ## Suggestions when "unknown command" happens695 696 Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behave similarly to the `git` command when a typo happens. For example:697 53 unmodified linesmodified:cobra.go+8 added-3 removed
41 unmodified lines42 var initializers []func()43 var finalizers []func()44 45 const (46- defaultPrefixMatching = false47- defaultCommandSorting = true48- defaultCaseInsensitive = false46+ defaultPrefixMatching = false47+ defaultCommandSorting = true48+ defaultCaseInsensitive = false49+ defaultTraverseRunHooks = false50 )51 52 // EnablePrefixMatching allows setting automatic prefix matching. Automatic prefix matching can be a dangerous thing53 // to automatically enable in CLI tools.6 unmodified lines60 61 // EnableCaseInsensitive allows case-insensitive commands names. (case sensitive by default)62 var EnableCaseInsensitive = defaultCaseInsensitive63 64+// EnableTraverseRunHooks executes persistent pre-run and post-run hooks from all parents.65+// By default this is disabled, which means only the first run hook to be found is executed.66+var EnableTraverseRunHooks = defaultTraverseRunHooks67+68 // MousetrapHelpText enables an information splash screen on Windows69 // if the CLI is started from explorer.exe.70 // To disable the mousetrap, just set this variable to blank string ("").71 // Works only on Microsoft Windows.173 unmodified linesmodified:command_test.go+47 added-59 removed
1528 unmodified lines1529 }1530 }1531 1532 func TestPersistentHooks(t *testing.T) {1533- var (1534- parentPersPreArgs string1535- parentPreArgs string1536- parentRunArgs string1537- parentPostArgs string1538- parentPersPostArgs string1539- )1533+ EnableTraverseRunHooks = true1534+ testPersistentHooks(t, []string{1535+ "parent PersistentPreRun",1536+ "child PersistentPreRun",1537+ "child PreRun",1538+ "child Run",1539+ "child PostRun",1540+ "child PersistentPostRun",1541+ "parent PersistentPostRun",1542+ })1543 1541- var (1542- childPersPreArgs string1543- childPreArgs string1544- childRunArgs string1545- childPostArgs string1546- childPersPostArgs string1547- )1544+ EnableTraverseRunHooks = false1545+ testPersistentHooks(t, []string{1546+ "child PersistentPreRun",1547+ "child PreRun",1548+ "child Run",1549+ "child PostRun",1550+ "child PersistentPostRun",1551+ })1552+}1553 1554+func testPersistentHooks(t *testing.T, expectedHookRunOrder []string) {1555+ var hookRunOrder []string1556+1557+ validateHook := func(args []string, hookName string) {1558+ hookRunOrder = append(hookRunOrder, hookName)1559+ got := strings.Join(args, " ")1560+ if onetwo != got {1561+ t.Errorf("Expected %s %q, got %q", hookName, onetwo, got)1562+ }1563+ }1564+1565 parentCmd := &Command{1566 Use: "parent",1567 PersistentPreRun: func(_ *Command, args []string) {1552- parentPersPreArgs = strings.Join(args, " ")1568+ validateHook(args, "parent PersistentPreRun")1569 },1570 PreRun: func(_ *Command, args []string) {1555- parentPreArgs = strings.Join(args, " ")1571+ validateHook(args, "parent PreRun")1572 },1573 Run: func(_ *Command, args []string) {1558- parentRunArgs = strings.Join(args, " ")1574+ validateHook(args, "parent Run")1575 },1576 PostRun: func(_ *Command, args []string) {1561- parentPostArgs = strings.Join(args, " ")1577+ validateHook(args, "parent PostRun")1578 },1579 PersistentPostRun: func(_ *Command, args []string) {1564- parentPersPostArgs = strings.Join(args, " ")1580+ validateHook(args, "parent PersistentPostRun")1581 },1582 }1583 1584 childCmd := &Command{1585 Use: "child",1586 PersistentPreRun: func(_ *Command, args []string) {1571- childPersPreArgs = strings.Join(args, " ")1587+ validateHook(args, "child PersistentPreRun")1588 },1589 PreRun: func(_ *Command, args []string) {1574- childPreArgs = strings.Join(args, " ")1590+ validateHook(args, "child PreRun")1591 },1592 Run: func(_ *Command, args []string) {1577- childRunArgs = strings.Join(args, " ")1593+ validateHook(args, "child Run")1594 },1595 PostRun: func(_ *Command, args []string) {1580- childPostArgs = strings.Join(args, " ")1596+ validateHook(args, "child PostRun")1597 },1598 PersistentPostRun: func(_ *Command, args []string) {1583- childPersPostArgs = strings.Join(args, " ")1599+ validateHook(args, "child PersistentPostRun")1600 },1601 }1602 parentCmd.AddCommand(childCmd)1603 4 unmodified lines1608 if err != nil {1609 t.Errorf("Unexpected error: %v", err)1610 }1611 1596- for _, v := range []struct {1597- name string1598- got string1599- }{1600- // TODO: currently PersistentPreRun* defined in parent does not1601- // run if the matching child subcommand has PersistentPreRun.1602- // If the behavior changes (https://github.com/spf13/cobra/issues/252)1603- // this test must be fixed.1604- {"parentPersPreArgs", parentPersPreArgs},1605- {"parentPreArgs", parentPreArgs},1606- {"parentRunArgs", parentRunArgs},1607- {"parentPostArgs", parentPostArgs},1608- // TODO: currently PersistentPostRun* defined in parent does not1609- // run if the matching child subcommand has PersistentPostRun.1610- // If the behavior changes (https://github.com/spf13/cobra/issues/252)1611- // this test must be fixed.1612- {"parentPersPostArgs", parentPersPostArgs},1613- } {1614- if v.got != "" {1615- t.Errorf("Expected blank %s, got %q", v.name, v.got)1612+ for idx, exp := range expectedHookRunOrder {1613+ if len(hookRunOrder) > idx {1614+ if act := hookRunOrder[idx]; act != exp {1615+ t.Errorf("Expected %q at %d, got %q", exp, idx, act)1616+ }1617+ } else {1618+ t.Errorf("Expected %q at %d, got nothing", exp, idx)1619 }1620 }1618-1619- for _, v := range []struct {1620- name string1621- got string1622- }{1623- {"childPersPreArgs", childPersPreArgs},1624- {"childPreArgs", childPreArgs},1625- {"childRunArgs", childRunArgs},1626- {"childPostArgs", childPostArgs},1627- {"childPersPostArgs", childPersPostArgs},1628- } {1629- if v.got != onetwo {1630- t.Errorf("Expected %s %q, got %q", v.name, onetwo, v.got)1631- }1632- }1621 }1622 1623 // Related to https://github.com/spf13/cobra/issues/521.1624 func TestGlobalNormFuncPropagation(t *testing.T) {1134 unmodified linesmodified:command.go+24 added-4 removed
932 unmodified lines933 if err := c.ValidateArgs(argWoFlags); err != nil {934 return err935 }936 937+ parents := make([]*Command, 0, 5)938 for p := c; p != nil; p = p.Parent() {939+ if EnableTraverseRunHooks {940+ // When EnableTraverseRunHooks is set:941+ // - Execute all persistent pre-runs from the root parent till this command.942+ // - Execute all persistent post-runs from this command till the root parent.943+ parents = append([]*Command{p}, parents...)944+ } else {945+ // Otherwise, execute only the first found persistent hook.946+ parents = append(parents, p)947+ }948+ }949+ for _, p := range parents {950 if p.PersistentPreRunE != nil {951 if err := p.PersistentPreRunE(c, argWoFlags); err != nil {952 return err953 }954+ if !EnableTraverseRunHooks {942- break955+ break956+ }957 } else if p.PersistentPreRun != nil {958 p.PersistentPreRun(c, argWoFlags)959+ if !EnableTraverseRunHooks {945- break960+ break961+ }962 }963 }964 if c.PreRunE != nil {965 if err := c.PreRunE(c, argWoFlags); err != nil {28 unmodified lines994 if p.PersistentPostRunE != nil {995 if err := p.PersistentPostRunE(c, argWoFlags); err != nil {996 return err997 }998+ if !EnableTraverseRunHooks {982- break999+ break1000+ }1001 } else if p.PersistentPostRun != nil {1002 p.PersistentPostRun(c, argWoFlags)1003+ if !EnableTraverseRunHooks {985- break1004+ break1005+ }1006 }1007 }1008 1009 return nil869 unmodified lines