Skip to content

Commit bef63db

Browse files
tiemvdan
authored andcommitted
fix panic with go1.18 workspaces
When running inside a Go workspace, go list -m returns all modules in the workspace.
1 parent f32c372 commit bef63db

File tree

2 files changed

+38
-3
lines changed

2 files changed

+38
-3
lines changed

gofmt.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ package main
66

77
import (
88
"bytes"
9+
"encoding/json"
910
"flag"
1011
"fmt"
1112
"go/ast"
@@ -134,10 +135,11 @@ func processFile(filename string, in io.Reader, out io.Writer, stdin bool) error
134135
// Apply gofumpt's changes before we print the code in gofumpt's format.
135136

136137
if *langVersion == "" {
137-
out, err := exec.Command("go", "list", "-m", "-f", "{{.GoVersion}}").Output()
138-
out = bytes.TrimSpace(out)
138+
out, err := exec.Command("go", "mod", "edit", "-json").Output()
139139
if err == nil && len(out) > 0 {
140-
*langVersion = string(out)
140+
var mod struct{ Go string }
141+
_ = json.Unmarshal(out, &mod)
142+
*langVersion = mod.Go
141143
}
142144
}
143145

testdata/scripts/workspaces.txt

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
[!go1.18] skip
2+
3+
# Octal literal prefixes were introduced in Go 1.13. If we are outside of the
4+
# module, language version should not be set.
5+
gofumpt a/go112
6+
cmp stdout a/go112
7+
8+
cd a
9+
gofumpt go112
10+
cmp stdout go113
11+
12+
-- a/go112 --
13+
package main
14+
15+
const x = 0777
16+
-- a/go113 --
17+
package main
18+
19+
const x = 0o777
20+
-- go.work --
21+
go 1.18
22+
use ./a
23+
use ./b
24+
-- a/go.mod --
25+
module a
26+
go 1.18
27+
-- a/a.go --
28+
package a
29+
-- b/go.mod --
30+
module b
31+
go 1.18
32+
-- b/b.go --
33+
package b

0 commit comments

Comments
 (0)