Skip to content

Commit 2e7045f

Browse files
committed
rule: add accessor for attribute comments
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 #237 (comment)
1 parent 2ff6075 commit 2e7045f

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

rule/rule.go

+10
Original file line numberDiff line numberDiff line change
@@ -957,6 +957,16 @@ func (r *Rule) SetAttr(key string, value interface{}) {
957957
r.updated = true
958958
}
959959

960+
// GetAttrComments returns the comments for an attribute.
961+
// It can be used to attach comments like "do not sort".
962+
func (r *Rule) GetAttrComments(key string) *bzl.Comments {
963+
attr, ok := r.attrs[key]
964+
if !ok {
965+
return nil
966+
}
967+
return attr.expr.Comment()
968+
}
969+
960970
// PrivateAttrKeys returns a sorted list of private attribute names.
961971
func (r *Rule) PrivateAttrKeys() []string {
962972
keys := make([]string, 0, len(r.private))

rule/rule_test.go

+39
Original file line numberDiff line numberDiff line change
@@ -599,3 +599,42 @@ func TestCheckFile(t *testing.T) {
599599
t.Errorf("unexpected error: %v", err)
600600
}
601601
}
602+
603+
func TestAttributeComment(t *testing.T) {
604+
f, err := LoadData(filepath.Join("old", "BUILD.bazel"), "", nil)
605+
if err != nil {
606+
t.Fatal(err)
607+
}
608+
609+
r := NewRule("a_rule", "name1")
610+
r.SetAttr("deps", []string{"foo", "bar", "baz"})
611+
r.SetAttr("hdrs", []string{"foo", "bar", "baz"})
612+
hdrComments := r.GetAttrComments("hdrs")
613+
hdrComments.Before = append(hdrComments.Before, bzl.Comment{
614+
Token: "# do not sort",
615+
})
616+
617+
r.Insert(f)
618+
619+
got := strings.TrimSpace(string(f.Format()))
620+
want := strings.TrimSpace(`
621+
a_rule(
622+
name = "name1",
623+
# do not sort
624+
hdrs = [
625+
"foo",
626+
"bar",
627+
"baz",
628+
],
629+
deps = [
630+
"bar",
631+
"baz",
632+
"foo",
633+
],
634+
)
635+
`)
636+
637+
if got != want {
638+
t.Errorf("got:%s\nwant:%s", got, want)
639+
}
640+
}

0 commit comments

Comments
 (0)