Last active
October 7, 2019 02:46
-
-
Save alpancs/9f6b589c84a873e2e62e7ca7b5b4ff0c to your computer and use it in GitHub Desktop.
run goimports automatically when saving Go code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# put this file in $HOME/.config/sublime-text-3/Packages | |
from sublime import * | |
from sublime_plugin import * | |
from os import environ | |
from subprocess import Popen, PIPE | |
class AutoGoimports(ViewEventListener): | |
def on_pre_save(self): | |
self.view.run_command("goimports") | |
class GoimportsCommand(TextCommand): | |
# edit if necessary | |
goimports = '{HOME}/go/bin/goimports'.format(**environ) | |
gofmt = '/usr/local/go/bin/gofmt' | |
def run(self, edit): | |
if not self.view.settings().get('syntax').endswith("Go.sublime-syntax"): return | |
region = Region(0, self.view.size()) | |
content = self.view.substr(region) | |
command = '{} | {} -s'.format(self.goimports, self.gofmt) | |
with Popen(command, shell=True, universal_newlines=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) as p: | |
stdout, stderr = p.communicate(content, 2) | |
if stderr: error_message(stderr.replace('<standard input>:', '')[:400]) | |
elif stdout != content: self.view.replace(edit, region, stdout) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment