forked from godoctor/godoctor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.go
408 lines (368 loc) · 11.1 KB
/
cli.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
// Copyright 2016 Auburn University. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The cli package provides a command-line interface for the Go Doctor.
package cli
import (
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"time"
"strings"
"github.com/godoctor/godoctor/doc"
"github.com/godoctor/godoctor/engine"
"github.com/godoctor/godoctor/engine/protocol"
"github.com/godoctor/godoctor/filesystem"
"github.com/godoctor/godoctor/refactoring"
"github.com/godoctor/godoctor/text"
)
const useHelp = "Run 'godoctor -help' for more information.\n"
func printHelp(aboutText string, flags *flag.FlagSet, stderr io.Writer) {
fmt.Fprintf(stderr, `%s - Go source code refactoring tool.
Usage: godoctor [<flag> ...] <refactoring> [<args> ...]
Each <flag> must be one of the following:
`, aboutText)
flags.VisitAll(func(flag *flag.Flag) {
fmt.Fprintf(stderr, " -%-8s %s\n", flag.Name, flag.Usage)
})
fmt.Fprintln(stderr, `
The <refactoring> argument determines the refactoring to perform:`)
for _, key := range engine.AllRefactoringNames() {
r := engine.GetRefactoring(key)
if !r.Description().Hidden {
fmt.Fprintf(stderr, " %-15s %s\n",
key, r.Description().Synopsis)
}
}
fmt.Fprintln(stderr, `
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`)
}
type CLIFlags struct {
*flag.FlagSet
fileFlag *string
posFlag *string
scopeFlag *string
completeFlag *bool
writeFlag *bool
verboseFlag *bool
veryVerboseFlag *bool
listFlag *bool
jsonFlag *bool
docFlag *string
}
// Flags returns the flags supported by the godoctor command line tool.
func Flags() *CLIFlags {
flags := CLIFlags{
FlagSet: flag.NewFlagSet("godoctor", flag.ContinueOnError)}
flags.fileFlag = flags.String("file", "",
"Filename containing an element to refactor (default: stdin)")
flags.posFlag = flags.String("pos", "1,1:1,1",
"Position of a syntax element to refactor (default: entire file)")
flags.scopeFlag = flags.String("scope", "",
"Package name(s), or source file containing a program entrypoint")
flags.completeFlag = flags.Bool("complete", false,
"Output entire modified source files instead of displaying a diff")
flags.writeFlag = flags.Bool("w", false,
"Modify source files on disk (write) instead of displaying a diff")
flags.verboseFlag = flags.Bool("v", false,
"Verbose: list affected files")
flags.veryVerboseFlag = flags.Bool("vv", false,
"Very verbose: list individual edits (implies -v)")
flags.listFlag = flags.Bool("list", false,
"List all refactorings and exit")
flags.jsonFlag = flags.Bool("json", false,
"Accept commands in OpenRefactory JSON protocol format")
flags.docFlag = flags.String("doc", "",
"Output documentation (install, user, man, or vim) and exit")
return &flags
}
// Run runs the Go Doctor command-line interface. Typical usage is
// os.Exit(cli.Run(os.Stdin, os.Stdout, os.Stderr, os.Args))
// All arguments must be non-nil, and args[0] is required.
func Run(aboutText string, stdin io.Reader, stdout io.Writer, stderr io.Writer, args []string) int {
flags := Flags()
// Don't print full help unless -help was requested.
// Just gently remind users that it's there.
flags.Usage = func() { fmt.Fprint(stderr, useHelp) }
flags.Init(args[0], flag.ContinueOnError)
flags.SetOutput(stderr)
if err := flags.Parse(args[1:]); err != nil {
// (err has already been printed)
if err == flag.ErrHelp {
// Invoked as "godoctor [flags] -help"
printHelp(aboutText, flags.FlagSet, stderr)
return 2
}
return 1
}
args = flags.Args()
if *flags.docFlag != "" {
if len(args) > 0 || flags.NFlag() != 1 {
fmt.Fprintln(stderr, "Error: The -doc flag cannot "+
"be used with any other flags or arguments")
return 1
}
switch *flags.docFlag {
case "man":
doc.PrintManPage(aboutText, flags.FlagSet, stdout)
case "install":
doc.PrintInstallGuide(aboutText, flags.FlagSet, stdout)
case "user":
doc.PrintUserGuide(aboutText, flags.FlagSet, stdout)
case "vim":
doc.PrintVimdoc(aboutText, flags.FlagSet, stdout)
default:
fmt.Fprintln(stderr, "Error: The -doc flag must be "+
"\"man\", \"install\", \"user\", or \"vim\"")
return 1
}
return 0
}
if *flags.listFlag {
if len(args) > 0 {
fmt.Fprintln(stderr, "Error: The -list flag "+
"cannot be used with any arguments")
return 1
}
if *flags.verboseFlag || *flags.veryVerboseFlag ||
*flags.writeFlag || *flags.completeFlag ||
*flags.jsonFlag {
fmt.Fprintln(stderr, "Error: The -list flag "+
"cannot be used with the -v, -vv, -w, "+
"-complete, or -json flags")
return 1
}
// Invoked: godoctor [-file=""] [-pos=""] [-scope=""] -list
fmt.Fprintf(stderr, "%-15s\t%-47s\t%s\n",
"Refactoring", "Description", " Multifile?")
fmt.Fprintf(stderr, "--------------------------------------------------------------------------------\n")
for _, key := range engine.AllRefactoringNames() {
r := engine.GetRefactoring(key)
d := r.Description()
if !r.Description().Hidden {
fmt.Fprintf(stderr, "%-15s\t%-50s\t%v\n",
key, d.Synopsis, d.Multifile)
}
}
return 0
}
if *flags.jsonFlag {
if flags.NFlag() != 1 {
fmt.Fprintln(stderr, "Error: The -json flag "+
"cannot be used with any other flags")
return 1
}
// Invoked as "godoctor -json [args]
protocol.Run(os.Stdout, aboutText, args)
return 0
}
if *flags.writeFlag && *flags.completeFlag {
fmt.Fprintln(stderr, "Error: The -w and -complete flags "+
"cannot both be present")
return 1
}
if len(args) == 0 || args[0] == "" || args[0] == "help" {
// Invoked as "godoctor [flags]" or "godoctor [flags] help"
printHelp(aboutText, flags.FlagSet, stderr)
return 2
}
refacName := args[0]
refac := engine.GetRefactoring(refacName)
if refac == nil {
fmt.Fprintf(stderr, "There is no refactoring named \"%s\"\n",
refacName)
return 1
}
args = args[1:]
if flags.NFlag() == 0 && flags.NArg() == 1 {
// Invoked as "godoctor refactoring"
fmt.Fprintf(stderr, "Usage: %s %s\n",
refacName, refac.Description().Usage)
return 2
}
stdinPath := ""
var fileName string
var fileSystem filesystem.FileSystem
if *flags.fileFlag != "" && *flags.fileFlag != "-" {
fileName = *flags.fileFlag
fileSystem = &filesystem.LocalFileSystem{}
} else {
// Filename is - or no filename given; read from standard input
var err error
stdinPath, err = filesystem.FakeStdinPath()
if err != nil {
fmt.Fprintln(stderr, err)
return 1
}
fileName = stdinPath
bytes, err := ioutil.ReadAll(stdin)
if err != nil {
fmt.Fprintln(stderr, err)
return 1
}
fileSystem, err = filesystem.NewSingleEditedFileSystem(
stdinPath, string(bytes))
if err != nil {
fmt.Fprintln(stderr, err)
return 1
}
}
selection, err := text.NewSelection(fileName, *flags.posFlag)
if err != nil {
fmt.Fprintf(stderr, "Error: %s.\n", err)
return 1
}
var scope []string
if *flags.scopeFlag == "" {
// If no scope provided, let refactoring.go guess the scope
scope = nil
} else if *flags.scopeFlag == "-" && stdinPath != "" {
// Use -scope=- to indicate "stdin file (not package) scope"
scope = []string{stdinPath}
} else {
// Use -scope=a,b,c to specify multiple files/packages
scope = strings.Split(*flags.scopeFlag, ",")
}
verbosity := 0
if *flags.verboseFlag {
verbosity = 1
}
if *flags.veryVerboseFlag {
verbosity = 2
}
result := refac.Run(&refactoring.Config{
FileSystem: fileSystem,
Scope: scope,
Selection: selection,
Args: refactoring.InterpretArgs(args, refac),
Verbosity: verbosity})
// Display log in GNU-style 'file:line.col-line.col: message' format
cwd, err := os.Getwd()
if err != nil {
cwd = ""
}
result.Log.Write(stderr, cwd)
// If input was supplied on standard input, ensure that the refactoring
// makes changes only to that code (and does not affect any other files)
if stdinPath != "" {
for f, _ := range result.Edits {
if f != stdinPath {
fmt.Fprintf(stderr, "Error: When source code is given on standard input, refactorings are prohibited from changing any other files. This refactoring would require modifying %s.\n", f)
return 1
}
}
}
if *flags.writeFlag {
err = writeToDisk(result, fileSystem)
} else if *flags.completeFlag {
err = writeFileContents(stdout, result.Edits, fileSystem)
} else {
err = writeDiff(stdout, result.Edits, fileSystem)
}
if err != nil {
fmt.Fprintf(stderr, "Error: %s.\n", err)
return 1
}
if result.Log.ContainsErrors() {
return 3
} else {
return 0
}
}
// writeDiff outputs a multi-file unified diff describing this refactoring's
// changes. It can be applied using GNU patch.
func writeDiff(out io.Writer, edits map[string]*text.EditSet, fs filesystem.FileSystem) error {
for f, e := range edits {
p, err := filesystem.CreatePatch(e, fs, f)
if err != nil {
return err
}
if !p.IsEmpty() {
inFile := f
outFile := f
stdinPath, _ := filesystem.FakeStdinPath()
if f == stdinPath {
inFile = os.Stdin.Name()
outFile = os.Stdout.Name()
} else {
rel := relativePath(f)
inFile = rel
outFile = rel
}
fmt.Fprintf(out, "diff -u %s %s\n", inFile, outFile)
p.Write(inFile, outFile, time.Time{}, time.Time{}, out)
}
}
return nil
}
// relativePath returns a relative path to fname, or fname if a relative path
// cannot be computed due to an error
func relativePath(fname string) string {
if cwd, err := os.Getwd(); err == nil {
if rel, err := filepath.Rel(cwd, fname); err == nil {
return rel
}
}
return fname
}
// writeFileContents outputs the complete contents of each file affected by
// this refactoring.
func writeFileContents(out io.Writer, edits map[string]*text.EditSet, fs filesystem.FileSystem) error {
for filename, edits := range edits {
data, err := filesystem.ApplyEdits(edits, fs, filename)
if err != nil {
return err
}
stdinPath, _ := filesystem.FakeStdinPath()
if filename == stdinPath {
filename = os.Stdin.Name()
}
if _, err := fmt.Fprintf(out, "@@@@@ %s @@@@@ %d @@@@@\n",
filename, len(data)); err != nil {
return err
}
n, err := out.Write(data)
if n < len(data) && err == nil {
err = io.ErrShortWrite
}
if err != nil {
return err
}
if len(data) > 0 && data[len(data)-1] != '\n' {
fmt.Fprintln(out)
}
}
return nil
}
// writeToDisk overwrites existing files with their refactored versions and
// applies any other changes to the file system that the refactoring requires
// (e.g., renaming directories).
func writeToDisk(result *refactoring.Result, fs filesystem.FileSystem) error {
for filename, edits := range result.Edits {
data, err := filesystem.ApplyEdits(edits, fs, filename)
if err != nil {
return err
}
f, err := fs.OverwriteFile(filename)
if err != nil {
return err
}
n, err := f.Write(data)
if err == nil && n < len(data) {
err = io.ErrShortWrite
}
if err1 := f.Close(); err == nil {
err = err1
}
if err != nil {
return err
}
}
return nil
}