Skip to content

Commit 5046e90

Browse files
committed
modfile: Fix trailing empty lines in require blocks
1 parent dec0365 commit 5046e90

File tree

2 files changed

+57
-1
lines changed

2 files changed

+57
-1
lines changed

modfile/read.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -865,7 +865,11 @@ func (in *input) parseLineBlock(start Position, token []string, lparen token) *L
865865
// Suffix comment, will be attached later by assignComments.
866866
in.lex()
867867
case '\n':
868-
// Blank line. Add an empty comment to preserve it.
868+
// Skip blank lines in require block or else add an empty comment to preserve it.
869+
if strings.Join(x.Token, " ") == "require" {
870+
in.lex()
871+
continue
872+
}
869873
in.lex()
870874
if len(comments) == 0 && len(x.Line) > 0 || len(comments) > 0 && comments[len(comments)-1].Token != "" {
871875
comments = append(comments, Comment{})

modfile/read_test.go

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -734,3 +734,55 @@ func TestCleanupMaintainsRefs(t *testing.T) {
734734
t.Errorf("got:\n%v\nwant:\n%v", syntax.Stmt[0], lineB)
735735
}
736736
}
737+
738+
func TestCleanupRemoveRequireBlockBlankLines(t *testing.T) {
739+
syntax := &FileSyntax{
740+
Stmt: []Expr{
741+
&Line{
742+
Token: []string{"module", "a"},
743+
},
744+
&LineBlock{
745+
Token: []string{"require"},
746+
Line: []*Line{
747+
{
748+
Token: []string{"golang.org/x/time", "v0.8.0"},
749+
InBlock: true,
750+
},
751+
{
752+
Token: nil, // Blank line
753+
InBlock: true,
754+
},
755+
{
756+
Token: []string{"golang.org/x/other", "v0.1.0"},
757+
InBlock: true,
758+
},
759+
},
760+
},
761+
},
762+
}
763+
syntax.Cleanup()
764+
765+
buf := &bytes.Buffer{}
766+
for _, stmt := range syntax.Stmt {
767+
switch stmt := stmt.(type) {
768+
case *Line:
769+
fmt.Fprintf(buf, "line: %v\n", strings.Join(stmt.Token, " "))
770+
case *LineBlock:
771+
fmt.Fprintf(buf, "block: %v\n", strings.Join(stmt.Token, " "))
772+
for _, line := range stmt.Line {
773+
fmt.Fprintf(buf, "blockline: %v\n", strings.Join(line.Token, " "))
774+
}
775+
}
776+
}
777+
778+
got := strings.TrimSpace(buf.String())
779+
want := strings.TrimSpace(`
780+
line: module a
781+
block: require
782+
blockline: golang.org/x/time v0.8.0
783+
blockline: golang.org/x/other v0.1.0
784+
`)
785+
if got != want {
786+
t.Errorf("got:\n%s\nwant:\n%s", got, want)
787+
}
788+
}

0 commit comments

Comments
 (0)