Skip to content

Commit ad8b86f

Browse files
committed
fail with -d if formatting any of the files resulted in a diff
This mimics the proposed and accepted behavior change for `gofmt -d` at https://go.dev/issue/46289. Fixes #114.
1 parent adce750 commit ad8b86f

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

Diff for: gofmt.go

+12-2
Original file line numberDiff line numberDiff line change
@@ -257,14 +257,23 @@ func (r *reporter) Report(err error) {
257257
panic("Report with nil error")
258258
}
259259
st := r.getState()
260-
scanner.PrintError(st.err, err)
261-
st.exitCode = 2
260+
switch err.(type) {
261+
case printedDiff:
262+
st.exitCode = 1
263+
default:
264+
scanner.PrintError(st.err, err)
265+
st.exitCode = 2
266+
}
262267
}
263268

264269
func (r *reporter) ExitCode() int {
265270
return r.getState().exitCode
266271
}
267272

273+
type printedDiff struct{}
274+
275+
func (printedDiff) Error() string { return "printed a diff, exiting with status code 1" }
276+
268277
// If info == nil, we are formatting stdin instead of a file.
269278
// If in == nil, the source is the contents of the file with the given filename.
270279
func processFile(filename string, info fs.FileInfo, in io.Reader, r *reporter, explicit bool) error {
@@ -358,6 +367,7 @@ func processFile(filename string, info fs.FileInfo, in io.Reader, r *reporter, e
358367
newName := filepath.ToSlash(filename)
359368
oldName := newName + ".orig"
360369
r.Write(diff.Diff(oldName, src, newName, res))
370+
return printedDiff{}
361371
}
362372
}
363373

Diff for: testdata/script/diff.txtar

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
# gofumpt fails with -d if there is a diff (TODO).
1+
# gofumpt fails with -d if there is a diff.
22

33
exec gofumpt -d good.go
44
! stdout .
55
! stderr .
66

7-
exec gofumpt -d bad.go
7+
! exec gofumpt -d bad.go
88
cmp stdout bad.go.diff
99
! stderr .
1010

0 commit comments

Comments
 (0)