Skip to content

Commit

Permalink
rule: add accessor for attribute comments
Browse files Browse the repository at this point in the history
This allows user to attach comments like "# do not sort" to the
assignment expressions maintained by rule.go.

rule.Format() calls into buildtools/build.Format() which in turn calls
Rewrite(). Rewrite() by default sorts certain label arguments like
"deps" and "hdrs". To preventing this sorting it is possible to provide
the comment "# do not sort". However this comment needs to be attached
to the assignment expression.
In rule.go the assignment expressions are not exposed to the user,
making it impossible to attach the comment to it.

See bazel-contrib#237 (comment)
  • Loading branch information
t-8ch authored and fmeum committed Dec 27, 2023
1 parent 2ff6075 commit 8ae0b60
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
8 changes: 8 additions & 0 deletions rule/rule.go
Original file line number Diff line number Diff line change
Expand Up @@ -957,6 +957,14 @@ func (r *Rule) SetAttr(key string, value interface{}) {
r.updated = true
}

func (r *Rule) GetAttrComments(key string) *bzl.Comments {
attr, ok := r.attrs[key]
if !ok {
return nil
}
return attr.expr.Comment()
}

// PrivateAttrKeys returns a sorted list of private attribute names.
func (r *Rule) PrivateAttrKeys() []string {
keys := make([]string, 0, len(r.private))
Expand Down
39 changes: 39 additions & 0 deletions rule/rule_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -599,3 +599,42 @@ func TestCheckFile(t *testing.T) {
t.Errorf("unexpected error: %v", err)
}
}

func TestAttributeComment(t *testing.T) {
f, err := LoadData(filepath.Join("old", "BUILD.bazel"), "", nil)
if err != nil {
t.Fatal(err)
}

r := NewRule("a_rule", "name1")
r.SetAttr("deps", []string{"foo", "bar", "baz"})
r.SetAttr("hdrs", []string{"foo", "bar", "baz"})
hdrComments := r.GetAttrComments("hdrs")
hdrComments.Before = append(hdrComments.Before, bzl.Comment{
Token: "# do not sort",
})

r.Insert(f)

got := strings.TrimSpace(string(f.Format()))
want := strings.TrimSpace(`
a_rule(
name = "name1",
# do not sort
hdrs = [
"foo",
"bar",
"baz",
],
deps = [
"bar",
"baz",
"foo",
],
)
`)

if got != want {
t.Errorf("got:%s\nwant:%s", got, want)
}
}

0 comments on commit 8ae0b60

Please sign in to comment.