Skip to content
Myr

Add `CalledAs` method to cobra.Command (w/ tests) (#567)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Add `CalledAs` method to Command (w/ tests) The `CalledAs` method returns the name of the command or alias that invoked the command -- as long as the command was actually invoked. Otherwise, it returns the empty string. The opens up possibilies for commands to behave differently based on which alias invoked the command (in the same vein as Linux programs which adjust their behavior based on the value of argv[0]). * Fixed formatting

authored by Tim Peoples · committed by Eric Paris · parent 9979838 · Browse files · 2 files+86 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+86 added−0 removed

  • other:+86 added−0 removed

2 files+86 added−0 removed

modified:command_test.go+63 added
1561 unmodified lines
1562 if originalName == c.Name() || c.Name() != "changedName" {1563 t.Error("c.Name() should be updated on changed c.Use")1564 }1565}15661567type calledAsTestcase struct {1568 args []string1569 call string1570 want string1571 epm bool1572 tc bool1573}15741575func (tc *calledAsTestcase) test(t *testing.T) {1576 defer func(ov bool) { EnablePrefixMatching = ov }(EnablePrefixMatching)1577 EnablePrefixMatching = tc.epm15781579 var called *Command1580 run := func(c *Command, _ []string) { t.Logf("called: %q", c.Name()); called = c }15811582 parent := &Command{Use: "parent", Run: run}1583 child1 := &Command{Use: "child1", Run: run, Aliases: []string{"this"}}1584 child2 := &Command{Use: "child2", Run: run, Aliases: []string{"that"}}15851586 parent.AddCommand(child1)1587 parent.AddCommand(child2)1588 parent.SetArgs(tc.args)15891590 output := new(bytes.Buffer)1591 parent.SetOutput(output)15921593 parent.Execute()15941595 if called == nil {1596 if tc.call != "" {1597 t.Errorf("missing expected call to command: %s", tc.call)1598 }1599 return1600 }16011602 if called.Name() != tc.call {1603 t.Errorf("called command == %q; Wanted %q", called.Name(), tc.call)1604 } else if got := called.CalledAs(); got != tc.want {1605 t.Errorf("%s.CalledAs() == %q; Wanted: %q", tc.call, got, tc.want)1606 }1607}16081609func TestCalledAs(t *testing.T) {1610 tests := map[string]calledAsTestcase{1611 "find/no-args": {nil, "parent", "parent", false, false},1612 "find/real-name": {[]string{"child1"}, "child1", "child1", false, false},1613 "find/full-alias": {[]string{"that"}, "child2", "that", false, false},1614 "find/part-no-prefix": {[]string{"thi"}, "", "", false, false},1615 "find/part-alias": {[]string{"thi"}, "child1", "this", true, false},1616 "find/conflict": {[]string{"th"}, "", "", true, false},1617 "traverse/no-args": {nil, "parent", "parent", false, true},1618 "traverse/real-name": {[]string{"child1"}, "child1", "child1", false, true},1619 "traverse/full-alias": {[]string{"that"}, "child2", "that", false, true},1620 "traverse/part-no-prefix": {[]string{"thi"}, "", "", false, true},1621 "traverse/part-alias": {[]string{"thi"}, "child1", "this", true, true},1622 "traverse/conflict": {[]string{"th"}, "", "", true, true},1623 }16241625 for name, tc := range tests {1626 t.Run(name, tc.test)1627 }1628}
modified:command.go+23 added
145 unmodified lines
146 commandsMaxCommandPathLen int147 commandsMaxNameLen int148 // commandsAreSorted defines, if command slice are sorted or not.149 commandsAreSorted bool150 // commandCalledAs is the name or alias value used to call this command.151 commandCalledAs struct {152 name string153 called bool154 }155156 // args is actual args parsed from flags.157 args []string158 // flagErrorBuf contains all error messages from pflag.
402 unmodified lines
561func (c *Command) findNext(next string) *Command {562 matches := make([]*Command, 0)563 for _, cmd := range c.commands {564 if cmd.Name() == next || cmd.HasAlias(next) {565 cmd.commandCalledAs.name = next566 return cmd567 }568 if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) {569 matches = append(matches, cmd)
2 unmodified lines
572573 if len(matches) == 1 {574 return matches[0]575 }576577 return nil578}579580// Traverse the command tree to find the command, and parse args for
253 unmodified lines
834 }835 return c, err836 }837838 cmd.commandCalledAs.called = true839 if cmd.commandCalledAs.name == "" {840 cmd.commandCalledAs.name = cmd.Name()841 }842843 err = cmd.execute(flags)844 if err != nil {845 // Always show help if requested, even if SilenceErrors is in846 // effect
299 unmodified lines
1146 }1147 return false1148}11491150// CalledAs returns the command name or alias that was used to invoke1151// this command or an empty string if the command has not been called.1152func (c *Command) CalledAs() string {1153 if c.commandCalledAs.called {1154 return c.commandCalledAs.name1155 }1156 return ""1157}11581159// hasNameOrAliasPrefix returns true if the Name or any of aliases start1160// with prefix1161func (c *Command) hasNameOrAliasPrefix(prefix string) bool {1162 if strings.HasPrefix(c.Name(), prefix) {1163 c.commandCalledAs.name = c.Name()1164 return true1165 }1166 for _, alias := range c.Aliases {1167 if strings.HasPrefix(alias, prefix) {1168 c.commandCalledAs.name = alias1169 return true1170 }1171 }1172 return false
332 unmodified lines