From 8fdb75e05392bffef1b5fb1967bd6530b99f2d7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Wei=C3=9Fschuh?= Date: Wed, 27 Dec 2023 12:13:42 +0000 Subject: [PATCH] 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 https://github.com/bazelbuild/bazel-gazelle/issues/237#issuecomment-399476945 --- rule/rule.go | 8 ++++++++ rule/rule_test.go | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/rule/rule.go b/rule/rule.go index abd0b5863..4afc7434a 100644 --- a/rule/rule.go +++ b/rule/rule.go @@ -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)) diff --git a/rule/rule_test.go b/rule/rule_test.go index 11c14296a..363a97b9e 100644 --- a/rule/rule_test.go +++ b/rule/rule_test.go @@ -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) + } +}