Skip to content

Instantly share code, notes, and snippets.

@reusee
Created January 31, 2020 06:27
Show Gist options
  • Save reusee/a3f81c6c9a510f9523014290ce1df852 to your computer and use it in GitHub Desktop.
Save reusee/a3f81c6c9a510f9523014290ce1df852 to your computer and use it in GitHub Desktop.
go rename
package main
import (
"bytes"
"go/format"
"go/types"
"io/ioutil"
"golang.org/x/tools/go/packages"
)
func main() {
// load std
pkgs, err := packages.Load(
&packages.Config{
Mode: packages.NeedTypesInfo |
packages.NeedTypes |
packages.NeedSyntax |
packages.NeedName,
},
"std",
)
if err != nil {
panic(err)
}
if packages.PrintErrors(pkgs) > 0 {
return
}
// find fmt.Sprintf object
var obj types.Object
for _, pkg := range pkgs {
if pkg.Name != "fmt" {
continue
}
obj = pkg.Types.Scope().Lookup("Sprintf")
break
}
if obj == nil {
panic("fmt.Sprintf not found")
}
for _, pkg := range pkgs {
// find all fmt.Sprintf usages and rename identifiers
affectedFiles := make(map[string]bool)
for ident, o := range pkg.TypesInfo.Uses {
if o == obj {
ident.Name = "foobarbaz"
affectedFiles[pkg.Fset.File(ident.Pos()).Name()] = true
}
}
// write updated files
for _, file := range pkg.Syntax {
filePath := pkg.Fset.File(file.Pos()).Name()
if _, ok := affectedFiles[filePath]; ok {
buf := new(bytes.Buffer)
if err := format.Node(buf, pkg.Fset, file); err != nil {
panic(err)
}
if err := ioutil.WriteFile(filePath, buf.Bytes(), 0644); err != nil {
panic(err)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment