Is there a way for me to run goimport or go fmt on save?

go
workspace
editor

#1

I’ve been using a runner to do this. But it’s still annoying to have to remember to do it every time, and I have to set up the runner everytime. I was wondering two things, how to create an image that I can use as a bases for my golang projects, and two how to get it so that every time I save the go file, it runs goimports or go fmt on that file.

Or how can I map cmd-shift-B to run goimports or go fmt?

Gautam.


#2

you can add the following init script from cloud9>open your init script menu

// You can access plugins via the 'services' global variable
/*global services, plugin*/

// helper to execute go fmt
function execGoFmt(path) {
    services.proc.execFile("go", {
        args: ["fmt", require("path").join(services.c9.workspaceDir, path)]
    }, function(e, a) {
        console.log(e, a, "===");
    });
}
// after save
services.save.on("afterSave", function(e) {
    if (e.path && e.path.endsWith(".go")) {
        execGoFmt(e.path)
    }
}, plugin);

// on format request
services.format.on("format", function(e) {
    if (e.mode != "golang") return;
    var tab = e.editor.ace.session.c9doc.tab;
    services.save.save(tab, {}, function() {
        // this line not is needed if save listener is added too
        // execGoFmt(tab.path);
    });
    return true;
}, plugin);

go imports is not installed by default, and i couldn’t find a way to install it into go directory instead of workspace


#3

Thanks, I’m assuming if it’s in my path it will work? So, if I copy or make sure the goimports is in my path then I can use go imports?


#4

it’s not working for me… Any other ways to have goimports run when saving files?


#5

We have added this to default preferences now


you can change the formatter command to run goimports instead.


#6

@harutyun I have set it to goimports, but I get the following message every time I save a file: “Error running code formatter for golang: goimports not found, please check your project settings”. Is there a way to make this work?


#7

Where did you install goimports? Is it available from commandline?


#8

@harutyun It is available from the Terminal window:

$ which goimports
/home/ubuntu/workspace/bin/goimports

And I have the following in the project settings:

"golang": {
        "@completion": true,
        "@formatOnSave": true,
        "@formatter": "goimports -w \"$file\""
},

Is there something more I need to do to enable it?


#9

@harutyun looks like it works now after changing the following:

"golang": {
        "@completion": true,
        "@formatOnSave": true,
        "@formatter": "/home/ubuntu/workspace/bin/goimports -w \"$file\""
},

/home/ubuntu/workspace/bin is in my $PATH in the terminal, because I added it to ~/.bashrc manually. What is the proper way to modify the path so that it’s picked up by the process running the @formatter command? Adding it to ~/.profile or ~/.bash_profile doesn’t seem to work either.