Debian Codegraph @

cmd/eg/eg.go

raw symbols SCIP
1 // Copyright 2014 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // The eg command performs example-based refactoring.
6 // For documentation, run the command, or see Help in
7 // golang.org/x/tools/refactor/eg.
8 package main // import "golang.org/x/tools/cmd/eg"
9
10 import (
11 "flag"
12 "fmt"
13 "go/ast"
14 "go/format"
15 "go/parser"
16 "go/token"
17 "go/types"
18 "os"
19 "os/exec"
20 "path/filepath"
21 "strings"
22
23 "golang.org/x/tools/go/packages"
24 "golang.org/x/tools/refactor/eg"
25 )
26
27 var (
28 beforeeditFlag = flag.String("beforeedit", "", "A command to exec before each file is edited (e.g. chmod, checkout). Whitespace delimits argument words. The string '{}' is replaced by the file name.")
29 helpFlag = flag.Bool("help", false, "show detailed help message")
30 tagsFlag = flag.String("tags", "", "comma-separated list of build tags to apply (see: go help buildconstraint)")
31 templateFlag = flag.String("t", "", "template.go file specifying the refactoring")
32 transitiveFlag = flag.Bool("transitive", false, "apply refactoring to all dependencies too")
33 writeFlag = flag.Bool("w", false, "rewrite input files in place (by default, the results are printed to standard output)")
34 verboseFlag = flag.Bool("v", false, "show verbose matcher diagnostics")
35 )
36
37 const usage = `eg: an example-based refactoring tool.
38
39 Usage: eg -t template.go [-w] [-transitive] [-tags=tag,...] <packages>
40
41 -help show detailed help message
42 -t template.go specifies the template file (use -help to see explanation)
43 -w causes files to be re-written in place.
44 -transitive causes all dependencies to be refactored too.
45 -v show verbose matcher diagnostics
46 -tags tag,... comma-separated list of build tags to apply (see: go help buildconstraint)
47 -beforeedit cmd a command to exec before each file is modified.
48 "{}" represents the name of the file.
49 `
50
51 func main() {
52 if err := doMain(); err != nil {
53 fmt.Fprintf(os.Stderr, "eg: %s\n", err)
54 os.Exit(1)
55 }
56 }
57
58 func doMain() error {
59 flag.Parse()
60 args := flag.Args()
61
62 if *helpFlag {
63 help := eg.Help // hide %s from vet
64 fmt.Fprint(os.Stderr, help)
65 os.Exit(2)
66 }
67
68 if len(args) == 0 {
69 fmt.Fprint(os.Stderr, usage)
70 os.Exit(1)
71 }
72
73 if *templateFlag == "" {
74 return fmt.Errorf("no -t template.go file specified")
75 }
76
77 tAbs, err := filepath.Abs(*templateFlag)
78 if err != nil {
79 return err
80 }
81 template, err := os.ReadFile(tAbs)
82 if err != nil {
83 return err
84 }
85
86 cfg := &packages.Config{
87 BuildFlags: []string{"-tags=" + *tagsFlag},
88 Fset: token.NewFileSet(),
89 Mode: packages.NeedTypesInfo | packages.NeedName | packages.NeedTypes | packages.NeedSyntax | packages.NeedImports | packages.NeedDeps | packages.NeedCompiledGoFiles,
90 Tests: true,
91 }
92
93 pkgs, err := packages.Load(cfg, args...)
94 if err != nil {
95 return err
96 }
97
98 tFile, err := parser.ParseFile(cfg.Fset, tAbs, template, parser.ParseComments)
99 if err != nil {
100 return err
101 }
102
103 // Type-check the template.
104 tInfo := types.Info{
105 Types: make(map[ast.Expr]types.TypeAndValue),
106 Defs: make(map[*ast.Ident]types.Object),
107 Uses: make(map[*ast.Ident]types.Object),
108 Implicits: make(map[ast.Node]types.Object),
109 Selections: make(map[*ast.SelectorExpr]*types.Selection),
110 Scopes: make(map[ast.Node]*types.Scope),
111 }
112 conf := types.Config{
113 Importer: pkgsImporter(pkgs),
114 }
115 tPkg, err := conf.Check("egtemplate", cfg.Fset, []*ast.File{tFile}, &tInfo)
116 if err != nil {
117 return err
118 }
119
120 // Analyze the template.
121 xform, err := eg.NewTransformer(cfg.Fset, tPkg, tFile, &tInfo, *verboseFlag)
122 if err != nil {
123 return err
124 }
125
126 // Apply it to the input packages.
127 var all []*packages.Package
128 if *transitiveFlag {
129 packages.Visit(pkgs, nil, func(p *packages.Package) { all = append(all, p) })
130 } else {
131 all = pkgs
132 }
133 var hadErrors bool
134 for _, pkg := range pkgs {
135 for i, filename := range pkg.CompiledGoFiles {
136 if filename == tAbs {
137 // Don't rewrite the template file.
138 continue
139 }
140 file := pkg.Syntax[i]
141 n := xform.Transform(pkg.TypesInfo, pkg.Types, file)
142 if n == 0 {
143 continue
144 }
145 fmt.Fprintf(os.Stderr, "=== %s (%d matches)\n", filename, n)
146 if *writeFlag {
147 // Run the before-edit command (e.g. "chmod +w", "checkout") if any.
148 if *beforeeditFlag != "" {
149 args := strings.Fields(*beforeeditFlag)
150 // Replace "{}" with the filename, like find(1).
151 for i := range args {
152 if i > 0 {
153 args[i] = strings.Replace(args[i], "{}", filename, -1)
154 }
155 }
156 cmd := exec.Command(args[0], args[1:]...)
157 cmd.Stdout = os.Stdout
158 cmd.Stderr = os.Stderr
159 if err := cmd.Run(); err != nil {
160 fmt.Fprintf(os.Stderr, "Warning: edit hook %q failed (%s)\n",
161 args, err)
162 }
163 }
164 if err := eg.WriteAST(cfg.Fset, filename, file); err != nil {
165 fmt.Fprintf(os.Stderr, "eg: %s\n", err)
166 hadErrors = true
167 }
168 } else {
169 format.Node(os.Stdout, cfg.Fset, file)
170 }
171 }
172 }
173 if hadErrors {
174 os.Exit(1)
175 }
176
177 return nil
178 }
179
180 type pkgsImporter []*packages.Package
181
182 func (p pkgsImporter) Import(path string) (tpkg *types.Package, err error) {
183 packages.Visit([]*packages.Package(p), func(pkg *packages.Package) bool {
184 if pkg.PkgPath == path {
185 tpkg = pkg.Types
186 return false
187 }
188 return true
189 }, nil)
190 if tpkg != nil {
191 return tpkg, nil
192 }
193 return nil, fmt.Errorf("package %q not found", path)
194 }