diff --git a/rule/rule.go b/rule/rule.go index 1eb72fbb4..c9ff2759e 100644 --- a/rule/rule.go +++ b/rule/rule.go @@ -357,7 +357,11 @@ func updateStmt(oldStmt *[]bzl.Expr, inserts, deletes, stmts []*stmt) { sort.Stable(byIndex(deletes)) sort.Stable(byIndex(inserts)) sort.Stable(byIndex(stmts)) - newStmt := make([]bzl.Expr, 0, len(*oldStmt)-len(deletes)+len(inserts)) + cap := len(*oldStmt) - len(deletes) + len(inserts) + if cap < 0 { + cap = 0 + } + newStmt := make([]bzl.Expr, 0, cap) var ii, di, si int for i, stmt := range *oldStmt { for ii < len(inserts) && inserts[ii].index == i { diff --git a/rule/rule_test.go b/rule/rule_test.go index 3b6992eba..ca1a15ea5 100644 --- a/rule/rule_test.go +++ b/rule/rule_test.go @@ -224,6 +224,24 @@ x_library(name = "bar") } } +func TestInsertDeleteSync(t *testing.T) { + old := []byte("") + f, err := LoadData(filepath.Join("old", "BUILD.bazel"), "", old) + if err != nil { + t.Fatal(err) + } + + foo := NewRule("filegroup", "test") + foo.Insert(f) + foo.Delete() + f.Sync() + got := strings.TrimSpace(string(f.Format())) + want := "" + if got != want { + t.Errorf("got:\n%s\nwant:%s", got, want) + } +} + func TestSymbolsReturnsKeys(t *testing.T) { f, err := LoadData(filepath.Join("load", "BUILD.bazel"), "", []byte(`load("a.bzl", "y", z = "a")`)) if err != nil {