From d250c1ae298d1e8d781f6b6e51b0609a18b51a58 Mon Sep 17 00:00:00 2001 From: River Date: Fri, 27 Jan 2023 04:30:02 -0800 Subject: [PATCH] Add `File#RuleNamed` Method (#1127) Add method to retrieve rule by name from a file pointer, similar to edit#FindRuleByName. This allows access from the file object itself instead of needing an extra package. --- build/rule.go | 11 +++++++++++ build/rule_test.go | 19 +++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/build/rule.go b/build/rule.go index ed8d4c161..44bb161ea 100644 --- a/build/rule.go +++ b/build/rule.go @@ -92,6 +92,17 @@ func (f *File) RuleAt(linenum int) *Rule { return all[0] } +// RuleNamed returns the rule in the file that has the specified name, or null if no such rule. +func (f *File) RuleNamed(name string) *Rule { + all := f.rules(func(rule *Rule) bool { + return rule.Name() == name + }) + if len(all) != 1 { + return nil + } + return all[0] +} + // DelRules removes rules with the given kind and name from the file. // An empty kind matches all kinds; an empty name matches all names. // It returns the number of rules that were deleted. diff --git a/build/rule_test.go b/build/rule_test.go index 867ac88be..f90caa585 100644 --- a/build/rule_test.go +++ b/build/rule_test.go @@ -175,6 +175,25 @@ func TestRulesDoubleNested(t *testing.T) { compare(t, f.Rules("java_library"), []*Rule{doubleNestedRule}) } +func TestRuleNamed(t *testing.T) { + tests := []struct { + name string + rules []Expr + want *Rule + description string + }{ + {"", []Expr{simpleCall}, nil, "Empty name matches no rules."}, + {"x", []Expr{simpleCall}, simpleRule, "Find single rule by name."}, + {"does_not_exist", []Expr{simpleCall}, nil, "Returns nil when no rules have specified name."}, + {"foo.bar.baz", []Expr{simpleCall, structCall}, nil, "Returns nil when multiple rules have specified name."}, + } + for _, tst := range tests { + f := &File{Stmt: tst.rules} + + compare(t, f.RuleNamed(tst.name), tst.want) + } +} + func TestImplicitName(t *testing.T) { tests := []struct { path string