A gofmt/goimports-like tool for Go programmers that fills in Go return statements with zero values to match the func return types

This tool adds zero-value return values to incomplete Go return statements, to save you time when writing Go. It is inspired by and based on goimports.

short screencast

full 30-second screencast: http://youtu.be/hyEMO9vtKZ8

For example, the following incomplete return statement:

func F() (*MyType, int, error) { return errors.New("foo") }

is made complete by adding nil and 0 returns (the zero values for *MyType and int):

func F() (*MyType, int, error) { return nil, 0, errors.New("foo") }

To install:

go get -u github.com/sqs/goreturns

To run:

goreturns file.go

To view a diff showing what it'd do on a sample file:

goreturns -d $GOPATH/github.com/sqs/goreturns/_sample/a.go

Editor integration: replace gofmt or goimports in your post-save hook with goreturns. By default goreturns calls goimports on files before performing its own processing.

It acts the same as gofmt (same flags, etc) but in addition to code formatting, also fixes returns.

Comments
  • Diff option -d always returns nothing

    Diff option -d always returns nothing

    This issue is in regards to vscode no longer adding/removing imports on save. An additional option was added to override the use of goreturns -d and fallback to goreturns -w, which gets things working for me again.

    The initial issue: https://github.com/Microsoft/vscode-go/issues/520

    I am using:

    • Go 1.6
    • vscode 1.6.1
    • vscode go plugin 0.6.45
    • windows 10 Home
  • goreturns: Install seems to be down

    goreturns: Install seems to be down

    Hi :)

    Your link sourcegraph.com/sqs/goreturns looks like being down. Also you seem to use gcimporter as a dependency, but it was moved to another page:

    + go get -u sourcegraph.com/sqs/goreturns
    package golang.org/x/tools/go/gcimporter: cannot find package "golang.org/x/tools/go/gcimporter" in any of:
        /usr/local/go/src/golang.org/x/tools/go/gcimporter (from $GOROOT)
        /home/ubuntu/.go_workspace/src/golang.org/x/tools/go/gcimporter (from $GOPATH)
        /usr/local/go_workspace/src/golang.org/x/tools/go/gcimporter
    package golang.org/x/tools/go/types: no buildable Go source files in /home/ubuntu/.go_workspace/src/golang.org/x/tools/go/types
    

    Taken from our build-log here: https://circleci.com/gh/coala-analyzer/coala-bears/975

    It would be nice if you could fix that as soon as possible, we from coala rely on your cool tool in our testing step :)

  • Issue with GoSublime compatibility.

    Issue with GoSublime compatibility.

    Okay, this is somewhat a bug/bad behavior upstream in GoSublime, but given that's it's quite popular and goreturns is meant to be a drop-in replacement for goimports or gofmt, I'll report it here.

    The problem is that sometimes GoSublime will fail to apply its changes when it's configured to use goreturns instead of goimports or gofmt.

    With the help of dump_args, I tracked it down the following weird behavior of GoSublime on save hook:

    • If the process (goreturns in this case) emits any output on stderr, then GoSublime will not proceed with applying the change. Even if exit code is 0. However, goreturns will sometimes output warnings/information to stderr.

    I've seen it output things like this to stderr:

    main.go:35:2: could not import code.google.com/p/go.net/websocket (can't find import: code.google.com/p/go.net/websocket)
    main.go: typechecking failed (continuing without type info)
    

    I'm pretty sure https://github.com/DisposaBoy/GoSublime should only look at the exit code, not whether stderr was written to, so you might want to try to get it resolved upstream with @DisposaBoy.

  • Install doesn't work

    Install doesn't work

    go version go1.6.2 linux/amd64

    $ go get github.com/sqs/goreturns
    package sourcegraph.com/sqs/goreturns/returns: unrecognized import path "sourcegraph.com/sqs/goreturns/returns" (parse https://sourcegraph.com/sqs/goreturns/returns?go-get=1: no go-import meta tags)
    

    The entire https://sourcegraph.com/sqs* tree returns a 404.

    PS: Looks like it's the same issue as https://github.com/sqs/goreturns/issues/21, but unable to figure out how the fix works

  • The plugin auto removed a used module in import list

    The plugin auto removed a used module in import list

    https://github.com/Microsoft/vscode-go/issues/1107 HI,there is an issue when i use "github.com/deckarep/golang-set". Formatting will auto removed the module from my imports while the package mapset is used in my code such as "mapset.NewSetFromSlice(x)". But other modules is ok. Is there any solutions to resolve this? Thank you.

  • Remove bare returns

    Remove bare returns

    It converts

    func Fb() (res int, err error) {
        err = errors.New("foo")
        return
    }
    

    into

    func Fb() (res int, err error) {
        err = errors.New("foo")
        return res, err
    }
    
  • Formatting inconsistent with gofmt

    Formatting inconsistent with gofmt

    Hi,

    The following code in g() seems to be indented differently depending if I use goimports (same formatting as gofmt) or goreturns :

    package test
    
    func g() {
            f().
                    Scan(a,
                    b)
            return
    }
    
    func h() {
            Scan(a,
                    b)
    }
    

    Note that there is no return value involved here... (I built this minimal sample from a much larger file where some coworkers and me were wondering why the formatting was always changing between our commits... turns out is was caused by us using different formatting tools !).

  • Update Import Path For Go Tools Packages

    Update Import Path For Go Tools Packages

    Reference: https://groups.google.com/forum/#!topic/golang-nuts/eD8dh3T9yyA

    Go Tools import paths have changed. This PR updates imports of Go Tools packages accordingly.

  • Be aware of func literals in addition to func declarations.

    Be aware of func literals in addition to func declarations.

    Fixes #2. Add test case for preserving returns in closures when correct number of values. Enable test case for processing returns in closures (not just top-level func decls).

  • Potential situation where goreturns incorrectly rewrites return statement.

    Potential situation where goreturns incorrectly rewrites return statement.

    This is a somewhat rare situation, so you can get away with delaying fixing this until later and use/evaluate goreturns on other stuff... But I'll report it here anyway.

    It seems when you're iterating over ast to adjust the returns, you're not taking into account potential func literals inside funcs/methods.

    So, here's a simple reproduce case. Take this valid Go code:

    http://play.golang.org/p/KQj9uHSvza

    After running it through goreturns, it will become incorrect:

    package main
    
    import "fmt"
    
    func getMessage() (string, error) {
        foo := func() string {
            return "", "Hello, playground."
        }
        return foo(), nil
    }
    
    func main() {
        m, err := getMessage()
        if err != nil {
            panic(err)
        }
        fmt.Println(m)
    }
    
    --- /var/folders/tw/kgz4v2kn4n7d7ryg5k_z3dk40000gn/T/gofmt388411413 2014-10-07 22:02:03.000000000 -0700
    +++ /var/folders/tw/kgz4v2kn4n7d7ryg5k_z3dk40000gn/T/gofmt302595696 2014-10-07 22:02:03.000000000 -0700
    @@ -4,7 +4,7 @@
    
     func getMessage() (string, error) {
        foo := func() string {
    -       return "Hello, playground."
    +       return "", "Hello, playground."
        }
        return foo(), nil
    
    
  • Consider not including tabwidth, tabs, comments flags.

    Consider not including tabwidth, tabs, comments flags.

    See this controversial gofmt issue https://code.google.com/p/go/issues/detail?id=7101.

    You might want to avoid going down that path by not including these options:

      -comments=true: print comments
      -tabs=true: indent with tabs
      -tabwidth=8: tab width
    

    Note that neither gofmt nor goimports includes those.

    Did you include them on purpose?

  • it doesn't work on a sample file

    it doesn't work on a sample file

    go version go1.18.3 linux/amd64

    test file aa.go

    package a
    
    func F() (*MyType, int, error) { return errors.New("foo") }
    

    Now the test

    user@PC:~$ goreturns <aa.go
    package a
    
    import "errors"
    
    func F() (*MyType, int, error) { return errors.New("foo") }
    

    'return' is not changed.

  • add return parameter incorrect for calling function with multiple return parameters

    add return parameter incorrect for calling function with multiple return parameters

    package main func func1() (ret, msg string) { return "ok", "done" } func func2() (string, string) { return func1() } func main() { func2() }

    run goreturns, -return func1()

    • return "", func1()

    full output: $ goreturns c.go package main

    func func1() (ret, msg string) { return "ok", "done" } func func2() (string, string) { return "", func1() } func main() { func2() }

    this will break build, confirmed this issue with latest goreturns.

  • Read default values of all flags from ~/.goreturns.json file

    Read default values of all flags from ~/.goreturns.json file

    Since vscode does not accept custom command / flags for goreturns, this seems the best way to add flags (for example -local in our case). Create a ~/.goreturns.json file with this template:

    {
    	"fragment": false,
    	"printErrors": false,
    	"allErrors": false,
    	"removeBareReturns": false,
    	"local": ""
    }
    

    Passing flags will override these values.

  • Remove bare doesn't give enough return arguments

    Remove bare doesn't give enough return arguments

    goreturns doesn't generate enough return parameters for the following snippet when using the -b flag to remove bare returns. goreturns -b -w file.go

    file.go:

    package main
    
    func temp() (a, b, c uint64, ok bool) {
    	return
    }
    

    Output:

    package main
    
    func temp() (a, b, c uint64, ok bool) {
    	return a, ok
    }
    

    Expected:

    package main
    
    func temp() (a, b, c uint64, ok bool) {
    	return a, b, c, ok
    }
    
  • Incorrect rewrite of bare return at end of block when comment follows

    Incorrect rewrite of bare return at end of block when comment follows

    Here is a diff example of bare return rewrite when using goreturns -b -i -l -w .:

     	if err != nil {
    -		return
    +		return output,
    +
    +			// Processing output
    +			err
     	}
    
    -	// Processing output
     	if updateCache {
    

    expected result:

     	if err != nil {
    -		return
    +		return output, err
     	}
    
    	// Processing output
     	if updateCache {
    

    It is interesting that the rewrite escapes the {...} block.

Zero Allocation JSON Logger
Zero Allocation JSON Logger

Zero Allocation JSON Logger The zerolog package provides a fast and simple logger dedicated to JSON output. Zerolog's API is designed to provide both

Jan 1, 2023
A powerful zero-dependency json logger.

ZKits Logger Library About This package is a library of ZKits project. This is a zero-dependency standard JSON log library that supports structured JS

Dec 14, 2022
Fast, zero config web endpoint change monitor
Fast, zero config web endpoint change monitor

web monitor fast, zero config web endpoint change monitor. for comparing responses, a selected list of http headers and the full response body is stor

Nov 17, 2022
alog is a dependency free, zero/minimum memory allocation JSON logger with extensions
alog is a dependency free, zero/minimum memory allocation JSON logger with extensions

Alog (c) 2020-2021 Gon Y Yi. https://gonyyi.com. MIT License Version 1.0.0 Intro Alog was built with a very simple goal in mind: Support Tagging (and

Dec 13, 2021
The open and composable observability and data visualization platform. Visualize metrics, logs, and traces from multiple sources like Prometheus, Loki, Elasticsearch, InfluxDB, Postgres and many more.
The open and composable observability and data visualization platform. Visualize metrics, logs, and traces from multiple sources like Prometheus, Loki, Elasticsearch, InfluxDB, Postgres and many more.

The open-source platform for monitoring and observability. Grafana allows you to query, visualize, alert on and understand your metrics no matter wher

Jan 3, 2023
Logstash like, written in golang

gogstash Logstash like, written in golang Download gogstash from github check latest version Use docker image tsaikd/gogstash curl 'https://github.com

Dec 18, 2022
Like Prometheus, but for logs.
Like Prometheus, but for logs.

Loki: like Prometheus, but for logs. Loki is a horizontally-scalable, highly-available, multi-tenant log aggregation system inspired by Prometheus. It

Dec 30, 2022
Request-logging-tool - A tool logs the md5 codes of the responses of the given domains in parameter

request-logging-tool Application to send http requests and log the md5 responses

Jan 7, 2022
A GNU/Linux monitoring and profiling tool focused on single processes.
A GNU/Linux monitoring and profiling tool focused on single processes.

Uroboros is a GNU/Linux monitoring tool focused on single processes. While utilities like top, ps and htop provide great overall details, they often l

Dec 26, 2022
rtop is an interactive, remote system monitoring tool based on SSH

rtop rtop is a remote system monitor. It connects over SSH to a remote system and displays vital system metrics (CPU, disk, memory, network). No speci

Dec 30, 2022
Cloudinsight Agent is a system tool that monitors system processes and services, and sends information back to your Cloudinsight account.

Cloudinsight Agent 中文版 README Cloudinsight Agent is written in Go for collecting metrics from the system it's running on, or from other services, and

Nov 3, 2022
A system and resource monitoring tool written in Golang!
A system and resource monitoring tool written in Golang!

Grofer A clean and modern system and resource monitor written purely in golang using termui and gopsutil! Currently compatible with Linux only. Curren

Jan 8, 2023
A tool to list and diagnose Go processes currently running on your system

gops gops is a command to list and diagnose Go processes currently running on your system. $ gops 983 980 uplink-soecks go1.9 /usr/local/bin/u

Dec 27, 2022
pprof is a tool for visualization and analysis of profiling data

Introduction pprof is a tool for visualization and analysis of profiling data. pprof reads a collection of profiling samples in profile.proto format a

Jan 8, 2023
Contextual Content Discovery Tool
Contextual Content Discovery Tool

Kiterunner Introduction For the longest of times, content discovery has been focused on finding files and folders. While this approach is effective fo

Dec 27, 2022
Changelog management tool, avoid merge conflicts and generate markdown changelogs.

chalog This is chalog, a changelog management tool. With chalog you can manage your project's changelog in a simple markdown format, split across mult

Jul 7, 2022
Gowl is a process management and process monitoring tool at once. An infinite worker pool gives you the ability to control the pool and processes and monitor their status.
Gowl is a process management and process monitoring tool at once. An infinite worker pool gives you the ability to control the pool and processes and monitor their status.

Gowl is a process management and process monitoring tool at once. An infinite worker pool gives you the ability to control the pool and processes and monitor their status.

Nov 10, 2022
gosivy - Real-time visualization tool for Go process metrics
 gosivy - Real-time visualization tool for Go process metrics

Gosivy tracks Go process's metrics and plot their evolution over time right into your terminal, no matter where it's running on. It helps you understand how your application consumes the resources.

Nov 27, 2022
Hidra is a tool to monitor all of your services without making a mess.

hidra Don't lose your mind monitoring your services. Hidra lends you its head. ICMP If you want to use ICMP scenario, you should activate on your syst

Nov 8, 2022