Skip to content

Commit 18d3f56

Browse files
crazybolillogopherbot
authored andcommitted
modfile: fix crash on AddGoStmt in empty File
AddGoStmt uses File.Syntax without checking whether it is nil or not. This causes crashes when using it on empty files that have not had their Syntax member initialized to a valid pointer. This change fixes it by ensuring File.Syntax is a valid pointer before proceeding. Fixes golang/go#62457. Change-Id: Iab02039f79e73d939ca5d3e48b29faa5e0a9a5ec Reviewed-on: https://go-review.googlesource.com/c/mod/+/570115 Reviewed-by: Michael Knyszek <[email protected]> Auto-Submit: Bryan Mills <[email protected]> Reviewed-by: Bryan Mills <[email protected]> LUCI-TryBot-Result: Go LUCI <[email protected]>
1 parent 766dc5d commit 18d3f56

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

modfile/rule.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -975,6 +975,8 @@ func (f *File) AddGoStmt(version string) error {
975975
var hint Expr
976976
if f.Module != nil && f.Module.Syntax != nil {
977977
hint = f.Module.Syntax
978+
} else if f.Syntax == nil {
979+
f.Syntax = new(FileSyntax)
978980
}
979981
f.Go = &Go{
980982
Version: version,

modfile/rule_test.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1549,6 +1549,20 @@ var fixVersionTests = []struct {
15491549
},
15501550
}
15511551

1552+
var modifyEmptyFilesTests = []struct {
1553+
desc string
1554+
operations func(f *File)
1555+
want string
1556+
}{
1557+
{
1558+
desc: `addGoStmt`,
1559+
operations: func(f *File) {
1560+
f.AddGoStmt("1.20")
1561+
},
1562+
want: `go 1.20`,
1563+
},
1564+
}
1565+
15521566
func fixV(path, version string) (string, error) {
15531567
if path != "example.com/m" {
15541568
return "", fmt.Errorf("module path must be example.com/m")
@@ -1846,3 +1860,29 @@ func TestFixVersion(t *testing.T) {
18461860
})
18471861
}
18481862
}
1863+
1864+
func TestAddOnEmptyFile(t *testing.T) {
1865+
for _, tt := range modifyEmptyFilesTests {
1866+
t.Run(tt.desc, func(t *testing.T) {
1867+
f := &File{}
1868+
tt.operations(f)
1869+
1870+
expect, err := Parse("out", []byte(tt.want), nil)
1871+
if err != nil {
1872+
t.Fatal(err)
1873+
}
1874+
golden, err := expect.Format()
1875+
if err != nil {
1876+
t.Fatal(err)
1877+
}
1878+
got, err := f.Format()
1879+
if err != nil {
1880+
t.Fatal(err)
1881+
}
1882+
1883+
if !bytes.Equal(got, golden) {
1884+
t.Fatalf("got:\n%s\nwant:\n%s", got, golden)
1885+
}
1886+
})
1887+
}
1888+
}

0 commit comments

Comments
 (0)