gohack undo leaves trailing newlines
This is how we can reproduce the issue:
$ git clone https://github.com/rogpeppe/go-internal.git
$ gohack get gopkg.in/errgo.v2
$ gohack undo
$ git status
On branch master
Your branch is up to date with 'origin/master'.
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: go.mod
no changes added to commit (use "git add" and/or "git commit -a")
git diff produces:
diff --git a/go.mod b/go.mod
index 1c11744..e980eb2 100644
--- a/go.mod
+++ b/go.mod
@@ -3,3 +3,5 @@ module github.com/rogpeppe/go-internal
go 1.11
require gopkg.in/errgo.v2 v2.1.0
+
+
What I expected is that it there should be no diff, i.e.
$ git status
On branch master
Your branch is up to date with 'origin/master'.
nothing to commit, working tree clean
Looking at the Go's source code https://github.com/golang/go/blob/26154f31ad6c801d8bad5ef58df1e9263c6beec7/src/cmd/go/internal/modcmd/edit.go#L209
maybe we could include modf.Cleanup() before modf.Format() in
https://github.com/rogpeppe/gohack/blob/03d2ff3646b7ffc380e059413e4302f6cbdeb09b/gomodcmd.go#L91
Created PR #69 for this. :smile:
There is a reason why the Go team doesn't provides a package to edit go.mod: the official go.mod editing API is go mod edit.
So gohack should just use go mod edit commands instead of editing the file itself.
Beware that gohack came out very early in the timeline of modules, before tools like go mod edit were fully developed.
Also, note that there is in fact a package to parse and print go.mod files: https://pkg.go.dev/golang.org/x/mod/modfile
The fact is that you have to keep in sync the version of your Go toolchain with any other tools that have go.mod editing capabilities.
For gohack to maintain compability with Go toolchain upgrades:
- the gohack maintainers have to keep to go.mod editing editing in sync with the toolchain (and that doesn't happen: the fact that
github.com/rogpeppe/go-internal/modfilehasn't been updated for 2 years just shows that doesn't work) - the end user has to update
gohackwhen (s)he updates the toolchain with agohackthat has upgraded its go.mod support.
That isn't sustainable.
golang.org/x/mod/modfile can help to solve the first point (but that would still require that the gohack maintainers to upgrade the dependency in case of a new go.mod format change), but that will never fix the second point.
So go mod edit is the only sustainable way.