aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/test/java/com/google/devtools/build/lib/bazel/rules/genrule/GenRuleConfiguredTargetTest.java
blob: a68b5450f5711d4367edb28f73bd737a3d420085 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.lib.bazel.rules.genrule;

import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.testutil.TestConstants.GENRULE_SETUP;
import static com.google.devtools.build.lib.testutil.TestConstants.GENRULE_SETUP_PATH;
import static org.junit.Assert.fail;

import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.actions.Action;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.util.ActionsTestUtil;
import com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.actions.SpawnAction;
import com.google.devtools.build.lib.analysis.configuredtargets.FileConfiguredTarget;
import com.google.devtools.build.lib.analysis.util.AnalysisMock;
import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.rules.cpp.CcToolchainProvider;
import com.google.devtools.build.lib.rules.cpp.CppConfiguration.Tool;
import com.google.devtools.build.lib.rules.cpp.CppHelper;
import com.google.devtools.build.lib.testutil.TestRuleClassProvider;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests of {@link BazelGenRule}. */
@RunWith(JUnit4.class)
public class GenRuleConfiguredTargetTest extends BuildViewTestCase {

  /** Filter to remove implicit dependencies of C/C++ rules. */
  private static final Predicate<ConfiguredTarget> CC_CONFIGURED_TARGET_FILTER =
      new Predicate<ConfiguredTarget>() {
        @Override
        public boolean apply(ConfiguredTarget target) {
          return AnalysisMock.get().ccSupport().labelFilter().apply(target.getLabel());
        }
      };

  /** Filter to remove implicit dependencies of Java rules. */
  private static final Predicate<ConfiguredTarget> JAVA_CONFIGURED_TARGET_FILTER =
      new Predicate<ConfiguredTarget>() {
        @Override
        public boolean apply(ConfiguredTarget target) {
          Label label = target.getLabel();
          String labelName = "//" + label.getPackageName();
          return !labelName.startsWith("//third_party/java/jdk");
        }
      };

  private static final Pattern SETUP_COMMAND_PATTERN =
      Pattern.compile(".*/genrule-setup.sh;\\s+(?<command>.*)");

  private void assertCommandEquals(String expected, String command) {
    // Ensure the command after the genrule setup is correct.
    Matcher m = SETUP_COMMAND_PATTERN.matcher(command);
    if (m.matches()) {
      command = m.group("command");
    }

    assertThat(command).isEqualTo(expected);
  }

  public void createFiles() throws Exception {
    scratch.file(
        "hello/BUILD",
        "genrule(",
        "    name = 'z',",
        "    outs = ['x/y'],",
        "    cmd = 'echo hi > $(@D)/y',",
        ")",
        "genrule(",
        "    name = 'w',",
        "    outs = ['a/b', 'c/d'],",
        "    cmd = 'echo hi | tee $(@D)/a/b $(@D)/c/d',",
        ")");
  }

  @Override
  protected ConfiguredRuleClassProvider getRuleClassProvider() {
    ConfiguredRuleClassProvider.Builder builder = new ConfiguredRuleClassProvider.Builder();
    TestRuleClassProvider.addStandardRules(builder);
    return builder.addRuleDefinition(new TestRuleClassProvider.MakeVariableTesterRule()).build();
  }

  @Test
  public void testToolchainMakeVariableExpansion() throws Exception {
    scratch.file("a/BUILD",
        "genrule(name='gr', srcs=[], outs=['out'], cmd='$(FOO)', toolchains=[':v'])",
        "make_variable_tester(name='v', variables={'FOO': 'FOOBAR'})");

    String cmd = getCommand("//a:gr");
    assertThat(cmd).endsWith("FOOBAR");
  }

  @Test
  public void testToolchainOverridesConfiguration() throws Exception {
    scratch.file("a/BUILD",
        "genrule(name='gr', srcs=[], outs=['out'], cmd='JAVABASE=$(JAVABASE)', toolchains=[':v'])",
        "make_variable_tester(name='v', variables={'JAVABASE': 'REPLACED'})");

    String cmd = getCommand("//a:gr");
    assertThat(cmd).endsWith("JAVABASE=REPLACED");
  }

  @Test
  public void testD() throws Exception {
    createFiles();
    ConfiguredTarget z = getConfiguredTarget("//hello:z");
    Artifact y = getOnlyElement(getFilesToBuild(z));
    assertThat(y.getRootRelativePath()).isEqualTo(PathFragment.create("hello/x/y"));
  }

  @Test
  public void testDMultiOutput() throws Exception {
    createFiles();
    ConfiguredTarget z = getConfiguredTarget("//hello:w");
    List<Artifact> files = getFilesToBuild(z).toList();
    assertThat(files).hasSize(2);
    assertThat(files.get(0).getRootRelativePath()).isEqualTo(PathFragment.create("hello/a/b"));
    assertThat(files.get(1).getRootRelativePath()).isEqualTo(PathFragment.create("hello/c/d"));
  }

  @Test
  public void testOutsWithSameNameAsRule() throws Exception {
    // The error was demoted to a warning.
    // Re-enable after June 1 2008 when we make it an error again.
    checkWarning(
        "genrule2",
        "hello_world",
        "target 'hello_world' is both a rule and a file;",
        "genrule(name = 'hello_world',",
        "srcs = ['ignore_me.txt'],",
        "outs = ['message.txt', 'hello_world'],",
        "cmd  = 'echo \"Hello, world.\" >$(location message.txt)')");
  }

  @Test
  public void testFilesToBuildIsOuts() throws Exception {
    scratch.file(
        "genrule1/BUILD",
        "genrule(name = 'hello_world',",
        "srcs = ['ignore_me.txt'],",
        "outs = ['message.txt'],",
        "cmd  = 'echo \"Hello, world.\" >$(location message.txt)')");
    Artifact messageArtifact = getFileConfiguredTarget("//genrule1:message.txt").getArtifact();
    assertThat(getFilesToBuild(getConfiguredTarget("//genrule1:hello_world")))
        .containsExactly(messageArtifact);
  }

  @Test
  public void testActionIsShellCommand() throws Exception {
    scratch.file(
        "genrule1/BUILD",
        "genrule(name = 'hello_world',",
        "srcs = ['ignore_me.txt'],",
        "outs = ['message.txt'],",
        "cmd  = 'echo \"Hello, world.\" >$(location message.txt)')");

    Artifact messageArtifact = getFileConfiguredTarget("//genrule1:message.txt").getArtifact();
    SpawnAction shellAction = (SpawnAction) getGeneratingAction(messageArtifact);

    Artifact ignoreMeArtifact = getFileConfiguredTarget("//genrule1:ignore_me.txt").getArtifact();
    Artifact genruleSetupArtifact = getFileConfiguredTarget(GENRULE_SETUP).getArtifact();

    assertThat(shellAction).isNotNull();
    assertThat(shellAction.getInputs()).containsExactly(ignoreMeArtifact, genruleSetupArtifact);
    assertThat(shellAction.getOutputs()).containsExactly(messageArtifact);

    String expected = "echo \"Hello, world.\" >" + messageArtifact.getExecPathString();
    assertThat(shellAction.getArguments().get(0))
        .isEqualTo(targetConfig.getShellExecutable().getPathString());
    assertThat(shellAction.getArguments().get(1)).isEqualTo("-c");
    assertCommandEquals(expected, shellAction.getArguments().get(2));
  }

  @Test
  public void testDependentGenrule() throws Exception {
    scratch.file(
        "genrule1/BUILD",
        "genrule(name = 'hello_world',",
        "srcs = ['ignore_me.txt'],",
        "outs = ['message.txt'],",
        "cmd  = 'echo \"Hello, world.\" >$(location message.txt)')");
    scratch.file(
        "genrule2/BUILD",
        "genrule(name = 'goodbye_world',",
        "srcs = ['goodbye.txt', '//genrule1:hello_world'],",
        "outs = ['farewell.txt'],",
        "cmd  = 'echo $(SRCS) >$(location farewell.txt)')");

    getConfiguredTarget("//genrule2:goodbye_world");

    Artifact farewellArtifact = getFileConfiguredTarget("//genrule2:farewell.txt").getArtifact();
    Artifact goodbyeArtifact = getFileConfiguredTarget("//genrule2:goodbye.txt").getArtifact();
    Artifact messageArtifact = getFileConfiguredTarget("//genrule1:message.txt").getArtifact();
    Artifact genruleSetupArtifact = getFileConfiguredTarget(GENRULE_SETUP).getArtifact();

    SpawnAction shellAction = (SpawnAction) getGeneratingAction(farewellArtifact);

    // inputs = { "goodbye.txt", "//genrule1:message.txt" }
    assertThat(shellAction.getInputs())
        .containsExactly(goodbyeArtifact, messageArtifact, genruleSetupArtifact);

    // outputs = { "farewell.txt" }
    assertThat(shellAction.getOutputs()).containsExactly(farewellArtifact);

    String expected =
        "echo "
            + goodbyeArtifact.getExecPathString()
            + " "
            + messageArtifact.getExecPathString()
            + " >"
            + farewellArtifact.getExecPathString();
    assertCommandEquals(expected, shellAction.getArguments().get(2));
  }

  /**
   * Ensure that the actions / artifacts created by genrule dependencies allow us to follow the
   * chain of generated files backward.
   */
  @Test
  public void testDependenciesViaFiles() throws Exception {
    scratch.file(
        "foo/BUILD",
        "genrule(name = 'bar',",
        "        srcs = ['bar_in.txt'],",
        "        cmd = 'touch $(OUTS)',",
        "        outs = ['bar_out.txt'])",
        "genrule(name = 'baz',",
        "        srcs = ['bar_out.txt'],",
        "        cmd = 'touch $(OUTS)',",
        "        outs = ['baz_out.txt'])");

    FileConfiguredTarget bazOutTarget = getFileConfiguredTarget("//foo:baz_out.txt");
    Action bazAction = getGeneratingAction(bazOutTarget.getArtifact());
    Artifact barOut = bazAction.getInputs().iterator().next();
    assertThat(barOut.getExecPath().endsWith(PathFragment.create("foo/bar_out.txt"))).isTrue();
    Action barAction = getGeneratingAction(barOut);
    Artifact barIn = barAction.getInputs().iterator().next();
    assertThat(barIn.getExecPath().endsWith(PathFragment.create("foo/bar_in.txt"))).isTrue();
  }

  /** Ensure that variable $(@D) gets expanded correctly in the genrule cmd. */
  @Test
  public void testOutputDirExpansion() throws Exception {
    scratch.file(
        "foo/BUILD",
        "genrule(name = 'bar',",
        "        srcs = ['bar_in.txt'],",
        "        cmd = 'touch $(@D)',",
        "        outs = ['bar/bar_out.txt'])",
        "genrule(name = 'baz',",
        "        srcs = ['bar/bar_out.txt'],",
        "        cmd = 'touch $(@D)',",
        "        outs = ['logs/baz_out.txt', 'logs/baz.log'])");

    getConfiguredTarget("//foo:bar");

    FileConfiguredTarget bazOutTarget = getFileConfiguredTarget("//foo:logs/baz_out.txt");

    SpawnAction bazAction = (SpawnAction) getGeneratingAction(bazOutTarget.getArtifact());

    // Make sure the expansion for $(@D) results in the
    // directory of the BUILD file ("foo"), not the common parent
    // directory of the output files ("logs")
    String bazExpected =
        "touch "
            + bazOutTarget
                .getArtifact()
                .getExecPath()
                .getParentDirectory()
                .getParentDirectory()
                .getPathString();
    assertCommandEquals(bazExpected, bazAction.getArguments().get(2));
    assertThat(bazAction.getArguments().get(2)).endsWith("/foo");

    getConfiguredTarget("//foo:bar");

    Artifact barOut = bazAction.getInputs().iterator().next();
    assertThat(barOut.getExecPath().endsWith(PathFragment.create("foo/bar/bar_out.txt"))).isTrue();
    SpawnAction barAction = (SpawnAction) getGeneratingAction(barOut);
    String barExpected = "touch " + barOut.getExecPath().getParentDirectory().getPathString();
    assertCommandEquals(barExpected, barAction.getArguments().get(2));
    assertThat(bazExpected.equals(barExpected)).isFalse();
  }

  /** Ensure that variable $(CC) gets expanded correctly in the genrule cmd. */
  @Test
  public void testMakeVarExpansion() throws Exception {
    scratch.file(
        "foo/BUILD",
        "genrule(name = 'bar',",
        "        srcs = ['bar.cc'],",
        "        cmd = '$(CC) -o $(OUTS) $(SRCS) $$shellvar',",
        "        outs = ['bar.o'])");
    FileConfiguredTarget barOutTarget = getFileConfiguredTarget("//foo:bar.o");
    FileConfiguredTarget barInTarget = getFileConfiguredTarget("//foo:bar.cc");

    SpawnAction barAction = (SpawnAction) getGeneratingAction(barOutTarget.getArtifact());

    CcToolchainProvider toolchain =
        CppHelper.getToolchainUsingDefaultCcToolchainAttribute(
            getRuleContext(getConfiguredTarget("//foo:bar")));
    String cc = toolchain.getToolPathFragment(Tool.GCC).getPathString();
    String expected =
        cc
            + " -o "
            + barOutTarget.getArtifact().getExecPathString()
            + " "
            + barInTarget.getArtifact().getRootRelativePath().getPathString()
            + " $shellvar";
    assertCommandEquals(expected, barAction.getArguments().get(2));
  }

  @Test
  public void onlyHasCcToolchainDepWhenCcMakeVariablesArePresent() throws Exception {
    scratch.file(
        "foo/BUILD",
        "genrule(name = 'no_cc',",
        "        srcs = [],",
        "        cmd = 'echo no CC variables here > $@',",
        "        outs = ['no_cc.out'])",
        "genrule(name = 'cc',",
        "        srcs = [],",
        "        cmd = 'echo $(CC) > $@',",
        "        outs = ['cc.out'])");
    String ccToolchainAttr = ":cc_toolchain";
    assertThat(getPrerequisites(getConfiguredTarget("//foo:no_cc"), ccToolchainAttr)).isEmpty();
    assertThat(getPrerequisites(getConfiguredTarget("//foo:cc"), ccToolchainAttr)).isNotEmpty();
  }

  /** Ensure that Java make variables get expanded under the *host* configuration. */
  @Test
  public void testJavaMakeVarExpansion() throws Exception {
    String ruleTemplate =
        "genrule(name = '%s',"
            + "  srcs = [],"
            + "  cmd = 'echo $(%s) > $@',"
            + "  outs = ['%s'])";

    scratch.file(
        "foo/BUILD",
        String.format(ruleTemplate, "java_rule", "JAVA", "java.txt"),
        String.format(ruleTemplate, "javabase_rule", "JAVABASE", "javabase.txt"));

    Artifact javaOutput = getFileConfiguredTarget("//foo:java.txt").getArtifact();
    Artifact javabaseOutput = getFileConfiguredTarget("//foo:javabase.txt").getArtifact();

    String javaCommand =
        ((SpawnAction) getGeneratingAction(javaOutput)).getArguments().get(2);
    assertThat(javaCommand).containsMatch("jdk/bin/java(.exe)? >");

    String javabaseCommand =
        ((SpawnAction) getGeneratingAction(javabaseOutput)).getArguments().get(2);
    assertThat(javabaseCommand).contains("jdk >");
  }

  // Returns the expansion of 'cmd' for the specified genrule.
  private String getCommand(String label) throws Exception {
    return getSpawnAction(label).getArguments().get(2);
  }

  // Returns the SpawnAction for the specified genrule.
  private SpawnAction getSpawnAction(String label) throws Exception {
    return (SpawnAction)
        getGeneratingAction(getFilesToBuild(getConfiguredTarget(label)).iterator().next());
  }

  @Test
  public void testMessage() throws Exception {
    scratch.file(
        "genrule3/BUILD",
        "genrule(name = 'hello_world',",
        "    srcs = ['ignore_me.txt'],",
        "    outs = ['hello.txt'],",
        "    cmd  = 'echo \"Hello, world.\" >hello.txt')",
        "genrule(name = 'goodbye_world',",
        "    srcs = ['ignore_me.txt'],",
        "    outs = ['goodbye.txt'],",
        "    message = 'Generating message',",
        "    cmd  = 'echo \"Goodbye, world.\" >goodbye.txt')");
    assertThat(getSpawnAction("//genrule3:hello_world").getProgressMessage())
        .isEqualTo("Executing genrule //genrule3:hello_world");
    assertThat(getSpawnAction("//genrule3:goodbye_world").getProgressMessage())
        .isEqualTo("Generating message //genrule3:goodbye_world");
  }

  /** Ensure that labels from binary targets expand to the executable */
  @Test
  public void testBinaryTargetsExpandToExecutable() throws Exception {
    scratch.file(
        "genrule3/BUILD",
        "genrule(name = 'hello_world',",
        "    srcs = ['ignore_me.txt'],",
        "    tools = ['echo'],",
        "    outs = ['message.txt'],",
        "    cmd  = '$(location :echo) \"Hello, world.\" >message.txt')",
        "cc_binary(name = 'echo',",
        "    srcs = ['echo.cc'])");
    String regex = "b.{4}-out/.*/bin/genrule3/echo(\\.exe)? \"Hello, world.\" >message.txt";
    assertThat(getCommand("//genrule3:hello_world")).containsMatch(regex);
  }

  @Test
  public void testOutputToBindir() throws Exception {
    scratch.file(
        "x/BUILD",
        "genrule(name='bin', ",
        "        outs=['bin.out'],",
        "        cmd=':',",
        "        output_to_bindir=1)",
        "genrule(name='genfiles', ",
        "        outs=['genfiles.out'],",
        "        cmd=':',",
        "        output_to_bindir=0)");

    assertThat(getFileConfiguredTarget("//x:bin.out").getArtifact())
        .isEqualTo(getBinArtifact("bin.out", "//x:bin"));
    assertThat(getFileConfiguredTarget("//x:genfiles.out").getArtifact())
        .isEqualTo(getGenfilesArtifact("genfiles.out", "//x:genfiles"));
  }

  @Test
  public void testMultipleOutputsToBindir() throws Exception {
    scratch.file(
        "x/BUILD",
        "genrule(name='bin', ",
        "        outs=['bin_a.out', 'bin_b.out'],",
        "        cmd=':',",
        "        output_to_bindir=1)",
        "genrule(name='genfiles', ",
        "        outs=['genfiles_a.out', 'genfiles_b.out'],",
        "        cmd=':',",
        "        output_to_bindir=0)");

    assertThat(getFileConfiguredTarget("//x:bin_a.out").getArtifact())
        .isEqualTo(getBinArtifact("bin_a.out", "//x:bin"));
    assertThat(getFileConfiguredTarget("//x:bin_b.out").getArtifact())
        .isEqualTo(getBinArtifact("bin_b.out", "//x:bin"));
    assertThat(getFileConfiguredTarget("//x:genfiles_a.out").getArtifact())
        .isEqualTo(getGenfilesArtifact("genfiles_a.out", "//x:genfiles"));
    assertThat(getFileConfiguredTarget("//x:genfiles_b.out").getArtifact())
        .isEqualTo(getGenfilesArtifact("genfiles_b.out", "//x:genfiles"));
  }

  @Test
  public void testMultipleOutsPreservesOrdering() throws Exception {
    scratch.file(
        "multiple/outs/BUILD",
        "genrule(name='test', ",
        "        outs=['file1.out', 'file2.out'],",
        "        cmd='touch $(OUTS)')");
    String regex =
        "touch b.{4}-out/.*/multiple/outs/file1.out "
            + "b.{4}-out/.*/multiple/outs/file2.out";
    assertThat(getCommand("//multiple/outs:test")).containsMatch(regex);
  }

  @Test
  public void testToolsAreHostConfiguration() throws Exception {
    scratch.file(
        "config/BUILD",
        "genrule(name='src', outs=['src.out'], cmd=':')",
        "genrule(name='tool', outs=['tool.out'], cmd=':')",
        "genrule(name='config', ",
        "        srcs=[':src'], tools=[':tool'], outs=['out'],",
        "        cmd='$(location :tool)')");

    Iterable<ConfiguredTarget> prereqs =
        Iterables.filter(
            Iterables.filter(
                getDirectPrerequisites(getConfiguredTarget("//config")),
                CC_CONFIGURED_TARGET_FILTER),
            JAVA_CONFIGURED_TARGET_FILTER);

    boolean foundSrc = false;
    boolean foundTool = false;
    boolean foundSetup = false;
    for (ConfiguredTarget prereq : prereqs) {
      String name = prereq.getLabel().getName();
      if (name.contains("cc-") || name.contains("jdk")) {
          // Ignore these, they are present due to the implied genrule dependency on crosstool and
          // JDK.
        continue;
      }
      switch (name) {
        case "src":
          assertConfigurationsEqual(getTargetConfiguration(), prereq.getConfiguration());
          foundSrc = true;
          break;
        case "tool":
          assertThat(getHostConfiguration().equalsOrIsSupersetOf(prereq.getConfiguration()))
              .isTrue();
          foundTool = true;
          break;
        case GENRULE_SETUP_PATH:
          assertThat(prereq.getConfiguration()).isNull();
          foundSetup = true;
          break;
        default:
          fail("unexpected prerequisite " + prereq + " (name: " + name + ")");
      }
    }

    assertThat(foundSrc).isTrue();
    assertThat(foundTool).isTrue();
    assertThat(foundSetup).isTrue();
  }

  @Test
  public void testLabelsContainingAtDAreExpanded() throws Exception {
    scratch.file(
        "puck/BUILD",
        "genrule(name='gen', ",
        "        tools=['puck'],",
        "        outs=['out'],",
        "        cmd='echo $(@D)')");
    String regex = "echo b.{4}-out/.*/puck";
    assertThat(getCommand("//puck:gen")).containsMatch(regex);
  }

  @Test
  public void testGetExecutable() throws Exception {
    ConfiguredTarget turtle =
        scratchConfiguredTarget(
            "java/com/google/turtle",
            "turtle_bootstrap",
            "genrule(name = 'turtle_bootstrap',",
            "    srcs = ['Turtle.java'],",
            "    outs = ['turtle'],",
            "    executable = 1,",
            "    cmd = 'touch $(OUTS)')");
    assertThat(getExecutable(turtle).getExecPath().getBaseName()).isEqualTo("turtle");
  }

  @Test
  public void testGetExecutableForNonExecutableOut() throws Exception {
    ConfiguredTarget turtle =
        scratchConfiguredTarget(
            "java/com/google/turtle",
            "turtle_bootstrap",
            "genrule(name = 'turtle_bootstrap',",
            "    srcs = ['Turtle.java'],",
            "    outs = ['debugdata.txt'],",
            "    cmd = 'touch $(OUTS)')");
    assertThat(getExecutable(turtle)).isNull();
  }

  @Test
  public void testGetExecutableForMultipleOuts() throws Exception {
    ConfiguredTarget turtle =
        scratchConfiguredTarget(
            "java/com/google/turtle",
            "turtle_bootstrap",
            "genrule(name = 'turtle_bootstrap',",
            "    srcs = ['Turtle.java'],",
            "    outs = ['turtle', 'debugdata.txt'],",
            "    cmd = 'touch $(OUTS)')");
    assertThat(getExecutable(turtle)).isNull();
  }

  @Test
  public void testGetExecutableFailsForMultipleOutputs() throws Exception {
    // Multiple output files are invalid when executable=1.
    checkError(
        "bad",
        "bad",
        "in executable attribute of genrule rule //bad:bad: "
            + "if genrules produce executables, they are allowed only one output. "
            + "If you need the executable=1 argument, then you should split this genrule into "
            + "genrules producing single outputs",
        "genrule(name = 'bad',",
        "        outs = [ 'bad_out1', 'bad_out2' ],",
        "        executable = 1,",
        "        cmd = 'touch $(OUTS)')");
  }

  @Test
  public void testEmptyOutsError() throws Exception {
    checkError(
        "x",
        "x",
        "Genrules without outputs don't make sense",
        "genrule(name = 'x', outs = [], cmd='echo')");
  }

  @Test
  public void testGenruleSetup() throws Exception {
    scratch.file(
        "foo/BUILD",
        "genrule(name = 'foo_sh',",
        "        outs = [ 'foo.sh' ],", // Shell script files are known to be executable.
        "        cmd = 'touch $@')");

    assertThat(getCommand("//foo:foo_sh")).contains(GENRULE_SETUP_PATH);
  }

  private void createStampingTargets() throws Exception {
    scratch.file(
        "u/BUILD",
        "genrule(name='foo_stamp', srcs=[], outs=['uu'], stamp=1, cmd='')",
        "genrule(name='foo_nostamp', srcs=[], outs=['vv'], stamp=0, cmd='')",
        "genrule(name='foo_default', srcs=[], outs=['xx'], cmd='')");
  }

  private void assertStamped(String target) throws Exception {
    assertStamped(getConfiguredTarget(target));
  }

  private void assertNotStamped(String target) throws Exception {
    assertNotStamped(getConfiguredTarget(target));
  }

  private void assertStamped(ConfiguredTarget target) throws Exception {
    Artifact out = Iterables.getFirst(getFilesToBuild(target), null);
    List<String> inputs = ActionsTestUtil.baseArtifactNames(getGeneratingAction(out).getInputs());
    assertThat(inputs).containsAllOf("build-info.txt", "build-changelist.txt");
  }

  private void assertNotStamped(ConfiguredTarget target) throws Exception {
    Artifact out = Iterables.getFirst(getFilesToBuild(target), null);
    List<String> inputs = ActionsTestUtil.baseArtifactNames(getGeneratingAction(out).getInputs());
    assertThat(inputs).doesNotContain("build-info.txt");
    assertThat(inputs).doesNotContain("build-changelist.txt");
  }

  @Test
  public void testStampingWithNoStamp() throws Exception {
    useConfiguration("--nostamp");
    createStampingTargets();
    assertStamped("//u:foo_stamp");
    assertStamped(getHostConfiguredTarget("//u:foo_stamp"));
    assertNotStamped("//u:foo_nostamp");
    assertNotStamped(getHostConfiguredTarget("//u:foo_nostamp"));
    assertNotStamped("//u:foo_default");
  }

  @Test
  public void testStampingWithStamp() throws Exception {
    useConfiguration("--stamp");
    createStampingTargets();
    assertStamped("//u:foo_stamp");
    assertStamped(getHostConfiguredTarget("//u:foo_stamp"));
    //assertStamped("//u:foo_nostamp");
    assertNotStamped(getHostConfiguredTarget("//u:foo_nostamp"));
    assertNotStamped("//u:foo_default");
  }

  @Test
  public void testRequiresDarwin() throws Exception {
    scratch.file(
        "foo/BUILD",
        "genrule(name='darwin', srcs=[], outs=['macout'], cmd='', tags=['requires-darwin'])");

    SpawnAction action = getSpawnAction("//foo:darwin");
    assertThat(action.getExecutionInfo().keySet()).contains("requires-darwin");
    // requires-darwin causes /bin/bash to be hard-coded, see CommandHelper.shellPath().
    assertThat(action.getCommandFilename())
        .isEqualTo("/bin/bash");
  }

  @Test
  public void testJarError() throws Exception {
    checkError(
        "foo",
        "grj",
        "in cmd attribute of genrule rule //foo:grj: $(JAR) not defined",
        "genrule(name='grj',"
            + "      srcs = [],"
            + "      outs=['grj'],"
            + "      cmd='$(JAR) foo bar')");
  }

  /** Regression test for b/15589451. */
  @Test
  public void testDuplicateLocalFlags() throws Exception {
    scratch.file(
        "foo/BUILD",
        "genrule(name='g',"
            + "      srcs = [],"
            + "      outs = ['grj'],"
            + "      cmd ='echo g',"
            + "      local = 1,"
            + "      tags = ['local'])");
    getConfiguredTarget("//foo:g");
    assertNoEvents();
  }
}