Go Doctor 0.5 (Beta) User's Guide

Getting Started

If this is your first time using the Go Doctor, see the Getting Started page on the Go Doctor Web site. It contains videos (and basic instructions) showing some typical uses of the Go Doctor using the Vim plug-in.

You will probably want to run the Go Doctor from Vim, since it allows you to rename variables, extract functions, and perform other refactorings with just a few keystrokes. Detailed information about the Vim plug-in is available in the Vim Plug-in Reference. If you are inclined to use the command-line godoctor tool directly, the godoctor man page contains several examples illustrating typical invocations.

Later parts of this user manual contain detailed information on each of the refactorings supported by the Go Doctor.

Online Documentation

The latest documentation for the Go Doctor (including this user manual, the godoctor man page, and the Vim Plug-in Reference) is always available online at http://gorefactor.org. If you want to install a local copy of the documentation, see below.

Installing Local Documentation

If you do not want to use the online documentation, you can install the Go Doctor documentation locally. The godoctor tool generates its own documentation. It can generate a local copy of the Installation Guide and User Guide on the Go Doctor Web site; it can generate a Unix man page for the godoctor tool; it can also generate more complete documentation for the Vim plug-in (by default, the Vim plug-in includes stub documentation pointing to the Go Doctor Web site).

  • To generate a local copy of the Installation Guide:

         godoctor -doc install >install.html
  • To generate a local copy of the User's Guide:

         godoctor -doc user >user.html
  • To generate a local copy of the godoctor man page,

    use the godoctor tool to generate the man page, then save it as godoctor.1 in a directory on your MANPATH. For example, if you installed godoctor into /usr/local/bin, you will probably want to install the man page into /usr/local/share/man:

    sudo mkdir -p /usr/local/share/man/man1

    sudo sh -c 'godoctor -doc man >/usr/local/share/man/man1/godoctor.1'

  • To install complete documentation for the Vim plug-in:
    1. Use the godoctor tool to generate the Vim documentation, and overwrite the godoctor-vim.txt file in the Vim plug-in's doc directory. For example:

      godoctor -doc vim >~/.vim/godoctor.vim/doc/godoctor-vim.txt
    2. In Vim, run

      :helptags ~/.vim/godoctor.vim/doc

      to generate help tags from the plug-in documentation.
    3. To view the Vim plug-in documentation, execute

      :help godoctor

Refactorings

Refactoring: Rename

Purpose

The Rename refactoring is used to change the names of variables, functions, methods, and types. Package renaming is not currently supported.

Usage

  1. Select an identifier to be renamed.
  2. Activate the Rename refactoring.
  3. Enter a new name for the identifier.

An error or warning will be reported if:

  • The renaming could introduce errors (e.g., two functions would have the same name).
  • The necessary changes cannot be made (e.g., the renaming would change the name of a function in the Go standard library).

Example

The example below demonstrates the effect of renaming the highlighted occurrence of hello to goodnight. Note that there are two different variables named hello; since the local identifier was selected, only references to that variable are renamed, as shown.

Before After
package main
import "fmt"

var hello = ":-("

func main() {
    hello = ":-)"
    var hello string = "hello"
    var world string = "world"
    hello = hello + ", " + world
    hello += "!"
    fmt.Println(hello)
}
    ⇒    
package main
import "fmt"

var hello = ":-("

func main() {
    hello = ":-)"
    var goodnight string = "hello"
    var world string = "world"
    goodnight = goodnight + ", " + world
    goodnight += "!"
    fmt.Println(goodnight)
}

Limitations

  • Package renaming is not currently supported. Package renaming requires renaming directories, which causes files to move on the file system. When the refactoring is activated from a text editor (e.g., Vim), the editor needs to be notified of such changes and respond appropriately. Additional work is needed to support this behavior.
  • Name collision detection is overly conservative. If renaming will introduce shadowing, this is reported as an error, even if it will not change the program's semantics.

Refactoring: Extract Function

Purpose

The Extract Function refactoring creates a new function (or method) from a sequence of statements, then replaces the original statements with a call to that function.

Usage

  1. Select a sequence of one or more statements inside an existing function or method.
  2. Activate the Extract Function refactoring.
  3. Enter a name for the new function that will be created.

The refactoring will automatically determine what local variables need to be passed to the extracted function and returned as results.

An error or warning will be reported if the selected statements cannot be extracted into a new function. Usually, this occurs because they contain a statement like return which will have a different meaning in the extracted function.

Limitations

  • Code containing return statements, defer statements, or anonymous functions cannot be extracted.

Refactoring: Extract Local Variable

Purpose

The Extract Local Variable takes an expression, assigns it to a new local variable, then replaces the original expression with a use of that variable.

Usage

  1. Select an expression in an existing statement.
  2. Activate the Extract Local Variable refactoring.
  3. Enter a name for the new variable that will be created.

An error or warning will be reported if the selected expression cannot be extracted into a variable assignment. For example, this could occur if the extracted expression is in a loop condition but its value may change on each iteration of the loop, or if the extracted variable's name is the same as the name of an existing variable.

Example

The example below demonstrates the effect of extracting the highlighted expression into a new local variable sum.

Before After
package main
import "fmt"

func main() {
    y := 2
    z := 3
    if x := 5; x == y + z {
        fmt.Println(x)
    }
}
    ⇒    
package main
import "fmt"

func main() {
    y := 2
    z := 3
    sum := y + z
    if x := 5; x == sum {
        fmt.Println(x)
    }
}

Refactoring: Toggle var ⇔ :=

Purpose

The Toggle var ⇔ := refactoring converts a var declaration to a short assignment statement (using :=), or vice versa.

Usage

  1. Select a local variable declaration (either a var declaration or a := statement).
  2. Activate the Toggle var ⇔ := refactoring.

If a var declaration is selected, it will be converted to a short assignment statement (:=). If a short assignment statement is selected, it will be converted to a var declaration (with an explicit type declaration).

An error or warning will be reported if the selected statements cannot be converted. For example, declarations at the file scope must be declared using var; they cannot be converted to short assignment statements.

Example

The example below demonstrates the effect of toggling the highlighted declaration of msg between a short assignment statement and a var declaration.

Before After
package main
import "fmt"

func main() {
    msg := hello
    fmt.Println(msg)
}
    ⇔    
package main
import "fmt"

func main() {
    var msg string = hello
    fmt.Println(msg)
}

Refactoring: Add GoDoc

Purpose

This refactoring searches a file for exported declarations that do not have GoDoc comments and adds TODO comment stubs to those declarations.

The refactored source code is formatted (similarly to gofmt).

Usage

This refactoring is applied to an entire file. It does not require any particular text to be selected, and it does not prompt for any additional user input.

Example

In the following example, Exported, Shaper, and Rectangle are all exported but lack doc comments. This refactoring adds a TODO comment for each.

Before After
package main
import "fmt"

func main() {
    Exported()
}

func Exported() {
    fmt.Println("Hello, Go")
}

type Shaper interface {
}
 
type Rectangle struct {
}
  
    ⇒    
package main
import "fmt"

func main() {
    Exported()
}

// Exported TODO: NEEDS COMMENT INFO
func Exported() {
    fmt.Println("Hello, Go")
}

// Exported TODO: NEEDS COMMENT INFO
type Shaper interface {
}
  
// Exported TODO: NEEDS COMMENT INFO
type Rectangle struct {
}

Limitations

  • When a single declaration contains non-exported declarations followed by exported declarations (e.g., var x, Y int), a documentation comment will not be added.

References

godoctor Man Page

godoctor

NAME
SYNOPSIS
DESCRIPTION
OPTIONS
EXAMPLES
EXIT STATUS
AUTHOR

NAME

godoctor − refactor Go source code

SYNOPSIS

godoctor [ flag ... ] refactoring [ args ... ]

DESCRIPTION

godoctor refactors Go Source code, outputting a patch file with the changes (unless the -w or -complete flag is specified).

The Go Doctor can be run from the command line, but it is more easily used from an editor like Vim.

For more information and detailed instructions, see the complete documentation at http://gorefactor.org

OPTIONS

The following flags control the behavior of the godoctor:
-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 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 are specific to each refactoring. For a list of the arguments a particular refactoring expects, run that refactoring without any arguments. For example: godoctor rename

EXAMPLES

Display a list of available refactorings:

godoctor -list

Display usage information for the Rename refactoring:

godoctor rename

Rename the identifier in main.go at line 5, column 6 to bar, outputting
a patch file:

godoctor -pos 5,6:5,6 -file main.go rename bar

Toy example: Pipe a file to the godoctor and rename n to foo,
displaying the result:

echo ’package main; import "fmt"; func main() { n := 1; fmt.Println(n) }’ | godoctor -pos 1,43:1,43 -w rename foo

EXIT STATUS

0

Success

1

One or more command line arguments were invalid

2

Help/usage information was displayed; no commands were executed

3

The refactoring could not be completed; output contains a detailed error log

AUTHOR

See http://gorefactor.org


Vim Plugin Reference

*godoctor-vim.txt*
*godoctor*
                                   - = = = -                                 ~


                           T H E   G O   D O C T O R                         ~

                           a golang refactoring tool                         ~


                                   - = = = -                                 ~


                             http://gorefactor.org/



                          Vim Plugin Reference Manual                        ~


==============================================================================
CONTENTS                                                   *godoctor-contents*

    1.Intro.........................................|godoctor-intro|
    2.Commands......................................|godoctor-commands|
    3.Global Options................................|godoctor-global-options|
    4.License.......................................|godoctor-license|


==============================================================================
1. Intro                                                      *godoctor-intro*

The Go Doctor provides source code refactoring for golang programs.

Complete documentation for the Go Doctor--including installation instructions,
a "quick start" introduction, and descriptions of all refactorings--can be
found at the Go Doctor Web site:

    https://gorefactor.org/

This documentation provides a reference for the commands and options unique to
the Go Doctor Vim plugin.

This documentation was generated for Go Doctor 0.5 (Beta).

==============================================================================
2. Commands                                                *godoctor-commands*

:Refactor                                                          *:Refactor*
:GoRefactor                                                      *:GoRefactor*

The Refactor and GoRefactor commands are synonymous; either can be used to
initiate a Go refactoring.  These commands are available only when a Go source
file is being edited.

The command name is followed by the refactoring name and arguments (if any).
For example, to rename an identifier in a Go program to "foo", move the cursor
over the identifier (or select it), and issue the command:

Example: >
    :Refactor rename foo
<

Vim will autocomplete the refactoring name ("rename" in the example above).

A list of files modified and errors that occurred (if any) are displayed in the
|location-list|.

:Rename                                                              *:Rename*

The Rename command is a shortcut for ":Refactor rename" and is otherwise used
similarly.

==============================================================================
3. Global Options                                    *godoctor-global-options*

                                                              *'doctor_scope'*
Default: ""
If this is set, its value is passed to the godoctor via the "-scope" flag.

For example: >
    let g:doctor_scope='/path/to/main.go'
<

Usually, the scope will point to the program entrypoint (main package) for the
program you want to refactor.  If an explicit scope is not set, the Go Doctor
assumes that the current directory contains a Go package, and it uses that
package as the scope.

==============================================================================
4. License                                                  *godoctor-license*

Copyright Auburn University and others.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors
   may be used to endorse or promote products derived from this software
   without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 vim:textwidth=78:shiftwidth=4:filetype=help:norl:

License

Copyright © Auburn University and others. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.