Delete code associated with `--experimental_dynamic_configs=retroactive`. This flag value is unused and untested outside of a couple unit tests for individual components. Removing it simplifies work on b/185778053, specifically unblocking the removal of `BuildOptions.DiffForReconstruction`. Also took this opportunity to apply fixes to warnings in the affected files. PiperOrigin-RevId: 369970226
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/BUILD b/src/test/java/com/google/devtools/build/lib/analysis/BUILD index a7c1bef..f7c236a 100644 --- a/src/test/java/com/google/devtools/build/lib/analysis/BUILD +++ b/src/test/java/com/google/devtools/build/lib/analysis/BUILD
@@ -137,7 +137,6 @@ "//src/main/java/com/google/devtools/build/lib/skyframe/serialization/autocodec", "//src/main/java/com/google/devtools/build/lib/skyframe/serialization/testutils", "//src/main/java/com/google/devtools/build/lib/skyframe/serialization/testutils:depsutils", - "//src/main/java/com/google/devtools/build/lib/skyframe/trimming:trimmed_configuration_cache", "//src/main/java/com/google/devtools/build/lib/util", "//src/main/java/com/google/devtools/build/lib/util:detailed_exit_code", "//src/main/java/com/google/devtools/build/lib/util:filetype", @@ -160,12 +159,10 @@ "//src/test/java/com/google/devtools/build/lib/packages:testutil", "//src/test/java/com/google/devtools/build/lib/rules/platform:testutil", "//src/test/java/com/google/devtools/build/lib/skyframe:testutil", - "//src/test/java/com/google/devtools/build/lib/skyframe/trimming:trimmable_test_fragments", "//src/test/java/com/google/devtools/build/lib/testutil", "//src/test/java/com/google/devtools/build/lib/testutil:JunitUtils", "//src/test/java/com/google/devtools/build/lib/testutil:TestConstants", "//src/test/java/com/google/devtools/build/skyframe:testutil", - "//third_party:auto_value", "//third_party:guava", "//third_party:guava-testlib", "//third_party:jsr305",
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/config/BuildOptionsCompareFragmentsTest.java b/src/test/java/com/google/devtools/build/lib/analysis/config/BuildOptionsCompareFragmentsTest.java deleted file mode 100644 index 3464e5f..0000000 --- a/src/test/java/com/google/devtools/build/lib/analysis/config/BuildOptionsCompareFragmentsTest.java +++ /dev/null
@@ -1,474 +0,0 @@ -// Copyright 2018 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.analysis.config; - -import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertThrows; - -import com.google.auto.value.AutoValue; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.devtools.build.lib.analysis.config.BuildOptions.OptionsDiffForReconstruction; -import com.google.devtools.build.lib.cmdline.Label; -import com.google.devtools.build.lib.skyframe.trimming.ConfigurationComparer; -import com.google.devtools.build.lib.skyframe.trimming.TrimmableTestConfigurationFragments.AOptions; -import com.google.devtools.build.lib.skyframe.trimming.TrimmableTestConfigurationFragments.BOptions; -import java.util.Objects; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -/** Tests of compareFragments in BuildOptions.OptionsDiffForReconstruction. */ -public final class BuildOptionsCompareFragmentsTest { - - /** Test cases for BuildOptionsCompareFragmentsTest. */ - @AutoValue - public abstract static class Case { - public abstract String getName(); - - public abstract BuildOptions getBase(); - - public abstract BuildOptions getLeft(); - - public abstract BuildOptions getRight(); - - public abstract ConfigurationComparer.Result getLeftToRightResult(); - - public abstract ConfigurationComparer.Result getRightToLeftResult(); - - public static Builder named(String name) { - return new AutoValue_BuildOptionsCompareFragmentsTest_Case.Builder().setName(name); - } - - /** Quick builder for test cases. */ - @AutoValue.Builder - public abstract static class Builder { - public abstract Builder setName(String name); - - public abstract Builder setBase(BuildOptions base); - - public Builder setBase(OptionsBuilder base) throws Exception { - return this.setBase(base.build()); - } - - public abstract Builder setLeft(BuildOptions left); - - public Builder setLeft(OptionsBuilder left) throws Exception { - return this.setLeft(left.build()); - } - - public abstract Builder setRight(BuildOptions right); - - public Builder setRight(OptionsBuilder right) throws Exception { - return this.setRight(right.build()); - } - - public Builder setResult(ConfigurationComparer.Result result) { - return this.setLeftToRightResult(result).setRightToLeftResult(result); - } - - public abstract Builder setLeftToRightResult(ConfigurationComparer.Result result); - - public abstract Builder setRightToLeftResult(ConfigurationComparer.Result result); - - public abstract Case build(); - } - - @Override - public final String toString() { - if (Objects.equals(this.getLeftToRightResult(), this.getRightToLeftResult())) { - return String.format("%s [result = %s]", this.getName(), this.getLeftToRightResult()); - } else { - return String.format( - "%s [compare(left, right) = %s; compare(right, left) = %s]", - this.getName(), this.getLeftToRightResult(), this.getRightToLeftResult()); - } - } - } - - /** Quick builder for BuildOptions instances. */ - public static final class OptionsBuilder { - private final ImmutableMap.Builder<Label, Object> starlarkOptions = - new ImmutableMap.Builder<>(); - private final ImmutableList.Builder<Class<? extends FragmentOptions>> fragments = - new ImmutableList.Builder<>(); - private final ImmutableList.Builder<String> nativeOptions = new ImmutableList.Builder<>(); - - public OptionsBuilder withNativeFragment( - Class<? extends FragmentOptions> fragment, String... flags) { - this.fragments.add(fragment); - this.nativeOptions.add(flags); - return this; - } - - public OptionsBuilder withStarlarkOption(String setting, Object value) { - this.starlarkOptions.put(Label.parseAbsoluteUnchecked(setting), value); - return this; - } - - public OptionsBuilder withStarlarkOption(String setting) { - return this.withStarlarkOption(setting, setting); - } - - public BuildOptions build() throws Exception { - return BuildOptions.builder() - .addStarlarkOptions(this.starlarkOptions.build()) - .merge( - BuildOptions.of( - this.fragments.build(), this.nativeOptions.build().toArray(new String[0]))) - .build(); - } - } - - /** Test cases for compareFragments which produce an ordinary result. */ - @RunWith(Parameterized.class) - public static final class NormalCases { - - @Parameters(name = "{index}: {0}") - public static Iterable<Case> cases() throws Exception { - return ImmutableList.of( - Case.named("both options equal to the base") - .setResult(ConfigurationComparer.Result.EQUAL) - .setBase( - new OptionsBuilder() - .withNativeFragment(AOptions.class) - .withStarlarkOption("//alpha")) - .setLeft( - new OptionsBuilder() - .withNativeFragment(AOptions.class) - .withStarlarkOption("//alpha")) - .setRight( - new OptionsBuilder() - .withNativeFragment(AOptions.class) - .withStarlarkOption("//alpha")) - .build(), - Case.named("both sides change native fragment to same value") - .setResult(ConfigurationComparer.Result.EQUAL) - .setBase(new OptionsBuilder().withNativeFragment(AOptions.class, "--alpha=base")) - .setLeft(new OptionsBuilder().withNativeFragment(AOptions.class, "--alpha=new")) - .setRight(new OptionsBuilder().withNativeFragment(AOptions.class, "--alpha=new")) - .build(), - Case.named("both sides add native fragment with same value") - .setResult(ConfigurationComparer.Result.EQUAL) - .setBase(new OptionsBuilder()) - .setLeft(new OptionsBuilder().withNativeFragment(AOptions.class, "--alpha=new")) - .setRight(new OptionsBuilder().withNativeFragment(AOptions.class, "--alpha=new")) - .build(), - Case.named("both sides remove same native fragment") - .setResult(ConfigurationComparer.Result.EQUAL) - .setBase(new OptionsBuilder().withNativeFragment(AOptions.class)) - .setLeft(new OptionsBuilder()) - .setRight(new OptionsBuilder()) - .build(), - Case.named("both sides change Starlark option to same value") - .setResult(ConfigurationComparer.Result.EQUAL) - .setBase(new OptionsBuilder().withStarlarkOption("//alpha", "base")) - .setLeft(new OptionsBuilder().withStarlarkOption("//alpha", "new")) - .setRight(new OptionsBuilder().withStarlarkOption("//alpha", "new")) - .build(), - Case.named("both sides add Starlark option with same value") - .setResult(ConfigurationComparer.Result.EQUAL) - .setBase(new OptionsBuilder()) - .setLeft(new OptionsBuilder().withStarlarkOption("//alpha", "new")) - .setRight(new OptionsBuilder().withStarlarkOption("//alpha", "new")) - .build(), - Case.named("both sides remove same Starlark option") - .setResult(ConfigurationComparer.Result.EQUAL) - .setBase(new OptionsBuilder().withStarlarkOption("//alpha")) - .setLeft(new OptionsBuilder()) - .setRight(new OptionsBuilder()) - .build(), - Case.named("native fragment removed from right") - .setLeftToRightResult(ConfigurationComparer.Result.SUPERSET) - .setRightToLeftResult(ConfigurationComparer.Result.SUBSET) - .setBase(new OptionsBuilder().withNativeFragment(AOptions.class)) - .setLeft(new OptionsBuilder().withNativeFragment(AOptions.class)) - .setRight(new OptionsBuilder()) - .build(), - Case.named("native fragment added to right") - .setLeftToRightResult(ConfigurationComparer.Result.SUBSET) - .setRightToLeftResult(ConfigurationComparer.Result.SUPERSET) - .setBase(new OptionsBuilder()) - .setLeft(new OptionsBuilder()) - .setRight(new OptionsBuilder().withNativeFragment(AOptions.class)) - .build(), - Case.named("native fragment changed in left and removed from right") - .setLeftToRightResult(ConfigurationComparer.Result.SUPERSET) - .setRightToLeftResult(ConfigurationComparer.Result.SUBSET) - .setBase(new OptionsBuilder().withNativeFragment(AOptions.class, "--alpha=base")) - .setLeft(new OptionsBuilder().withNativeFragment(AOptions.class, "--alpha=left")) - .setRight(new OptionsBuilder()) - .build(), - Case.named("native fragment added to left and another fragment removed from right") - .setLeftToRightResult(ConfigurationComparer.Result.SUPERSET) - .setRightToLeftResult(ConfigurationComparer.Result.SUBSET) - .setBase(new OptionsBuilder().withNativeFragment(AOptions.class)) - .setLeft( - new OptionsBuilder() - .withNativeFragment(AOptions.class) - .withNativeFragment(BOptions.class)) - .setRight(new OptionsBuilder()) - .build(), - Case.named("Starlark option removed from right") - .setLeftToRightResult(ConfigurationComparer.Result.SUPERSET) - .setRightToLeftResult(ConfigurationComparer.Result.SUBSET) - .setBase(new OptionsBuilder().withStarlarkOption("//alpha")) - .setLeft(new OptionsBuilder().withStarlarkOption("//alpha")) - .setRight(new OptionsBuilder()) - .build(), - Case.named("Starlark option added to right") - .setLeftToRightResult(ConfigurationComparer.Result.SUBSET) - .setRightToLeftResult(ConfigurationComparer.Result.SUPERSET) - .setBase(new OptionsBuilder()) - .setLeft(new OptionsBuilder()) - .setRight(new OptionsBuilder().withStarlarkOption("//alpha")) - .build(), - Case.named("Starlark option changed in left and removed from right") - .setLeftToRightResult(ConfigurationComparer.Result.SUPERSET) - .setRightToLeftResult(ConfigurationComparer.Result.SUBSET) - .setBase(new OptionsBuilder().withStarlarkOption("//alpha", "base")) - .setLeft(new OptionsBuilder().withStarlarkOption("//alpha", "left")) - .setRight(new OptionsBuilder()) - .build(), - Case.named("Starlark option added to left and another option removed from right") - .setLeftToRightResult(ConfigurationComparer.Result.SUPERSET) - .setRightToLeftResult(ConfigurationComparer.Result.SUBSET) - .setBase(new OptionsBuilder().withStarlarkOption("//alpha")) - .setLeft( - new OptionsBuilder().withStarlarkOption("//alpha").withStarlarkOption("//bravo")) - .setRight(new OptionsBuilder()) - .build(), - Case.named("different native fragment added to each side") - .setResult(ConfigurationComparer.Result.ALL_SHARED_FRAGMENTS_EQUAL) - .setBase(new OptionsBuilder()) - .setLeft(new OptionsBuilder().withNativeFragment(AOptions.class)) - .setRight(new OptionsBuilder().withNativeFragment(BOptions.class)) - .build(), - Case.named("different native fragment removed from each side") - .setResult(ConfigurationComparer.Result.ALL_SHARED_FRAGMENTS_EQUAL) - .setBase( - new OptionsBuilder() - .withNativeFragment(AOptions.class) - .withNativeFragment(BOptions.class)) - .setLeft(new OptionsBuilder().withNativeFragment(AOptions.class)) - .setRight(new OptionsBuilder().withNativeFragment(BOptions.class)) - .build(), - Case.named("native fragment added and different fragment removed on left") - .setResult(ConfigurationComparer.Result.ALL_SHARED_FRAGMENTS_EQUAL) - .setBase(new OptionsBuilder().withNativeFragment(BOptions.class)) - .setLeft(new OptionsBuilder().withNativeFragment(AOptions.class)) - .setRight(new OptionsBuilder().withNativeFragment(BOptions.class)) - .build(), - Case.named( - "native fragment added to right; " - + "other fragment changed on left and removed from right") - .setResult(ConfigurationComparer.Result.ALL_SHARED_FRAGMENTS_EQUAL) - .setBase(new OptionsBuilder().withNativeFragment(AOptions.class, "--alpha=base")) - .setLeft(new OptionsBuilder().withNativeFragment(AOptions.class, "--alpha=left")) - .setRight(new OptionsBuilder().withNativeFragment(BOptions.class)) - .build(), - Case.named("native fragment changed on each side, removed from the other") - .setResult(ConfigurationComparer.Result.ALL_SHARED_FRAGMENTS_EQUAL) - .setBase( - new OptionsBuilder() - .withNativeFragment(AOptions.class, "--alpha=base") - .withNativeFragment(BOptions.class, "--bravo=base")) - .setLeft(new OptionsBuilder().withNativeFragment(AOptions.class, "--alpha=left")) - .setRight(new OptionsBuilder().withNativeFragment(BOptions.class, "--bravo=right")) - .build(), - Case.named( - "native fragment changed on left, removed from right; " - + "other fragment removed from left") - .setResult(ConfigurationComparer.Result.ALL_SHARED_FRAGMENTS_EQUAL) - .setBase( - new OptionsBuilder() - .withNativeFragment(AOptions.class, "--alpha=base") - .withNativeFragment(BOptions.class)) - .setLeft(new OptionsBuilder().withNativeFragment(AOptions.class, "--alpha=left")) - .setRight(new OptionsBuilder().withNativeFragment(BOptions.class)) - .build(), - Case.named("different Starlark option added to each side") - .setResult(ConfigurationComparer.Result.ALL_SHARED_FRAGMENTS_EQUAL) - .setBase(new OptionsBuilder()) - .setLeft(new OptionsBuilder().withStarlarkOption("//alpha")) - .setRight(new OptionsBuilder().withStarlarkOption("//bravo")) - .build(), - Case.named("different Starlark option removed from each side") - .setResult(ConfigurationComparer.Result.ALL_SHARED_FRAGMENTS_EQUAL) - .setBase( - new OptionsBuilder().withStarlarkOption("//alpha").withStarlarkOption("//bravo")) - .setLeft(new OptionsBuilder().withStarlarkOption("//alpha")) - .setRight(new OptionsBuilder().withStarlarkOption("//bravo")) - .build(), - Case.named("Starlark option added and different option removed on left") - .setResult(ConfigurationComparer.Result.ALL_SHARED_FRAGMENTS_EQUAL) - .setBase(new OptionsBuilder().withStarlarkOption("//bravo")) - .setLeft(new OptionsBuilder().withStarlarkOption("//alpha")) - .setRight(new OptionsBuilder().withStarlarkOption("//bravo")) - .build(), - Case.named( - "Starlark option added to right; " - + "other option changed on left and removed from right") - .setResult(ConfigurationComparer.Result.ALL_SHARED_FRAGMENTS_EQUAL) - .setBase(new OptionsBuilder().withStarlarkOption("//alpha", "base")) - .setLeft(new OptionsBuilder().withStarlarkOption("//alpha", "left")) - .setRight(new OptionsBuilder().withStarlarkOption("//bravo")) - .build(), - Case.named("Starlark option changed on each side, removed from the other") - .setResult(ConfigurationComparer.Result.ALL_SHARED_FRAGMENTS_EQUAL) - .setBase( - new OptionsBuilder() - .withStarlarkOption("//alpha", "base") - .withStarlarkOption("//bravo", "base")) - .setLeft(new OptionsBuilder().withStarlarkOption("//alpha", "left")) - .setRight(new OptionsBuilder().withStarlarkOption("//bravo", "right")) - .build(), - Case.named( - "Starlark option changed on left, removed from right; " - + "other option removed from left") - .setResult(ConfigurationComparer.Result.ALL_SHARED_FRAGMENTS_EQUAL) - .setBase( - new OptionsBuilder() - .withStarlarkOption("//alpha", "base") - .withStarlarkOption("//bravo")) - .setLeft(new OptionsBuilder().withStarlarkOption("//alpha", "left")) - .setRight(new OptionsBuilder().withStarlarkOption("//bravo")) - .build(), - Case.named("Starlark option removed from left, native option removed from right") - .setResult(ConfigurationComparer.Result.ALL_SHARED_FRAGMENTS_EQUAL) - .setBase( - new OptionsBuilder() - .withNativeFragment(AOptions.class) - .withStarlarkOption("//bravo")) - .setLeft(new OptionsBuilder().withNativeFragment(AOptions.class)) - .setRight(new OptionsBuilder().withStarlarkOption("//bravo")) - .build(), - Case.named("Starlark option added to left, native option added to right") - .setResult(ConfigurationComparer.Result.ALL_SHARED_FRAGMENTS_EQUAL) - .setBase(new OptionsBuilder()) - .setLeft(new OptionsBuilder().withStarlarkOption("//alpha")) - .setRight(new OptionsBuilder().withNativeFragment(BOptions.class)) - .build(), - Case.named("native fragment is unchanged in left, changes in right") - .setResult(ConfigurationComparer.Result.DIFFERENT) - .setBase(new OptionsBuilder().withNativeFragment(AOptions.class, "--alpha=base")) - .setLeft(new OptionsBuilder().withNativeFragment(AOptions.class, "--alpha=base")) - .setRight(new OptionsBuilder().withNativeFragment(AOptions.class, "--alpha=right")) - .build(), - Case.named("native fragment is changed to different values") - .setResult(ConfigurationComparer.Result.DIFFERENT) - .setBase(new OptionsBuilder().withNativeFragment(AOptions.class, "--alpha=base")) - .setLeft(new OptionsBuilder().withNativeFragment(AOptions.class, "--alpha=left")) - .setRight(new OptionsBuilder().withNativeFragment(AOptions.class, "--alpha=right")) - .build(), - Case.named("native fragment is added with different values") - .setResult(ConfigurationComparer.Result.DIFFERENT) - .setBase(new OptionsBuilder()) - .setLeft(new OptionsBuilder().withNativeFragment(AOptions.class, "--alpha=left")) - .setRight(new OptionsBuilder().withNativeFragment(AOptions.class, "--alpha=right")) - .build(), - Case.named("Starlark option is unchanged in left, changes in right") - .setResult(ConfigurationComparer.Result.DIFFERENT) - .setBase(new OptionsBuilder().withStarlarkOption("//alpha", "base")) - .setLeft(new OptionsBuilder().withStarlarkOption("//alpha", "base")) - .setRight(new OptionsBuilder().withStarlarkOption("//alpha", "right")) - .build(), - Case.named("Starlark option is changed to different values") - .setResult(ConfigurationComparer.Result.DIFFERENT) - .setBase(new OptionsBuilder().withStarlarkOption("//alpha", "base")) - .setLeft(new OptionsBuilder().withStarlarkOption("//alpha", "left")) - .setRight(new OptionsBuilder().withStarlarkOption("//alpha", "right")) - .build(), - Case.named("Starlark option is added with different values") - .setResult(ConfigurationComparer.Result.DIFFERENT) - .setBase(new OptionsBuilder()) - .setLeft(new OptionsBuilder().withStarlarkOption("//alpha", "left")) - .setRight(new OptionsBuilder().withStarlarkOption("//alpha", "right")) - .build()); - } - - private final Case testCase; - - public NormalCases(Case testCase) { - this.testCase = testCase; - } - - @Test - public void compareLeftToRight() throws Exception { - OptionsDiffForReconstruction diffLeft = - BuildOptions.diffForReconstruction(testCase.getBase(), testCase.getLeft()); - OptionsDiffForReconstruction diffRight = - BuildOptions.diffForReconstruction(testCase.getBase(), testCase.getRight()); - - assertThat(OptionsDiffForReconstruction.compareFragments(diffLeft, diffRight)) - .isEqualTo(testCase.getLeftToRightResult()); - } - - @Test - public void compareRightToLeft() throws Exception { - OptionsDiffForReconstruction diffLeft = - BuildOptions.diffForReconstruction(testCase.getBase(), testCase.getLeft()); - OptionsDiffForReconstruction diffRight = - BuildOptions.diffForReconstruction(testCase.getBase(), testCase.getRight()); - - assertThat(OptionsDiffForReconstruction.compareFragments(diffRight, diffLeft)) - .isEqualTo(testCase.getRightToLeftResult()); - } - } - - /** Test cases for compareFragments which produce errors. */ - @RunWith(JUnit4.class) - public static final class ExceptionalCases { - @Test - public void withDifferentBases_throwsError() throws Exception { - BuildOptions baseA = - new OptionsBuilder() - .withNativeFragment(AOptions.class, "--alpha=A") - .withNativeFragment(BOptions.class, "--bravo=base") - .build(); - BuildOptions newA = - new OptionsBuilder() - .withNativeFragment(AOptions.class, "--alpha=A") - .withNativeFragment(BOptions.class, "--bravo=new") - .build(); - BuildOptions baseB = - new OptionsBuilder() - .withNativeFragment(AOptions.class, "--alpha=B") - .withNativeFragment(BOptions.class, "--bravo=base") - .build(); - BuildOptions newB = - new OptionsBuilder() - .withNativeFragment(AOptions.class, "--alpha=B") - .withNativeFragment(BOptions.class, "--bravo=old") - .build(); - - OptionsDiffForReconstruction diffA = BuildOptions.diffForReconstruction(baseA, newA); - OptionsDiffForReconstruction diffB = BuildOptions.diffForReconstruction(baseB, newB); - - IllegalArgumentException forwardException = - assertThrows( - IllegalArgumentException.class, - () -> OptionsDiffForReconstruction.compareFragments(diffA, diffB)); - assertThat(forwardException).hasMessageThat().contains("diffs with different bases"); - - IllegalArgumentException reverseException = - assertThrows( - IllegalArgumentException.class, - () -> OptionsDiffForReconstruction.compareFragments(diffB, diffA)); - assertThat(reverseException).hasMessageThat().contains("diffs with different bases"); - } - } -}
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/util/BuildViewForTesting.java b/src/test/java/com/google/devtools/build/lib/analysis/util/BuildViewForTesting.java index 3f8b306..293a0b7 100644 --- a/src/test/java/com/google/devtools/build/lib/analysis/util/BuildViewForTesting.java +++ b/src/test/java/com/google/devtools/build/lib/analysis/util/BuildViewForTesting.java
@@ -18,7 +18,6 @@ import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.collect.Streams.stream; -import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Functions; import com.google.common.base.Preconditions; import com.google.common.collect.Collections2; @@ -32,7 +31,6 @@ import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; -import com.google.common.collect.Streams; import com.google.common.eventbus.EventBus; import com.google.devtools.build.lib.actions.ActionLookupKey; import com.google.devtools.build.lib.actions.ArtifactFactory; @@ -160,7 +158,6 @@ this.skyframeBuildView = skyframeExecutor.getSkyframeBuildView(); } - @VisibleForTesting public Set<ActionLookupKey> getSkyframeEvaluatedActionLookupKeyCountForTesting() { Set<ActionLookupKey> actionLookupKeys = populateActionLookupKeyMapAndGetDiff(); Preconditions.checkState( @@ -188,7 +185,6 @@ /** * Returns whether the given configured target has errors. */ - @VisibleForTesting public boolean hasErrors(ConfiguredTarget configuredTarget) { return configuredTarget == null; } @@ -223,8 +219,7 @@ eventBus); } - /** Sets the configurations. Not thread-safe. DO NOT CALL except from tests! */ - @VisibleForTesting + /** Sets the configurations. Not thread-safe. */ public void setConfigurationsForTesting( EventHandler eventHandler, BuildConfigurationCollection configurations) { skyframeBuildView.setConfigurations( @@ -242,7 +237,6 @@ * the fragments needed by the fragment and its transitive closure. Else unconditionally includes * all fragments. */ - @VisibleForTesting public BuildConfiguration getConfigurationForTesting( Target target, BuildConfiguration config, ExtendedEventHandler eventHandler) throws InvalidConfigurationException, InterruptedException { @@ -262,22 +256,19 @@ * Sets the possible artifact roots in the artifact factory. This allows the factory to resolve * paths with unknown roots to artifacts. */ - @VisibleForTesting // for BuildViewTestCase public void setArtifactRoots(PackageRoots packageRoots) { getArtifactFactory().setPackageRoots(packageRoots.getPackageRootLookup()); } - @VisibleForTesting // TODO(janakr): pass the configuration in as a parameter here. public Collection<ConfiguredTarget> getDirectPrerequisitesForTesting( ExtendedEventHandler eventHandler, ConfiguredTarget ct, BuildConfigurationCollection configurations) - throws DependencyResolver.Failure, InvalidConfigurationException, InterruptedException, + throws DependencyResolver.Failure, InvalidConfigurationException, InconsistentAspectOrderException, StarlarkTransition.TransitionException { return Collections2.transform( - getConfiguredTargetAndDataDirectPrerequisitesForTesting( - eventHandler, ct, ct.getConfigurationKey(), configurations), + getConfiguredTargetAndDataDirectPrerequisitesForTesting(eventHandler, ct, configurations), ConfiguredTargetAndData::getConfiguredTarget); } @@ -285,9 +276,8 @@ getConfiguredTargetAndDataDirectPrerequisitesForTesting( ExtendedEventHandler eventHandler, ConfiguredTarget ct, - BuildConfigurationValue.Key configuration, BuildConfigurationCollection configurations) - throws DependencyResolver.Failure, InvalidConfigurationException, InterruptedException, + throws DependencyResolver.Failure, InvalidConfigurationException, InconsistentAspectOrderException, StarlarkTransition.TransitionException { SkyframeExecutorWrappingWalkableGraph walkableGraph = @@ -313,23 +303,18 @@ walkableGraph.getDirectDeps( ConfiguredTargetKey.builder().setConfiguredTarget(ct).build()); - // Turn the keys back into ConfiguredTarget instances, possibly merging in aspects that - // were propagated from the original target. - Collection<ConfiguredTargetAndData> cts = - Streams.stream(directPrerequisites) - .filter(dep -> dep instanceof ConfiguredTargetKey) - .map(dep -> (ConfiguredTargetKey) dep) - .map(configuredTargetKey -> getConfiguredTarget(walkableGraph, configuredTargetKey)) - // For each configured target, add in any aspects from depNodeNames. - .map( - configuredTarget -> - mergeAspects( - walkableGraph, - configuredTarget, - findDependencyKey(dependencyKeys, configuredTarget))) - .collect(toImmutableList()); - - return cts; + // Turn the keys back into ConfiguredTarget instances, possibly merging in aspects that were + // propagated from the original target. + return stream(Iterables.filter(directPrerequisites, ConfiguredTargetKey.class)) + .map(configuredTargetKey -> getConfiguredTarget(walkableGraph, configuredTargetKey)) + // For each configured target, add in any aspects from depNodeNames. + .map( + configuredTarget -> + mergeAspects( + walkableGraph, + configuredTarget, + findDependencyKey(dependencyKeys, configuredTarget))) + .collect(toImmutableList()); } catch (InterruptedException e) { return ImmutableList.of(); } @@ -363,7 +348,7 @@ } @Nullable - private DependencyKey findDependencyKey( + private static DependencyKey findDependencyKey( Multimap<Label, DependencyKey> dependencyKeys, ConfiguredTargetAndData configuredTarget) { // TODO(blaze-configurability): Figure out how to map the ConfiguredTarget back to the correct // DependencyKey when there are more than one. @@ -371,7 +356,7 @@ } // Helper method to find the aspects needed for a target and merge them. - protected ConfiguredTargetAndData mergeAspects( + protected static ConfiguredTargetAndData mergeAspects( WalkableGraph graph, ConfiguredTargetAndData ctd, @Nullable DependencyKey dependencyKey) { if (dependencyKey == null || dependencyKey.getAspects().getUsedAspects().isEmpty()) { return ctd; @@ -400,7 +385,6 @@ } } - @VisibleForTesting public OrderedSetMultimap<DependencyKind, DependencyKey> getDirectPrerequisiteDependenciesForTesting( final ExtendedEventHandler eventHandler, @@ -410,7 +394,7 @@ throws DependencyResolver.Failure, InterruptedException, InconsistentAspectOrderException, StarlarkTransition.TransitionException, InvalidConfigurationException { - Target target = null; + Target target; try { target = skyframeExecutor.getPackageManager().getTarget(eventHandler, ct.getLabel()); } catch (NoSuchPackageException | NoSuchTargetException | InterruptedException e) { @@ -558,7 +542,6 @@ * * <p>Returns {@code null} if something goes wrong. */ - @VisibleForTesting public ConfiguredTarget getConfiguredTargetForTesting( ExtendedEventHandler eventHandler, Label label, BuildConfiguration config) throws StarlarkTransition.TransitionException, InvalidConfigurationException, @@ -571,7 +554,6 @@ return skyframeExecutor.getConfiguredTargetForTesting(eventHandler, label, config, transition); } - @VisibleForTesting ConfiguredTargetAndData getConfiguredTargetAndDataForTesting( ExtendedEventHandler eventHandler, Label label, BuildConfiguration config) throws StarlarkTransition.TransitionException, InvalidConfigurationException, @@ -588,7 +570,6 @@ /** * Returns a RuleContext which is the same as the original RuleContext of the target parameter. */ - @VisibleForTesting public RuleContext getRuleContextForTesting( ConfiguredTarget target, StoredEventHandler eventHandler, @@ -611,7 +592,6 @@ .setLabel(target.getLabel()) .setConfiguration(targetConfig) .build(), - /*isSystemEnv=*/ false, targetConfig.extendedSanityChecks(), targetConfig.allowAnalysisFailures(), eventHandler, @@ -624,7 +604,6 @@ * Creates and returns a rule context that is equivalent to the one that was used to create the * given configured target. */ - @VisibleForTesting public RuleContext getRuleContextForTesting( ExtendedEventHandler eventHandler, ConfiguredTarget configuredTarget, @@ -635,7 +614,7 @@ StarlarkTransition.TransitionException, InvalidExecGroupException { BuildConfiguration targetConfig = skyframeExecutor.getConfiguration(eventHandler, configuredTarget.getConfigurationKey()); - Target target = null; + Target target; try { target = skyframeExecutor.getPackageManager().getTarget(eventHandler, configuredTarget.getLabel()); @@ -740,7 +719,6 @@ } /** Clears the analysis cache as in --discard_analysis_cache. */ - @VisibleForTesting void clearAnalysisCache( Collection<ConfiguredTarget> topLevelTargets, ImmutableSet<AspectKey> topLevelAspects) { skyframeBuildView.clearAnalysisCache(topLevelTargets, topLevelAspects);
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/util/BuildViewTestCase.java b/src/test/java/com/google/devtools/build/lib/analysis/util/BuildViewTestCase.java index b1da3f9..aac74b6 100644 --- a/src/test/java/com/google/devtools/build/lib/analysis/util/BuildViewTestCase.java +++ b/src/test/java/com/google/devtools/build/lib/analysis/util/BuildViewTestCase.java
@@ -338,9 +338,9 @@ packageOptions, buildLanguageOptions, UUID.randomUUID(), - ImmutableMap.<String, String>of(), + ImmutableMap.of(), tsgm); - skyframeExecutor.setActionEnv(ImmutableMap.<String, String>of()); + skyframeExecutor.setActionEnv(ImmutableMap.of()); useConfiguration(); setUpSkyframe(); this.actionLogBufferPathGenerator = @@ -411,7 +411,7 @@ } protected Iterable<EnvironmentExtension> getEnvironmentExtensions() { - return ImmutableList.<EnvironmentExtension>of(); + return ImmutableList.of(); } protected StarlarkSemantics getStarlarkSemantics() { @@ -452,8 +452,7 @@ optionsParser.setStarlarkOptions(starlarkOptions); BuildOptions buildOptions = ruleClassProvider.createBuildOptions(optionsParser); - return skyframeExecutor.createConfigurations( - reporter, buildOptions, ImmutableSet.<String>of(), false); + return skyframeExecutor.createConfigurations(reporter, buildOptions, ImmutableSet.of(), false); } protected Target getTarget(String label) @@ -559,8 +558,6 @@ * Invalidates all existing packages. Optionally invalidates configurations too. * * <p>Tests should invalidate both unless they have specific reason not to. - * - * @throws InterruptedException */ protected void invalidatePackages(boolean alsoConfigs) throws InterruptedException { skyframeExecutor.invalidateFilesUnderPathForTesting( @@ -605,7 +602,6 @@ * @param starlarkOptions map of Starlark-defined options where the keys are option names (in the * form of label-like strings) and the values are option values * @param args native option name/pair descriptions in command line form (e.g. "--cpu=k8") - * @throws IllegalArgumentException */ protected void useConfiguration(ImmutableMap<String, Object> starlarkOptions, String... args) throws Exception { @@ -624,11 +620,10 @@ } /** - * Creates BuildView using current hostConfig/targetConfig values. - * Ensures that hostConfig is either identical to the targetConfig or has - * 'host' short name. + * Creates BuildView using current hostConfig/targetConfig values. Ensures that hostConfig is + * either identical to the targetConfig or has 'host' short name. */ - protected final void createBuildView() throws Exception { + protected final void createBuildView() { Preconditions.checkNotNull(masterConfig); Preconditions.checkState(getHostConfiguration().equals(getTargetConfiguration()) || getHostConfiguration().isHostConfiguration(), @@ -664,7 +659,6 @@ return null; } }, - /*isSystemEnv=*/ true, /*extendedSanityChecks=*/ false, /*allowAnalysisFailures=*/ false, reporter, @@ -680,7 +674,7 @@ */ protected final Collection<ConfiguredTarget> getDirectPrerequisites(ConfiguredTarget target) throws TransitionException, InvalidConfigurationException, InconsistentAspectOrderException, - Failure, InterruptedException { + Failure { return view.getDirectPrerequisitesForTesting(reporter, target, masterConfig); } @@ -703,7 +697,6 @@ view.getConfiguredTargetAndDataDirectPrerequisitesForTesting( reporter, ctad.getConfiguredTarget(), - ctad.getConfiguredTarget().getConfigurationKey(), masterConfig)) { if (candidate.getConfiguredTarget().getLabel().equals(candidateLabel)) { return candidate; @@ -733,10 +726,10 @@ * comparison. * * <p>Generally, this means they share the same checksum, which is computed by iterating over all - * the individual @Option annotated values contained within the {@link FragmentOption} classes + * the individual @Option annotated values contained within the {@link FragmentOptions} classes * contained within the {@link BuildOptions} inside the given configurations. */ - protected void assertConfigurationsEqual( + protected static void assertConfigurationsEqual( BuildConfiguration config1, BuildConfiguration config2, Set<Class<? extends FragmentOptions>> excludeFragmentOptions) { @@ -747,8 +740,9 @@ .isEqualTo(trimConfiguration(config1.cloneOptions(), excludeFragmentOptions)); } - protected void assertConfigurationsEqual(BuildConfiguration config1, BuildConfiguration config2) { - assertConfigurationsEqual(config1, config2, ImmutableSet.of()); + protected static void assertConfigurationsEqual( + BuildConfiguration config1, BuildConfiguration config2) { + assertConfigurationsEqual(config1, config2, /*excludeFragmentOptions=*/ ImmutableSet.of()); } /** @@ -1099,11 +1093,9 @@ * @param ruleName the name of the rule. * @param lines the text of the rule. * @return the configured target instance for the created rule. - * @throws IOException - * @throws Exception */ protected ConfiguredTarget scratchConfiguredTarget( - String packageName, String ruleName, String... lines) throws IOException, Exception { + String packageName, String ruleName, String... lines) throws Exception { return scratchConfiguredTarget(packageName, ruleName, targetConfig, lines); } @@ -1115,12 +1107,10 @@ * @param config the configuration to use to construct the configured rule. * @param lines the text of the rule. * @return the configured target instance for the created rule. - * @throws IOException - * @throws Exception */ protected ConfiguredTarget scratchConfiguredTarget( String packageName, String ruleName, BuildConfiguration config, String... lines) - throws IOException, Exception { + throws Exception { ConfiguredTargetAndData ctad = scratchConfiguredTargetAndData(packageName, ruleName, config, lines); return ctad == null ? null : ctad.getConfiguredTarget(); @@ -1133,7 +1123,6 @@ * @param rulename the name of the rule. * @param lines the text of the rule. * @return the configured tatarget and target instance for the created rule. - * @throws Exception */ protected ConfiguredTargetAndData scratchConfiguredTargetAndData( String packageName, String rulename, String... lines) throws Exception { @@ -1148,8 +1137,6 @@ * @param config the configuration to use to construct the configured rule. * @param lines the text of the rule. * @return the ConfiguredTargetAndData instance for the created rule. - * @throws IOException - * @throws Exception */ protected ConfiguredTargetAndData scratchConfiguredTargetAndData( String packageName, String ruleName, BuildConfiguration config, String... lines) @@ -1165,8 +1152,6 @@ * @param ruleName the name of the rule. * @param lines the text of the rule. * @return the rule instance for the created rule. - * @throws IOException - * @throws Exception */ protected Rule scratchRule(String packageName, String ruleName, String... lines) throws Exception { @@ -1427,7 +1412,7 @@ } /** Returns the input {@link Artifact}s to the given {@link Action} with the given exec paths. */ - protected List<Artifact> getInputs(Action owner, Collection<String> execPaths) { + protected static List<Artifact> getInputs(Action owner, Collection<String> execPaths) { Set<String> expectedPaths = new HashSet<>(execPaths); List<Artifact> result = new ArrayList<>(); for (Artifact output : owner.getInputs().toList()) { @@ -1664,11 +1649,11 @@ : outputPath; } - protected String fileName(Artifact artifact) { + protected static String fileName(Artifact artifact) { return artifact.getExecPathString(); } - protected String fileName(FileConfiguredTarget target) { + protected static String fileName(FileConfiguredTarget target) { return fileName(target.getArtifact()); } @@ -1722,8 +1707,9 @@ "'" + packageName + ":a.foo' does not produce any " + descriptionPlural); } - protected void assertSrcsValidity(String ruleType, String targetName, boolean expectedError, - String... expectedMessages) throws Exception{ + protected void assertSrcsValidity( + String ruleType, String targetName, boolean expectedError, String... expectedMessages) + throws Exception { ConfiguredTarget target = getConfiguredTarget(targetName); if (expectedError) { assertThat(view.hasErrors(target)).isTrue(); @@ -1757,10 +1743,10 @@ .build(); } - protected static List<String> actionInputsToPaths(NestedSet<? extends ActionInput> actionInputs) { + protected static ImmutableList<String> actionInputsToPaths( + NestedSet<? extends ActionInput> actionInputs) { return ImmutableList.copyOf( - Iterables.transform( - actionInputs.toList(), (actionInput) -> actionInput.getExecPathString())); + Lists.transform(actionInputs.toList(), ActionInput::getExecPathString)); } /** @@ -1774,20 +1760,19 @@ } /** - * Utility method for asserting that a list contains the elements of a - * sublist. This is useful for checking that a list of arguments contains a - * particular set of arguments. + * Utility method for asserting that a list contains the elements of a sublist. This is useful for + * checking that a list of arguments contains a particular set of arguments. */ - protected void assertContainsSublist(List<String> list, List<String> sublist) { + protected static void assertContainsSublist(List<String> list, List<String> sublist) { assertContainsSublist(null, list, sublist); } /** - * Utility method for asserting that a list contains the elements of a - * sublist. This is useful for checking that a list of arguments contains a - * particular set of arguments. + * Utility method for asserting that a list contains the elements of a sublist. This is useful for + * checking that a list of arguments contains a particular set of arguments. */ - protected void assertContainsSublist(String message, List<String> list, List<String> sublist) { + protected static void assertContainsSublist( + String message, List<String> list, List<String> sublist) { if (Collections.indexOfSubList(list, sublist) == -1) { fail((message == null ? "" : (message + ' ')) + "expected: <" + list + "> to contain sublist: <" + sublist + ">"); @@ -1795,10 +1780,10 @@ } protected void assertContainsSelfEdgeEvent(String label) { - assertContainsEvent(Pattern.compile(label + " \\([a-f0-9]+\\) \\[self-edge\\]")); + assertContainsEvent(Pattern.compile(label + " \\([a-f0-9]+\\) \\[self-edge]")); } - protected NestedSet<Artifact> collectRunfiles(ConfiguredTarget target) { + protected static NestedSet<Artifact> collectRunfiles(ConfiguredTarget target) { RunfilesProvider runfilesProvider = target.getProvider(RunfilesProvider.class); if (runfilesProvider != null) { return runfilesProvider.getDefaultRunfiles().getAllArtifacts(); @@ -1807,7 +1792,7 @@ } } - protected NestedSet<Artifact> getFilesToBuild(TransitiveInfoCollection target) { + protected static NestedSet<Artifact> getFilesToBuild(TransitiveInfoCollection target) { return target.getProvider(FileProvider.class).getFilesToBuild(); } @@ -1851,15 +1836,16 @@ return ImmutableList.copyOf(result); } - protected NestedSet<Artifact> getOutputGroup( + protected static NestedSet<Artifact> getOutputGroup( TransitiveInfoCollection target, String outputGroup) { OutputGroupInfo provider = OutputGroupInfo.get(target); return provider == null - ? NestedSetBuilder.<Artifact>emptySet(Order.STABLE_ORDER) + ? NestedSetBuilder.emptySet(Order.STABLE_ORDER) : provider.getOutputGroup(outputGroup); } - protected NestedSet<Artifact.DerivedArtifact> getExtraActionArtifacts(ConfiguredTarget target) { + protected static NestedSet<Artifact.DerivedArtifact> getExtraActionArtifacts( + ConfiguredTarget target) { return target.getProvider(ExtraActionArtifactsProvider.class).getExtraActionArtifacts(); } @@ -1867,15 +1853,15 @@ return getConfiguredTarget(label).getProvider(FilesToRunProvider.class).getExecutable(); } - protected Artifact getExecutable(TransitiveInfoCollection target) { + protected static Artifact getExecutable(TransitiveInfoCollection target) { return target.getProvider(FilesToRunProvider.class).getExecutable(); } - protected NestedSet<Artifact> getFilesToRun(TransitiveInfoCollection target) { + protected static NestedSet<Artifact> getFilesToRun(TransitiveInfoCollection target) { return target.getProvider(FilesToRunProvider.class).getFilesToRun(); } - protected NestedSet<Artifact> getFilesToRun(Label label) throws Exception { + protected NestedSet<Artifact> getFilesToRun(Label label) { return getConfiguredTarget(label, targetConfig) .getProvider(FilesToRunProvider.class).getFilesToRun(); } @@ -1888,7 +1874,7 @@ return getConfiguredTarget(label).getProvider(FilesToRunProvider.class).getRunfilesSupport(); } - protected RunfilesSupport getRunfilesSupport(TransitiveInfoCollection target) { + protected static RunfilesSupport getRunfilesSupport(TransitiveInfoCollection target) { return target.getProvider(FilesToRunProvider.class).getRunfilesSupport(); } @@ -1984,7 +1970,7 @@ boolean doAnalysis, EventBus eventBus) throws Exception { return update( - targets, ImmutableList.<String>of(), keepGoing, loadingPhaseThreads, doAnalysis, eventBus); + targets, ImmutableList.of(), keepGoing, loadingPhaseThreads, doAnalysis, eventBus); } protected AnalysisResult update( @@ -2058,51 +2044,53 @@ return result; } - protected String getErrorMsgNoGoodFiles(String attrName, String ruleType, String ruleName, - String depRuleName) { + protected static String getErrorMsgNoGoodFiles( + String attrName, String ruleType, String ruleName, String depRuleName) { return "in " + attrName + " attribute of " + ruleType + " rule " + ruleName + ": '" + depRuleName + "' does not produce any " + ruleType + " " + attrName + " files"; } - protected String getErrorMsgMisplacedFiles(String attrName, String ruleType, String ruleName, - String fileName) { + protected static String getErrorMsgMisplacedFiles( + String attrName, String ruleType, String ruleName, String fileName) { return "in " + attrName + " attribute of " + ruleType + " rule " + ruleName + ": source file '" + fileName + "' is misplaced here"; } - protected String getErrorNonExistingTarget(String attrName, String ruleType, String ruleName, - String targetName) { + protected static String getErrorNonExistingTarget( + String attrName, String ruleType, String ruleName, String targetName) { return "in " + attrName + " attribute of " + ruleType + " rule " + ruleName + ": target '" + targetName + "' does not exist"; } - protected String getErrorNonExistingRule(String attrName, String ruleType, String ruleName, - String targetName) { + protected static String getErrorNonExistingRule( + String attrName, String ruleType, String ruleName, String targetName) { return "in " + attrName + " attribute of " + ruleType + " rule " + ruleName + ": rule '" + targetName + "' does not exist"; } - protected String getErrorMsgMisplacedRules(String attrName, String ruleType, String ruleName, - String depRuleType, String depRuleName) { + protected static String getErrorMsgMisplacedRules( + String attrName, String ruleType, String ruleName, String depRuleType, String depRuleName) { return "in " + attrName + " attribute of " + ruleType + " rule " + ruleName + ": " + depRuleType + " rule '" + depRuleName + "' is misplaced here"; } - protected String getErrorMsgNonEmptyList(String attrName, String ruleType, String ruleName) { + protected static String getErrorMsgNonEmptyList( + String attrName, String ruleType, String ruleName) { return "in " + attrName + " attribute of " + ruleType + " rule " + ruleName + ": attribute " + "must be non empty"; } - protected String getErrorMsgMandatoryMissing(String attrName, String ruleType) { + protected static String getErrorMsgMandatoryMissing(String attrName, String ruleType) { return "missing value for mandatory attribute '" + attrName + "' in '" + ruleType + "' rule"; } - protected String getErrorMsgWrongAttributeValue(String value, String... expected) { + protected static String getErrorMsgWrongAttributeValue(String value, String... expected) { return String.format("has to be one of %s instead of '%s'", StringUtil.joinEnglishList(ImmutableSet.copyOf(expected), "or", "'"), value); } - protected String getErrorMsgMandatoryProviderMissing(String offendingRule, String providerName) { + protected static String getErrorMsgMandatoryProviderMissing( + String offendingRule, String providerName) { return String.format("'%s' does not have mandatory providers: '%s'", offendingRule, providerName); } @@ -2122,7 +2110,7 @@ String packageName, String... lines) throws Exception { eventCollector.clear(); reporter.removeHandler(failFastHandler); - scratch.file("" + packageName + "/BUILD", lines); + scratch.file(packageName + "/BUILD", lines); return getPackageManager() .getPackage(reporter, PackageIdentifier.createInMainRepo(packageName)); } @@ -2193,7 +2181,7 @@ } @Override - public ImmutableMap<String, Object> getStarlarkDefinedBuiltins() throws InterruptedException { + public ImmutableMap<String, Object> getStarlarkDefinedBuiltins() { throw new UnsupportedOperationException(); } @@ -2427,7 +2415,7 @@ /** Creates instances of {@link ActionExecutionContext} consistent with test case. */ public class ActionExecutionContextBuilder { private MetadataProvider actionInputFileCache = null; - private TreeMap<String, String> clientEnv = new TreeMap<>(); + private final TreeMap<String, String> clientEnv = new TreeMap<>(); private ArtifactExpander artifactExpander = null; private Executor executor = new DummyExecutor(fileSystem, getExecRoot());
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/util/CompileOnlyTestCase.java b/src/test/java/com/google/devtools/build/lib/analysis/util/CompileOnlyTestCase.java index a3c196d..84f760c 100644 --- a/src/test/java/com/google/devtools/build/lib/analysis/util/CompileOnlyTestCase.java +++ b/src/test/java/com/google/devtools/build/lib/analysis/util/CompileOnlyTestCase.java
@@ -22,7 +22,7 @@ */ public abstract class CompileOnlyTestCase extends BuildViewTestCase { - protected Artifact getArtifactByExecPathSuffix(ConfiguredTarget target, String path) { + protected static Artifact getArtifactByExecPathSuffix(ConfiguredTarget target, String path) { for (Artifact artifact : getOutputGroup(target, OutputGroupInfo.FILES_TO_COMPILE).toList()) { if (artifact.getExecPathString().endsWith(path)) { return artifact;
diff --git a/src/test/java/com/google/devtools/build/lib/rules/android/ResourceTestBase.java b/src/test/java/com/google/devtools/build/lib/rules/android/ResourceTestBase.java index 2fe0e5d..d81d1fe 100644 --- a/src/test/java/com/google/devtools/build/lib/rules/android/ResourceTestBase.java +++ b/src/test/java/com/google/devtools/build/lib/rules/android/ResourceTestBase.java
@@ -210,10 +210,6 @@ return getArtifact(RESOURCE_ROOT, pathString); } - Artifact getOutput(String pathString) { - return getArtifact("outputs", pathString); - } - private Artifact getArtifact(String subdir, String pathString) { Path path = fileSystem.getPath("/" + subdir + "/" + pathString); return new Artifact.SourceArtifact( @@ -244,7 +240,6 @@ .setLabel(dummyTarget.getLabel()) .setConfiguration(targetConfig) .build(), - /*isSystemEnv=*/ false, targetConfig.extendedSanityChecks(), targetConfig.allowAnalysisFailures(), eventHandler, @@ -262,7 +257,7 @@ /** * Assets that the action used to generate the given outputs has the expected inputs and outputs. */ - void assertActionArtifacts( + static void assertActionArtifacts( RuleContext ruleContext, ImmutableList<Artifact> inputs, ImmutableList<Artifact> outputs) { // Actions must have at least one output assertThat(outputs).isNotEmpty();
diff --git a/src/test/java/com/google/devtools/build/lib/rules/cpp/StarlarkCcCommonTest.java b/src/test/java/com/google/devtools/build/lib/rules/cpp/StarlarkCcCommonTest.java index 173b3ea..194998b 100644 --- a/src/test/java/com/google/devtools/build/lib/rules/cpp/StarlarkCcCommonTest.java +++ b/src/test/java/com/google/devtools/build/lib/rules/cpp/StarlarkCcCommonTest.java
@@ -1479,10 +1479,7 @@ assertThat(userLinkFlags.getImmutableList()) .containsExactly("-la", "-lc2", "-DEP2_LINKOPT", "-lc1", "-lc2", "-DEP1_LINKOPT"); Depset additionalInputs = info.getValue("additional_inputs", Depset.class); - assertThat( - additionalInputs.toList(Artifact.class).stream() - .map(x -> x.getFilename()) - .collect(ImmutableList.toImmutableList())) + assertThat(additionalInputs.toList(Artifact.class).stream().map(Artifact::getFilename)) .containsExactly("b.lds", "d.lds"); Collection<LibraryToLink> librariesToLink = info.getValue("libraries_to_link", Depset.class).toList(LibraryToLink.class); @@ -4661,11 +4658,11 @@ (CcToolchainConfigInfo) target.get(CcToolchainConfigInfo.PROVIDER.getKey()); ImmutableSet<String> featureNames = ccToolchainConfigInfo.getFeatures().stream() - .map(feature -> feature.getName()) + .map(Feature::getName) .collect(ImmutableSet.toImmutableSet()); ImmutableSet<String> actionConfigNames = ccToolchainConfigInfo.getActionConfigs().stream() - .map(actionConfig -> actionConfig.getActionName()) + .map(ActionConfig::getActionName) .collect(ImmutableSet.toImmutableSet()); assertThat(featureNames).containsExactly("no_legacy_features", "custom_feature"); assertThat(actionConfigNames).containsExactly("custom_action"); @@ -4730,11 +4727,11 @@ (CcToolchainConfigInfo) target.get(CcToolchainConfigInfo.PROVIDER.getKey()); ImmutableList<String> featureNames = ccToolchainConfigInfo.getFeatures().stream() - .map(feature -> feature.getName()) + .map(Feature::getName) .collect(ImmutableList.toImmutableList()); ImmutableSet<String> actionConfigNames = ccToolchainConfigInfo.getActionConfigs().stream() - .map(actionConfig -> actionConfig.getActionName()) + .map(ActionConfig::getActionName) .collect(ImmutableSet.toImmutableSet()); // fdo_optimize should not be re-added to the list of features by legacy behavior assertThat(featureNames).containsNoDuplicates(); @@ -4882,7 +4879,7 @@ assertThat(toolchain.getCcTargetOs()).isEqualTo("os"); assertThat( toolchain.getFeatureList().stream() - .map(feature -> feature.getName()) + .map(CToolchain.Feature::getName) .collect(ImmutableList.toImmutableList())) .containsAtLeast("featureone", "sysroot") .inOrder(); @@ -4925,7 +4922,7 @@ assertThat( toolchain.getActionConfigList().stream() - .map(actionConfig -> actionConfig.getActionName()) + .map(CToolchain.ActionConfig::getActionName) .collect(ImmutableList.toImmutableList())) .containsAtLeast("action_one", "action_two") .inOrder(); @@ -5318,7 +5315,7 @@ ConfiguredTarget target = getConfiguredTarget("//foo:starlark_lib"); assertThat( getFilesToBuild(target).toList().stream() - .map(x -> x.getFilename()) + .map(Artifact::getFilename) .collect(ImmutableList.toImmutableList())) .contains("libstarlark_lib.a"); } @@ -5330,12 +5327,12 @@ ConfiguredTarget target = getConfiguredTarget("//foo:starlark_lib"); assertThat( getFilesToBuild(target).toList().stream() - .map(x -> x.getFilename()) + .map(Artifact::getFilename) .collect(ImmutableList.toImmutableList())) .doesNotContain("libstarlark_lib.a"); } - private List<String> getFilenamesToBuild(ConfiguredTarget target) { + private static ImmutableList<String> getFilenamesToBuild(ConfiguredTarget target) { return getFilesToBuild(target).toList().stream() .map(Artifact::getFilename) .collect(ImmutableList.toImmutableList());
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/BUILD b/src/test/java/com/google/devtools/build/lib/skyframe/BUILD index fef712a..7739ef0 100644 --- a/src/test/java/com/google/devtools/build/lib/skyframe/BUILD +++ b/src/test/java/com/google/devtools/build/lib/skyframe/BUILD
@@ -8,7 +8,7 @@ filegroup( name = "srcs", testonly = 0, - srcs = glob(["**"]) + ["//src/test/java/com/google/devtools/build/lib/skyframe/trimming:srcs"], + srcs = glob(["**"]), visibility = ["//src/test/java/com/google/devtools/build/lib:__pkg__"], )
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/PlatformLookupUtilTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/PlatformLookupUtilTest.java index 1c588ac..085ba2e 100644 --- a/src/test/java/com/google/devtools/build/lib/skyframe/PlatformLookupUtilTest.java +++ b/src/test/java/com/google/devtools/build/lib/skyframe/PlatformLookupUtilTest.java
@@ -158,7 +158,7 @@ } } - EvaluationResult<GetPlatformInfoValue> getPlatformInfo(GetPlatformInfoKey key) + private EvaluationResult<GetPlatformInfoValue> getPlatformInfo(GetPlatformInfoKey key) throws InterruptedException { try { // Must re-enable analysis for Skyframe functions that create configured targets. @@ -188,7 +188,7 @@ GetPlatformInfoKey key = (GetPlatformInfoKey) skyKey; try { Map<ConfiguredTargetKey, PlatformInfo> platforms = - PlatformLookupUtil.getPlatformInfo(key.platformKeys(), env, false); + PlatformLookupUtil.getPlatformInfo(key.platformKeys(), env); if (env.valuesMissing()) { return null; } @@ -205,8 +205,8 @@ } } - private static class GetPlatformInfoFunctionException extends SkyFunctionException { - public GetPlatformInfoFunctionException(InvalidPlatformException e) { + private static final class GetPlatformInfoFunctionException extends SkyFunctionException { + GetPlatformInfoFunctionException(InvalidPlatformException e) { super(e, Transience.PERSISTENT); } }
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/ToolchainTypeLookupUtilTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/ToolchainTypeLookupUtilTest.java index f85600c..47999e7 100644 --- a/src/test/java/com/google/devtools/build/lib/skyframe/ToolchainTypeLookupUtilTest.java +++ b/src/test/java/com/google/devtools/build/lib/skyframe/ToolchainTypeLookupUtilTest.java
@@ -182,8 +182,8 @@ } } - EvaluationResult<GetToolchainTypeInfoValue> getToolchainTypeInfo(GetToolchainTypeInfoKey key) - throws InterruptedException { + private EvaluationResult<GetToolchainTypeInfoValue> getToolchainTypeInfo( + GetToolchainTypeInfoKey key) throws InterruptedException { try { // Must re-enable analysis for Skyframe functions that create configured targets. skyframeExecutor.getSkyframeBuildView().enableAnalysis(true); @@ -212,7 +212,7 @@ GetToolchainTypeInfoKey key = (GetToolchainTypeInfoKey) skyKey; try { Map<Label, ToolchainTypeInfo> toolchainTypes = - ToolchainTypeLookupUtil.resolveToolchainTypes(env, key.toolchainTypeKeys(), false); + ToolchainTypeLookupUtil.resolveToolchainTypes(env, key.toolchainTypeKeys()); if (env.valuesMissing()) { return null; } @@ -229,8 +229,8 @@ } } - private static class GetToolchainTypeInfoFunctionException extends SkyFunctionException { - public GetToolchainTypeInfoFunctionException(InvalidToolchainTypeException e) { + private static final class GetToolchainTypeInfoFunctionException extends SkyFunctionException { + GetToolchainTypeInfoFunctionException(InvalidToolchainTypeException e) { super(e, Transience.PERSISTENT); } }
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/trimming/BUILD b/src/test/java/com/google/devtools/build/lib/skyframe/trimming/BUILD deleted file mode 100644 index 9636055..0000000 --- a/src/test/java/com/google/devtools/build/lib/skyframe/trimming/BUILD +++ /dev/null
@@ -1,85 +0,0 @@ -# Tests for the trimming support classes. - -load("@rules_java//java:defs.bzl", "java_library", "java_test") - -package( - default_testonly = 1, -) - -filegroup( - name = "srcs", - testonly = 0, - srcs = glob(["**"]), - visibility = ["//src:__subpackages__"], -) - -java_library( - name = "trimmable_test_fragments", - srcs = ["TrimmableTestConfigurationFragments.java"], - visibility = ["//src/test:__subpackages__"], - deps = [ - "//src/main/java/com/google/devtools/build/lib/actions", - "//src/main/java/com/google/devtools/build/lib/actions:artifacts", - "//src/main/java/com/google/devtools/build/lib/analysis:analysis_cluster", - "//src/main/java/com/google/devtools/build/lib/analysis:config/build_options", - "//src/main/java/com/google/devtools/build/lib/analysis:config/core_options", - "//src/main/java/com/google/devtools/build/lib/analysis:config/fragment", - "//src/main/java/com/google/devtools/build/lib/analysis:config/fragment_options", - "//src/main/java/com/google/devtools/build/lib/analysis:config/fragment_provider", - "//src/main/java/com/google/devtools/build/lib/analysis:config/transitions/patch_transition", - "//src/main/java/com/google/devtools/build/lib/analysis:config/transitions/transition_factory", - "//src/main/java/com/google/devtools/build/lib/analysis:configured_target", - "//src/main/java/com/google/devtools/build/lib/analysis:file_provider", - "//src/main/java/com/google/devtools/build/lib/analysis:platform_configuration", - "//src/main/java/com/google/devtools/build/lib/analysis:platform_options", - "//src/main/java/com/google/devtools/build/lib/analysis:resolved_toolchain_context", - "//src/main/java/com/google/devtools/build/lib/analysis:test/test_configuration", - "//src/main/java/com/google/devtools/build/lib/analysis/platform", - "//src/main/java/com/google/devtools/build/lib/cmdline", - "//src/main/java/com/google/devtools/build/lib/collect/nestedset", - "//src/main/java/com/google/devtools/build/lib/events", - "//src/main/java/com/google/devtools/build/lib/packages", - "//src/main/java/com/google/devtools/build/lib/rules:core_rules", - "//src/main/java/com/google/devtools/build/lib/rules:repository/bind_rule", - "//src/main/java/com/google/devtools/build/lib/rules:repository/workspace_base_rule", - "//src/main/java/com/google/devtools/build/lib/rules:toolchain_type", - "//src/main/java/com/google/devtools/build/lib/util:filetype", - "//src/main/java/com/google/devtools/common/options", - "//src/main/java/net/starlark/java/annot", - "//src/main/java/net/starlark/java/eval", - "//src/main/java/net/starlark/java/syntax", - "//src/test/java/com/google/devtools/build/lib/analysis/util", - "//src/test/java/com/google/devtools/build/lib/testutil", - "//third_party:guava", - "//third_party:jsr305", - ], -) - -java_library( - name = "test_key", - srcs = ["TestKey.java"], - deps = [ - "//src/main/java/com/google/devtools/build/lib/skyframe/trimming:trimmed_configuration_cache", - "//third_party:auto_value", - "//third_party:guava", - ], -) - -java_test( - name = "TrimmedConfigurationCacheTests", - size = "small", - srcs = [ - "TestKeyTest.java", - "TrimmedConfigurationCacheTest.java", - ], - test_class = "com.google.devtools.build.lib.AllTests", - runtime_deps = ["//src/test/java/com/google/devtools/build/lib:test_runner"], - deps = [ - ":test_key", - "//src/main/java/com/google/devtools/build/lib/skyframe/trimming:trimmed_configuration_cache", - "//third_party:guava", - "//third_party:guava-testlib", - "//third_party:junit4", - "//third_party:truth", - ], -)
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/trimming/TestKey.java b/src/test/java/com/google/devtools/build/lib/skyframe/trimming/TestKey.java deleted file mode 100644 index 45316c1..0000000 --- a/src/test/java/com/google/devtools/build/lib/skyframe/trimming/TestKey.java +++ /dev/null
@@ -1,91 +0,0 @@ -// Copyright 2018 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.skyframe.trimming; - -import com.google.auto.value.AutoValue; -import com.google.common.base.Preconditions; -import com.google.common.base.Splitter; -import com.google.common.base.Strings; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Sets; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** A simple key suitable for putting into a TrimmedConfigurationCache for testing it. */ -@AutoValue -abstract class TestKey { - abstract String descriptor(); - - abstract ImmutableMap<String, String> configuration(); - - static TestKey create(String descriptor, ImmutableMap<String, String> configuration) { - return new AutoValue_TestKey(descriptor, configuration); - } - - // Test keys look like <config: value, config: value> descriptor - private static final Pattern TEST_KEY_SHAPE = - Pattern.compile("<(?<config>[^>]*)>(?<descriptor>.+)"); - - static TestKey parse(String input) { - Matcher matcher = TEST_KEY_SHAPE.matcher(input.trim()); - Preconditions.checkArgument(matcher.matches()); - return create( - matcher.group("descriptor").trim(), parseConfiguration(matcher.group("config").trim())); - } - - static ImmutableMap<String, String> parseConfiguration(String input) { - if (Strings.isNullOrEmpty(input)) { - return ImmutableMap.of(); - } - return ImmutableMap.copyOf( - Splitter.on(',') - .trimResults() - .withKeyValueSeparator(Splitter.on(':').trimResults()) - .split(input)); - } - - static ConfigurationComparer.Result compareConfigurations( - ImmutableMap<String, String> left, - ImmutableMap<String, String> right) { - Set<String> sharedKeys = Sets.intersection(left.keySet(), right.keySet()); - for (String key : sharedKeys) { - if (!left.get(key).equals(right.get(key))) { - return ConfigurationComparer.Result.DIFFERENT; - } - } - boolean hasLeftOnlyKeys = !Sets.difference(left.keySet(), right.keySet()).isEmpty(); - boolean hasRightOnlyKeys = !Sets.difference(right.keySet(), left.keySet()).isEmpty(); - if (hasLeftOnlyKeys) { - if (hasRightOnlyKeys) { - return ConfigurationComparer.Result.ALL_SHARED_FRAGMENTS_EQUAL; - } else { - return ConfigurationComparer.Result.SUPERSET; - } - } else { - if (hasRightOnlyKeys) { - return ConfigurationComparer.Result.SUBSET; - } else { - return ConfigurationComparer.Result.EQUAL; - } - } - } - - /** Produces a cache suitable for storing TestKeys. */ - static TrimmedConfigurationCache<TestKey, String, ImmutableMap<String, String>> newCache() { - return new TrimmedConfigurationCache<>( - TestKey::descriptor, TestKey::configuration, TestKey::compareConfigurations); - } -}
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/trimming/TestKeyTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/trimming/TestKeyTest.java deleted file mode 100644 index ede356f..0000000 --- a/src/test/java/com/google/devtools/build/lib/skyframe/trimming/TestKeyTest.java +++ /dev/null
@@ -1,152 +0,0 @@ -// Copyright 2018 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.skyframe.trimming; - -import static com.google.common.truth.Truth.assertThat; - -import com.google.common.collect.ImmutableMap; -import com.google.common.testing.EqualsTester; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests for TestKey's parsing functionality. */ -@RunWith(JUnit4.class) -public final class TestKeyTest { - - @Test - public void parseEmptyConfig() throws Exception { - assertThat(TestKey.parse("<> //foo").configuration()).isEmpty(); - assertThat(TestKey.parse("< > //foo").configuration()).isEmpty(); - assertThat(TestKey.parse(" < > //foo").configuration()).isEmpty(); - } - - @Test - public void parseOneElementConfig() throws Exception { - assertThat(TestKey.parse("<A:1> //foo").configuration()).containsExactly("A", "1"); - assertThat(TestKey.parse("< A : 1 > //foo").configuration()).containsExactly("A", "1"); - assertThat(TestKey.parse(" < A : 1 > //foo").configuration()) - .containsExactly("A", "1"); - } - - @Test - public void parseMultiElementConfig() throws Exception { - assertThat(TestKey.parse("<A:1,B:6,C:90> //foo").configuration()) - .containsExactly("A", "1", "B", "6", "C", "90"); - assertThat(TestKey.parse("< A : 1 , B : 6 , C : 90 > //foo").configuration()) - .containsExactly("A", "1", "B", "6", "C", "90"); - assertThat(TestKey.parse(" < A : 1, B: 6, C :90 > //foo").configuration()) - .containsExactly("A", "1", "B", "6", "C", "90"); - } - - @Test - public void parseConfigWithSpaces() throws Exception { - assertThat(TestKey.parse("<An Item: A Value> //foo").configuration()) - .containsExactly("An Item", "A Value"); - } - - @Test - public void parseDescriptor() throws Exception { - assertThat(TestKey.parse("<>//foo").descriptor()).isEqualTo("//foo"); - assertThat(TestKey.parse("<> //foo ").descriptor()).isEqualTo("//foo"); - assertThat(TestKey.parse(" < A : 1, B: 6, C :90 > //foo ").descriptor()) - .isEqualTo("//foo"); - } - - @Test - public void parseDescriptorWithSpaces() throws Exception { - assertThat(TestKey.parse("<>//foo with space").descriptor()).isEqualTo("//foo with space"); - assertThat(TestKey.parse("<> //foo with space ").descriptor()) - .isEqualTo("//foo with space"); - } - - @Test - public void parseMissingConfiguration() throws Exception { - assertThat(TestKey.parse("<>//foo with space").descriptor()).isEqualTo("//foo with space"); - assertThat(TestKey.parse("<> //foo with space ").descriptor()) - .isEqualTo("//foo with space"); - } - - @Test - public void equality() throws Exception { - new EqualsTester() - .addEqualityGroup( - TestKey.parse("<>//foo"), - TestKey.parse(" < > //foo "), - TestKey.create("//foo", ImmutableMap.of())) - .addEqualityGroup( - TestKey.parse("<A:1>//foo"), - TestKey.parse(" < A : 1 > //foo "), - TestKey.create("//foo", ImmutableMap.of("A", "1"))) - .addEqualityGroup( - TestKey.parse("<>//bar"), - TestKey.parse(" < > //bar "), - TestKey.create("//bar", ImmutableMap.of())) - .addEqualityGroup( - TestKey.parse("<A:1>//bar"), - TestKey.parse(" < A : 1 > //bar "), - TestKey.create("//bar", ImmutableMap.of("A", "1"))) - .testEquals(); - } - - @Test - public void compareConfigurations_EqualCases() throws Exception { - assertThat(TestKey.compareConfigurations(ImmutableMap.of(), ImmutableMap.of())) - .isEqualTo(ConfigurationComparer.Result.EQUAL); - assertThat(TestKey.compareConfigurations(ImmutableMap.of("A", "1"), ImmutableMap.of("A", "1"))) - .isEqualTo(ConfigurationComparer.Result.EQUAL); - } - - @Test - public void compareConfigurations_SubsetCases() throws Exception { - assertThat(TestKey.compareConfigurations(ImmutableMap.of(), ImmutableMap.of("A", "1"))) - .isEqualTo(ConfigurationComparer.Result.SUBSET); - assertThat( - TestKey.compareConfigurations( - ImmutableMap.of("A", "1"), ImmutableMap.of("A", "1", "B", "2"))) - .isEqualTo(ConfigurationComparer.Result.SUBSET); - } - - @Test - public void compareConfigurations_SupersetCases() throws Exception { - assertThat(TestKey.compareConfigurations(ImmutableMap.of("A", "1"), ImmutableMap.of())) - .isEqualTo(ConfigurationComparer.Result.SUPERSET); - assertThat( - TestKey.compareConfigurations( - ImmutableMap.of("A", "1", "B", "2"), ImmutableMap.of("A", "1"))) - .isEqualTo(ConfigurationComparer.Result.SUPERSET); - } - - @Test - public void compareConfigurations_AllSharedFragmentsEqualCases() throws Exception { - assertThat(TestKey.compareConfigurations(ImmutableMap.of("A", "1"), ImmutableMap.of("B", "1"))) - .isEqualTo(ConfigurationComparer.Result.ALL_SHARED_FRAGMENTS_EQUAL); - assertThat( - TestKey.compareConfigurations( - ImmutableMap.of("A", "1", "B", "2"), ImmutableMap.of("A", "1", "C", "3"))) - .isEqualTo(ConfigurationComparer.Result.ALL_SHARED_FRAGMENTS_EQUAL); - } - - @Test - public void compareConfigurations_DifferentCases() throws Exception { - assertThat(TestKey.compareConfigurations(ImmutableMap.of("A", "1"), ImmutableMap.of("A", "2"))) - .isEqualTo(ConfigurationComparer.Result.DIFFERENT); - assertThat( - TestKey.compareConfigurations( - ImmutableMap.of("A", "1", "B", "2", "C", "3"), - ImmutableMap.of("A", "2", "B", "2", "D", "4"))) - .isEqualTo(ConfigurationComparer.Result.DIFFERENT); - } -}
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/trimming/TrimmableTestConfigurationFragments.java b/src/test/java/com/google/devtools/build/lib/skyframe/trimming/TrimmableTestConfigurationFragments.java deleted file mode 100644 index 8218e76..0000000 --- a/src/test/java/com/google/devtools/build/lib/skyframe/trimming/TrimmableTestConfigurationFragments.java +++ /dev/null
@@ -1,652 +0,0 @@ -// Copyright 2018 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.skyframe.trimming; - -import static com.google.devtools.build.lib.packages.Attribute.attr; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.devtools.build.lib.actions.Artifact; -import com.google.devtools.build.lib.actions.MutableActionGraph.ActionConflictException; -import com.google.devtools.build.lib.analysis.BaseRuleClasses; -import com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider; -import com.google.devtools.build.lib.analysis.ConfiguredTarget; -import com.google.devtools.build.lib.analysis.FileProvider; -import com.google.devtools.build.lib.analysis.PlatformConfiguration; -import com.google.devtools.build.lib.analysis.PlatformOptions; -import com.google.devtools.build.lib.analysis.ResolvedToolchainContext; -import com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder; -import com.google.devtools.build.lib.analysis.RuleConfiguredTargetFactory; -import com.google.devtools.build.lib.analysis.RuleContext; -import com.google.devtools.build.lib.analysis.Runfiles; -import com.google.devtools.build.lib.analysis.RunfilesProvider; -import com.google.devtools.build.lib.analysis.actions.FileWriteAction; -import com.google.devtools.build.lib.analysis.config.BuildOptions; -import com.google.devtools.build.lib.analysis.config.BuildOptionsView; -import com.google.devtools.build.lib.analysis.config.CoreOptions; -import com.google.devtools.build.lib.analysis.config.Fragment; -import com.google.devtools.build.lib.analysis.config.FragmentOptions; -import com.google.devtools.build.lib.analysis.config.RequiresOptions; -import com.google.devtools.build.lib.analysis.config.transitions.PatchTransition; -import com.google.devtools.build.lib.analysis.config.transitions.TransitionFactory; -import com.google.devtools.build.lib.analysis.platform.ToolchainInfo; -import com.google.devtools.build.lib.analysis.platform.ToolchainTypeInfo; -import com.google.devtools.build.lib.analysis.test.TestConfiguration; -import com.google.devtools.build.lib.analysis.util.MockRule; -import com.google.devtools.build.lib.cmdline.Label; -import com.google.devtools.build.lib.cmdline.LabelSyntaxException; -import com.google.devtools.build.lib.collect.nestedset.Depset; -import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder; -import com.google.devtools.build.lib.collect.nestedset.Order; -import com.google.devtools.build.lib.events.EventHandler; -import com.google.devtools.build.lib.packages.AttributeMap; -import com.google.devtools.build.lib.packages.BuildType; -import com.google.devtools.build.lib.packages.ImplicitOutputsFunction; -import com.google.devtools.build.lib.packages.NonconfigurableAttributeMapper; -import com.google.devtools.build.lib.packages.Rule; -import com.google.devtools.build.lib.packages.RuleClass.ToolchainResolutionMode; -import com.google.devtools.build.lib.packages.Type; -import com.google.devtools.build.lib.rules.ToolchainType.ToolchainTypeRule; -import com.google.devtools.build.lib.rules.core.CoreRules; -import com.google.devtools.build.lib.rules.repository.BindRule; -import com.google.devtools.build.lib.rules.repository.WorkspaceBaseRule; -import com.google.devtools.build.lib.testutil.Scratch; -import com.google.devtools.build.lib.util.FileTypeSet; -import com.google.devtools.common.options.Option; -import com.google.devtools.common.options.OptionDefinition; -import com.google.devtools.common.options.OptionDocumentationCategory; -import com.google.devtools.common.options.OptionEffectTag; -import com.google.devtools.common.options.OptionsParser; -import java.io.IOException; -import java.util.List; -import javax.annotation.Nullable; -import net.starlark.java.annot.StarlarkBuiltin; -import net.starlark.java.eval.EvalException; -import net.starlark.java.eval.Starlark; -import net.starlark.java.eval.StarlarkValue; - -/** Set of trimmable fragments for testing automatic trimming. */ -public final class TrimmableTestConfigurationFragments { - - private TrimmableTestConfigurationFragments() { - // Utility class, non-instantiable - } - - public static void installStarlarkRules(Scratch scratch, String path) - throws LabelSyntaxException, IOException { - installStarlarkRules( - scratch, path, Label.parseAbsolute("//:undefined_toolchain_type", ImmutableMap.of())); - } - - public static void installStarlarkRules(Scratch scratch, String path, Label toolchainTypeLabel) - throws LabelSyntaxException, IOException { - scratch.file( - path, - "toolchainTypeLabel = " + Starlark.repr(toolchainTypeLabel), - "def _impl(ctx):", - " ctx.actions.write(ctx.outputs.main, '')", - " files = depset(", - " direct = [ctx.outputs.main],", - " transitive = [dep.files for dep in ctx.attr.deps])", - " return [DefaultInfo(files=files)]", - "alpha_starlark = rule(", - " implementation = _impl,", - " attrs = {'deps': attr.label_list(allow_files=True)},", - " fragments = ['alpha'],", - " outputs = {'main': '%{name}.sa'},", - ")", - "bravo_starlark = rule(", - " implementation = _impl,", - " attrs = {'deps': attr.label_list(allow_files=True)},", - " fragments = ['bravo'],", - " outputs = {'main': '%{name}.sb'},", - ")", - "charlie_starlark = rule(", - " implementation = _impl,", - " attrs = {'deps': attr.label_list(allow_files=True)},", - " fragments = ['charlie'],", - " outputs = {'main': '%{name}.sc'},", - ")", - "delta_starlark = rule(", - " implementation = _impl,", - " attrs = {'deps': attr.label_list(allow_files=True)},", - " fragments = ['delta'],", - " outputs = {'main': '%{name}.sd'},", - ")", - "echo_starlark = rule(", - " implementation = _impl,", - " attrs = {'deps': attr.label_list(allow_files=True)},", - " fragments = ['echo'],", - " outputs = {'main': '%{name}.se'},", - ")", - "platformer_starlark = rule(", - " implementation = _impl,", - " attrs = {'deps': attr.label_list(allow_files=True)},", - " outputs = {'main': '%{name}.sp'},", - ")", - "def _uses_toolchains_impl(ctx):", - " ctx.actions.write(ctx.outputs.main, '')", - " transitive_depsets = [dep.files for dep in ctx.attr.deps]", - " toolchain_deps = ctx.toolchains[toolchainTypeLabel].files", - " files = depset(", - " direct = [ctx.outputs.main],", - " transitive = transitive_depsets + [toolchain_deps])", - " return [DefaultInfo(files=files)]", - "uses_toolchains_starlark = rule(", - " implementation = _uses_toolchains_impl,", - " attrs = {'deps': attr.label_list(allow_files=True)},", - " outputs = {'main': '%{name}.su'},", - " toolchains = [str(toolchainTypeLabel)],", - ")", - "def _toolchain_impl(ctx):", - " ctx.actions.write(ctx.outputs.main, '')", - " files = depset(", - " direct = [ctx.outputs.main],", - " transitive = [dep.files for dep in ctx.attr.deps])", - " return [DefaultInfo(files=files), platform_common.ToolchainInfo(files=files)]", - "toolchain_starlark = rule(", - " implementation = _toolchain_impl,", - " attrs = {'deps': attr.label_list(allow_files=True)},", - " outputs = {'main': '%{name}.st'},", - ")", - "def _group_impl(ctx):", - " files = depset(transitive = [dep.files for dep in ctx.attr.deps])", - " return [DefaultInfo(files=files)]", - "group = rule(", - " implementation = _group_impl,", - " attrs = {'deps': attr.label_list(allow_files=True)},", - ")"); - } - - public static void installFragmentsAndNativeRules(ConfiguredRuleClassProvider.Builder builder) { - installFragmentsAndNativeRules(builder, null); - } - - public static void installFragmentsAndNativeRules( - ConfiguredRuleClassProvider.Builder builder, @Nullable Label toolchainTypeLabel) { - // boilerplate: - builder - // must be set, but it doesn't matter here what it's set to - .setToolsRepository("@") - // must be set, but it doesn't matter here what it's set to - .setRunfilesPrefix("runfiles") - // must be set, but it doesn't matter here what it's set to - .setPrerequisiteValidator((contextBuilder, prerequisite, attribute) -> {}) - // must be set, but it doesn't matter here what it's set to - .setPrelude("//:prelude.bzl") - // must be part of BuildOptions for various reasons e.g. dynamic configs - .addConfigurationOptions(CoreOptions.class) - .addConfigurationFragment(TestConfiguration.class) - // needed for the default workspace - .addRuleDefinition(new WorkspaceBaseRule()) - .addRuleDefinition(new BindRule()) - // needed for our native rules - .addRuleDefinition(new BaseRuleClasses.NativeBuildRule()) - // needed to define toolchains - .addRuleDefinition(new ToolchainTypeRule()) - // needs to be set to something - .addUniversalConfigurationFragment(TestConfiguration.class); - - CoreRules.INSTANCE.init(builder); - - MockRule transitionRule = - () -> - MockRule.ancestor(BaseRuleClasses.NativeBuildRule.class) - .factory(DepsCollectingFactory.class) - .define( - "with_configuration", - (ruleBuilder, env) -> - ruleBuilder - .requiresConfigurationFragments( - AConfig.class, - BConfig.class, - CConfig.class, - DConfig.class, - EConfig.class, - PlatformConfiguration.class) - .cfg(new TestFragmentTransitionFactory()) - .add( - attr("deps", BuildType.LABEL_LIST) - .allowedFileTypes(FileTypeSet.ANY_FILE)) - .add( - attr("alpha", Type.STRING) - .value((String) null) - .nonconfigurable("used in transition")) - .add( - attr("bravo", Type.STRING) - .value((String) null) - .nonconfigurable("used in transition")) - .add( - attr("charlie", Type.STRING) - .value((String) null) - .nonconfigurable("used in transition")) - .add( - attr("delta", Type.STRING) - .value((String) null) - .nonconfigurable("used in transition")) - .add( - attr("echo", Type.STRING) - .value((String) null) - .nonconfigurable("used in transition")) - .add( - attr("platforms", BuildType.NODEP_LABEL_LIST) - .value((List<Label>) null) - .nonconfigurable("used in transition")) - .add( - attr("extra_execution_platforms", Type.STRING_LIST) - .value((List<String>) null) - .nonconfigurable("used in transition")) - .add( - attr("extra_toolchains", Type.STRING_LIST) - .value((List<String>) null) - .nonconfigurable("used in transition"))); - - MockRule alphaRule = - () -> - MockRule.ancestor(BaseRuleClasses.NativeBuildRule.class) - .factory(DepsCollectingFactory.class) - .define( - "alpha_native", - (ruleBuilder, env) -> - ruleBuilder - .add( - attr("deps", BuildType.LABEL_LIST) - .allowedFileTypes(FileTypeSet.ANY_FILE)) - .requiresConfigurationFragments(AConfig.class) - .setImplicitOutputsFunction( - ImplicitOutputsFunction.fromTemplates("%{name}.a"))); - - MockRule bravoRule = - () -> - MockRule.ancestor(BaseRuleClasses.NativeBuildRule.class) - .factory(DepsCollectingFactory.class) - .define( - "bravo_native", - (ruleBuilder, env) -> - ruleBuilder - .add( - attr("deps", BuildType.LABEL_LIST) - .allowedFileTypes(FileTypeSet.ANY_FILE)) - .requiresConfigurationFragments(BConfig.class) - .setImplicitOutputsFunction( - ImplicitOutputsFunction.fromTemplates("%{name}.b"))); - - MockRule charlieRule = - () -> - MockRule.ancestor(BaseRuleClasses.NativeBuildRule.class) - .factory(DepsCollectingFactory.class) - .define( - "charlie_native", - (ruleBuilder, env) -> - ruleBuilder - .add( - attr("deps", BuildType.LABEL_LIST) - .allowedFileTypes(FileTypeSet.ANY_FILE)) - .requiresConfigurationFragments(CConfig.class) - .setImplicitOutputsFunction( - ImplicitOutputsFunction.fromTemplates("%{name}.c"))); - - MockRule deltaRule = - () -> - MockRule.ancestor(BaseRuleClasses.NativeBuildRule.class) - .factory(DepsCollectingFactory.class) - .define( - "delta_native", - (ruleBuilder, env) -> - ruleBuilder - .add( - attr("deps", BuildType.LABEL_LIST) - .allowedFileTypes(FileTypeSet.ANY_FILE)) - .requiresConfigurationFragments(DConfig.class) - .setImplicitOutputsFunction( - ImplicitOutputsFunction.fromTemplates("%{name}.d"))); - - MockRule echoRule = - () -> - MockRule.ancestor(BaseRuleClasses.NativeBuildRule.class) - .factory(DepsCollectingFactory.class) - .define( - "echo_native", - (ruleBuilder, env) -> - ruleBuilder - .add( - attr("deps", BuildType.LABEL_LIST) - .allowedFileTypes(FileTypeSet.ANY_FILE)) - .requiresConfigurationFragments(EConfig.class) - .setImplicitOutputsFunction( - ImplicitOutputsFunction.fromTemplates("%{name}.e"))); - - MockRule platformlessRule = - () -> - MockRule.ancestor(BaseRuleClasses.NativeBuildRule.class) - .factory(DepsCollectingFactory.class) - .define( - "platformless_native", - (ruleBuilder, env) -> - ruleBuilder - .add( - attr("deps", BuildType.LABEL_LIST) - .allowedFileTypes(FileTypeSet.ANY_FILE)) - .useToolchainResolution(ToolchainResolutionMode.DISABLED) - .setImplicitOutputsFunction( - ImplicitOutputsFunction.fromTemplates("%{name}.np"))); - - MockRule platformerRule = - () -> - MockRule.ancestor(BaseRuleClasses.NativeBuildRule.class) - .factory(DepsCollectingFactory.class) - .define( - "platformer_native", - (ruleBuilder, env) -> - ruleBuilder - .add( - attr("deps", BuildType.LABEL_LIST) - .allowedFileTypes(FileTypeSet.ANY_FILE)) - .useToolchainResolution(ToolchainResolutionMode.ENABLED) - .setImplicitOutputsFunction( - ImplicitOutputsFunction.fromTemplates("%{name}.p"))); - - builder - .addConfigurationFragment(AConfig.class) - .addConfigurationFragment(BConfig.class) - .addConfigurationFragment(CConfig.class) - .addConfigurationFragment(DConfig.class) - .addConfigurationFragment(EConfig.class) - .addRuleDefinition(transitionRule) - .addRuleDefinition(alphaRule) - .addRuleDefinition(bravoRule) - .addRuleDefinition(charlieRule) - .addRuleDefinition(deltaRule) - .addRuleDefinition(echoRule) - .addRuleDefinition(platformlessRule) - .addRuleDefinition(platformerRule); - - if (toolchainTypeLabel != null) { - MockRule usesToolchainsRule = - () -> - MockRule.ancestor(BaseRuleClasses.NativeBuildRule.class) - .factory(DepsCollectingFactory.class) - .define( - "uses_toolchains_native", - (ruleBuilder, env) -> - ruleBuilder - .add( - attr("deps", BuildType.LABEL_LIST) - .allowedFileTypes(FileTypeSet.ANY_FILE)) - .useToolchainResolution(ToolchainResolutionMode.ENABLED) - .addRequiredToolchains(toolchainTypeLabel) - .setImplicitOutputsFunction( - ImplicitOutputsFunction.fromTemplates("%{name}.u"))); - builder.addRuleDefinition(usesToolchainsRule); - } - } - - /** Set of test options. */ - public static final class AOptions extends FragmentOptions { - @Option( - name = "alpha", - documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, - effectTags = {OptionEffectTag.NO_OP}, - defaultValue = "0") - public String alpha; - } - - /** Test configuration fragment. */ - @StarlarkBuiltin(name = "alpha", doc = "Test config fragment.") - @RequiresOptions(options = {AOptions.class}) - public static final class AConfig extends Fragment implements StarlarkValue { - private final String value; - - public AConfig(BuildOptions buildOptions) { - this.value = buildOptions.get(AOptions.class).alpha; - } - - @Override - public String getOutputDirectoryName() { - return "A" + value; - } - } - - /** Set of test options. */ - public static final class BOptions extends FragmentOptions { - @Option( - name = "bravo", - documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, - effectTags = {OptionEffectTag.NO_OP}, - defaultValue = "0") - public String bravo; - } - - /** Test configuration fragment. */ - @StarlarkBuiltin(name = "bravo", doc = "Test config fragment.") - @RequiresOptions(options = {BOptions.class}) - public static final class BConfig extends Fragment implements StarlarkValue { - private final String value; - - public BConfig(BuildOptions buildOptions) { - this.value = buildOptions.get(BOptions.class).bravo; - } - - @Override - public String getOutputDirectoryName() { - return "B" + value; - } - } - - /** Set of test options. */ - public static final class COptions extends FragmentOptions { - @Option( - name = "charlie", - documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, - effectTags = {OptionEffectTag.NO_OP}, - defaultValue = "0") - public String charlie; - } - - /** Test configuration fragment. */ - @StarlarkBuiltin(name = "charlie", doc = "Test config fragment.") - @RequiresOptions(options = {COptions.class}) - public static final class CConfig extends Fragment implements StarlarkValue { - private final String value; - - public CConfig(BuildOptions buildOptions) { - this.value = buildOptions.get(COptions.class).charlie; - } - - @Override - public String getOutputDirectoryName() { - return "C" + value; - } - } - - /** Set of test options. */ - public static final class DOptions extends FragmentOptions { - @Option( - name = "delta", - documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, - effectTags = {OptionEffectTag.NO_OP}, - defaultValue = "0") - public String delta; - } - - /** Test configuration fragment. */ - @StarlarkBuiltin(name = "delta", doc = "Test config fragment.") - @RequiresOptions(options = {DOptions.class}) - public static final class DConfig extends Fragment implements StarlarkValue { - private final String value; - - public DConfig(BuildOptions buildOptions) { - this.value = buildOptions.get(DOptions.class).delta; - } - - @Override - public String getOutputDirectoryName() { - return "D" + value; - } - } - - /** Set of test options. */ - public static final class EOptions extends FragmentOptions { - public static final OptionDefinition ECHO = - OptionsParser.getOptionDefinitionByName(EOptions.class, "echo"); - - @Option( - name = "echo", - documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, - effectTags = {OptionEffectTag.NO_OP}, - defaultValue = "0") - public String echo; - } - - /** Test configuration fragment. */ - @StarlarkBuiltin(name = "echo", doc = "Test config fragment.") - @RequiresOptions(options = {EOptions.class}) - public static final class EConfig extends Fragment implements StarlarkValue { - private final String value; - - public EConfig(BuildOptions buildOptions) { - this.value = buildOptions.get(EOptions.class).echo; - } - - @Override - public String getOutputDirectoryName() { - return "E" + value; - } - } - - private static final class TestFragmentTransitionFactory implements TransitionFactory<Rule> { - private static final class SetValuesTransition implements PatchTransition { - private final String alpha; - private final String bravo; - private final String charlie; - private final String delta; - private final String echo; - private final List<Label> platforms; - private final List<String> extraExecutionPlatforms; - private final List<String> extraToolchains; - - public SetValuesTransition( - String alpha, - String bravo, - String charlie, - String delta, - String echo, - List<Label> platforms, - List<String> extraExecutionPlatforms, - List<String> extraToolchains) { - this.alpha = alpha; - this.bravo = bravo; - this.charlie = charlie; - this.delta = delta; - this.echo = echo; - this.platforms = platforms; - this.extraExecutionPlatforms = extraExecutionPlatforms; - this.extraToolchains = extraToolchains; - } - - @Override - public ImmutableSet<Class<? extends FragmentOptions>> requiresOptionFragments() { - return ImmutableSet.of( - AOptions.class, - BOptions.class, - COptions.class, - DOptions.class, - EOptions.class, - PlatformOptions.class); - } - - @Override - public BuildOptions patch(BuildOptionsView target, EventHandler eventHandler) { - BuildOptionsView output = target.clone(); - if (alpha != null) { - output.get(AOptions.class).alpha = alpha; - } - if (bravo != null) { - output.get(BOptions.class).bravo = bravo; - } - if (charlie != null) { - output.get(COptions.class).charlie = charlie; - } - if (delta != null) { - output.get(DOptions.class).delta = delta; - } - if (echo != null) { - output.get(EOptions.class).echo = echo; - } - if (platforms != null) { - output.get(PlatformOptions.class).platforms = platforms; - } - if (extraExecutionPlatforms != null) { - output.get(PlatformOptions.class).extraExecutionPlatforms = extraExecutionPlatforms; - } - if (extraToolchains != null) { - output.get(PlatformOptions.class).extraToolchains = extraToolchains; - } - return output.underlying(); - } - } - - @Override - public PatchTransition create(Rule rule) { - AttributeMap attributes = NonconfigurableAttributeMapper.of(rule); - return new SetValuesTransition( - attributes.get("alpha", Type.STRING), - attributes.get("bravo", Type.STRING), - attributes.get("charlie", Type.STRING), - attributes.get("delta", Type.STRING), - attributes.get("echo", Type.STRING), - attributes.get("platforms", BuildType.NODEP_LABEL_LIST), - attributes.get("extra_execution_platforms", Type.STRING_LIST), - attributes.get("extra_toolchains", Type.STRING_LIST)); - } - } - - /** RuleConfiguredTargetFactory which collects dependencies. */ - public static final class DepsCollectingFactory implements RuleConfiguredTargetFactory { - @Override - public ConfiguredTarget create(RuleContext ruleContext) - throws InterruptedException, RuleErrorException, ActionConflictException { - NestedSetBuilder<Artifact> filesToBuild = NestedSetBuilder.stableOrder(); - filesToBuild.addAll(ruleContext.getOutputArtifacts()); - for (FileProvider dep : ruleContext.getPrerequisites("deps", FileProvider.class)) { - filesToBuild.addTransitive(dep.getFilesToBuild()); - } - for (Artifact artifact : ruleContext.getOutputArtifacts()) { - ruleContext.registerAction( - FileWriteAction.createEmptyWithInputs( - ruleContext.getActionOwner(), - NestedSetBuilder.emptySet(Order.STABLE_ORDER), - artifact)); - } - if (ruleContext.getToolchainContext() != null) { - ResolvedToolchainContext toolchainContext = ruleContext.getToolchainContext(); - for (ToolchainTypeInfo toolchainType : toolchainContext.requiredToolchainTypes()) { - ToolchainInfo toolchainInfo = toolchainContext.forToolchainType(toolchainType); - try { - filesToBuild.addTransitive( - ((Depset) toolchainInfo.getValue("files")).getSet(Artifact.class)); - } catch (EvalException | Depset.TypeException ex) { - throw new AssertionError(ex); - } - } - } - return new RuleConfiguredTargetBuilder(ruleContext) - .setFilesToBuild(filesToBuild.build()) - .setRunfilesSupport(null, null) - .add(RunfilesProvider.class, RunfilesProvider.simple(Runfiles.EMPTY)) - .build(); - } - } -}
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/trimming/TrimmedConfigurationCacheTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/trimming/TrimmedConfigurationCacheTest.java deleted file mode 100644 index e3ae994..0000000 --- a/src/test/java/com/google/devtools/build/lib/skyframe/trimming/TrimmedConfigurationCacheTest.java +++ /dev/null
@@ -1,401 +0,0 @@ -// Copyright 2018 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.skyframe.trimming; - -import static com.google.common.truth.Truth.assertThat; -import static com.google.common.truth.Truth8.assertThat; - -import com.google.common.collect.ImmutableMap; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests for the TrimmedConfigurationCache. */ -@RunWith(JUnit4.class) -public final class TrimmedConfigurationCacheTest { - - private TrimmedConfigurationCache<TestKey, String, ImmutableMap<String, String>> cache; - - @Before - public void initializeCache() { - cache = TestKey.newCache(); - } - - @Test - public void get_onFreshCache_returnsEmpty() throws Exception { - assertThat(cache.get(TestKey.parse("<A: 1> //foo"))).isEmpty(); - } - - @Test - public void get_afterAddingSubsetCacheEntry_returnsMatchingValue() throws Exception { - TestKey canonicalKey = TestKey.parse("<A: 1, B: 1> //foo"); - cache.putIfAbsent(canonicalKey, TestKey.parseConfiguration("A: 1")); - - assertThat(cache.get(TestKey.parse("<A: 1, C: 1> //foo"))).hasValue(canonicalKey); - } - - @Test - public void get_afterRemovingMatchingCacheEntry_returnsEmpty() throws Exception { - TestKey canonicalKey = TestKey.parse("<A: 1, B: 1> //foo"); - cache.putIfAbsent(canonicalKey, TestKey.parseConfiguration("A: 1")); - cache.remove(canonicalKey); - - assertThat(cache.get(TestKey.parse("<A: 1, B: 2> //foo"))).isEmpty(); - } - - @Test - public void get_afterRemovingCacheEntryWithDifferentConfig_returnsOriginalKey() throws Exception { - TestKey canonicalKey = TestKey.parse("<A: 1, B: 1> //foo"); - cache.putIfAbsent(canonicalKey, TestKey.parseConfiguration("A: 1")); - TestKey removedOtherKey = TestKey.parse("<A: 1, B: 2> //foo"); - cache.remove(removedOtherKey); - - assertThat(cache.get(canonicalKey)).hasValue(canonicalKey); - } - - @Test - public void get_afterRemovingCacheEntryWithDifferentDescriptor_returnsOriginalKey() - throws Exception { - TestKey canonicalKey = TestKey.parse("<A: 1, B: 1> //foo"); - cache.putIfAbsent(canonicalKey, TestKey.parseConfiguration("A: 1")); - TestKey removedOtherKey = TestKey.parse("<A: 1, B: 1> //bar"); - cache.remove(removedOtherKey); - - assertThat(cache.get(canonicalKey)).hasValue(canonicalKey); - } - - @Test - public void get_afterClearingMatchingCacheEntry_returnsEmpty() throws Exception { - cache.putIfAbsent(TestKey.parse("<A: 1, B: 1> //foo"), TestKey.parseConfiguration("A: 1")); - cache.clear(); - - assertThat(cache.get(TestKey.parse("<A: 1, B: 2> //foo"))).isEmpty(); - } - - @Test - public void get_afterRemovingAndReAddingCacheEntry_returnsNewValue() throws Exception { - TestKey oldKey = TestKey.parse("<A: 1, B: 1> //foo"); - ImmutableMap<String, String> trimmedConfiguration = TestKey.parseConfiguration("A: 1"); - cache.putIfAbsent(oldKey, trimmedConfiguration); - cache.remove(oldKey); - TestKey newKey = TestKey.parse("<A: 1, C: 1> //foo"); - cache.putIfAbsent(newKey, trimmedConfiguration); - - assertThat(cache.get(TestKey.parse("<A: 1, D: 1> //foo"))).hasValue(newKey); - } - - @Test - public void get_afterAddingMatchingConfigurationForDifferentDescriptor_returnsEmpty() - throws Exception { - cache.putIfAbsent(TestKey.parse("<A: 1, B: 1> //bar"), TestKey.parseConfiguration("A: 1")); - - assertThat(cache.get(TestKey.parse("<A: 1, B: 1> //foo"))).isEmpty(); - } - - @Test - public void get_afterAddingNonMatchingConfigurationForSameDescriptor_returnsEmpty() - throws Exception { - cache.putIfAbsent(TestKey.parse("<A: 1, B: 1> //foo"), TestKey.parseConfiguration("A: 1")); - - assertThat(cache.get(TestKey.parse("<A: 2, B: 1> //foo"))).isEmpty(); - } - - @Test - public void get_afterAddingAndInvalidatingMatchingCacheEntry_returnsEmpty() throws Exception { - TestKey canonicalKey = TestKey.parse("<A: 1, B: 1> //foo"); - cache.putIfAbsent(canonicalKey, TestKey.parseConfiguration("A: 1")); - cache.invalidate(canonicalKey); - - assertThat(cache.get(TestKey.parse("<A: 1, C: 1> //foo"))).isEmpty(); - } - - @Test - public void get_afterAddingAndInvalidatingAndReAddingMatchingCacheEntry_returnsOriginalValue() - throws Exception { - TestKey oldKey = TestKey.parse("<A: 1, B: 1> //foo"); - ImmutableMap<String, String> trimmedConfiguration = TestKey.parseConfiguration("A: 1"); - cache.putIfAbsent(oldKey, trimmedConfiguration); - cache.invalidate(oldKey); - TestKey newKey = TestKey.parse("<A: 1, C: 1> //foo"); - cache.putIfAbsent(newKey, trimmedConfiguration); - - assertThat(cache.get(TestKey.parse("<A: 1, D: 1> //foo"))).hasValue(oldKey); - } - - @Test - public void get_afterAddingAndInvalidatingAndRevalidatingMatchingCacheEntry_returnsOriginalValue() - throws Exception { - TestKey oldKey = TestKey.parse("<A: 1, B: 1> //foo"); - ImmutableMap<String, String> trimmedConfiguration = TestKey.parseConfiguration("A: 1"); - cache.putIfAbsent(oldKey, trimmedConfiguration); - cache.invalidate(oldKey); - cache.revalidate(oldKey); - - assertThat(cache.get(TestKey.parse("<A: 1, D: 1> //foo"))).hasValue(oldKey); - } - - @Test - public void get_afterMovingKeyToDifferentTrimming_returnsEmpty() throws Exception { - TestKey oldKey = TestKey.parse("<A: 1, B: 1> //foo"); - cache.putIfAbsent(oldKey, TestKey.parseConfiguration("A: 1")); - cache.invalidate(oldKey); - cache.putIfAbsent(oldKey, TestKey.parseConfiguration("B: 1")); - - assertThat(cache.get(TestKey.parse("<A: 1, B: 2> //foo"))).isEmpty(); - } - - @Test(expected = IllegalArgumentException.class) - public void putIfAbsent_forNonSubsetConfiguration_throwsIllegalArgumentException() - throws Exception { - cache.putIfAbsent(TestKey.parse("<A: 1> //foo"), TestKey.parseConfiguration("A: 2")); - } - - @Test - public void putIfAbsent_onFreshCache_returnsInputKey() throws Exception { - TestKey inputKey = TestKey.parse("<A: 1, B: 1> //foo"); - - assertThat(cache.putIfAbsent(inputKey, TestKey.parseConfiguration("A: 1"))).isEqualTo(inputKey); - } - - @Test - public void putIfAbsent_afterRemoving_returnsNewKey() throws Exception { - TestKey oldKey = TestKey.parse("<A: 1, B: 1> //foo"); - ImmutableMap<String, String> trimmedConfiguration = TestKey.parseConfiguration("A: 1"); - cache.putIfAbsent(oldKey, trimmedConfiguration); - cache.remove(oldKey); - TestKey newKey = TestKey.parse("<A: 1, B: 2> //foo"); - - assertThat(cache.putIfAbsent(newKey, trimmedConfiguration)).isEqualTo(newKey); - } - - @Test - public void putIfAbsent_afterAddingEqualConfigurationForDifferentDescriptor_returnsInputKey() - throws Exception { - TestKey oldKey = TestKey.parse("<A: 1, B: 1> //foo"); - ImmutableMap<String, String> trimmedConfiguration = TestKey.parseConfiguration("A: 1"); - cache.putIfAbsent(oldKey, trimmedConfiguration); - TestKey newKey = TestKey.parse("<A: 1, B: 1> //bar"); - - assertThat(cache.putIfAbsent(newKey, trimmedConfiguration)).isEqualTo(newKey); - } - - @Test - public void putIfAbsent_afterAddingNonEqualConfigurationForSameDescriptor_returnsInputKey() - throws Exception { - cache.putIfAbsent(TestKey.parse("<A: 1, B: 1> //foo"), TestKey.parseConfiguration("A: 1")); - TestKey newKey = TestKey.parse("<A: 2, B: 2> //foo"); - - assertThat(cache.putIfAbsent(newKey, TestKey.parseConfiguration("A: 2"))).isEqualTo(newKey); - } - - @Test - public void putIfAbsent_afterAddingEqualConfigurationForSameDescriptor_returnsOriginalKey() - throws Exception { - TestKey oldKey = TestKey.parse("<A: 1, B: 1> //foo"); - ImmutableMap<String, String> trimmedConfiguration = TestKey.parseConfiguration("A: 1"); - cache.putIfAbsent(oldKey, trimmedConfiguration); - - assertThat(cache.putIfAbsent(TestKey.parse("<A: 1, B: 2> //foo"), trimmedConfiguration)) - .isEqualTo(oldKey); - } - - @Test - public void putIfAbsent_afterInvalidatingEqualEntry_returnsOriginalKey() throws Exception { - TestKey oldKey = TestKey.parse("<A: 1, B: 1> //foo"); - ImmutableMap<String, String> trimmedConfiguration = TestKey.parseConfiguration("A: 1"); - cache.putIfAbsent(oldKey, trimmedConfiguration); - cache.invalidate(oldKey); - - assertThat(cache.putIfAbsent(TestKey.parse("<A: 1, B: 2> //foo"), trimmedConfiguration)) - .isEqualTo(oldKey); - } - - @Test - public void putIfAbsent_forKeyAssociatedWithDifferentTrimming_returnsOldKey() throws Exception { - TestKey oldKey = TestKey.parse("<A: 1, B: 1> //foo"); - cache.putIfAbsent(oldKey, TestKey.parseConfiguration("A: 1")); - cache.invalidate(oldKey); - - assertThat(cache.putIfAbsent(oldKey, TestKey.parseConfiguration("B: 1"))).isEqualTo(oldKey); - } - - @Test - public void putIfAbsent_afterMovingPreviousAssociatedKeyToNewTrimming_returnsNewKey() - throws Exception { - TestKey oldKey = TestKey.parse("<A: 1, B: 1> //foo"); - ImmutableMap<String, String> trimmedA1 = TestKey.parseConfiguration("A: 1"); - ImmutableMap<String, String> trimmedB1 = TestKey.parseConfiguration("B: 1"); - cache.putIfAbsent(oldKey, trimmedA1); - cache.invalidate(oldKey); - cache.putIfAbsent(oldKey, trimmedB1); - cache.invalidate(oldKey); - TestKey newKey = TestKey.parse("<A: 1, B: 2> //foo"); - - // This is testing that oldKey is not still associated with trimmedA1, because now it's - // associated with trimmedB1 instead. - assertThat(cache.putIfAbsent(newKey, trimmedA1)).isEqualTo(newKey); - } - - @Test - public void putIfAbsent_afterInvalidatingAndReAddingEqualEntry_returnsOriginalKey() - throws Exception { - TestKey oldKey = TestKey.parse("<A: 1, B: 1> //foo"); - ImmutableMap<String, String> trimmedConfiguration = TestKey.parseConfiguration("A: 1"); - cache.putIfAbsent(oldKey, trimmedConfiguration); - cache.invalidate(oldKey); - cache.putIfAbsent(TestKey.parse("<A: 1, B: 2> //foo"), trimmedConfiguration); - - assertThat(cache.putIfAbsent(TestKey.parse("<A: 1, B: 3> //foo"), trimmedConfiguration)) - .isEqualTo(oldKey); - } - - @Test - public void putIfAbsent_afterInvalidatingAndRevalidatingEqualEntry_returnsOriginalKey() - throws Exception { - TestKey oldKey = TestKey.parse("<A: 1, B: 1> //foo"); - ImmutableMap<String, String> trimmedConfiguration = TestKey.parseConfiguration("A: 1"); - cache.putIfAbsent(oldKey, trimmedConfiguration); - cache.invalidate(oldKey); - cache.revalidate(oldKey); - - assertThat(cache.putIfAbsent(TestKey.parse("<A: 1, B: 2> //foo"), trimmedConfiguration)) - .isEqualTo(oldKey); - } - - @Test - public void putIfAbsent_afterAddingAndInvalidatingSubsetConfiguration_returnsInputKey() - throws Exception { - TestKey oldKey = TestKey.parse("<A: 1, B: 1> //foo"); - ImmutableMap<String, String> trimmedConfiguration = TestKey.parseConfiguration("A: 1"); - cache.putIfAbsent(oldKey, trimmedConfiguration); - cache.invalidate(oldKey); - TestKey newKey = TestKey.parse("<A: 1, B: 2> //foo"); - - assertThat(cache.putIfAbsent(newKey, TestKey.parseConfiguration("A: 1, B: 2"))) - .isEqualTo(newKey); - } - - @Test - public void putIfAbsent_afterAddingAndInvalidatingSupersetConfiguration_returnsInputKey() - throws Exception { - TestKey oldKey = TestKey.parse("<A: 1, B: 1, C: 1> //foo"); - cache.putIfAbsent(oldKey, TestKey.parseConfiguration("A: 1, B: 1")); - cache.invalidate(oldKey); - TestKey newKey = TestKey.parse("<A: 1, B: 1, C: 2> //foo"); - - assertThat(cache.putIfAbsent(newKey, TestKey.parseConfiguration("A: 1"))).isEqualTo(newKey); - } - - @Test - public void invalidate_onEntryNotInCache_doesNotThrow() throws Exception { - // Expect no exception here. - cache.invalidate(TestKey.parse("<A: 1> //foo")); - } - - @Test - public void invalidate_onAlreadyInvalidatedEntry_doesNotThrow() throws Exception { - TestKey oldKey = TestKey.parse("<A: 1, B: 1> //foo"); - cache.putIfAbsent(oldKey, TestKey.parseConfiguration("A: 1")); - cache.invalidate(oldKey); - - // Expect no exception here. - cache.invalidate(oldKey); - } - - @Test - public void invalidate_onRemovedEntry_doesNotThrow() throws Exception { - TestKey oldKey = TestKey.parse("<A: 1, B: 1> //foo"); - cache.putIfAbsent(oldKey, TestKey.parseConfiguration("A: 1")); - cache.remove(oldKey); - - // Expect no exception here. - cache.invalidate(oldKey); - } - - @Test - public void revalidate_onEntryNotInCache_doesNotThrow() throws Exception { - // Expect no exception here. - cache.revalidate(TestKey.parse("<A: 1> //foo")); - } - - @Test - public void revalidate_onAlreadyInvalidatedAndRevalidatedEntry_doesNotThrow() throws Exception { - TestKey oldKey = TestKey.parse("<A: 1, B: 1> //foo"); - cache.putIfAbsent(oldKey, TestKey.parseConfiguration("A: 1")); - cache.invalidate(oldKey); - cache.revalidate(oldKey); - - // Expect no exception here. - cache.revalidate(oldKey); - } - - @Test - public void revalidate_onRemovedEntry_doesNotThrow() throws Exception { - TestKey oldKey = TestKey.parse("<A: 1, B: 1> //foo"); - cache.putIfAbsent(oldKey, TestKey.parseConfiguration("A: 1")); - cache.remove(oldKey); - - // Expect no exception here. - cache.revalidate(oldKey); - } - - @Test - public void remove_onEntryNotInCache_doesNotThrow() throws Exception { - // Expect no exception here. - cache.remove(TestKey.parse("<A: 1> //foo")); - } - - @Test - public void remove_onAlreadyInvalidatedEntry_doesNotThrow() throws Exception { - TestKey oldKey = TestKey.parse("<A: 1, B: 1> //foo"); - cache.putIfAbsent(oldKey, TestKey.parseConfiguration("A: 1")); - cache.invalidate(oldKey); - - // Expect no exception here. - cache.remove(oldKey); - } - - @Test - public void remove_onEntryWithDifferentConfiguration_doesNotThrow() throws Exception { - cache.putIfAbsent(TestKey.parse("<A: 1, B: 1> //foo"), TestKey.parseConfiguration("A: 1")); - - // Expect no exception here. - cache.remove(TestKey.parse("<A: 1, B: 2> //foo")); - } - - @Test - public void remove_onEntryWithDifferentDescriptor_doesNotThrow() throws Exception { - cache.putIfAbsent(TestKey.parse("<A: 1, B: 1> //foo"), TestKey.parseConfiguration("A: 1")); - - // Expect no exception here. - cache.remove(TestKey.parse("<A: 1, B: 1> //bar")); - } - - @Test - public void remove_onRemovedEntry_doesNotThrow() throws Exception { - TestKey oldKey = TestKey.parse("<A: 1, B: 1> //foo"); - cache.putIfAbsent(oldKey, TestKey.parseConfiguration("A: 1")); - cache.remove(oldKey); - - // Expect no exception here. - cache.remove(oldKey); - } - - @Test - public void clear_onEmptyCache_doesNotThrow() throws Exception { - cache.clear(); - } -}