diff --git a/cmd/errtrace/main.go b/cmd/errtrace/main.go index ee0b363..e0ababa 100644 --- a/cmd/errtrace/main.go +++ b/cmd/errtrace/main.go @@ -19,6 +19,7 @@ import ( "flag" "fmt" "go/ast" + gofmt "go/format" "go/parser" "go/token" "io" @@ -38,8 +39,22 @@ func main() { } type mainParams struct { - Write bool // -w - Files []string // list of files to process + Write bool // -w + Format format // -format + Files []string // list of files to process +} + +func (p *mainParams) shouldFormat() bool { + switch p.Format { + case formatAuto: + return p.Write + case formatAlways: + return true + case formatNever: + return false + default: + panic(fmt.Sprintf("unknown format %q", p.Format)) + } } func (p *mainParams) Parse(w io.Writer, args []string) error { @@ -50,8 +65,10 @@ func (p *mainParams) Parse(w io.Writer, args []string) error { flag.PrintDefaults() } + flag.Var(&p.Format, "format", "whether to format ouput; one of: [auto, always, never].\n"+ + "auto will format if the output is being written to a file.") flag.BoolVar(&p.Write, "w", false, - "write result to the given source files instead of stdout") + "write result to the given source files instead of stdout.") // TODO: toolexec mode if err := flag.Parse(args); err != nil { @@ -67,6 +84,64 @@ func (p *mainParams) Parse(w io.Writer, args []string) error { return nil } +// format specifies whether the output should be gofmt'd. +type format int + +var _ flag.Getter = (*format)(nil) + +const ( + // formatAuto formats the output + // if it's being written to a file + // but not if it's being written to stdout. + // + // This is the default. + formatAuto format = iota + + // formatAlways always formats the output. + formatAlways + + // formatNever never formats the output. + formatNever +) + +func (f *format) Get() interface{} { + return *f +} + +// IsBoolFlag tells the flag package that plain "-format" is a valid flag. +// When "-format" is used without a value, +// the flag package will call Set("true") on the flag. +func (f *format) IsBoolFlag() bool { + return true +} + +func (f *format) Set(s string) error { + switch s { + case "auto": + *f = formatAuto + case "always", "true": // "true" comes from "-format" without a value + *f = formatAlways + case "never": + *f = formatNever + default: + return fmt.Errorf("invalid format %q is not one of [auto, always, never]", s) + } + return nil +} + +func (f *format) String() string { + switch *f { + case formatAuto: + return "auto" + case formatAlways: + return "always" + case formatNever: + return "never" + default: + return fmt.Sprintf("format(%d)", *f) + } +} + type mainCmd struct { Stderr io.Writer Stdout io.Writer @@ -84,7 +159,12 @@ func (cmd *mainCmd) Run(args []string) (exitCode int) { } for _, file := range p.Files { - if err := cmd.processFile(p.Write, file); err != nil { + req := fileRequest{ + Format: p.shouldFormat(), + Write: p.Write, + Filename: file, + } + if err := cmd.processFile(req); err != nil { cmd.log.Printf("%s:%s", file, err) exitCode = 1 } @@ -93,6 +173,12 @@ func (cmd *mainCmd) Run(args []string) (exitCode int) { return exitCode } +type fileRequest struct { + Format bool + Write bool + Filename string +} + // processFile processes a single file. // This operates in two phases: // @@ -101,14 +187,14 @@ func (cmd *mainCmd) Run(args []string) (exitCode int) { // // The collected information is used to pick a package name, // whether we need an import, etc. and *then* the edits are applied. -func (cmd *mainCmd) processFile(write bool, filename string) error { +func (cmd *mainCmd) processFile(r fileRequest) error { fset := token.NewFileSet() - src, err := os.ReadFile(filename) + src, err := os.ReadFile(r.Filename) if err != nil { return err } - f, err := parser.ParseFile(fset, filename, src, parser.ParseComments) + f, err := parser.ParseFile(fset, r.Filename, src, parser.ParseComments) if err != nil { return err } @@ -278,11 +364,19 @@ func (cmd *mainCmd) processFile(write bool, filename string) error { } _, _ = out.Write(src[lastOffset:]) // flush remaining - if write { - return os.WriteFile(filename, out.Bytes(), 0o644) + outSrc := out.Bytes() + if r.Format { + outSrc, err = gofmt.Source(outSrc) + if err != nil { + return fmt.Errorf("format: %w", err) + } } - _, err = cmd.Stdout.Write(out.Bytes()) + if r.Write { + err = os.WriteFile(r.Filename, outSrc, 0o644) + } else { + _, err = cmd.Stdout.Write(outSrc) + } return err } diff --git a/cmd/errtrace/main_test.go b/cmd/errtrace/main_test.go index bea535b..205dbc5 100644 --- a/cmd/errtrace/main_test.go +++ b/cmd/errtrace/main_test.go @@ -2,6 +2,7 @@ package main import ( "bytes" + "flag" "fmt" "go/parser" "go/token" @@ -73,7 +74,7 @@ func testGolden(t *testing.T, file string) { exitCode := (&mainCmd{ Stdout: &stdout, // We don't care about stdout. Stderr: &stderr, - }).Run([]string{"-w", srcPath}) + }).Run([]string{"-format=never", "-w", srcPath}) if want := 0; exitCode != want { t.Errorf("exit code = %d, want %d", exitCode, want) @@ -118,6 +119,199 @@ func testGolden(t *testing.T, file string) { }) } +func TestParseFormatFlag(t *testing.T) { + tests := []struct { + name string + give []string + want format + }{ + { + name: "default", + want: formatAuto, + }, + { + name: "auto explicit", + give: []string{"-format=auto"}, + want: formatAuto, + }, + { + name: "always", + give: []string{"-format=always"}, + want: formatAlways, + }, + { + name: "always explicit", + give: []string{"-format"}, + want: formatAlways, + }, + { + name: "never", + give: []string{"-format=never"}, + want: formatNever, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + flag := flag.NewFlagSet(t.Name(), flag.ContinueOnError) + flag.SetOutput(io.Discard) + + var got format + flag.Var(&got, "format", "") + if err := flag.Parse(tt.give); err != nil { + t.Fatal(err) + } + + if want, got := tt.want, got; got != want { + t.Errorf("got %v, want %v", got, want) + } + }) + } +} + +func TestFormatFlagError(t *testing.T) { + flag := flag.NewFlagSet(t.Name(), flag.ContinueOnError) + flag.SetOutput(io.Discard) + + var got format + flag.Var(&got, "format", "") + err := flag.Parse([]string{"-format=unknown"}) + if err == nil { + t.Fatal("no error") + } + + if want, got := `invalid format "unknown"`, err.Error(); !strings.Contains(got, want) { + t.Errorf("error %q does not contain %q", got, want) + } +} + +func TestFormatFlagString(t *testing.T) { + tests := []struct { + give format + want string + }{ + {formatAuto, "auto"}, + {formatAlways, "always"}, + {formatNever, "never"}, + {format(999), "format(999)"}, + } + + for _, tt := range tests { + t.Run(fmt.Sprintf("%d", tt.give), func(t *testing.T) { + if want, got := tt.want, tt.give.String(); got != want { + t.Errorf("got %q, want %q", got, want) + } + }) + } +} + +func TestShouldFormat(t *testing.T) { + tests := []struct { + name string + give mainParams + want bool + }{ + {"auto/no write", mainParams{Format: formatAuto}, false}, + {"auto/write", mainParams{Format: formatAuto, Write: true}, true}, + {"always", mainParams{Format: formatAlways}, true}, + {"never", mainParams{Format: formatNever}, false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if want, got := tt.want, tt.give.shouldFormat(); got != want { + t.Errorf("got %v, want %v", got, want) + } + }) + } + + t.Run("unknown", func(t *testing.T) { + defer func() { + if err := recover(); err == nil { + t.Fatal("no panic") + } + }() + + (&mainParams{Format: format(999)}).shouldFormat() + }) +} + +// -format=auto should format the file if used with -w, +// and not format the file if used without -w. +func TestFormatAuto(t *testing.T) { + give := strings.Join([]string{ + "package foo", + `import "errors"`, + "func foo() error {", + ` return errors.New("foo")`, + "}", + }, "\n") + + wantUnformatted := strings.Join([]string{ + "package foo", + `import "errors"; import "braces.dev/errtrace"`, + "func foo() error {", + ` return errtrace.Wrap(errors.New("foo"))`, + "}", + }, "\n") + + wantFormatted := strings.Join([]string{ + "package foo", + "", + `import "errors"`, + `import "braces.dev/errtrace"`, + "", + "func foo() error {", + ` return errtrace.Wrap(errors.New("foo"))`, + "}", + "", + }, "\n") + + t.Run("write", func(t *testing.T) { + srcPath := filepath.Join(t.TempDir(), "src.go") + if err := os.WriteFile(srcPath, []byte(give), 0o600); err != nil { + t.Fatal(err) + } + + exitCode := (&mainCmd{ + Stdout: io.Discard, + Stderr: io.Discard, + }).Run([]string{"-w", srcPath}) + if want := 0; exitCode != want { + t.Errorf("exit code = %d, want %d", exitCode, want) + } + + bs, err := os.ReadFile(srcPath) + if err != nil { + t.Fatal(err) + } + + if want, got := wantFormatted, string(bs); got != want { + t.Errorf("got:\n%s\nwant:\n%s\ndiff:\n%s", indent(got), indent(want), indent(diffLines(want, got))) + } + }) + + t.Run("stdout", func(t *testing.T) { + srcPath := filepath.Join(t.TempDir(), "src.go") + if err := os.WriteFile(srcPath, []byte(give), 0o600); err != nil { + t.Fatal(err) + } + + var out bytes.Buffer + exitCode := (&mainCmd{ + Stdout: &out, + Stderr: io.Discard, + }).Run([]string{srcPath}) + if want := 0; exitCode != want { + t.Errorf("exit code = %d, want %d", exitCode, want) + } + + if want, got := wantUnformatted, out.String(); got != want { + t.Errorf("got:\n%s\nwant:\n%s\ndiff:\n%s", indent(got), indent(want), indent(diffLines(want, got))) + } + }) +} + func indent(s string) string { return "\t" + strings.ReplaceAll(s, "\n", "\n\t") }