Created
August 6, 2017 00:08
-
-
Save justyntemme/21ea897037b7505c5bab73948333d224 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python3 | |
from gi.repository import GObject | |
from gi.repository import Ide | |
from gi.repository import Gio | |
class GofmtOnSave(GObject.Object, Ide.GoFmtWorkbenchAddin): | |
def do_load(self, workbench): | |
self.gofmt_enable = workbench.add_switch( | |
'code-insight', 'completion' | |
'org.gnome.builder.extension-type', 'disabled','/', | |
None, | |
_("Gofmt on save"), | |
_("Use gofmt to format Go-lang Code"), | |
None, 30) | |
context = workbench.get_context() | |
bufmgr = context.get_buffer_manager() | |
self.handler = bufmgr.connect('save-buffer', self.on_save_buffer) | |
def do_unload(self, workbench): | |
workbench.remove_id(gofmt_enable) | |
context = workbench.get_context() | |
bufmgr = context.get_buffer_manager() | |
bufmgr.disconnect(self.handler) | |
def on_save_buffer(self, bufmgr, buffer): | |
# If not go code return and exit | |
lang = buffer.get_language() | |
if lang is None or lang.get_id() not in ('go'): | |
return | |
launcher = Ide.SubprocessLauncher.new(0) | |
launcher.set_flags(Gio.SubprocessFlags.STDIN_PIPE | Gio.SubprocessFlags.STDOUT_PIPE) | |
#setup our cmdline arguments | |
launcher.push_argv('gofmt') | |
launcher.set_run_on_host(True) | |
#launch the process | |
subprocess = launcher.spawn() | |
begin, end = buffer.get_bounds() | |
text = buffer.get_text(begin, end, True) | |
if text == '': | |
return | |
#Write the buffer to the gofmt process | |
ret, stdout, stderr = subprocess.communicate_utf8(text, None) | |
# Write the new contents to the buffer | |
buffer.set_text(stdout, len(stdout)) | |
print("Gofmt complete") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment