Skip to content

Commit ab5cadc

Browse files
authored
Allow to reset the templates to the default (#2229)
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 <[email protected]>
1 parent 4ba5566 commit ab5cadc

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

command.go

+12
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,10 @@ func (c *Command) SetUsageFunc(f func(*Command) error) {
315315

316316
// SetUsageTemplate sets usage template. Can be defined by Application.
317317
func (c *Command) SetUsageTemplate(s string) {
318+
if s == "" {
319+
c.usageTemplate = nil
320+
return
321+
}
318322
c.usageTemplate = tmpl(s)
319323
}
320324

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

352356
// SetHelpTemplate sets help template to be used. Application can use it to set custom template.
353357
func (c *Command) SetHelpTemplate(s string) {
358+
if s == "" {
359+
c.helpTemplate = nil
360+
return
361+
}
354362
c.helpTemplate = tmpl(s)
355363
}
356364

357365
// SetVersionTemplate sets version template to be used. Application can use it to set custom template.
358366
func (c *Command) SetVersionTemplate(s string) {
367+
if s == "" {
368+
c.versionTemplate = nil
369+
return
370+
}
359371
c.versionTemplate = tmpl(s)
360372
}
361373

command_test.go

+24
Original file line numberDiff line numberDiff line change
@@ -1047,6 +1047,18 @@ func TestSetHelpTemplate(t *testing.T) {
10471047
if got != expected {
10481048
t.Errorf("Expected %q, got %q", expected, got)
10491049
}
1050+
1051+
// Reset the root command help template and make sure
1052+
// it falls back to the default
1053+
rootCmd.SetHelpTemplate("")
1054+
got, err = executeCommand(rootCmd, "--help")
1055+
if err != nil {
1056+
t.Errorf("Unexpected error: %v", err)
1057+
}
1058+
1059+
if !strings.Contains(got, "Usage:") {
1060+
t.Errorf("Expected to contain %q, got %q", "Usage:", got)
1061+
}
10501062
}
10511063

10521064
func TestHelpFlagExecuted(t *testing.T) {
@@ -1139,6 +1151,18 @@ func TestSetUsageTemplate(t *testing.T) {
11391151

11401152
expected = "WORKS " + childCmd.UseLine()
11411153
checkStringContains(t, got, expected)
1154+
1155+
// Reset the root command usage template and make sure
1156+
// it falls back to the default
1157+
rootCmd.SetUsageTemplate("")
1158+
got, err = executeCommand(rootCmd, "--invalid")
1159+
if err == nil {
1160+
t.Errorf("Expected error but did not get one")
1161+
}
1162+
1163+
if !strings.Contains(got, "Usage:") {
1164+
t.Errorf("Expected to contain %q, got %q", "Usage:", got)
1165+
}
11421166
}
11431167

11441168
func TestVersionFlagExecuted(t *testing.T) {

0 commit comments

Comments
 (0)