Skip to content

Commit

Permalink
Allow adding arguments to Rules (#1310)
Browse files Browse the repository at this point in the history
This allows supporting patterns like `maybe`, which take a
rule-to-instantiate as a positional argument.
  • Loading branch information
illicitonion committed Aug 3, 2022
1 parent 622d888 commit 2b30bc4
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
5 changes: 5 additions & 0 deletions rule/rule.go
Original file line number Diff line number Diff line change
Expand Up @@ -880,6 +880,11 @@ func (r *Rule) Args() []bzl.Expr {
return r.args
}

// AddArg adds a positional argument to the rule.
func (r *Rule) AddArg(value bzl.Expr) {
r.args = append(r.args, value)
}

// Insert marks this statement for insertion at the end of the file. Multiple
// statements will be inserted in the order Insert is called.
func (r *Rule) Insert(f *File) {
Expand Down
35 changes: 33 additions & 2 deletions rule/rule_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,11 @@ y_library(name = "bar")
foo.Delete()
bar := f.Rules[1]
bar.SetAttr("srcs", []string{"bar.y"})
baz := NewRule("z", "baz")
loadMaybe := NewLoad("//some:maybe.bzl")
loadMaybe.Add("maybe")
loadMaybe.Insert(f, 0)
baz := NewRule("maybe", "baz")
baz.AddArg(&bzl.LiteralExpr{Token: "z"})
baz.SetAttr("srcs", GlobValue{
Patterns: []string{"**"},
Excludes: []string{"*.pem"},
Expand All @@ -67,6 +71,7 @@ y_library(name = "bar")

got := strings.TrimSpace(string(f.Format()))
want := strings.TrimSpace(`
load("//some:maybe.bzl", "maybe")
load("b.bzl", "x_library")
load(
"c.bzl",
Expand All @@ -79,7 +84,8 @@ y_library(
srcs = ["bar.y"],
)
z(
maybe(
z,
name = "baz",
srcs = glob(
["**"],
Expand Down Expand Up @@ -167,6 +173,31 @@ def foo():
}
}

func TestArgsAlwaysEndUpBeforeKwargs(t *testing.T) {
f, err := LoadData(filepath.Join("old", "BUILD.bazel"), "", nil)
if err != nil {
t.Fatal(err)
}

bar := NewRule("maybe", "bar")
bar.SetAttr("url", "https://doesnotexist.com")
bar.AddArg(&bzl.Ident{Name: "http_archive"})
bar.Insert(f)
f.Sync()
got := strings.TrimSpace(string(f.Format()))
want := strings.TrimSpace(`
maybe(
http_archive,
name = "bar",
url = "https://doesnotexist.com",
)
`)

if got != want {
t.Errorf("got:\n%s\nwant:%s", got, want)
}
}

func TestDeleteSyncDelete(t *testing.T) {
old := []byte(`
x_library(name = "foo")
Expand Down

0 comments on commit 2b30bc4

Please sign in to comment.