Skip to content

Commit

Permalink
Add File#RuleNamed Method (#1127)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
jkjk822 authored Jan 27, 2023
1 parent d15c4e8 commit d250c1a
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
11 changes: 11 additions & 0 deletions build/rule.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
19 changes: 19 additions & 0 deletions build/rule_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit d250c1a

Please sign in to comment.