|
| 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 | +} |
0 commit comments