Skip to content

proposal: x/tools/cmd/stringer: add -trimsuffix #60267

Open
@golightlyb

Description

@golightlyb

x/tools/cmd/stringer has -trimprefix option and should add a matching -trimsuffix option.

stringer's help would then look like:

Usage of stringer:
	stringer [flags] -type T [directory]
	stringer [flags] -type T files... # Must be a single package
For more information, see:
	https://pkg.go.dev/golang.org/x/tools/cmd/stringer
Flags:
  -linecomment
    	use line comment text as printed text when present
  -output string
    	output file name; default srcdir/<type>_string.go
  -tags string
    	comma-separated list of build tags to apply
  -trimprefix prefix
    	trim the prefix from the generated constant names
+  -trimsuffix suffix
+    	trim the suffix from the generated constant names
  -type string
    	comma-separated list of type names; must be set

stringer should exit with an error if the -trimprefix and -trimsuffix flags appear simultaneously, so that we don't need to think about an ordering like -trimprefix=ab -trimsuffix=bc for an input "abc". Also, giving a constant identifier both a prefix and a suffix is not something you ever see.

Rationale

From an unscientific code search, most Go "enum"-like constants take the form:

type Type int
const (
    Foo = Type(iota)
    Bar
    ...
)

or

type Type int
const (
    TypeFoo = Type(iota)
    TypeBar
    ...
)

However, less commonly but still not uncommonly, you see

type Type int
const (
    FooType = Type(iota)
    BarType
    ...
)

e.g. even in the stdlib (admittedly these don't have a String() method anyway):

Sometimes it's clearly more natural e.g. "FragmentShader" vs "ShaderFragment", "UpperCase" vs "CaseUpper".

There are advantages to using a prefix everywhere, but this is not to argue which is better, merely that the suffix form exists.

While there's probably some mileage in extracting the stringer into a library that can build a custom stringer command that can arbitrarily rewrite names, this is not that proposal. The stringer command itself should probably not be made any more complicated than this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Incoming

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions