Skip to content

Commit aaeb67e

Browse files
committed
chore: Move template functions closer to usage
1 parent 32951b3 commit aaeb67e

File tree

1 file changed

+27
-20
lines changed

1 file changed

+27
-20
lines changed

cli/root.go

Lines changed: 27 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"os"
77
"strconv"
88
"strings"
9+
"text/template"
910
"time"
1011

1112
"golang.org/x/xerrors"
@@ -52,26 +53,8 @@ var (
5253
)
5354

5455
func init() {
55-
// Customizes the color of headings to make subcommands more visually
56-
// appealing.
57-
header := cliui.Styles.Placeholder
58-
cobra.AddTemplateFunc("usageHeader", func(s string) string {
59-
return header.Render(s)
60-
})
61-
cobra.AddTemplateFunc("isWorkspaceCommand", isWorkspaceCommand)
62-
}
63-
64-
func isWorkspaceCommand(cmd *cobra.Command) bool {
65-
if _, ok := cmd.Annotations["workspaces"]; ok {
66-
return true
67-
}
68-
var ws bool
69-
cmd.VisitParents(func(cmd *cobra.Command) {
70-
if _, ok := cmd.Annotations["workspaces"]; ok {
71-
ws = true
72-
}
73-
})
74-
return ws
56+
// Set cobra template functions in init to avoid conflicts in tests.
57+
cobra.AddTemplateFuncs(templateFunctions)
7558
}
7659

7760
func Root() *cobra.Command {
@@ -325,6 +308,30 @@ func isTTYOut(cmd *cobra.Command) bool {
325308
return isatty.IsTerminal(file.Fd())
326309
}
327310

311+
var templateFunctions = template.FuncMap{
312+
"usageHeader": usageHeader,
313+
"isWorkspaceCommand": isWorkspaceCommand,
314+
}
315+
316+
func usageHeader(s string) string {
317+
// Customizes the color of headings to make subcommands more visually
318+
// appealing.
319+
return cliui.Styles.Placeholder.Render(s)
320+
}
321+
322+
func isWorkspaceCommand(cmd *cobra.Command) bool {
323+
if _, ok := cmd.Annotations["workspaces"]; ok {
324+
return true
325+
}
326+
var ws bool
327+
cmd.VisitParents(func(cmd *cobra.Command) {
328+
if _, ok := cmd.Annotations["workspaces"]; ok {
329+
ws = true
330+
}
331+
})
332+
return ws
333+
}
334+
328335
func usageTemplate() string {
329336
// usageHeader is defined in init().
330337
return `{{usageHeader "Usage:"}}

0 commit comments

Comments
 (0)