Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rewrite: support insert at end of file #979

Merged
merged 1 commit into from
Dec 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions v2/codegen/internal/rewrite/rewrite.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,17 @@ func (r *Rewriter) ReplaceNode(node ast.Node, data []byte) {
}

func (r *Rewriter) Insert(start token.Pos, data []byte) {
// If the pos is at the very end of the file, insert a new segment directly,
// since calling r.seg(start) would panic.
if len(r.segs) > 0 && r.segs[len(r.segs)-1].end == int(start) {
r.segs = append(r.segs, segment{
start: int(start),
end: int(start) + len(data),
data: data,
})
return
}

si, so := r.seg(start)
r.replace(si, so, si, so, data)
}
Expand Down Expand Up @@ -93,10 +104,12 @@ func (r *Rewriter) seg(pos token.Pos) (idx int, offset int) {
return i, int(p - seg.start)
}
}

panic(fmt.Sprintf("original file does not contain pos %v", pos))
}

type segment struct {
start, end int
data []byte
start int // inclusive
end int // exclusive
data []byte
}
12 changes: 12 additions & 0 deletions v2/codegen/internal/rewrite/rewrite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,15 @@ func TestDelete(t *testing.T) {
t.Errorf("got data %s, want %s", got, want)
}
}

func TestInsertAtEnd(t *testing.T) {
rw := New([]byte(""), 1)
rw.Insert(1, []byte("// test"))
if got, want := rw.Data(), []byte("// test"); !bytes.Equal(got, want) {
t.Errorf("got data %s, want %s", got, want)
}
rw.Delete(1, 4)
if got, want := rw.Data(), []byte("test"); !bytes.Equal(got, want) {
t.Errorf("got data %s, want %s", got, want)
}
}
Loading