Skip to content

Commit

Permalink
Allow to reset the templates to the default (#2229)
Browse files Browse the repository at this point in the history
Follow-up to #1956.

This commit allows a program to reset any of the tree templates to their
default behaviour, as it was possible to do before the change of #1956.

Signed-off-by: Marc Khouzam <marc.khouzam@gmail.com>
  • Loading branch information
marckhouzam authored Feb 6, 2025
1 parent 4ba5566 commit ab5cadc
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
12 changes: 12 additions & 0 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,10 @@ func (c *Command) SetUsageFunc(f func(*Command) error) {

// SetUsageTemplate sets usage template. Can be defined by Application.
func (c *Command) SetUsageTemplate(s string) {
if s == "" {
c.usageTemplate = nil
return
}
c.usageTemplate = tmpl(s)
}

Expand Down Expand Up @@ -351,11 +355,19 @@ func (c *Command) SetCompletionCommandGroupID(groupID string) {

// SetHelpTemplate sets help template to be used. Application can use it to set custom template.
func (c *Command) SetHelpTemplate(s string) {
if s == "" {
c.helpTemplate = nil
return
}
c.helpTemplate = tmpl(s)
}

// SetVersionTemplate sets version template to be used. Application can use it to set custom template.
func (c *Command) SetVersionTemplate(s string) {
if s == "" {
c.versionTemplate = nil
return
}
c.versionTemplate = tmpl(s)
}

Expand Down
24 changes: 24 additions & 0 deletions command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1047,6 +1047,18 @@ func TestSetHelpTemplate(t *testing.T) {
if got != expected {
t.Errorf("Expected %q, got %q", expected, got)
}

// Reset the root command help template and make sure
// it falls back to the default
rootCmd.SetHelpTemplate("")
got, err = executeCommand(rootCmd, "--help")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}

if !strings.Contains(got, "Usage:") {
t.Errorf("Expected to contain %q, got %q", "Usage:", got)
}
}

func TestHelpFlagExecuted(t *testing.T) {
Expand Down Expand Up @@ -1139,6 +1151,18 @@ func TestSetUsageTemplate(t *testing.T) {

expected = "WORKS " + childCmd.UseLine()
checkStringContains(t, got, expected)

// Reset the root command usage template and make sure
// it falls back to the default
rootCmd.SetUsageTemplate("")
got, err = executeCommand(rootCmd, "--invalid")
if err == nil {
t.Errorf("Expected error but did not get one")
}

if !strings.Contains(got, "Usage:") {
t.Errorf("Expected to contain %q, got %q", "Usage:", got)
}
}

func TestVersionFlagExecuted(t *testing.T) {
Expand Down

0 comments on commit ab5cadc

Please sign in to comment.