Skip to content

Commit a64d5be

Browse files
committed
cmd/go/internal/list: make a copy of the package before zeroing fields
go list -json=<fields> zeroes out the fields in the package struct that aren't specified. The problem with this is that some of the fields have references into other fields: specifically, the NoGoError's Error() function accesses the package struct's Dir field, so if we clear it out the error will just print out "no Go files in" without a directory. Instead, make a copy of the package struct before we zero out the fields so the original values are still there. For #64946 Change-Id: I95103e91fa0782bb23a86a965d5eb87cb12654c6 Cq-Include-Trybots: luci.golang.try:gotip-linux-amd64-longtest,gotip-windows-amd64-longtest Reviewed-on: https://go-review.googlesource.com/c/go/+/553795 LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com> Reviewed-by: Bryan Mills <bcmills@google.com>
1 parent e076c1b commit a64d5be

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

src/cmd/go/internal/list/list.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -449,13 +449,15 @@ func runList(ctx context.Context, cmd *base.Command, args []string) {
449449
if listJson {
450450
do = func(x any) {
451451
if !listJsonFields.needAll() {
452-
v := reflect.ValueOf(x).Elem() // do is always called with a non-nil pointer.
453-
// Clear all non-requested fields.
452+
// Set x to a copy of itself with all non-requested fields cleared.
453+
v := reflect.New(reflect.TypeOf(x).Elem()).Elem() // do is always called with a non-nil pointer.
454+
v.Set(reflect.ValueOf(x).Elem())
454455
for i := 0; i < v.NumField(); i++ {
455456
if !listJsonFields.needAny(v.Type().Field(i).Name) {
456457
v.Field(i).SetZero()
457458
}
458459
}
460+
x = v.Interface()
459461
}
460462
b, err := json.MarshalIndent(x, "", "\t")
461463
if err != nil {
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
cd mod
2+
go list -e -json=ImportPath,Error ./foo
3+
stdout '"Err": "no Go files in .*(/|\\\\)src(/|\\\\)mod(/|\\\\)foo"'
4+
5+
-- mod/go.mod --
6+
module example.com/foo
7+
8+
go 1.21
9+
-- mod/foo/README.md --
10+
empty

0 commit comments

Comments
 (0)