Created
August 6, 2017 00:43
-
-
Save justyntemme/9cf6c45b66e56765c842d0bcc3a65122 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 GofmtPreferences(GObject.Object, Ide.PreferencesAddin): | |
def do_load(self, prefs): | |
self.completion_id =( | |
'code-format','completion', | |
'org.gnome.builder.extension-type', 'disabled', '/', | |
None, | |
_("Gofmt on save"), | |
_("Format code go with Gofmt on save, then writes the result to the buffer"), | |
None, 30) | |
def do_unload(self, prefs): | |
prefs.remove_id(self.completion_id) | |
class GofmtOnSave(GObject.Object, Ide.WorkbenchAddin): | |
def do_load(self, workbench): | |
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(self.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