Skip to content

Commit e94761a

Browse files
committed
Restructure code to let linker perform deadcode elimination step
Cobra, in its default configuration, will execute a template to generate help, usage and version outputs. Text/template execution calls MethodByName and MethodByName disables dead code elimination in the Go linker, therefore all programs that make use of cobra will be linked with dead code elimination disabled, even if they end up replacing the default usage, help and version formatters with a custom function and no actual text/template evaluations are ever made at runtime. Dead code elimination in the linker helps reduce disk space and memory utilization of programs. For example, for the simple example program used by TestDeadcodeElimination 40% of the final executable size is dead code. For a more realistic example, 12% of the size of Delve's executable is deadcode. This PR changes Cobra so that, in its default configuration, it does not automatically inhibit deadcode elimination by: 1. changing Cobra's default behavior to emit output for usage and help using simple Go functions instead of template execution 2. quarantining all calls to template execution into SetUsageTemplate, SetHelpTemplate and SetVersionTemplate so that the linker can statically determine if they are reachable
1 parent e94f6d0 commit e94761a

File tree

3 files changed

+236
-56
lines changed

3 files changed

+236
-56
lines changed

cobra.go

+10-6
Original file line numberDiff line numberDiff line change
@@ -176,12 +176,16 @@ func rpad(s string, padding int) string {
176176
return fmt.Sprintf(formattedString, s)
177177
}
178178

179-
// tmpl executes the given template text on data, writing the result to w.
180-
func tmpl(w io.Writer, text string, data interface{}) error {
181-
t := template.New("top")
182-
t.Funcs(templateFuncs)
183-
template.Must(t.Parse(text))
184-
return t.Execute(w, data)
179+
func tmpl(text string) *tmplFunc {
180+
return &tmplFunc{
181+
tmpl: text,
182+
fn: func(w io.Writer, data interface{}) error {
183+
t := template.New("top")
184+
t.Funcs(templateFuncs)
185+
template.Must(t.Parse(text))
186+
return t.Execute(w, data)
187+
},
188+
}
185189
}
186190

187191
// ld compares two strings and returns the levenshtein distance between them.

cobra_test.go

+58
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@
1515
package cobra
1616

1717
import (
18+
"os"
19+
"os/exec"
20+
"path/filepath"
21+
"strings"
1822
"testing"
1923
"text/template"
2024
)
@@ -222,3 +226,57 @@ func TestRpad(t *testing.T) {
222226
})
223227
}
224228
}
229+
230+
func TestDeadcodeElimination(t *testing.T) {
231+
// check that a simple program using cobra in its default configuration is
232+
// linked with deadcode elimination enabled.
233+
const (
234+
dirname = "test_deadcode"
235+
progname = "test_deadcode_elimination"
236+
)
237+
os.Mkdir(dirname, 0770)
238+
filename := filepath.Join(dirname, progname+".go")
239+
err := os.WriteFile(filename, []byte(`package main
240+
241+
import (
242+
"fmt"
243+
"os"
244+
245+
"github.com/spf13/cobra"
246+
)
247+
248+
var rootCmd = &cobra.Command{
249+
Version: "1.0",
250+
Use: "example_program",
251+
Short: "example_program - test fixture to check that deadcode elimination is allowed",
252+
Run: func(cmd *cobra.Command, args []string) {
253+
fmt.Println("hello world")
254+
},
255+
Aliases: []string{"alias1", "alias2"},
256+
Example: "stringer --help",
257+
}
258+
259+
func main() {
260+
if err := rootCmd.Execute(); err != nil {
261+
fmt.Fprintf(os.Stderr, "Whoops. There was an error while executing your CLI '%s'", err)
262+
os.Exit(1)
263+
}
264+
}
265+
`), 0660)
266+
if err != nil {
267+
t.Fatalf("could not write test program: %v", err)
268+
}
269+
defer os.RemoveAll(dirname)
270+
buf, err := exec.Command("go", "build", filename).CombinedOutput()
271+
if err != nil {
272+
t.Fatalf("could not compile test program: %s", string(buf))
273+
}
274+
defer os.Remove(progname)
275+
buf, err = exec.Command("go", "tool", "nm", progname).CombinedOutput()
276+
if err != nil {
277+
t.Fatalf("could not run go tool nm: %v", err)
278+
}
279+
if strings.Contains(string(buf), "MethodByName") {
280+
t.Error("compiled programs contains MethodByName symbol")
281+
}
282+
}

0 commit comments

Comments
 (0)