Search in sources :

Example 16 with BuildConfiguration

use of com.google.devtools.build.lib.analysis.config.BuildConfiguration in project bazel by bazelbuild.

the class AndroidBinary method init.

private static RuleConfiguredTargetBuilder init(RuleContext ruleContext, NestedSetBuilder<Artifact> filesBuilder, ResourceDependencies resourceDeps, JavaCommon javaCommon, AndroidCommon androidCommon, JavaSemantics javaSemantics, AndroidSemantics androidSemantics) throws InterruptedException, RuleErrorException {
    validateRuleContext(ruleContext);
    // TODO(bazel-team): Find a way to simplify this code.
    // treeKeys() means that the resulting map sorts the entries by key, which is necessary to
    // ensure determinism.
    Multimap<String, TransitiveInfoCollection> depsByArchitecture = MultimapBuilder.treeKeys().arrayListValues().build();
    AndroidConfiguration androidConfig = ruleContext.getFragment(AndroidConfiguration.class);
    for (Map.Entry<Optional<String>, ? extends List<? extends TransitiveInfoCollection>> entry : ruleContext.getSplitPrerequisites("deps").entrySet()) {
        String cpu = entry.getKey().or(androidConfig.getCpu());
        depsByArchitecture.putAll(cpu, entry.getValue());
    }
    Map<String, BuildConfiguration> configurationMap = new LinkedHashMap<>();
    Map<String, CcToolchainProvider> toolchainMap = new LinkedHashMap<>();
    for (Map.Entry<Optional<String>, ? extends List<? extends TransitiveInfoCollection>> entry : ruleContext.getSplitPrerequisites(":cc_toolchain_split").entrySet()) {
        String cpu = entry.getKey().or(androidConfig.getCpu());
        TransitiveInfoCollection dep = Iterables.getOnlyElement(entry.getValue());
        CcToolchainProvider toolchain = CppHelper.getToolchain(ruleContext, dep);
        configurationMap.put(cpu, dep.getConfiguration());
        toolchainMap.put(cpu, toolchain);
    }
    NativeLibs nativeLibs = NativeLibs.fromLinkedNativeDeps(ruleContext, androidSemantics.getNativeDepsFileName(), depsByArchitecture, toolchainMap, configurationMap);
    // TODO(bazel-team): Resolve all the different cases of resource handling so this conditional
    // can go away: recompile from android_resources, and recompile from android_binary attributes.
    ApplicationManifest applicationManifest;
    ResourceApk resourceApk;
    ResourceApk incrementalResourceApk;
    ResourceApk instantRunResourceApk;
    ResourceApk splitResourceApk;
    if (LocalResourceContainer.definesAndroidResources(ruleContext.attributes())) {
        // Retrieve and compile the resources defined on the android_binary rule.
        LocalResourceContainer.validateRuleContext(ruleContext);
        ApplicationManifest ruleManifest = androidSemantics.getManifestForRule(ruleContext);
        applicationManifest = ruleManifest.mergeWith(ruleContext, resourceDeps);
        resourceApk = applicationManifest.packWithDataAndResources(ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_RESOURCES_APK), ruleContext, false, /* isLibrary */
        resourceDeps, ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_R_TXT), null, /* Artifact symbolsTxt */
        ResourceConfigurationFilter.fromRuleContext(ruleContext), ruleContext.getTokenizedStringListAttr("nocompress_extensions"), ruleContext.attributes().get("crunch_png", Type.BOOLEAN), ruleContext.getTokenizedStringListAttr("densities"), false, /* incremental */
        ProguardHelper.getProguardConfigArtifact(ruleContext, ""), createMainDexProguardSpec(ruleContext), ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_PROCESSED_MANIFEST), ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_RESOURCES_ZIP), DataBinding.isEnabled(ruleContext) ? DataBinding.getLayoutInfoFile(ruleContext) : null);
        ruleContext.assertNoErrors();
        incrementalResourceApk = applicationManifest.addMobileInstallStubApplication(ruleContext).packWithDataAndResources(ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_INCREMENTAL_RESOURCES_APK), ruleContext, false, /* isLibrary */
        resourceDeps, null, /* Artifact rTxt */
        null, /* Artifact symbolsTxt */
        ResourceConfigurationFilter.fromRuleContext(ruleContext), ruleContext.getTokenizedStringListAttr("nocompress_extensions"), ruleContext.attributes().get("crunch_png", Type.BOOLEAN), ruleContext.getTokenizedStringListAttr("densities"), true, /* incremental */
        ProguardHelper.getProguardConfigArtifact(ruleContext, "incremental"), null, /* mainDexProguardCfg */
        null, /* manifestOut */
        null, /* mergedResourcesOut */
        null);
        ruleContext.assertNoErrors();
        instantRunResourceApk = applicationManifest.addInstantRunStubApplication(ruleContext).packWithDataAndResources(getDxArtifact(ruleContext, "android_instant_run.ap_"), ruleContext, false, /* isLibrary */
        resourceDeps, null, /* Artifact rTxt */
        null, /* Artifact symbolsTxt */
        ResourceConfigurationFilter.fromRuleContext(ruleContext), ruleContext.getTokenizedStringListAttr("nocompress_extensions"), ruleContext.attributes().get("crunch_png", Type.BOOLEAN), ruleContext.getTokenizedStringListAttr("densities"), true, /* incremental */
        ProguardHelper.getProguardConfigArtifact(ruleContext, "instant_run"), null, /* mainDexProguardCfg */
        null, /* manifestOut */
        null, /* mergedResourcesOut */
        null);
        ruleContext.assertNoErrors();
        splitResourceApk = applicationManifest.createSplitManifest(ruleContext, "android_resources", false).packWithDataAndResources(getDxArtifact(ruleContext, "android_resources.ap_"), ruleContext, false, /* isLibrary */
        resourceDeps, null, /* Artifact rTxt */
        null, /* Artifact symbolsTxt */
        ResourceConfigurationFilter.fromRuleContext(ruleContext), ruleContext.getTokenizedStringListAttr("nocompress_extensions"), ruleContext.attributes().get("crunch_png", Type.BOOLEAN), ruleContext.getTokenizedStringListAttr("densities"), true, /* incremental */
        ProguardHelper.getProguardConfigArtifact(ruleContext, "incremental_split"), null, /* mainDexProguardCfg */
        null, /* manifestOut */
        null, /* mergedResourcesOut */
        null);
        ruleContext.assertNoErrors();
    } else {
        if (!ruleContext.attributes().get("crunch_png", Type.BOOLEAN)) {
            ruleContext.throwWithRuleError("Setting crunch_png = 0 is not supported for android_binary" + " rules which depend on android_resources rules.");
        }
        // Retrieve the resources from the resources attribute on the android_binary rule
        // and recompile them if necessary.
        ApplicationManifest resourcesManifest = ApplicationManifest.fromResourcesRule(ruleContext);
        if (resourcesManifest == null) {
            throw new RuleErrorException();
        }
        applicationManifest = resourcesManifest.mergeWith(ruleContext, resourceDeps);
        // Always recompiling resources causes AndroidTest to fail in certain circumstances.
        if (shouldRegenerate(ruleContext, resourceDeps)) {
            resourceApk = applicationManifest.packWithResources(ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_RESOURCES_APK), ruleContext, resourceDeps, true, /* createSource */
            ProguardHelper.getProguardConfigArtifact(ruleContext, ""), createMainDexProguardSpec(ruleContext));
            ruleContext.assertNoErrors();
        } else {
            resourceApk = applicationManifest.useCurrentResources(ruleContext, ProguardHelper.getProguardConfigArtifact(ruleContext, ""), createMainDexProguardSpec(ruleContext));
            ruleContext.assertNoErrors();
        }
        incrementalResourceApk = applicationManifest.addMobileInstallStubApplication(ruleContext).packWithResources(ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_INCREMENTAL_RESOURCES_APK), ruleContext, resourceDeps, false, /* createSource */
        ProguardHelper.getProguardConfigArtifact(ruleContext, "incremental"), null);
        ruleContext.assertNoErrors();
        instantRunResourceApk = applicationManifest.addInstantRunStubApplication(ruleContext).packWithResources(getDxArtifact(ruleContext, "android_instant_run.ap_"), ruleContext, resourceDeps, false, /* createSource */
        ProguardHelper.getProguardConfigArtifact(ruleContext, "instant_run"), null);
        ruleContext.assertNoErrors();
        splitResourceApk = applicationManifest.createSplitManifest(ruleContext, "android_resources", false).packWithResources(getDxArtifact(ruleContext, "android_resources.ap_"), ruleContext, resourceDeps, false, /* createSource */
        ProguardHelper.getProguardConfigArtifact(ruleContext, "incremental_split"), null);
        ruleContext.assertNoErrors();
    }
    boolean shrinkResources = shouldShrinkResources(ruleContext);
    JavaTargetAttributes resourceClasses = androidCommon.init(javaSemantics, androidSemantics, resourceApk, ruleContext.getConfiguration().isCodeCoverageEnabled(), true, /* collectJavaCompilationArgs */
    true);
    ruleContext.assertNoErrors();
    Function<Artifact, Artifact> derivedJarFunction = collectDesugaredJars(ruleContext, androidCommon, androidSemantics, resourceClasses);
    Artifact deployJar = createDeployJar(ruleContext, javaSemantics, androidCommon, resourceClasses, derivedJarFunction);
    Artifact proguardMapping = ruleContext.getPrerequisiteArtifact("proguard_apply_mapping", Mode.TARGET);
    return createAndroidBinary(ruleContext, filesBuilder, deployJar, derivedJarFunction, /* isBinaryJarFiltered */
    false, javaCommon, androidCommon, javaSemantics, androidSemantics, nativeLibs, applicationManifest, resourceApk, incrementalResourceApk, instantRunResourceApk, splitResourceApk, shrinkResources, resourceClasses, ImmutableList.<Artifact>of(), ImmutableList.<Artifact>of(), proguardMapping);
}
Also used : Optional(com.google.common.base.Optional) CcToolchainProvider(com.google.devtools.build.lib.rules.cpp.CcToolchainProvider) JavaTargetAttributes(com.google.devtools.build.lib.rules.java.JavaTargetAttributes) Artifact(com.google.devtools.build.lib.actions.Artifact) LinkedHashMap(java.util.LinkedHashMap) BuildConfiguration(com.google.devtools.build.lib.analysis.config.BuildConfiguration) TransitiveInfoCollection(com.google.devtools.build.lib.analysis.TransitiveInfoCollection) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) LinkedHashMap(java.util.LinkedHashMap)

Example 17 with BuildConfiguration

use of com.google.devtools.build.lib.analysis.config.BuildConfiguration in project bazel by bazelbuild.

the class AnalysisTestUtil method artifactsToStrings.

/**
   * Given a collection of Artifacts, returns a corresponding set of strings of
   * the form "{root} {relpath}", such as "bin x/libx.a".  Such strings make
   * assertions easier to write.
   *
   * <p>The returned set preserves the order of the input.
   */
public static Set<String> artifactsToStrings(BuildConfigurationCollection configurations, Iterable<Artifact> artifacts) {
    Map<String, String> rootMap = new HashMap<>();
    BuildConfiguration targetConfiguration = Iterables.getOnlyElement(configurations.getTargetConfigurations());
    rootMap.put(targetConfiguration.getBinDirectory(RepositoryName.MAIN).getPath().toString(), "bin");
    rootMap.put(targetConfiguration.getGenfilesDirectory(RepositoryName.MAIN).getPath().toString(), "genfiles");
    rootMap.put(targetConfiguration.getMiddlemanDirectory(RepositoryName.MAIN).getPath().toString(), "internal");
    BuildConfiguration hostConfiguration = configurations.getHostConfiguration();
    rootMap.put(hostConfiguration.getBinDirectory(RepositoryName.MAIN).getPath().toString(), "bin(host)");
    rootMap.put(hostConfiguration.getGenfilesDirectory(RepositoryName.MAIN).getPath().toString(), "genfiles(host)");
    rootMap.put(hostConfiguration.getMiddlemanDirectory(RepositoryName.MAIN).getPath().toString(), "internal(host)");
    if (targetConfiguration.useDynamicConfigurations()) {
        // With dynamic configurations, the output paths that bin, genfiles, etc. refer to may
        // or may not include the C++-contributed pieces. e.g. they may be
        // bazel-out/gcc-X-glibc-Y-k8-fastbuild/ or they may be bazel-out/fastbuild/. This code
        // adds support for the non-C++ case, too.
        Map<String, String> prunedRootMap = new HashMap<>();
        for (Map.Entry<String, String> root : rootMap.entrySet()) {
            prunedRootMap.put(OUTPUT_PATH_CPP_PREFIX_PATTERN.matcher(root.getKey()).replaceFirst(""), root.getValue());
        }
        rootMap.putAll(prunedRootMap);
    }
    Set<String> files = new LinkedHashSet<>();
    for (Artifact artifact : artifacts) {
        Root root = artifact.getRoot();
        if (root.isSourceRoot()) {
            files.add("src " + artifact.getRootRelativePath());
        } else {
            String name = rootMap.get(root.getPath().toString());
            if (name == null) {
                name = "/";
            }
            files.add(name + " " + artifact.getRootRelativePath());
        }
    }
    return files;
}
Also used : BuildConfiguration(com.google.devtools.build.lib.analysis.config.BuildConfiguration) LinkedHashSet(java.util.LinkedHashSet) Root(com.google.devtools.build.lib.actions.Root) HashMap(java.util.HashMap) HashMap(java.util.HashMap) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) Artifact(com.google.devtools.build.lib.actions.Artifact)

Example 18 with BuildConfiguration

use of com.google.devtools.build.lib.analysis.config.BuildConfiguration in project bazel by bazelbuild.

the class GenRuleConfiguredTargetTest method testJavaMakeVarExpansion.

/** Ensure that Java make variables get expanded under the *host* configuration. */
@Test
public void testJavaMakeVarExpansion() throws Exception {
    String ruleTemplate = "genrule(name = '%s'," + "  srcs = []," + "  cmd = 'echo $(%s) > $@'," + "  outs = ['%s'])";
    scratch.file("foo/BUILD", String.format(ruleTemplate, "java_rule", "JAVA", "java.txt"), String.format(ruleTemplate, "javabase_rule", "JAVABASE", "javabase.txt"));
    Artifact javaOutput = getFileConfiguredTarget("//foo:java.txt").getArtifact();
    Artifact javabaseOutput = getFileConfiguredTarget("//foo:javabase.txt").getArtifact();
    String expectedPattern = "echo %s > %s";
    BuildConfiguration hostConfig = getHostConfiguration();
    String expectedJava = hostConfig.getFragment(Jvm.class).getJavaExecutable().getPathString();
    String expectedJavabase = hostConfig.getFragment(Jvm.class).getJavaHome().getPathString();
    assertCommandEquals(String.format(expectedPattern, expectedJava, javaOutput.getExecPathString()), ((SpawnAction) getGeneratingAction(javaOutput)).getArguments().get(2));
    assertCommandEquals(String.format(expectedPattern, expectedJavabase, javabaseOutput.getExecPathString()), ((SpawnAction) getGeneratingAction(javabaseOutput)).getArguments().get(2));
}
Also used : BuildConfiguration(com.google.devtools.build.lib.analysis.config.BuildConfiguration) SpawnAction(com.google.devtools.build.lib.analysis.actions.SpawnAction) Artifact(com.google.devtools.build.lib.actions.Artifact) Test(org.junit.Test)

Example 19 with BuildConfiguration

use of com.google.devtools.build.lib.analysis.config.BuildConfiguration in project bazel by bazelbuild.

the class ConfigurationsForTargetsWithDynamicConfigurationsTest method testNonConflictingAttributeAndRuleClassTransitions.

@Test
public void testNonConflictingAttributeAndRuleClassTransitions() throws Exception {
    setRulesAvailableInTests(new TestAspects.BaseRule(), new TestAspects.AttributeTransitionRule(), new TestAspects.RuleClassTransitionRule());
    scratch.file("a/BUILD", "attribute_transition(", "   name='attribute',", "   with_host_cpu_transition = ':rule_class',", ")", "rule_class_transition(name='rule_class')");
    List<ConfiguredTarget> deps = getConfiguredDeps("//a:attribute", "with_host_cpu_transition");
    BuildConfiguration ruleclass = Iterables.getOnlyElement(deps).getConfiguration();
    assertThat(ruleclass.getCpu()).isEqualTo("SET BY PATCH");
    assertThat(ruleclass.getHostCpu()).isEqualTo("SET BY SPLIT");
}
Also used : BuildConfiguration(com.google.devtools.build.lib.analysis.config.BuildConfiguration) ConfiguredTarget(com.google.devtools.build.lib.analysis.ConfiguredTarget) TestAspects(com.google.devtools.build.lib.analysis.util.TestAspects) Test(org.junit.Test)

Example 20 with BuildConfiguration

use of com.google.devtools.build.lib.analysis.config.BuildConfiguration in project bazel by bazelbuild.

the class ConfigurationsForTargetsWithDynamicConfigurationsTest method testEmptySplitDoesNotSuppressRuleClassTransition.

@Test
public void testEmptySplitDoesNotSuppressRuleClassTransition() throws Exception {
    setRulesAvailableInTests(new TestAspects.BaseRule(), new TestAspects.EmptySplitRule(), new TestAspects.RuleClassTransitionRule());
    scratch.file("a/BUILD", "empty_split(", "   name = 'empty',", "   with_empty_transition = ':rule_class',", ")", "rule_class_transition(name='rule_class')");
    List<ConfiguredTarget> deps = getConfiguredDeps("//a:empty", "with_empty_transition");
    BuildConfiguration ruleclass = Iterables.getOnlyElement(deps).getConfiguration();
    assertThat(ruleclass.getCpu()).isEqualTo("SET BY PATCH");
}
Also used : BuildConfiguration(com.google.devtools.build.lib.analysis.config.BuildConfiguration) ConfiguredTarget(com.google.devtools.build.lib.analysis.ConfiguredTarget) TestAspects(com.google.devtools.build.lib.analysis.util.TestAspects) Test(org.junit.Test)

Aggregations

BuildConfiguration (com.google.devtools.build.lib.analysis.config.BuildConfiguration)51 ConfiguredTarget (com.google.devtools.build.lib.analysis.ConfiguredTarget)13 Label (com.google.devtools.build.lib.cmdline.Label)12 Artifact (com.google.devtools.build.lib.actions.Artifact)11 ImmutableList (com.google.common.collect.ImmutableList)8 ImmutableMap (com.google.common.collect.ImmutableMap)8 Test (org.junit.Test)8 Attribute (com.google.devtools.build.lib.packages.Attribute)7 BuildOptions (com.google.devtools.build.lib.analysis.config.BuildOptions)6 InvalidConfigurationException (com.google.devtools.build.lib.analysis.config.InvalidConfigurationException)6 Rule (com.google.devtools.build.lib.packages.Rule)6 Target (com.google.devtools.build.lib.packages.Target)6 PathFragment (com.google.devtools.build.lib.vfs.PathFragment)6 SkyKey (com.google.devtools.build.skyframe.SkyKey)6 ArrayList (java.util.ArrayList)6 Map (java.util.Map)6 Nullable (javax.annotation.Nullable)6 Root (com.google.devtools.build.lib.actions.Root)5 TransitiveInfoCollection (com.google.devtools.build.lib.analysis.TransitiveInfoCollection)5 HashMap (java.util.HashMap)5