gofmt rewrite rules

276 views
Skip to first unread message

Chris Hopkins

unread,
Jan 23, 2018, 8:02:58 AM1/23/18
to golang-nuts
Hi,
I'm tidying up some code and I think this would be a great use for gofmt's rewrite capabilities, but I can't make it work. I have some code where error checking is missing.
In the code every instance of Set returns an error value that is not checked, so I assumed I could write:

gofmt -w -r 'a.Set(b,c) -> err:=a.Set(b,c)\nif err != nil{log.Fatal("Set Error",err)}'

and (for example) this would change:
x.Set(bob,fred)
to:
err := x.Set(bob,fred)
if err != nil{log.Fatal("Set Error",err)}

(Actual error handling removed for simplicity of example)

Before I crack out sed or perl, any suggestions for if this is possible the "correct" way?

In a follow up question, I've come across go IDEs which allow you to do things like automatically rename handler receivers to be consistent across a type. Unfortunately it doesn't seem to be possible to do this with gofmt out of the box, as rewrite rules can't target specific types that I know of. Is this actually possible?

I guess a further question is, while I have found some examples of gofmt rules, they seem to be quite thin on the ground, is anyone aware of a good collection of examples?

Regards

Chris

Jan Mercl

unread,
Jan 23, 2018, 8:16:03 AM1/23/18
to Chris Hopkins, golang-nuts
On Tue, Jan 23, 2018 at 2:03 PM Chris Hopkins <cbeho...@gmail.com> wrote:

> gofmt -w -r 'a.Set(b,c) -> err:=a.Set(b,c)\nif err != nil{log.Fatal("Set Error",err)}'

I think the -r flag can handle only forms like 'expr1 -> expr2', but in this case expr2 is a statement. To my surprise I cannot find the flag documented anywhere except using -h. Haven't looked into the source code.




--

-j

Sebastien Binet

unread,
Jan 23, 2018, 8:18:13 AM1/23/18
to Chris Hopkins, golang-nuts
Wouldn't this be more a job for 'eg' instead?

sent from my droid

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages