Skip to content

Commit

Permalink
rewrite: support insert at end of file
Browse files Browse the repository at this point in the history
In some rare situations Encore would try to add code at the end
of a file, which would panic because no segment exists at that pos.

Thanks Rob Gray for the report.
  • Loading branch information
eandre committed Dec 7, 2023
1 parent 6c38020 commit d06bb0a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
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)
}
}

0 comments on commit d06bb0a

Please sign in to comment.