Skip to content

Commit b9a636b

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 f5a5c5d commit b9a636b

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

rule/rule.go

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

960+
func (r *Rule) GetAttrComments(key string) *bzl.Comments {
961+
attr, ok := r.attrs[key]
962+
if !ok {
963+
return nil
964+
}
965+
return attr.expr.Comment()
966+
}
967+
960968
// PrivateAttrKeys returns a sorted list of private attribute names.
961969
func (r *Rule) PrivateAttrKeys() []string {
962970
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)