2014-09-23 08:23:04 -06:00
|
|
|
// Copyright 2014 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
2016-01-06 12:56:13 -07:00
|
|
|
// +build go1.5
|
|
|
|
|
2014-09-23 08:23:04 -06:00
|
|
|
// Package rename contains the implementation of the 'gorename' command
|
2014-12-30 08:48:23 -07:00
|
|
|
// whose main function is in golang.org/x/tools/cmd/gorename.
|
|
|
|
// See the Usage constant for the command documentation.
|
2014-12-08 21:00:58 -07:00
|
|
|
package rename // import "golang.org/x/tools/refactor/rename"
|
2014-09-23 08:23:04 -06:00
|
|
|
|
|
|
|
import (
|
2015-03-17 09:17:36 -06:00
|
|
|
"bytes"
|
2014-09-23 08:23:04 -06:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"go/ast"
|
|
|
|
"go/build"
|
|
|
|
"go/format"
|
|
|
|
"go/parser"
|
|
|
|
"go/token"
|
2015-12-29 14:26:28 -07:00
|
|
|
"io"
|
2015-03-17 09:17:36 -06:00
|
|
|
"io/ioutil"
|
2015-12-29 14:26:28 -07:00
|
|
|
"log"
|
2014-09-23 08:23:04 -06:00
|
|
|
"os"
|
2015-12-29 14:26:28 -07:00
|
|
|
"os/exec"
|
2014-12-20 16:33:48 -07:00
|
|
|
"path"
|
2014-09-23 08:23:04 -06:00
|
|
|
"sort"
|
2014-12-20 16:33:48 -07:00
|
|
|
"strconv"
|
2014-09-23 08:23:04 -06:00
|
|
|
"strings"
|
|
|
|
|
2014-11-09 14:50:40 -07:00
|
|
|
"golang.org/x/tools/go/loader"
|
|
|
|
"golang.org/x/tools/go/types"
|
2015-06-05 11:18:37 -06:00
|
|
|
"golang.org/x/tools/go/types/typeutil"
|
2014-11-09 14:50:40 -07:00
|
|
|
"golang.org/x/tools/refactor/importgraph"
|
|
|
|
"golang.org/x/tools/refactor/satisfy"
|
2014-09-23 08:23:04 -06:00
|
|
|
)
|
|
|
|
|
2014-12-30 08:48:23 -07:00
|
|
|
const Usage = `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
|
|
|
|
|
2015-01-15 08:13:01 -07:00
|
|
|
Double-quotes must be escaped when writing a shell command.
|
|
|
|
Quotes may be omitted for single-segment import paths such as "fmt".
|
|
|
|
|
2014-12-30 08:48:23 -07:00
|
|
|
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.)
|
|
|
|
|
2015-12-29 14:26:28 -07:00
|
|
|
-d display diffs instead of rewriting files
|
2014-12-30 08:48:23 -07:00
|
|
|
|
|
|
|
-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:
|
|
|
|
|
2015-10-19 08:00:53 -06:00
|
|
|
$ gorename -offset file.go:#123 -to foo
|
2014-12-30 08:48:23 -07:00
|
|
|
|
|
|
|
Rename the object whose identifier is at byte offset 123 within file file.go.
|
|
|
|
|
2015-10-19 08:00:53 -06:00
|
|
|
$ gorename -from '"bytes".Buffer.Len' -to Size
|
2014-12-30 08:48:23 -07:00
|
|
|
|
|
|
|
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.
|
|
|
|
`
|
|
|
|
|
2014-09-23 08:23:04 -06:00
|
|
|
var (
|
|
|
|
// Force enables patching of the source files even if conflicts were reported.
|
|
|
|
// The resulting program may be ill-formed.
|
|
|
|
// It may even cause gorename to crash. TODO(adonovan): fix that.
|
|
|
|
Force bool
|
|
|
|
|
2015-12-29 14:26:28 -07:00
|
|
|
// Diff causes the tool to display diffs instead of rewriting files.
|
|
|
|
Diff bool
|
|
|
|
|
|
|
|
// DiffCmd specifies the diff command used by the -d feature.
|
|
|
|
// (The command must accept a -u flag and two filename arguments.)
|
|
|
|
DiffCmd = "diff"
|
2014-09-23 08:23:04 -06:00
|
|
|
|
2014-09-23 13:17:49 -06:00
|
|
|
// ConflictError is returned by Main when it aborts the renaming due to conflicts.
|
2014-09-23 08:23:04 -06:00
|
|
|
// (It is distinguished because the interesting errors are the conflicts themselves.)
|
|
|
|
ConflictError = errors.New("renaming aborted due to conflicts")
|
|
|
|
|
|
|
|
// Verbose enables extra logging.
|
|
|
|
Verbose bool
|
|
|
|
)
|
|
|
|
|
2015-12-29 14:26:28 -07:00
|
|
|
var stdout io.Writer
|
|
|
|
|
2014-09-23 08:23:04 -06:00
|
|
|
type renamer struct {
|
|
|
|
iprog *loader.Program
|
|
|
|
objsToUpdate map[types.Object]bool
|
|
|
|
hadConflicts bool
|
|
|
|
to string
|
|
|
|
satisfyConstraints map[satisfy.Constraint]bool
|
|
|
|
packages map[*types.Package]*loader.PackageInfo // subset of iprog.AllPackages to inspect
|
2015-06-05 11:18:37 -06:00
|
|
|
msets typeutil.MethodSetCache
|
cmd/gorename: support renaming of methods with consequences for other types, iff initiated at an abstract method.
Previously, gorename rejected all method renamings if it would
change the assignability relation.
Now, so long as the renaming was initiated at an abstract
method, the renaming proceeds, changing concrete methods (and
possibly other abstract methods) as needed. The user
intention is clear.
The intention of a renaming initiated at a concrete method is
less clear, so we still reject it if it would change the
assignability relation. The diagnostic advises the user to
rename the abstract method if that was the intention.
Additional safety checks are required: for each
satisfy.Constraint that couples a concrete type C and an
interface type I, we must treat it just like a set of implicit
selections C.f, one per abstract method f of I, and ensure the
selections' meanings are unchanged.
The satisfy package no longer canonicalizes types, since this
substitutes one interface for another (equivalent) one, which
is sound, but makes the type names random and the error
messages confusing.
Also, fixed a bug in 'satisfy' relating to map keys.
+ Lots more tests.
LGTM=sameer
R=sameer
CC=golang-codereviews
https://golang.org/cl/173430043
2014-12-04 07:37:50 -07:00
|
|
|
changeMethods bool
|
2014-09-23 08:23:04 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
var reportError = func(posn token.Position, message string) {
|
|
|
|
fmt.Fprintf(os.Stderr, "%s: %s\n", posn, message)
|
|
|
|
}
|
|
|
|
|
2014-12-20 16:33:48 -07:00
|
|
|
// importName renames imports of the package with the given path in
|
|
|
|
// the given package. If fromName is not empty, only imports as
|
2015-02-25 10:37:17 -07:00
|
|
|
// fromName will be renamed. If the renaming would lead to a conflict,
|
|
|
|
// the file is left unchanged.
|
|
|
|
func importName(iprog *loader.Program, info *loader.PackageInfo, fromPath, fromName, to string) error {
|
2014-12-20 16:33:48 -07:00
|
|
|
for _, f := range info.Files {
|
|
|
|
var from types.Object
|
|
|
|
for _, imp := range f.Imports {
|
|
|
|
importPath, _ := strconv.Unquote(imp.Path.Value)
|
|
|
|
importName := path.Base(importPath)
|
|
|
|
if imp.Name != nil {
|
|
|
|
importName = imp.Name.Name
|
|
|
|
}
|
|
|
|
if importPath == fromPath && (fromName == "" || importName == fromName) {
|
|
|
|
from = info.Implicits[imp]
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if from == nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
r := renamer{
|
|
|
|
iprog: iprog,
|
|
|
|
objsToUpdate: make(map[types.Object]bool),
|
|
|
|
to: to,
|
|
|
|
packages: map[*types.Package]*loader.PackageInfo{info.Pkg: info},
|
|
|
|
}
|
|
|
|
r.check(from)
|
|
|
|
if r.hadConflicts {
|
|
|
|
continue // ignore errors; leave the existing name
|
|
|
|
}
|
|
|
|
if err := r.update(); err != nil {
|
2015-02-25 10:37:17 -07:00
|
|
|
return err
|
2014-12-20 16:33:48 -07:00
|
|
|
}
|
|
|
|
}
|
2015-02-25 10:37:17 -07:00
|
|
|
return nil
|
2014-12-20 16:33:48 -07:00
|
|
|
}
|
|
|
|
|
2014-09-23 08:23:04 -06:00
|
|
|
func Main(ctxt *build.Context, offsetFlag, fromFlag, to string) error {
|
|
|
|
// -- Parse the -from or -offset specifier ----------------------------
|
|
|
|
|
|
|
|
if (offsetFlag == "") == (fromFlag == "") {
|
|
|
|
return fmt.Errorf("exactly one of the -from and -offset flags must be specified")
|
|
|
|
}
|
|
|
|
|
|
|
|
if !isValidIdentifier(to) {
|
|
|
|
return fmt.Errorf("-to %q: not a valid identifier", to)
|
|
|
|
}
|
|
|
|
|
2015-12-29 14:26:28 -07:00
|
|
|
if Diff {
|
|
|
|
defer func(saved func(string, []byte) error) { writeFile = saved }(writeFile)
|
|
|
|
writeFile = diff
|
|
|
|
}
|
|
|
|
|
2014-09-23 08:23:04 -06:00
|
|
|
var spec *spec
|
|
|
|
var err error
|
|
|
|
if fromFlag != "" {
|
|
|
|
spec, err = parseFromFlag(ctxt, fromFlag)
|
|
|
|
} else {
|
|
|
|
spec, err = parseOffsetFlag(ctxt, offsetFlag)
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if spec.fromName == to {
|
|
|
|
return fmt.Errorf("the old and new names are the same: %s", to)
|
|
|
|
}
|
|
|
|
|
|
|
|
// -- Load the program consisting of the initial package -------------
|
|
|
|
|
|
|
|
iprog, err := loadProgram(ctxt, map[string]bool{spec.pkg: true})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
fromObjects, err := findFromObjects(iprog, spec)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// -- Load a larger program, for global renamings ---------------------
|
|
|
|
|
|
|
|
if requiresGlobalRename(fromObjects, to) {
|
|
|
|
// For a local refactoring, we needn't load more
|
|
|
|
// packages, but if the renaming affects the package's
|
|
|
|
// API, we we must load all packages that depend on the
|
|
|
|
// package defining the object, plus their tests.
|
|
|
|
|
|
|
|
if Verbose {
|
2015-12-29 14:26:28 -07:00
|
|
|
log.Print("Potentially global renaming; scanning workspace...")
|
2014-09-23 08:23:04 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
// Scan the workspace and build the import graph.
|
|
|
|
_, rev, errors := importgraph.Build(ctxt)
|
|
|
|
if len(errors) > 0 {
|
2015-06-04 16:38:33 -06:00
|
|
|
// With a large GOPATH tree, errors are inevitable.
|
|
|
|
// Report them but proceed.
|
2014-09-23 08:23:04 -06:00
|
|
|
fmt.Fprintf(os.Stderr, "While scanning Go workspace:\n")
|
|
|
|
for path, err := range errors {
|
|
|
|
fmt.Fprintf(os.Stderr, "Package %q: %s.\n", path, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Enumerate the set of potentially affected packages.
|
|
|
|
affectedPackages := make(map[string]bool)
|
|
|
|
for _, obj := range fromObjects {
|
|
|
|
// External test packages are never imported,
|
|
|
|
// so they will never appear in the graph.
|
|
|
|
for path := range rev.Search(obj.Pkg().Path()) {
|
|
|
|
affectedPackages[path] = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO(adonovan): allow the user to specify the scope,
|
|
|
|
// or -ignore patterns? Computing the scope when we
|
|
|
|
// don't (yet) support inputs containing errors can make
|
|
|
|
// the tool rather brittle.
|
|
|
|
|
|
|
|
// Re-load the larger program.
|
|
|
|
iprog, err = loadProgram(ctxt, affectedPackages)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
fromObjects, err = findFromObjects(iprog, spec)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// -- Do the renaming -------------------------------------------------
|
|
|
|
|
|
|
|
r := renamer{
|
|
|
|
iprog: iprog,
|
|
|
|
objsToUpdate: make(map[types.Object]bool),
|
|
|
|
to: to,
|
|
|
|
packages: make(map[*types.Package]*loader.PackageInfo),
|
|
|
|
}
|
|
|
|
|
cmd/gorename: support renaming of methods with consequences for other types, iff initiated at an abstract method.
Previously, gorename rejected all method renamings if it would
change the assignability relation.
Now, so long as the renaming was initiated at an abstract
method, the renaming proceeds, changing concrete methods (and
possibly other abstract methods) as needed. The user
intention is clear.
The intention of a renaming initiated at a concrete method is
less clear, so we still reject it if it would change the
assignability relation. The diagnostic advises the user to
rename the abstract method if that was the intention.
Additional safety checks are required: for each
satisfy.Constraint that couples a concrete type C and an
interface type I, we must treat it just like a set of implicit
selections C.f, one per abstract method f of I, and ensure the
selections' meanings are unchanged.
The satisfy package no longer canonicalizes types, since this
substitutes one interface for another (equivalent) one, which
is sound, but makes the type names random and the error
messages confusing.
Also, fixed a bug in 'satisfy' relating to map keys.
+ Lots more tests.
LGTM=sameer
R=sameer
CC=golang-codereviews
https://golang.org/cl/173430043
2014-12-04 07:37:50 -07:00
|
|
|
// A renaming initiated at an interface method indicates the
|
|
|
|
// intention to rename abstract and concrete methods as needed
|
|
|
|
// to preserve assignability.
|
|
|
|
for _, obj := range fromObjects {
|
|
|
|
if obj, ok := obj.(*types.Func); ok {
|
|
|
|
recv := obj.Type().(*types.Signature).Recv()
|
|
|
|
if recv != nil && isInterface(recv.Type().Underlying()) {
|
|
|
|
r.changeMethods = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-09-23 08:23:04 -06:00
|
|
|
// Only the initially imported packages (iprog.Imported) and
|
|
|
|
// their external tests (iprog.Created) should be inspected or
|
|
|
|
// modified, as only they have type-checked functions bodies.
|
|
|
|
// The rest are just dependencies, needed only for package-level
|
|
|
|
// type information.
|
|
|
|
for _, info := range iprog.Imported {
|
|
|
|
r.packages[info.Pkg] = info
|
|
|
|
}
|
|
|
|
for _, info := range iprog.Created { // (tests)
|
|
|
|
r.packages[info.Pkg] = info
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, from := range fromObjects {
|
|
|
|
r.check(from)
|
|
|
|
}
|
|
|
|
if r.hadConflicts && !Force {
|
|
|
|
return ConflictError
|
|
|
|
}
|
|
|
|
return r.update()
|
|
|
|
}
|
|
|
|
|
|
|
|
// loadProgram loads the specified set of packages (plus their tests)
|
|
|
|
// and all their dependencies, from source, through the specified build
|
|
|
|
// context. Only packages in pkgs will have their functions bodies typechecked.
|
|
|
|
func loadProgram(ctxt *build.Context, pkgs map[string]bool) (*loader.Program, error) {
|
|
|
|
conf := loader.Config{
|
2015-02-23 15:03:22 -07:00
|
|
|
Build: ctxt,
|
|
|
|
ParserMode: parser.ParseComments,
|
2014-09-23 08:23:04 -06:00
|
|
|
|
|
|
|
// TODO(adonovan): enable this. Requires making a lot of code more robust!
|
|
|
|
AllowErrors: false,
|
|
|
|
}
|
|
|
|
|
|
|
|
// Optimization: don't type-check the bodies of functions in our
|
|
|
|
// dependencies, since we only need exported package members.
|
|
|
|
conf.TypeCheckFuncBodies = func(p string) bool {
|
|
|
|
return pkgs[p] || pkgs[strings.TrimSuffix(p, "_test")]
|
|
|
|
}
|
|
|
|
|
|
|
|
if Verbose {
|
|
|
|
var list []string
|
|
|
|
for pkg := range pkgs {
|
|
|
|
list = append(list, pkg)
|
|
|
|
}
|
|
|
|
sort.Strings(list)
|
|
|
|
for _, pkg := range list {
|
2015-12-29 14:26:28 -07:00
|
|
|
log.Printf("Loading package: %s", pkg)
|
2014-09-23 08:23:04 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
for pkg := range pkgs {
|
2015-01-30 11:30:23 -07:00
|
|
|
conf.ImportWithTests(pkg)
|
2014-09-23 08:23:04 -06:00
|
|
|
}
|
|
|
|
return conf.Load()
|
|
|
|
}
|
|
|
|
|
|
|
|
// requiresGlobalRename reports whether this renaming could potentially
|
|
|
|
// affect other packages in the Go workspace.
|
|
|
|
func requiresGlobalRename(fromObjects []types.Object, to string) bool {
|
|
|
|
var tfm bool
|
|
|
|
for _, from := range fromObjects {
|
|
|
|
if from.Exported() {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
switch objectKind(from) {
|
|
|
|
case "type", "field", "method":
|
|
|
|
tfm = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if ast.IsExported(to) && tfm {
|
|
|
|
// A global renaming may be necessary even if we're
|
|
|
|
// exporting a previous unexported name, since if it's
|
|
|
|
// the name of a type, field or method, this could
|
|
|
|
// change selections in other packages.
|
|
|
|
// (We include "type" in this list because a type
|
|
|
|
// used as an embedded struct field entails a field
|
|
|
|
// renaming.)
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// update updates the input files.
|
|
|
|
func (r *renamer) update() error {
|
|
|
|
// We use token.File, not filename, since a file may appear to
|
|
|
|
// belong to multiple packages and be parsed more than once.
|
|
|
|
// token.File captures this distinction; filename does not.
|
|
|
|
var nidents int
|
|
|
|
var filesToUpdate = make(map[*token.File]bool)
|
|
|
|
for _, info := range r.packages {
|
|
|
|
// Mutate the ASTs and note the filenames.
|
|
|
|
for id, obj := range info.Defs {
|
|
|
|
if r.objsToUpdate[obj] {
|
|
|
|
nidents++
|
|
|
|
id.Name = r.to
|
|
|
|
filesToUpdate[r.iprog.Fset.File(id.Pos())] = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for id, obj := range info.Uses {
|
|
|
|
if r.objsToUpdate[obj] {
|
|
|
|
nidents++
|
|
|
|
id.Name = r.to
|
|
|
|
filesToUpdate[r.iprog.Fset.File(id.Pos())] = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO(adonovan): don't rewrite cgo + generated files.
|
|
|
|
var nerrs, npkgs int
|
|
|
|
for _, info := range r.packages {
|
|
|
|
first := true
|
|
|
|
for _, f := range info.Files {
|
|
|
|
tokenFile := r.iprog.Fset.File(f.Pos())
|
|
|
|
if filesToUpdate[tokenFile] {
|
|
|
|
if first {
|
|
|
|
npkgs++
|
|
|
|
first = false
|
|
|
|
if Verbose {
|
2015-12-29 14:26:28 -07:00
|
|
|
log.Printf("Updating package %s", info.Pkg.Path())
|
2014-09-23 08:23:04 -06:00
|
|
|
}
|
|
|
|
}
|
2015-12-29 14:26:28 -07:00
|
|
|
|
|
|
|
filename := tokenFile.Name()
|
|
|
|
var buf bytes.Buffer
|
|
|
|
if err := format.Node(&buf, r.iprog.Fset, f); err != nil {
|
|
|
|
log.Printf("failed to pretty-print syntax tree: %v", err)
|
|
|
|
nerrs++
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if err := writeFile(filename, buf.Bytes()); err != nil {
|
|
|
|
log.Print(err)
|
2014-09-23 08:23:04 -06:00
|
|
|
nerrs++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-12-29 14:26:28 -07:00
|
|
|
if !Diff {
|
|
|
|
fmt.Printf("Renamed %d occurrence%s in %d file%s in %d package%s.\n",
|
|
|
|
nidents, plural(nidents),
|
|
|
|
len(filesToUpdate), plural(len(filesToUpdate)),
|
|
|
|
npkgs, plural(npkgs))
|
|
|
|
}
|
2014-09-23 08:23:04 -06:00
|
|
|
if nerrs > 0 {
|
|
|
|
return fmt.Errorf("failed to rewrite %d file%s", nerrs, plural(nerrs))
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func plural(n int) string {
|
|
|
|
if n != 1 {
|
|
|
|
return "s"
|
|
|
|
}
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
2015-12-29 14:26:28 -07:00
|
|
|
// writeFile is a seam for testing and for the -d flag.
|
|
|
|
var writeFile = reallyWriteFile
|
|
|
|
|
|
|
|
func reallyWriteFile(filename string, content []byte) error {
|
|
|
|
return ioutil.WriteFile(filename, content, 0644)
|
|
|
|
}
|
|
|
|
|
|
|
|
func diff(filename string, content []byte) error {
|
2015-12-30 09:05:30 -07:00
|
|
|
renamed := fmt.Sprintf("%s.%d.renamed", filename, os.Getpid())
|
2015-12-29 14:26:28 -07:00
|
|
|
if err := ioutil.WriteFile(renamed, content, 0644); err != nil {
|
|
|
|
return err
|
2014-12-05 12:07:01 -07:00
|
|
|
}
|
2015-12-29 14:26:28 -07:00
|
|
|
defer os.Remove(renamed)
|
|
|
|
|
|
|
|
diff, err := exec.Command(DiffCmd, "-u", filename, renamed).CombinedOutput()
|
|
|
|
if len(diff) > 0 {
|
|
|
|
// diff exits with a non-zero status when the files don't match.
|
|
|
|
// Ignore that failure as long as we get output.
|
|
|
|
stdout.Write(diff)
|
|
|
|
return nil
|
2014-09-23 08:23:04 -06:00
|
|
|
}
|
2015-12-29 14:26:28 -07:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("computing diff: %v", err)
|
|
|
|
}
|
|
|
|
return nil
|
2014-09-23 08:23:04 -06:00
|
|
|
}
|