Go语言不完全工具列表

1 impl

go get -u github.com/josharian/impl
impl -h
Usage of impl:
  -dir string
      package source directory, useful for vendored code
impl 'f *File' io.ReadWriteCloser
1
2
3
4
5
6
7
8
9
10
11
func (f *File) Read(p []byte) (n int, err error) {
panic("not implemented")
}

func (f *File) Write(p []byte) (n int, err error) {
panic("not implemented")
}

func (f *File) Close() error {
panic("not implemented")
}

2 gomodifytags

请参见之前的文章gomodifytags

3 go-outline

go get -u github.com/lukehoban/go-outline
go-outline -h
Usage of go-outline:
  -f string
      the path to the file to outline
  -imports-only
      parse imports only
  -src string
      source code of the file to outline
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package main

import "fmt"

type Outline struct {
Label string
Type string
}

func (ol *Outline) Label() string {
return ol.Label
}

const (
name = "brantou"
)

const email = "brantou89@gmail.com"

var (
cmd string
args string
)

func main() {
fmt.Printf("hello world!")
}
go-outline -f main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
[
{
"label": "main",
"type": "package",
"start": 1,
"end": 290,
"children": [
{
"label": "\"fmt\"",
"type": "import",
"start": 23,
"end": 28
},

{
"label": "Outline",
"type": "type",
"start": 35,
"end": 83
},

{
"label": "Label",
"type": "function",
"receiverType": "*Outline",
"start": 85,
"end": 140
},

{
"label": "name",
"type": "constant",
"start": 152,
"end": 156
},

{
"label": "email",
"type": "constant",
"start": 178,
"end": 183
},

{
"label": "cmd",
"type": "variable",
"start": 217,
"end": 220
},

{
"label": "args",
"type": "variable",
"start": 231,
"end": 235
},

{
"label": "main",
"type": "function",
"start": 246,
"end": 290
}

]
}

]
go-outline -f main.go -imports-only

4 go-symbols

go get -u github.com/newhook/go-symbols
go-symbols -h
Usage of go-symbols:
  -tags build tags
      a list of build tags to consider satisfied during the build. For more information about build tags, see the description of build constraints in the documentation for the go/build package
go-symbols $GOPATH/src/github.com/astaxie/beego beego
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
[
{
"name": "BeegoOutput",
"kind": "type",
"package": "context",
"path": "/home/parallels/.gvm/pkgsets/go1.9/global/src/github.com/astaxie/beego/context/output.go",
"line": 35,
"character": 0
},

{
"name": "BeegoInput",
"kind": "type",
"package": "context",
"path": "/home/parallels/.gvm/pkgsets/go1.9/global/src/github.com/astaxie/beego/context/input.go",
"line": 43,
"character": 0
},

{
"name": "NewBeegoRequest",
"kind": "func",
"package": "httplib",
"path": "/home/parallels/.gvm/pkgsets/go1.9/global/src/github.com/astaxie/beego/httplib/httplib.go",
"line": 80,
"character": 0
},

{
"name": "BeegoHTTPSettings",
"kind": "type",
"package": "httplib",
"path": "/home/parallels/.gvm/pkgsets/go1.9/global/src/github.com/astaxie/beego/httplib/httplib.go",
"line": 130,
"character": 0
},

{
"name": "BeegoHTTPRequest",
"kind": "type",
"package": "httplib",
"path": "/home/parallels/.gvm/pkgsets/go1.9/global/src/github.com/astaxie/beego/httplib/httplib.go",
"line": 146,
"character": 0
}

]

5 gocode

An autocompletion daemon for the Go programming language.

go get -u -v github.com/nsf/gocode
gocode -h
Usage: gocode [-s] [-f=<format>] [-in=<path>] [-sock=<type>] [-addr=<addr>]
     <command> [<args>]

Flags:
  -addr string
      address for tcp socket (default "127.0.0.1:37373")
  -debug
      enable server-side debug mode
  -f string
      output format (vim | emacs | nice | csv | csv-with-package | json) (default "nice")
  -in string
      use this file instead of stdin input
  -profile int
      port on which to expose profiling information for pprof; 0 to disable profiling
  -s	run a server instead of a client
  -sock string
      socket type (unix | tcp) (default "unix")

Commands:
  autocomplete [<path>] <offset>     main autocompletion command
  close                              close the gocode daemon
  status                             gocode daemon status report
  drop-cache                         drop gocode daemon's cache
  set [<name> [<value>]]             list or set config options

6 godef

Print where symbols are defined in Go source code.

go get -u -v github.com/rogpeppe/godef
godef -h
usage: godef [flags] [expr]
  -A	print all type and members information
  -a	print public type and member information
  -acme
      use current acme window
  -debug
      debug mode
  -f string
      Go source filename
  -i	read file from stdin
  -json
      output location in JSON format (-t flag is ignored)
  -o int
      file offset of identifier in stdin (default -1)
  -t	print type information

7 gogetdoc

Retrieve documentation for items in Go source code.

go get -u -v github.com/zmb3/gogetdoc
gogetdoc -h
Usage of gogetdoc
  -cpuprofile string
      write cpu profile to file
  -json
      enable extended JSON output
  -linelength int
      maximum length of a line in the output (in Unicode code points) (default 80)
  -modified
      read an archive of modified files from standard input
  -pos string
      Filename and byte offset of item to document, e.g. foo.go:#123
  -tags build tags
      a list of build tags to consider satisfied during the build. For more information about build tags, see the description of build constraints in the documentation for the go/build package
  -u	show unexported fields

The archive format for the -modified flag consists of the file name, followed
by a newline, the decimal file size, another newline, and the contents of the file.

This allows editors to supply gogetdoc with the contents of their unsaved buffers.

8 golint

Golint is a linter for Go source code.

go get -u github.com/golang/lint/golint
golint -h
Usage of golint:
	golint [flags] # runs on package in current directory
	golint [flags] [packages]
	golint [flags] [directories] # where a '/...' suffix includes all sub-directories
	golint [flags] [files] # all must belong to a single package
Flags:
  -min_confidence float
      minimum confidence of a problem to print it (default 0.8)
  -set_exit_status
      set exit status to 1 if any issues are found
golint google.go
google.go:19:1: exported function Search should have comment or be unexported

9 gopkgs

Gopkgs is tools that provide list of available Go packages that can be imported. This are alternative to go list all, it just faster.

go get github.com/uudashr/gopkgs/cmd/gopkgs
gopkgs -help
Usage of gopkgs:
  -format string
      custom output format (default "{ {.ImportPath} }")
  -help
      show this message


Use -format to custom the output using template syntax. The struct being passed to template is:

  type Pkg struct {
      Dir        string // directory containing package sources
      ImportPath string // import path of package in dir
      Name       string // package name
  }
gopkgs -format "{ {.Name} };{ {.ImportPath} }"

10 gorename

go get -u -v golang.org/x/tools/cmd/gorename
gorename -help
gorename: precise type-safe renaming of identifiers in Go source code.

Usage:

 gorename (-from <spec> | -offset <file>:#<byte-offset>) -to <name> [-force]

You must specify the object (named entity) to rename using the -offset
or -from flag.  Exactly one must be specified.

Flags:

  -offset    specifies the filename and byte offset of an identifier to rename.
             This form is intended for use by text editors.

  -from      specifies the object to rename using a query notation;
             This form is intended for interactive use at the command line.
             A legal -from query has one of the following forms:

    "encoding/json".Decoder.Decode        method of package-level named type
    (*"encoding/json".Decoder).Decode     ditto, alternative syntax
    "encoding/json".Decoder.buf           field of package-level named struct type
    "encoding/json".HTMLEscape            package member (const, func, var, type)
    "encoding/json".Decoder.Decode::x     local object x within a method
    "encoding/json".HTMLEscape::x         local object x within a function
    "encoding/json"::x                    object x anywhere within a package
    json.go::x                            object x within file json.go

             Double-quotes must be escaped when writing a shell command.
             Quotes may be omitted for single-segment import paths such as "fmt".

             For methods, the parens and '*' on the receiver type are both
             optional.

             It is an error if one of the ::x queries matches multiple
             objects.

  -to        the new name.

  -force     causes the renaming to proceed even if conflicts were reported.
             The resulting program may be ill-formed, or experience a change
             in behaviour.

             WARNING: this flag may even cause the renaming tool to crash.
             (In due course this bug will be fixed by moving certain
             analyses into the type-checker.)

  -d         display diffs instead of rewriting files

  -v         enables verbose logging.

gorename automatically computes the set of packages that might be
affected.  For a local renaming, this is just the package specified by
-from or -offset, but for a potentially exported name, gorename scans
the workspace ($GOROOT and $GOPATH).

gorename rejects renamings of concrete methods that would change the
assignability relation between types and interfaces.  If the interface
change was intentional, initiate the renaming at the interface method.

gorename rejects any renaming that would create a conflict at the point
of declaration, or a reference conflict (ambiguity or shadowing), or
anything else that could cause the resulting program not to compile.


Examples:

$ gorename -offset file.go:#123 -to foo

  Rename the object whose identifier is at byte offset 123 within file file.go.

$ gorename -from '"bytes".Buffer.Len' -to Size

  Rename the "Len" method of the *bytes.Buffer type to "Size".

---- TODO ----

Correctness:
- handle dot imports correctly
- document limitations (reflection, 'implements' algorithm).
- sketch a proof of exhaustiveness.

Features:
- support running on packages specified as *.go files on the command line
- support running on programs containing errors (loader.Config.AllowErrors)
- allow users to specify a scope other than "global" (to avoid being
  stuck by neglected packages in $GOPATH that don't build).
- support renaming the package clause (no object)
- support renaming an import path (no ident or object)
  (requires filesystem + SCM updates).
- detect and reject edits to autogenerated files (cgo, protobufs)
  and optionally $GOROOT packages.
- report all conflicts, or at least all qualitatively distinct ones.
  Sometimes we stop to avoid redundancy, but
  it may give a disproportionate sense of safety in -force mode.
- support renaming all instances of a pattern, e.g.
  all receiver vars of a given type,
  all local variables of a given type,
  all PkgNames for a given package.
- emit JSON output for other editors and tools.

11 godoctor

go get -u -v github.com/godoctor/godoctor
godoctor -h
Usage: godoctor [<flag> ...] <refactoring> [<args> ...]

Each <flag> must be one of the following:
    -complete Output entire modified source files instead of displaying a diff
    -doc      Output documentation (install, user, man, or vim) and exit
    -file     Filename containing an element to refactor (default: stdin)
    -json     Accept commands in OpenRefactory JSON protocol format
    -list     List all refactorings and exit
    -pos      Position of a syntax element to refactor (default: entire file)
    -scope    Package name(s), or source file containing a program entrypoint
    -v        Verbose: list affected files
    -vv       Very verbose: list individual edits (implies -v)
    -w        Modify source files on disk (write) instead of displaying a diff


The <refactoring> argument determines the refactoring to perform:
    rename          Changes the name of an identifier
    extract         Extracts statements to a new function/method
    var             Extracts an expression, assigning it to a variable
    toggle          Toggles between a var declaration and := statement
    godoc           Adds stub GoDoc comments where they are missing

The <args> following the refactoring name vary depending on the refactoring.

To display usage information for a particular refactoring, such as rename, use:
    %% godoctor rename

For complete usage information, see the user manual: http://gorefactor.org/doc.html

12 goreturns

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

go get -u sourcegraph.com/sqs/goreturns
1
2
3
4
5
package goreturnsdemo

import "errors"

func F() (int, error) { return errors.New("foo") }
goreturns -h
usage: goreturns [flags] [path ...]
  -b	remove bare returns
  -d	display diffs instead of rewriting files
  -e	report all errors (not just the first 10 on different lines)
  -i	run goimports on the file prior to processing (default true)
  -l	list files whose formatting differs from goreturns's
  -local string
put imports beginning with this string after 3rd-party packages (see goimports)
  -p	print non-fatal typechecking errors to stderr
  -w	write result to (source) file instead of stdout
goreturns goreturnsdemo.go
1
2
3
4
5
package goreturnsdemo

import "errors"

func F() (int, error) { return 0, errors.New("foo") }
goreturns -d goreturnsdemo.go
1
2
3
4
5
6
7
8
9
10
11
diff goreturnsdemo.go gofmt/goreturnsdemo.go
--- /tmp/gofmt948886532 2017-11-26 18:59:03.671955645 +0800
+++ /tmp/gofmt584282515 2017-11-26 18:59:03.671955645 +0800
@@ -1,6 +1,5 @@
package goreturnsdemo

-
import "errors"

-func F() (int, error) { return errors.New("foo") }
+func F() (int, error) { return 0, errors.New("foo") }

13 gotests

Generate Go tests from your source code.

go get -u -v github.com/cweill/gotests/...
gotests -h
Usage of gotests:
  -all
      generate tests for all functions and methods
  -excl string
      regexp. generate tests for functions and methods that don't match. Takes precedence over -only, -exported, and -all
  -exported
      generate tests for exported functions and methods. Takes precedence over -only and -all
  -i	print test inputs in error messages
  -nosubtests
      disable generating tests using the Go 1.7 subtests feature
  -only string
      regexp. generate tests for functions and methods that match only. Takes precedence over -all
  -w	write output to (test) files instead of stdout
gotests -all ./

14 guru

guru: a tool for answering questions about Go source code.

15 godepgraph

godepgraph is a program for generating a dependency graph of Go packages.

go get github.com/kisielk/godepgraph
godepgraph -h
Usage of godepgraph:
  -d	show dependencies of packages in the Go standard library
  -horizontal
      lay out the dependency graph horizontally instead of vertically
  -i string
      a comma-separated list of packages to ignore
  -l int
      max level of go dependency graph (default 256)
  -o string
      a comma-separated list of prefixes to include
  -p string
      a comma-separated list of prefixes to ignore
  -s	ignore packages in the Go standard library
  -t	include test packages
  -tags string
      a comma-separated list of build tags to consider satisified during the build
godepgraph github.com/kisielk/godepgraph
digraph godep {
_0 [label="flag" style="filled" color="palegreen"];
_1 [label="fmt" style="filled" color="palegreen"];
_2 [label="github.com/kisielk/godepgraph" style="filled" color="paleturquoise"];
_2 -> _0;
_2 -> _1;
_2 -> _3;
_2 -> _4;
_2 -> _5;
_2 -> _6;
_2 -> _7;
_3 [label="go/build" style="filled" color="palegreen"];
_4 [label="log" style="filled" color="palegreen"];
_5 [label="os" style="filled" color="palegreen"];
_6 [label="sort" style="filled" color="palegreen"];
_7 [label="strings" style="filled" color="palegreen"];
}
godepgraph github.com/kisielk/godepgraph | dot -Tpng -o godepgraph.png

<img src="/images/go-tool/godepgraph.png” />

16 go-callvis

go get -u github.com/TrueFurby/go-callvis
go-callvis -h
Usage of go-callvis:
  -debug
      Enable verbose log.
  -focus string
      Focus package with name or import path. (default "main")
  -group string
      Grouping functions by [pkg, type] (separate multiple by comma).
  -ignore string
      Ignore package paths with prefix (separate multiple by comma).
  -limit string
      Limit package paths to prefix. (separate multiple by comma)
  -minlen uint
      Minimum edge length (for wider output). (default 2)
  -nodesep float
      Minimum space between two adjacent nodes in the same rank (for taller output). (default 0.35)
  -nostd
      Omit calls to/from std packages.
  -tests
      Include test code.
  -version
      Show version and exit.
go-callvis github.com/TrueFurby/go-callvis | dot -Tpng -o go-callvis.png

<img src="/images/go-tool/go-callvis.png” />

17 depth

go get -u github.com/KyleBanks/depth/cmd/depth
depth -h
Usage of depth:
  -explain string
      If set, show which packages import the specified target
  -internal
      If set, resolves dependencies of internal (stdlib) packages.
  -json
      If set, outputs the depencies in JSON format.
  -max int
      Sets the maximum depth of dependencies to resolve.
  -test
      If set, resolves dependencies used for testing.
depth github.com/KyleBanks/depth/cmd/depth
github.com/KyleBanks/depth/cmd/depth
  ├ encoding/json
  ├ flag
  ├ fmt
  ├ io
  ├ os
  ├ strings
  └ github.com/KyleBanks/depth
    ├ bytes
    ├ errors
    ├ go/build
    ├ os
    ├ path
    ├ sort
    └ strings
12 dependencies (11 internal, 1 external, 0 testing).
depth -internal strings
strings
  ├ errors
  ├ internal/cpu
  ├ io
    ├ errors
    └ sync
      ├ internal/race
        └ unsafe
      ├ runtime
        ├ runtime/internal/atomic
          └ unsafe
        ├ runtime/internal/sys
        └ unsafe
      ├ sync/atomic
        └ unsafe
      └ unsafe
  ├ unicode
  └ unicode/utf8
12 dependencies (12 internal, 0 external, 0 testing).
strings
  ├ errors
  ├ internal/cpu
  ├ io
  ├ unicode
  └ unicode/utf8
5 dependencies (5 internal, 0 external, 0 testing).

18 interface

go get -u -v mvdan.cc/interfacer
interfacer -h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package single

func Empty() {
}

type Closer interface {
Close()
}

type ReadCloser interface {
Closer
Read()
}

func Basic(c Closer) {
c.Close()
}

func BasicWrong(rc ReadCloser) { // WARN rc can be Closer
rc.Close()
}

func OtherWrong(s St) { // WARN s can be Closer
s.Close()
}
interfacer simple.go

simple.go:24:19: undeclared name: St

19 safesql

go get -u github.com/stripe/safesql
safesql
Usage: safesql [-q] [-v] package1 [package2 ...]
  -q	Only print on failure
  -v	Verbose mode

20 aligncheck

go get github.com/opennota/check/cmd/aligncheck
aligncheck  github.com/astaxie/beego
github.com/astaxie/beego: config.go:33:6: struct Config could have size 520 (currently 552)
github.com/astaxie/beego: config.go:51:6: struct Listen could have size 120 (currently 152)
github.com/astaxie/beego: config.go:71:6: struct WebConfig could have size 264 (currently 288)
github.com/astaxie/beego: config.go:89:6: struct SessionConfig could have size 104 (currently 128)
github.com/astaxie/beego: controller.go:67:6: struct Controller could have size 224 (currently 232)
github.com/astaxie/beego: router.go:124:6: struct ControllerRegister could have size 168 (currently 176)

21 structcheck

go get github.com/opennota/check/cmd/structcheck
structcheck -h
Usage of structcheck:
  -a	Count assignments only
  -e	Report exported fields
  -t	Load test files too
  -tags string
      Build tags
structcheck fmt
fmt: ~/.gvm/gos/go1.9/src/fmt/scan.go:169:2: fmt.ssave.nlIsEnd
fmt: ~/.gvm/gos/go1.9/src/fmt/scan.go:170:2: fmt.ssave.nlIsSpace
fmt: ~/.gvm/gos/go1.9/src/fmt/scan.go:171:2: fmt.ssave.argLimit
fmt: ~/.gvm/gos/go1.9/src/fmt/scan.go:172:2: fmt.ssave.limit
fmt: ~/.gvm/gos/go1.9/src/fmt/scan.go:173:2: fmt.ssave.maxWid
fmt: ~/.gvm/gos/go1.9/src/fmt/format.go:30:2: fmt.fmtFlags.zero
fmt: ~/.gvm/gos/go1.9/src/fmt/format.go:35:2: fmt.fmtFlags.plusV
fmt: ~/.gvm/gos/go1.9/src/fmt/format.go:36:2: fmt.fmtFlags.sharpV
fmt: ~/.gvm/gos/go1.9/src/fmt/format.go:25:2: fmt.fmtFlags.precPresent
fmt: ~/.gvm/gos/go1.9/src/fmt/format.go:27:2: fmt.fmtFlags.plus
fmt: ~/.gvm/gos/go1.9/src/fmt/format.go:29:2: fmt.fmtFlags.space
fmt: ~/.gvm/gos/go1.9/src/fmt/format.go:24:2: fmt.fmtFlags.widPresent
fmt: ~/.gvm/gos/go1.9/src/fmt/format.go:26:2: fmt.fmtFlags.minus
fmt: ~/.gvm/gos/go1.9/src/fmt/format.go:28:2: fmt.fmtFlags.sharp

22 varcheck

go get github.com/opennota/check/cmd/varcheck
varcheck -h
Usage of varcheck:
  -e	Report exported variables and constants
varcheck image/jpeg
image/jpeg: ~/.gvm/gos/go1.9/src/image/jpeg/reader.go:74:2: adobeTransformYCbCr
image/jpeg: ~/.gvm/gos/go1.9/src/image/jpeg/reader.go:75:2: adobeTransformYCbCrK
image/jpeg: ~/.gvm/gos/go1.9/src/image/jpeg/writer.go:54:2: quantIndexLuminance
image/jpeg: ~/.gvm/gos/go1.9/src/image/jpeg/writer.go:55:2: quantIndexChrominance
image/jpeg: ~/.gvm/gos/go1.9/src/image/jpeg/writer.go:91:2: huffIndexLuminanceDC
image/jpeg: ~/.gvm/gos/go1.9/src/image/jpeg/writer.go:92:2: huffIndexLuminanceAC
image/jpeg: ~/.gvm/gos/go1.9/src/image/jpeg/writer.go:93:2: huffIndexChrominanceDC
image/jpeg: ~/.gvm/gos/go1.9/src/image/jpeg/writer.go:94:2: huffIndexChrominanceAC

23 eg

go get golang.org/x/tools/cmd/eg
1
2
3
4
5
6
7
package main

import "time"

func ExtendWith50000ns(t time.Time) time.Time {
return t.Add(time.Duration(50000))
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package template

import (
"time"
)

func before(t time.Time, d time.Duration) time.Time {
// if already time.Duration, do not cast.
return t.Add(time.Duration(d))
}

func after(t time.Time, d time.Duration) time.Time {
return t.Add(d * time.Nanosecond)
}
eg -t T.template .
1
2
3
4
5
6
7
package main

import "time"

func ExtendWith50000ns(t time.Time) time.Time {
return t.Add(50000 * time.Nanosecond)
}
Last Updated 2017-12-13 Wed 18:24.
Render by hexo-renderer-org with Emacs 25.3.2 (Org mode 8.2.10)