Skip to content

Commit f6f38ed

Browse files
authored
Merge pull request #2441 from kolyshkin/no-template-tag
Add urfave_cli_no_template build tag Tested-by: Eng Zer Jun <[email protected]> Reviewed-by: Eng Zer Jun <[email protected]>
2 parents 925b1e3 + 2c876a1 commit f6f38ed

19 files changed

Lines changed: 1605 additions & 249 deletions

‎.github/workflows/test.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ jobs:
4141
run: make lint
4242

4343
- run: make vet
44+
- run: make test GFLAGS='--tags urfave_cli_no_template'
4445
- run: make test
4546
- run: make check-binary-size
4647

‎README.md‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,27 @@ command line tools in Go featuring:
2828
See the hosted documentation website at <https://cli.urfave.org>. Contents of
2929
this website are built from the [`./docs`](./docs) directory.
3030

31+
## Build tags
32+
33+
You can use the following build tags:
34+
35+
### `urfave_cli_no_template`
36+
37+
When set, the default help and fish completion are rendered without using
38+
`text/template`, which makes the Go linker disable dead code elimination (see
39+
[Binary Size](https://cli.urfave.org/v3/binary-size/#urfave_cli_no_template)).
40+
The output is the same, but help templates can not be customized:
41+
42+
- `RootCommandHelpTemplate`, `CommandHelpTemplate`, `SubcommandHelpTemplate`
43+
and `FishCompletionTemplate` are constants;
44+
- if the default help printer is used with a custom template (such as
45+
`CustomRootCommandHelpTemplate` or `CustomHelpTemplate`), it panics;
46+
- custom template functions other than `wrap` and `wrapAt` are ignored.
47+
48+
Replacing `cli.HelpPrinter` works as usual, except it receives `"root"`,
49+
`"command"` or `"subcommand"` as `templ` instead of the default template text
50+
(a custom template is passed as is).
51+
3152
## Support
3253

3354
Check the [Q&A discussions]. If you don't find answer to your question, [create

‎dce_test.go‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package cli
2+
3+
import (
4+
"os/exec"
5+
"path/filepath"
6+
"strings"
7+
"testing"
8+
9+
"github.com/stretchr/testify/assert"
10+
"github.com/stretchr/testify/require"
11+
)
12+
13+
// reflectMethodSymbols builds examples/example-cli with the given tags,
14+
// and returns the number of reachable symbols using reflect.Method or
15+
// reflect.MethodByName with a non-constant argument. If there are any,
16+
// the linker's dead code elimination of exported methods is disabled.
17+
func reflectMethodSymbols(t *testing.T, tags string) int {
18+
t.Helper()
19+
out := filepath.Join(t.TempDir(), "example-cli")
20+
cmd := exec.Command("go", "build", "-tags", tags, "-ldflags=-dumpdep", "-o", out, "./examples/example-cli")
21+
deps, err := cmd.CombinedOutput()
22+
require.NoError(t, err, string(deps))
23+
return strings.Count(string(deps), "<ReflectMethod>")
24+
}
25+
26+
// Using text/template (or anything else calling reflect.Method or
27+
// reflect.MethodByName with a non-constant argument) disables linker's
28+
// dead code elimination of exported methods. Make sure this does not
29+
// happen with urfave_cli_no_template tag.
30+
func TestNoTemplateTagDCE(t *testing.T) {
31+
// Sanity check: without the tag, DCE is disabled by text/template.
32+
assert.NotZero(t, reflectMethodSymbols(t, ""))
33+
34+
assert.Zero(t, reflectMethodSymbols(t, "urfave_cli_no_template"))
35+
}

‎docs/migrate-v2-to-v3.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ These tags are **not available in v3** because they are no longer necessary:
238238
- **Shell completion** uses `embed.FS` for its scripts, with no external dependencies.
239239
- **Altsrc** has been extracted to a separate module, `github.com/urfave/cli-altsrc/v3` (see below).
240240

241-
Binary size in v3 is managed through architectural simplification rather than build tags. v3's minimal dependency tree (only `github.com/stretchr/testify` in tests) means the core library contributes very little to your final binary.
241+
Binary size in v3 is managed through architectural simplification rather than build tags (the only exception is the `urfave_cli_no_template` tag, see [Binary Size](v3/binary-size.md#urfave_cli_no_template)). v3's minimal dependency tree (only `github.com/stretchr/testify` in tests) means the core library contributes very little to your final binary.
242242

243243
### Order of precedence of envvars, filepaths, altsrc now depends on the order in which they are defined
244244

‎docs/v3/binary-size.md‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,9 @@ Reflection and templates can contribute noticeably to binary size because additi
116116
of the packages worth investigating when analyzing binary size. These numbers
117117
show their contribution to the analyzed binary, but do not by themselves
118118
prove that all of this code comes from a single feature.
119+
120+
See [`urfave_cli_no_template`](#urfave_cli_no_template) for a way to avoid
121+
linking `text/template`.
119122

120123
## Hiding Built-in Help
121124

@@ -152,6 +155,26 @@ configurations or changes to the library — would be required.
152155

153156
## Current v3 Build Tags
154157

158+
### `urfave_cli_no_template`
159+
160+
Using `text/template` makes the Go linker disable dead code elimination of
161+
exported methods for the whole program, since templates can call arbitrary
162+
methods by name (see [golang/go#72895](https://github.com/golang/go/issues/72895)).
163+
For larger programs, this can noticeably increase the binary size.
164+
165+
With the `urfave_cli_no_template` build tag, the default help and fish
166+
completion are rendered without `text/template`, producing the same output,
167+
and dead code elimination is no longer disabled:
168+
169+
```sh-session
170+
go build -tags urfave_cli_no_template -o myapp ./cmd/myapp
171+
```
172+
173+
Note that help templates can not be customized with this tag; see
174+
[README](https://github.com/urfave/cli#urfave_cli_no_template) for details.
175+
176+
### Other tags
177+
155178
The v3 module does not currently define build tags such as
156179
`urfave_cli_no_docs`, `urfave_cli_no_completion`, or `urfave_cli_minimal`.
157180
Documentation generation lives outside the core module in

‎examples_template_test.go‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
//go:build !urfave_cli_no_template
2+
3+
package cli_test
4+
5+
import (
6+
"context"
7+
"fmt"
8+
"os"
9+
10+
"github.com/urfave/cli/v3"
11+
)
12+
13+
func ExampleCommand_Suggest() {
14+
cmd := &cli.Command{
15+
Name: "greet",
16+
ErrWriter: os.Stdout,
17+
Suggest: true,
18+
HideHelp: false,
19+
HideHelpCommand: true,
20+
CustomRootCommandHelpTemplate: "(this space intentionally left blank)\n",
21+
Flags: []cli.Flag{
22+
&cli.StringFlag{Name: "name", Value: "squirrel", Usage: "a name to say"},
23+
},
24+
Action: func(_ context.Context, cmd *cli.Command) error {
25+
fmt.Printf("Hello %v\n", cmd.String("name"))
26+
return nil
27+
},
28+
}
29+
30+
if cmd.Run(context.Background(), []string{"greet", "--nema", "chipmunk"}) == nil {
31+
fmt.Println("Expected error")
32+
}
33+
// Output:
34+
// Incorrect Usage: flag provided but not defined: -nema
35+
//
36+
// Did you mean "--name"?
37+
//
38+
// (this space intentionally left blank)
39+
}

‎examples_test.go‎

Lines changed: 0 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -540,34 +540,6 @@ func ExampleBoolWithInverseFlag() {
540540
// flags: 2
541541
}
542542

543-
func ExampleCommand_Suggest() {
544-
cmd := &cli.Command{
545-
Name: "greet",
546-
ErrWriter: os.Stdout,
547-
Suggest: true,
548-
HideHelp: false,
549-
HideHelpCommand: true,
550-
CustomRootCommandHelpTemplate: "(this space intentionally left blank)\n",
551-
Flags: []cli.Flag{
552-
&cli.StringFlag{Name: "name", Value: "squirrel", Usage: "a name to say"},
553-
},
554-
Action: func(_ context.Context, cmd *cli.Command) error {
555-
fmt.Printf("Hello %v\n", cmd.String("name"))
556-
return nil
557-
},
558-
}
559-
560-
if cmd.Run(context.Background(), []string{"greet", "--nema", "chipmunk"}) == nil {
561-
fmt.Println("Expected error")
562-
}
563-
// Output:
564-
// Incorrect Usage: flag provided but not defined: -nema
565-
//
566-
// Did you mean "--name"?
567-
//
568-
// (this space intentionally left blank)
569-
}
570-
571543
func ExampleCommand_Suggest_command() {
572544
cmd := &cli.Command{
573545
ErrWriter: os.Stdout,

‎fish.go‎

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import (
55
"fmt"
66
"io"
77
"strings"
8-
"text/template"
98
)
109

1110
// ToFishCompletion creates a fish completion string for the `*Command`
@@ -25,12 +24,6 @@ type fishCommandCompletionTemplate struct {
2524
}
2625

2726
func (cmd *Command) writeFishCompletionTemplate(w io.Writer) error {
28-
const name = "cli"
29-
t, err := template.New(name).Parse(FishCompletionTemplate)
30-
if err != nil {
31-
return err
32-
}
33-
3427
// Add global flags
3528
completions := prepareFishFlags(cmd.Name, cmd)
3629

@@ -57,7 +50,7 @@ func (cmd *Command) writeFishCompletionTemplate(w io.Writer) error {
5750
toplevelCommandNames = append(toplevelCommandNames, child.Names()...)
5851
}
5952

60-
return t.ExecuteTemplate(w, name, &fishCommandCompletionTemplate{
53+
return renderFishCompletion(w, &fishCommandCompletionTemplate{
6154
Command: cmd,
6255
Completions: completions,
6356
AllCommands: toplevelCommandNames,

‎fish_template_test.go‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
//go:build !urfave_cli_no_template
2+
3+
package cli
4+
5+
import (
6+
"testing"
7+
8+
"github.com/stretchr/testify/assert"
9+
)
10+
11+
func TestFishCompletionTemplateError(t *testing.T) {
12+
defer func(old string) { FishCompletionTemplate = old }(FishCompletionTemplate)
13+
FishCompletionTemplate = "{{something"
14+
15+
_, err := buildExtendedTestCommand().ToFishCompletion()
16+
assert.Error(t, err)
17+
}

‎fish_test.go‎

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -23,16 +23,6 @@ func TestFishCompletion(t *testing.T) {
2323
})
2424
cmd.setupCommandGraph()
2525

26-
oldTemplate := FishCompletionTemplate
27-
defer func() { FishCompletionTemplate = oldTemplate }()
28-
FishCompletionTemplate = "{{something"
29-
30-
// test error case
31-
_, err1 := cmd.ToFishCompletion()
32-
assert.Error(t, err1)
33-
34-
// reset the template
35-
FishCompletionTemplate = oldTemplate
3626
// When
3727
res, err := cmd.ToFishCompletion()
3828

0 commit comments

Comments
 (0)