| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package cmd |
| 6 |
|
| 7 |
import ( |
| 8 |
"context" |
| 9 |
"flag" |
| 10 |
"fmt" |
| 11 |
|
| 12 |
"golang.org/x/tools/gopls/internal/protocol" |
| 13 |
) |
| 14 |
|
| 15 |
|
| 16 |
type format struct { |
| 17 |
EditFlags |
| 18 |
app *Application |
| 19 |
} |
| 20 |
|
| 21 |
func (c *format) Name() string { return "format" } |
| 22 |
func (c *format) Parent() string { return c.app.Name() } |
| 23 |
func (c *format) Usage() string { return "[format-flags] <filerange>" } |
| 24 |
func (c *format) ShortHelp() string { return "format the code according to the go standard" } |
| 25 |
func (c *format) DetailedHelp(f *flag.FlagSet) { |
| 26 |
fmt.Fprint(f.Output(), ` |
| 27 |
The arguments supplied may be simple file names, or ranges within files. |
| 28 |
|
| 29 |
Example: reformat this file: |
| 30 |
|
| 31 |
$ gopls format -w internal/cmd/check.go |
| 32 |
|
| 33 |
format-flags: |
| 34 |
`) |
| 35 |
printFlagDefaults(f) |
| 36 |
} |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
func (c *format) Run(ctx context.Context, args ...string) error { |
| 41 |
if len(args) == 0 { |
| 42 |
return nil |
| 43 |
} |
| 44 |
c.app.editFlags = &c.EditFlags |
| 45 |
cli, _, err := c.app.connect(ctx) |
| 46 |
if err != nil { |
| 47 |
return err |
| 48 |
} |
| 49 |
defer cli.terminate(ctx) |
| 50 |
for _, arg := range args { |
| 51 |
spn := parseSpan(arg) |
| 52 |
file, err := cli.openFile(ctx, spn.URI()) |
| 53 |
if err != nil { |
| 54 |
return err |
| 55 |
} |
| 56 |
loc, err := file.spanLocation(spn) |
| 57 |
if err != nil { |
| 58 |
return err |
| 59 |
} |
| 60 |
if loc.Range.Start != loc.Range.End { |
| 61 |
return fmt.Errorf("only full file formatting supported") |
| 62 |
} |
| 63 |
p := protocol.DocumentFormattingParams{ |
| 64 |
TextDocument: protocol.TextDocumentIdentifier{URI: loc.URI}, |
| 65 |
} |
| 66 |
edits, err := cli.server.Formatting(ctx, &p) |
| 67 |
if err != nil { |
| 68 |
return fmt.Errorf("%v: %v", spn, err) |
| 69 |
} |
| 70 |
if err := applyTextEdits(file.mapper, edits, c.app.editFlags); err != nil { |
| 71 |
return err |
| 72 |
} |
| 73 |
} |
| 74 |
return nil |
| 75 |
} |