Join GitHub today
x/tools/cmd/stringer: add a -trimprefix flag #16539
//go:generate stringer -type=Type type Type uint8 const ( TypeUnknown Type = iota TypePayPal TypeAmazon TypeWorldPay )
Would result in:
fmt.Println(TypeUnknown.String()) // out: TypeUnknown fmt.Println(TypePayPal.String()) // out: TypePayPal
Whilst this is desirable for certain situations there are some in which its not:
Add an additional flag
//go:generate stringer -type=Type -trimprefix type Type uint8 const ( TypeUnknown Type = iota TypePayPal TypeAmazon TypeWorldPay )
fmt.Println(TypeUnknown.String()) // out: Unknown fmt.Println(TypePayPal.String()) // out: PayPal
And a contrived example with a value
//go:generate stringer -type=Type -trimprefix=Ty type Type uint8 const ( TypeUnknown Type = iota TypePayPal TypeAmazon TypeWorldPay )
fmt.Println(TypeUnknown.String()) // out: peUnknown fmt.Println(TypePayPal.String()) // out: pePayPal
I'd be happy to create a PR with the following feature if its accepted.
That would change the behavior of stringer, as @quentinmit pointed out.
Maybe a value that's not a valid identifier could trigger it without requiring spelling the prefix out? Something like
Unrelated, but I assume that if you did
The strings would be
Is that correct?
@minux that was actually my first idea but I thought using the type name by default was simpler, I'm not opposed to going back to that idea though if thats the consensus.
@jimmyfrasche if we implemented @minux's idea of trimming the longest common prefix when you pass just a
@adrianduke Assuming -trimprefix is a stdlib flag package flag.String
You could have an -autotrimprefix and a -trimprefix but that seems messy. To me, having a magic name seems the best way to go, but it can't be something that either
Of those left,
@jimmyfrasche ah I understand now! There appears to be many valid special characters when placed as flag values (at least for BASH), heres a short list of some that make some amount of sense to me:
Although having 2 separate flags doesn't seem that horrendous of an idea, having 1 flag with a special meaning character will most certainly be harder to get across to the user rather than your example of 2 flags:
flags are cheap and explicit, special characters are exceptions and harder to communicate.
changed the title from
proposal: x/tools/cmd/stringer Add a -trimprefix flag
x/tools/cmd/stringer: add a -trimprefix flag
Aug 7, 2017
This would be useful for #15462, and I see the issue has been accepted for a while with little activity, so I have given it a go.
I have left out the automatic detection of prefixes for now. That can always be added later, with whatever extra flag or special trim value that we agree on.