Intellij IDEA: Run goimports on file save

goimports is a Go tool to remove unused and add missing imports. It also formats your code the same as go fmt.

This is one solution for running goimports when saving *.go files in Intellij IDEA. If you have a better way (not involving snark about emacs), please comment.

Assumptions

  1. You have goimports installed. If not, install with:
    1. go get code.google.com/p/go.tools/cmd/goimports
  2. You’re probably using the golang plugin. That plugin isn’t necessary for this goimports-on-save business, but if you’re using Intellij to write Go code then you might as well use the plugin, too.

Big Picture

  1. Create a shell script to run goimports against the incoming file name if it is a .go file
  2. Add an external tool to Intellij that runs that shell script against the current file
  3. Record a macro that runs that tool and then saves the file
  4. Override ctrl/cmd+S with that macro

Details

1. Create the shell script, like so:

#!/bin/sh

if [[ $1 == *.go ]]
then
  goimports -w $1
fi

2. Add a new external tool to Intellij

  1. ctrl/cmd+, to open up Settings
  2. Filter on “external tools”
  3. Click the “+” icon to add a tool
  4. Name the tool, uncheck “open console”, paste the full path to your shell script in the “Program” field, and add $FilePath$ in the “Parameters” field.
  5. Save the tool
  6. Optionally, in Keymap, give this a keyboard shortcut
  7. This will now show up in the “Tools” menu

Screen Shot 2014-03-29 at 6.31.21 PM

3. Record a macro that runs the tool and saves the file

  1. “Edit” menu — “Macros” — “Start recording macro”
  2. “Tools” menu, then click your new tool
  3. “File” menu, then “Save all”
  4. Finish recording your macro, and give it a name, such as “go_imports_on_save”

4. Override ctrl/cmd+S with that macro

  1. ctrl/cmd+, to open Settings, then filter on “Keymap”
  2. In the keymap, filter on your new macro name, such as “go_imports_on_save”
  3. Double-click it, select “Add keyboard shortcut”, and then hit your normal save combination on the keyboard, such as ctrl/cmd+S
  4. It’ll prompt you to remove the default. Accept it.

That’s it. Now, when you save your .go files, goimports will run and overwrite the contents of your editor. All other files are left alone.

Hat tip to this stackoverflow answer for inspiration.

 

2 thoughts on “Intellij IDEA: Run goimports on file save

  1. From my experience, 3.2 and 3.3 needs to be inverted : your latest modifications need to be saved on the disk before you run the tool, which will overwrite the file (so no need to save after)

Leave a Reply

Your email address will not be published.