diff options
author | jingwen <jingwen@google.com> | 2017-12-18 08:24:12 -0800 |
---|---|---|
committer | Copybara-Service <copybara-piper@google.com> | 2017-12-18 08:25:32 -0800 |
commit | 094caa508fa74081d861e9e8f8eb50934811bf65 (patch) | |
tree | c6911010ba0c7dea50fa13ee718f93719b43eb8a | |
parent | 310fe150811c6abe0c52232eb5cb0e4380a6e084 (diff) |
Automatic formatting cleanup of Android *.java files.
RELNOTES: None.
PiperOrigin-RevId: 179425421
105 files changed, 1814 insertions, 1790 deletions
diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AarGeneratorBuilder.java b/src/main/java/com/google/devtools/build/lib/rules/android/AarGeneratorBuilder.java index eb6169eee6..82657d3c7e 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AarGeneratorBuilder.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AarGeneratorBuilder.java @@ -32,9 +32,7 @@ import com.google.devtools.build.lib.util.OS; import java.util.ArrayList; import java.util.List; -/** - * Builder for creating aar generator action. - */ +/** Builder for creating aar generator action. */ public class AarGeneratorBuilder { private ResourceContainer primary; @@ -152,22 +150,24 @@ public class AarGeneratorBuilder { .build(context)); } - private void addPrimaryResourceContainer(List<Artifact> inputs, List<String> args, - ResourceContainer container) { + private void addPrimaryResourceContainer( + List<Artifact> inputs, List<String> args, ResourceContainer container) { Iterables.addAll(inputs, container.getArtifacts()); inputs.add(container.getManifest()); // no R.txt, because it will be generated from this action. - args.add(String.format("%s:%s:%s", - convertRoots(container, ResourceType.RESOURCES), - convertRoots(container, ResourceType.ASSETS), - container.getManifest().getExecPathString() - )); + args.add( + String.format( + "%s:%s:%s", + convertRoots(container, ResourceType.RESOURCES), + convertRoots(container, ResourceType.ASSETS), + container.getManifest().getExecPathString())); } private static String convertRoots(ResourceContainer container, ResourceType resourceType) { - return Joiner.on("#").join( - Iterators.transform( - container.getRoots(resourceType).iterator(), Functions.toStringFunction())); + return Joiner.on("#") + .join( + Iterators.transform( + container.getRoots(resourceType).iterator(), Functions.toStringFunction())); } } diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AarImport.java b/src/main/java/com/google/devtools/build/lib/rules/android/AarImport.java index 5067f30e75..822bb4fa57 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AarImport.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AarImport.java @@ -44,7 +44,7 @@ import com.google.devtools.build.lib.vfs.PathFragment; /** * An implementation for the aar_import rule. * - * AAR files are zip archives that contain an Android Manifest, JARs, resources, assets, native + * <p>AAR files are zip archives that contain an Android Manifest, JARs, resources, assets, native * libraries, Proguard configuration and lint jars. Currently the aar_import rule supports AARs with * an AndroidManifest.xml, classes.jar, libs/, res/ and jni/. Assets are not yet supported. * @@ -78,18 +78,19 @@ public class AarImport implements RuleConfiguredTargetFactory { // AndroidManifest.xml is required in every AAR. Artifact androidManifestArtifact = createAarArtifact(ruleContext, ANDROID_MANIFEST); - ruleContext.registerAction(createSingleFileExtractorActions( - ruleContext, aar, ANDROID_MANIFEST, androidManifestArtifact)); + ruleContext.registerAction( + createSingleFileExtractorActions( + ruleContext, aar, ANDROID_MANIFEST, androidManifestArtifact)); Artifact resources = createAarTreeArtifact(ruleContext, "resources"); - ruleContext.registerAction( - createAarResourcesExtractorActions(ruleContext, aar, resources)); + ruleContext.registerAction(createAarResourcesExtractorActions(ruleContext, aar, resources)); ApplicationManifest androidManifest = ApplicationManifest.fromExplicitManifest(ruleContext, androidManifestArtifact); - FileProvider resourcesProvider = new FileProvider( - new NestedSetBuilder<Artifact>(Order.NAIVE_LINK_ORDER).add(resources).build()); + FileProvider resourcesProvider = + new FileProvider( + new NestedSetBuilder<Artifact>(Order.NAIVE_LINK_ORDER).add(resources).build()); Artifact resourcesZip = ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_RESOURCES_ZIP); @@ -141,19 +142,21 @@ public class AarImport implements RuleConfiguredTargetFactory { .addCompileTimeJarAsFullJar(mergedJar) .build()); - JavaInfo javaInfo = JavaInfo.Builder.create() - .addProvider(JavaCompilationArgsProvider.class, - JavaCompilationArgsProvider.create( - common.collectJavaCompilationArgs( - /* recursive = */ false, - JavaCommon.isNeverLink(ruleContext), - /* srcLessDepsExport = */ false), - common.collectJavaCompilationArgs( - /* recursive = */ true, - JavaCommon.isNeverLink(ruleContext), - /* srcLessDepsExport = */ false))) - .addProvider(JavaRuleOutputJarsProvider.class, jarProviderBuilder.build()) - .build(); + JavaInfo javaInfo = + JavaInfo.Builder.create() + .addProvider( + JavaCompilationArgsProvider.class, + JavaCompilationArgsProvider.create( + common.collectJavaCompilationArgs( + /* recursive = */ false, + JavaCommon.isNeverLink(ruleContext), + /* srcLessDepsExport = */ false), + common.collectJavaCompilationArgs( + /* recursive = */ true, + JavaCommon.isNeverLink(ruleContext), + /* srcLessDepsExport = */ false))) + .addProvider(JavaRuleOutputJarsProvider.class, jarProviderBuilder.build()) + .build(); return ruleBuilder .setFilesToBuild(filesToBuildBuilder.build()) @@ -173,8 +176,8 @@ public class AarImport implements RuleConfiguredTargetFactory { .build(); } - private static Action[] createSingleFileExtractorActions(RuleContext ruleContext, Artifact aar, - String filename, Artifact outputArtifact) { + private static Action[] createSingleFileExtractorActions( + RuleContext ruleContext, Artifact aar, String filename, Artifact outputArtifact) { return new SpawnAction.Builder() .useDefaultShellEnvironment() .setExecutable(ruleContext.getExecutablePrerequisite(AarImportBaseRule.ZIPPER, Mode.HOST)) @@ -209,8 +212,11 @@ public class AarImport implements RuleConfiguredTargetFactory { .build(ruleContext); } - private static Action[] createAarEmbeddedJarsExtractorActions(RuleContext ruleContext, - Artifact aar, Artifact jarsTreeArtifact, Artifact singleJarParamFile) { + private static Action[] createAarEmbeddedJarsExtractorActions( + RuleContext ruleContext, + Artifact aar, + Artifact jarsTreeArtifact, + Artifact singleJarParamFile) { return new SpawnAction.Builder() .useDefaultShellEnvironment() .setExecutable( @@ -230,8 +236,8 @@ public class AarImport implements RuleConfiguredTargetFactory { .build(ruleContext); } - private static Action[] createAarJarsMergingActions(RuleContext ruleContext, - Artifact jarsTreeArtifact, Artifact mergedJar, Artifact paramFile) { + private static Action[] createAarJarsMergingActions( + RuleContext ruleContext, Artifact jarsTreeArtifact, Artifact mergedJar, Artifact paramFile) { return singleJarSpawnActionBuilder(ruleContext) .setMnemonic("AarJarsMerger") .setProgressMessage("Merging AAR embedded jars") @@ -247,8 +253,8 @@ public class AarImport implements RuleConfiguredTargetFactory { .build(ruleContext); } - private static Action[] createAarNativeLibsFilterActions(RuleContext ruleContext, Artifact aar, - Artifact outputZip) { + private static Action[] createAarNativeLibsFilterActions( + RuleContext ruleContext, Artifact aar, Artifact outputZip) { SpawnAction.Builder actionBuilder = new SpawnAction.Builder() .useDefaultShellEnvironment() diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AarImportBaseRule.java b/src/main/java/com/google/devtools/build/lib/rules/android/AarImportBaseRule.java index 81778db38c..bba8627e8b 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AarImportBaseRule.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AarImportBaseRule.java @@ -48,26 +48,27 @@ public class AarImportBaseRule implements RuleDefinition { Targets to export to rules that depend on this rule. See <a href="${link java_library.exports}">java_library.exports. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ - .add(attr("exports", LABEL_LIST) - .allowedRuleClasses("aar_import", "java_import") - .allowedFileTypes() - .validityPredicate(ANY_EDGE)) - .add(attr(AAR_EMBEDDED_JARS_EXTACTOR, LABEL) - .cfg(HOST) - .exec() - .value(env.getToolsLabel("//tools/android:aar_embedded_jars_extractor"))) - .add(attr(AAR_NATIVE_LIBS_ZIP_CREATOR, LABEL) - .cfg(HOST) - .exec() - .value(env.getToolsLabel("//tools/android:aar_native_libs_zip_creator"))) - .add(attr(AAR_RESOURCES_EXTRACTOR, LABEL) - .cfg(HOST) - .exec() - .value(env.getToolsLabel("//tools/android:aar_resources_extractor"))) - .add(attr(ZIPPER, LABEL) - .cfg(HOST) - .exec() - .value(env.getToolsLabel("//tools/zip:zipper"))) + .add( + attr("exports", LABEL_LIST) + .allowedRuleClasses("aar_import", "java_import") + .allowedFileTypes() + .validityPredicate(ANY_EDGE)) + .add( + attr(AAR_EMBEDDED_JARS_EXTACTOR, LABEL) + .cfg(HOST) + .exec() + .value(env.getToolsLabel("//tools/android:aar_embedded_jars_extractor"))) + .add( + attr(AAR_NATIVE_LIBS_ZIP_CREATOR, LABEL) + .cfg(HOST) + .exec() + .value(env.getToolsLabel("//tools/android:aar_native_libs_zip_creator"))) + .add( + attr(AAR_RESOURCES_EXTRACTOR, LABEL) + .cfg(HOST) + .exec() + .value(env.getToolsLabel("//tools/android:aar_resources_extractor"))) + .add(attr(ZIPPER, LABEL).cfg(HOST).exec().value(env.getToolsLabel("//tools/zip:zipper"))) .advertiseSkylarkProvider(SkylarkProviderIdentifier.forKey(JavaInfo.PROVIDER.getKey())) .build(); } diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidAaptActionHelper.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidAaptActionHelper.java index ee9b3ce6a4..5cfe931eae 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidAaptActionHelper.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidAaptActionHelper.java @@ -34,9 +34,7 @@ import java.util.LinkedHashSet; import java.util.List; import javax.annotation.Nullable; -/** - * Helper class to generate Android aapt actions. - */ +/** Helper class to generate Android aapt actions. */ public final class AndroidAaptActionHelper { private final RuleContext ruleContext; private final Artifact manifest; @@ -46,22 +44,19 @@ public final class AndroidAaptActionHelper { /** * Constructs an instance of AndroidAaptActionHelper. * - * @param ruleContext RuleContext for which the aapt actions - * will be generated. - * @param manifest Artifact representing the AndroidManifest.xml that will be - * used to package resources. + * @param ruleContext RuleContext for which the aapt actions will be generated. + * @param manifest Artifact representing the AndroidManifest.xml that will be used to package + * resources. * @param resourceContainers The transitive closure of the ResourceContainers. */ - public AndroidAaptActionHelper(RuleContext ruleContext, Artifact manifest, - Iterable<ResourceContainer> resourceContainers) { + public AndroidAaptActionHelper( + RuleContext ruleContext, Artifact manifest, Iterable<ResourceContainer> resourceContainers) { this.ruleContext = ruleContext; this.manifest = manifest; this.resourceContainers = resourceContainers; } - /** - * Returns the artifacts needed as inputs to process the resources/assets. - */ + /** Returns the artifacts needed as inputs to process the resources/assets. */ private Iterable<Artifact> getInputs() { if (inputs.isEmpty()) { inputs.add(AndroidSdkProvider.fromRuleContext(ruleContext).getAndroidJar()); @@ -75,22 +70,25 @@ public final class AndroidAaptActionHelper { } /** - * Creates an Action that will invoke aapt to generate symbols java sources from the - * resources and pack them into a srcjar. - * @param javaSourcesJar Artifact to be generated by executing the action - * created by this method. + * Creates an Action that will invoke aapt to generate symbols java sources from the resources and + * pack them into a srcjar. + * + * @param javaSourcesJar Artifact to be generated by executing the action created by this method. * @param rTxt R.txt artifact to be generated by the aapt invocation. * @param javaPackage The package for which resources will be generated - * @param inlineConstants whether or not constants in Java generated sources - * should be inlined by the compiler. + * @param inlineConstants whether or not constants in Java generated sources should be inlined by + * the compiler. */ - public void createGenerateResourceSymbolsAction(Artifact javaSourcesJar, - Artifact rTxt, String javaPackage, boolean inlineConstants) { + public void createGenerateResourceSymbolsAction( + Artifact javaSourcesJar, Artifact rTxt, String javaPackage, boolean inlineConstants) { // java path from the provided package for the resources PathFragment javaPath = PathFragment.create(javaPackage.replace('.', '/')); - PathFragment javaResourcesRoot = javaSourcesJar.getRoot().getExecPath().getRelative( - ruleContext.getUniqueDirectory("_java_resources")); + PathFragment javaResourcesRoot = + javaSourcesJar + .getRoot() + .getExecPath() + .getRelative(ruleContext.getUniqueDirectory("_java_resources")); String javaResources = javaResourcesRoot.getRelative(javaPath).getPathString(); @@ -99,9 +97,18 @@ public final class AndroidAaptActionHelper { args.add(javaResourcesRoot.getPathString()); args.add(javaResources); - args.addAll(createAaptCommand("javasrcs", javaSourcesJar, rTxt, inlineConstants, - "-J", javaResources, "--custom-package", javaPackage, "--rename-manifest-package", - javaPackage)); + args.addAll( + createAaptCommand( + "javasrcs", + javaSourcesJar, + rTxt, + inlineConstants, + "-J", + javaResources, + "--custom-package", + javaPackage, + "--rename-manifest-package", + javaPackage)); final Builder builder = new SpawnAction.Builder() .addInputs(getInputs()) @@ -120,19 +127,27 @@ public final class AndroidAaptActionHelper { } /** - * Creates an Action that will invoke aapt to package the android resources - * into an apk file. + * Creates an Action that will invoke aapt to package the android resources into an apk file. + * * @param apk Packed resources artifact to be generated by the aapt invocation. */ - public void createGenerateApkAction(Artifact apk, String renameManifestPackage, - List<String> aaptOpts, List<String> densities) { + public void createGenerateApkAction( + Artifact apk, String renameManifestPackage, List<String> aaptOpts, List<String> densities) { List<String> args; if (renameManifestPackage == null) { args = createAaptCommand("apk", apk, null, true, "-F", apk.getExecPathString()); } else { - args = createAaptCommand("apk", apk, null, true, "-F", - apk.getExecPathString(), "--rename-manifest-package", renameManifestPackage); + args = + createAaptCommand( + "apk", + apk, + null, + true, + "-F", + apk.getExecPathString(), + "--rename-manifest-package", + renameManifestPackage); } if (!densities.isEmpty()) { @@ -157,19 +172,30 @@ public final class AndroidAaptActionHelper { .build(ruleContext)); } - private List<String> createAaptCommand(String actionKind, Artifact output, - Artifact rTxtOutput, boolean inlineConstants, String... outputArgs) { + private List<String> createAaptCommand( + String actionKind, + Artifact output, + Artifact rTxtOutput, + boolean inlineConstants, + String... outputArgs) { return createAaptCommand( actionKind, output, rTxtOutput, inlineConstants, Arrays.asList(outputArgs)); } - private List<String> createAaptCommand(String actionKind, Artifact output, - Artifact rTxtOutput, boolean inlineConstants, Collection<String> outputArgs) { + private List<String> createAaptCommand( + String actionKind, + Artifact output, + Artifact rTxtOutput, + boolean inlineConstants, + Collection<String> outputArgs) { List<String> args = new ArrayList<>(); args.addAll(getArgs(output, actionKind, ResourceType.RESOURCES)); args.addAll(getArgs(output, actionKind, ResourceType.ASSETS)); args.add( - AndroidSdkProvider.fromRuleContext(ruleContext).getAapt().getExecutable().getExecPathString()); + AndroidSdkProvider.fromRuleContext(ruleContext) + .getAapt() + .getExecutable() + .getExecPathString()); args.add("package"); args.addAll(outputArgs); // Allow overlay in case the same resource appears in more than one target, @@ -223,13 +249,10 @@ public final class AndroidAaptActionHelper { } } - /** - * Returns optional part of the <code>aapt</code> command line: - * optionName output_path. - */ + /** Returns optional part of the <code>aapt</code> command line: optionName output_path. */ @VisibleForTesting - public List<String> getResourcesDirArg(Artifact output, String actionKind, String resourceArg, - ResourceType resourceType) { + public List<String> getResourcesDirArg( + Artifact output, String actionKind, String resourceArg, ResourceType resourceType) { PathFragment outputPath = outputPath(output, actionKind, resourceType); List<String> dirArgs = new ArrayList<>(); Collection<String> paths = new LinkedHashSet<>(); @@ -248,12 +271,13 @@ public final class AndroidAaptActionHelper { return ImmutableList.copyOf(dirArgs); } - /** - * Returns a resourceType specific unique output location for the given action kind. - */ + /** Returns a resourceType specific unique output location for the given action kind. */ private PathFragment outputPath(Artifact output, String actionKind, ResourceType resourceType) { - return output.getRoot().getExecPath().getRelative(ruleContext.getUniqueDirectory( - "_" + resourceType.getAttribute() + "_" + actionKind)); + return output + .getRoot() + .getExecPath() + .getRelative( + ruleContext.getUniqueDirectory("_" + resourceType.getAttribute() + "_" + actionKind)); } public void createGenerateProguardAction( diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidBinary.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidBinary.java index e39683e1f9..c23e947b87 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidBinary.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidBinary.java @@ -76,14 +76,13 @@ import java.util.Map; import java.util.Objects; import javax.annotation.Nullable; -/** - * An implementation for the "android_binary" rule. - */ +/** An implementation for the "android_binary" rule. */ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { private static final String DX_MINIMAL_MAIN_DEX_OPTION = "--minimal-main-dex"; protected abstract JavaSemantics createJavaSemantics(); + protected abstract AndroidSemantics createAndroidSemantics(); protected abstract CppSemantics createCppSemantics(); @@ -120,28 +119,33 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { return builder.build(); } - /** - * Checks expected rule invariants, throws rule errors if anything is set wrong. - */ + /** Checks expected rule invariants, throws rule errors if anything is set wrong. */ private static void validateRuleContext(RuleContext ruleContext) throws RuleErrorException { if (getMultidexMode(ruleContext) != MultidexMode.LEGACY - && ruleContext.attributes().isAttributeValueExplicitlySpecified( - "main_dex_proguard_specs")) { - ruleContext.throwWithAttributeError("main_dex_proguard_specs", "The " - + "'main_dex_proguard_specs' attribute is only allowed if 'multidex' is set to 'legacy'"); + && ruleContext + .attributes() + .isAttributeValueExplicitlySpecified("main_dex_proguard_specs")) { + ruleContext.throwWithAttributeError( + "main_dex_proguard_specs", + "The 'main_dex_proguard_specs' attribute is only allowed if 'multidex' is" + + " set to 'legacy'"); } if (ruleContext.attributes().isAttributeValueExplicitlySpecified("proguard_apply_mapping") - && ruleContext.attributes() + && ruleContext + .attributes() .get(ProguardHelper.PROGUARD_SPECS, BuildType.LABEL_LIST) .isEmpty()) { - ruleContext.throwWithAttributeError("proguard_apply_mapping", + ruleContext.throwWithAttributeError( + "proguard_apply_mapping", "'proguard_apply_mapping' can only be used when 'proguard_specs' is also set"); } if (ruleContext.attributes().isAttributeValueExplicitlySpecified("proguard_apply_dictionary") - && ruleContext.attributes() + && ruleContext + .attributes() .get(ProguardHelper.PROGUARD_SPECS, BuildType.LABEL_LIST) .isEmpty()) { - ruleContext.throwWithAttributeError("proguard_apply_mapping", + ruleContext.throwWithAttributeError( + "proguard_apply_mapping", "'proguard_apply_dictionary' can only be used when 'proguard_specs' is also set"); } if (ruleContext.attributes().isAttributeValueExplicitlySpecified("rex_package_map") @@ -151,10 +155,12 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { "'rex_package_map' can only be used when 'rewrite_dexes_with_rex' is also set"); } if (ruleContext.attributes().isAttributeValueExplicitlySpecified("rex_package_map") - && ruleContext.attributes() - .get(ProguardHelper.PROGUARD_SPECS, BuildType.LABEL_LIST) - .isEmpty()) { - ruleContext.throwWithAttributeError("rex_package_map", + && ruleContext + .attributes() + .get(ProguardHelper.PROGUARD_SPECS, BuildType.LABEL_LIST) + .isEmpty()) { + ruleContext.throwWithAttributeError( + "rex_package_map", "'rex_package_map' can only be used when 'proguard_specs' is also set"); } if (ruleContext.attributes().isAttributeValueExplicitlySpecified("rexopts") @@ -163,9 +169,10 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { "rexopts", "'rexopts' can only be used when 'rewrite_dexes_with_rex' is also set"); } if (ruleContext.attributes().isAttributeValueExplicitlySpecified("resources") - && DataBinding.isEnabled(ruleContext)) { - ruleContext.throwWithRuleError("Data binding doesn't work with the \"resources\" attribute. " - + "Use \"resource_files\" instead."); + && DataBinding.isEnabled(ruleContext)) { + ruleContext.throwWithRuleError( + "Data binding doesn't work with the \"resources\" attribute. " + + "Use \"resource_files\" instead."); } AndroidCommon.validateResourcesAttribute(ruleContext); } @@ -237,8 +244,9 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { } 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."); + 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 @@ -251,22 +259,23 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { // 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)); + 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)); + resourceApk = + applicationManifest.useCurrentResources( + ruleContext, + ProguardHelper.getProguardConfigArtifact(ruleContext, ""), + createMainDexProguardSpec(ruleContext)); ruleContext.assertNoErrors(); } - } // Remove the library resource JARs from the binary's runtime classpath. @@ -278,20 +287,27 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { // both binaries and libraries. NestedSet<Artifact> excludedRuntimeArtifacts = getLibraryResourceJars(ruleContext); - JavaTargetAttributes resourceClasses = androidCommon.init( - javaSemantics, - androidSemantics, - resourceApk, - ruleContext.getConfiguration().isCodeCoverageEnabled(), - true /* collectJavaCompilationArgs */, - true, /* isBinary */ - excludedRuntimeArtifacts); + JavaTargetAttributes resourceClasses = + androidCommon.init( + javaSemantics, + androidSemantics, + resourceApk, + ruleContext.getConfiguration().isCodeCoverageEnabled(), + true /* collectJavaCompilationArgs */, + true, /* isBinary */ + excludedRuntimeArtifacts); ruleContext.assertNoErrors(); Function<Artifact, Artifact> derivedJarFunction = collectDesugaredJars(ruleContext, androidCommon, androidSemantics, resourceClasses); - Artifact deployJar = createDeployJar(ruleContext, javaSemantics, androidCommon, resourceClasses, - AndroidCommon.getAndroidConfig(ruleContext).checkDesugarDeps(), derivedJarFunction); + Artifact deployJar = + createDeployJar( + ruleContext, + javaSemantics, + androidCommon, + resourceClasses, + AndroidCommon.getAndroidConfig(ruleContext).checkDesugarDeps(), + derivedJarFunction); if (isInstrumentation(ruleContext)) { deployJar = getFilteredDeployJar(ruleContext, deployJar); @@ -320,16 +336,14 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { .build(ruleContext); } - Artifact proguardMapping = ruleContext.getPrerequisiteArtifact( - "proguard_apply_mapping", Mode.TARGET); - Artifact proguardDictionary = ruleContext.getPrerequisiteArtifact( - "proguard_apply_dictionary", Mode.TARGET); + Artifact proguardMapping = + ruleContext.getPrerequisiteArtifact("proguard_apply_mapping", Mode.TARGET); + Artifact proguardDictionary = + ruleContext.getPrerequisiteArtifact("proguard_apply_dictionary", Mode.TARGET); MobileInstallResourceApks mobileInstallResourceApks = AndroidBinaryMobileInstall.createMobileInstallResourceApks( - ruleContext, - applicationManifest, - resourceDeps); + ruleContext, applicationManifest, resourceDeps); return createAndroidBinary( ruleContext, @@ -375,8 +389,9 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { @Nullable Artifact oneVersionEnforcementArtifact) throws InterruptedException, RuleErrorException { - ImmutableList<Artifact> proguardSpecs = ProguardHelper.collectTransitiveProguardSpecs( - ruleContext, ImmutableList.of(resourceApk.getResourceProguardConfig())); + ImmutableList<Artifact> proguardSpecs = + ProguardHelper.collectTransitiveProguardSpecs( + ruleContext, ImmutableList.of(resourceApk.getResourceProguardConfig())); boolean assumeMinSdkVersion = ruleContext.getFragment(AndroidConfiguration.class).assumeMinSdkVersion(); @@ -394,7 +409,7 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { boolean rexEnabled = ruleContext.getFragment(AndroidConfiguration.class).useRexToCompressDexFiles() - || (ruleContext.attributes().get("rewrite_dexes_with_rex", Type.BOOLEAN)); + || (ruleContext.attributes().get("rewrite_dexes_with_rex", Type.BOOLEAN)); // TODO(bazel-team): Verify that proguard spec files don't contain -printmapping directions // which this -printmapping command line flag will override. @@ -403,9 +418,11 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { || ProguardHelper.getJavaOptimizationMode(ruleContext).alwaysGenerateOutputMapping() || shrinkResources) { if (rexEnabled) { - proguardOutputMap = ProguardHelper.getProguardTempArtifact(ruleContext, - ProguardHelper.getJavaOptimizationMode(ruleContext).name().toLowerCase(), - "proguard_output_for_rex.map"); + proguardOutputMap = + ProguardHelper.getProguardTempArtifact( + ruleContext, + ProguardHelper.getJavaOptimizationMode(ruleContext).name().toLowerCase(), + "proguard_output_for_rex.map"); } else { proguardOutputMap = ruleContext.getImplicitOutputArtifact(JavaSemantics.JAVA_BINARY_PROGUARD_MAP); @@ -424,12 +441,8 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { proguardOutputMap); if (shrinkResources) { - resourceApk = shrinkResources( - ruleContext, - resourceApk, - proguardSpecs, - proguardOutput, - filesBuilder); + resourceApk = + shrinkResources(ruleContext, resourceApk, proguardSpecs, proguardOutput, filesBuilder); } Artifact jarToDex = proguardOutput.getOutputJar(); @@ -545,8 +558,7 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { additionalMergedManifests, ImmutableList.<Artifact>builder().add(zipAlignedApk).addAll(apksUnderTest).build()); - RuleConfiguredTargetBuilder builder = - new RuleConfiguredTargetBuilder(ruleContext); + RuleConfiguredTargetBuilder builder = new RuleConfiguredTargetBuilder(ruleContext); // If this is an instrumentation APK, create the provider for android_instrumentation_test. if (isInstrumentation(ruleContext)) { @@ -574,9 +586,7 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { /* isResourcesOnly = */ false); if (proguardOutput.getMapping() != null) { - builder.add( - ProguardMappingProvider.class, - ProguardMappingProvider.create(finalProguardMap)); + builder.add(ProguardMappingProvider.class, ProguardMappingProvider.create(finalProguardMap)); } if (oneVersionEnforcementArtifact != null) { @@ -674,7 +684,8 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { ImmutableList<Artifact> proguardSpecs, Artifact proguardMapping, Artifact proguardDictionary, - @Nullable Artifact proguardOutputMap) throws InterruptedException { + @Nullable Artifact proguardOutputMap) + throws InterruptedException { Artifact proguardOutputJar = ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_BINARY_PROGUARD_JAR); @@ -685,33 +696,35 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { // still have a Proguard jar implicit output, as it is impossible to tell what a select will // produce at the time of implicit output determination. As a result, this artifact must // always be created. - return createEmptyProguardAction(ruleContext, javaSemantics, proguardOutputJar, - deployJarArtifact, proguardOutputMap); + return createEmptyProguardAction( + ruleContext, javaSemantics, proguardOutputJar, deployJarArtifact, proguardOutputMap); } AndroidSdkProvider sdk = AndroidSdkProvider.fromRuleContext(ruleContext); - NestedSet<Artifact> libraryJars = NestedSetBuilder.<Artifact>naiveLinkOrder() - .add(sdk.getAndroidJar()) - .addTransitive(common.getTransitiveNeverLinkLibraries()) - .build(); + NestedSet<Artifact> libraryJars = + NestedSetBuilder.<Artifact>naiveLinkOrder() + .add(sdk.getAndroidJar()) + .addTransitive(common.getTransitiveNeverLinkLibraries()) + .build(); Artifact proguardSeeds = ruleContext.getImplicitOutputArtifact(JavaSemantics.JAVA_BINARY_PROGUARD_SEEDS); Artifact proguardUsage = ruleContext.getImplicitOutputArtifact(JavaSemantics.JAVA_BINARY_PROGUARD_USAGE); - ProguardOutput result = ProguardHelper.createOptimizationActions( - ruleContext, - sdk.getProguard(), - deployJarArtifact, - proguardSpecs, - proguardSeeds, - proguardUsage, - proguardMapping, - proguardDictionary, - libraryJars, - proguardOutputJar, - javaSemantics, - getProguardOptimizationPasses(ruleContext), - proguardOutputMap); + ProguardOutput result = + ProguardHelper.createOptimizationActions( + ruleContext, + sdk.getProguard(), + deployJarArtifact, + proguardSpecs, + proguardSeeds, + proguardUsage, + proguardMapping, + proguardDictionary, + libraryJars, + proguardOutputJar, + javaSemantics, + getProguardOptimizationPasses(ruleContext), + proguardOutputMap); return result; } @@ -724,10 +737,13 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { } } - private static ProguardOutput createEmptyProguardAction(RuleContext ruleContext, - JavaSemantics semantics, Artifact proguardOutputJar, Artifact deployJarArtifact, + private static ProguardOutput createEmptyProguardAction( + RuleContext ruleContext, + JavaSemantics semantics, + Artifact proguardOutputJar, + Artifact deployJarArtifact, Artifact proguardOutputMap) - throws InterruptedException { + throws InterruptedException { NestedSetBuilder<Artifact> failures = NestedSetBuilder.<Artifact>stableOrder(); ProguardOutput outputs = ProguardHelper.getProguardOutputs( @@ -743,7 +759,8 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { new FailAction( ruleContext.getActionOwner(), failures.build(), - String.format("Can't run Proguard %s", + String.format( + "Can't run Proguard %s", optMode == JavaOptimizationMode.LEGACY ? "without proguard_specs" : "in optimization mode " + optMode))); @@ -779,7 +796,8 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { ResourceApk resourceApk, ImmutableList<Artifact> proguardSpecs, ProguardOutput proguardOutput, - NestedSetBuilder<Artifact> filesBuilder) throws InterruptedException, RuleErrorException { + NestedSetBuilder<Artifact> filesBuilder) + throws InterruptedException, RuleErrorException { if (LocalResourceContainer.definesAndroidResources(ruleContext.attributes()) && !proguardSpecs.isEmpty()) { @@ -806,9 +824,10 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { .setUncompressedExtensions( ruleContext.getExpander().withDataLocations().tokenized("nocompress_extensions")) .build(); - filesBuilder.add(ruleContext.getImplicitOutputArtifact( - AndroidRuleClasses.ANDROID_RESOURCE_SHRINKER_LOG)); - return new ResourceApk(apk, + filesBuilder.add( + ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_RESOURCE_SHRINKER_LOG)); + return new ResourceApk( + apk, resourceApk.getResourceJavaSrcJar(), resourceApk.getResourceJavaClassJar(), resourceApk.getResourceDependencies(), @@ -846,13 +865,15 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { @Nullable Artifact mainDexProguardSpec, JavaTargetAttributes attributes, Function<Artifact, Artifact> derivedJarFunction, - @Nullable Artifact proguardOutputMap) + @Nullable Artifact proguardOutputMap) throws InterruptedException, RuleErrorException { List<String> dexopts = ruleContext.getExpander().withDataLocations().tokenized("dexopts"); MultidexMode multidexMode = getMultidexMode(ruleContext); if (!supportsMultidexMode(ruleContext, multidexMode)) { - ruleContext.throwWithRuleError("Multidex mode \"" + multidexMode.getAttributeValue() - + "\" not supported by this version of the Android SDK"); + ruleContext.throwWithRuleError( + "Multidex mode \"" + + multidexMode.getAttributeValue() + + "\" not supported by this version of the Android SDK"); } int dexShards = ruleContext.attributes().get("dex_shards", Type.INTEGER); @@ -914,16 +935,19 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { if (multidexMode == MultidexMode.LEGACY) { // For legacy multidex, we need to generate a list for the dexer's --main-dex-list flag. - mainDexList = createMainDexListAction( - ruleContext, androidSemantics, proguardedJar, mainDexProguardSpec, proguardOutputMap); + mainDexList = + createMainDexListAction( + ruleContext, + androidSemantics, + proguardedJar, + mainDexProguardSpec, + proguardOutputMap); } Artifact classesDex = getDxArtifact(ruleContext, "classes.dex.zip"); if (dexShards > 1) { - ImmutableList<Artifact> shards = makeShardArtifacts( - ruleContext, - dexShards, - usesDexArchives ? ".jar.dex.zip" : ".jar"); + ImmutableList<Artifact> shards = + makeShardArtifacts(ruleContext, dexShards, usesDexArchives ? ".jar.dex.zip" : ".jar"); Artifact javaResourceJar = createShuffleJarActions( @@ -1005,12 +1029,17 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { // Because the dexer also places resources into this zip, we also need to create a cleanup // action that removes all non-.dex files before staging for apk building. // Create an artifact for the intermediate zip output that includes non-.dex files. - Artifact classesDexIntermediate = AndroidBinary.getDxArtifact( - ruleContext, "intermediate_classes.dex.zip"); + Artifact classesDexIntermediate = + AndroidBinary.getDxArtifact(ruleContext, "intermediate_classes.dex.zip"); // Have the dexer generate the intermediate file and the "cleaner" action consume this to // generate the final archive with only .dex files. - AndroidCommon.createDexAction(ruleContext, proguardedJar, - classesDexIntermediate, dexopts, /*multidex=*/ true, mainDexList); + AndroidCommon.createDexAction( + ruleContext, + proguardedJar, + classesDexIntermediate, + dexopts, + /*multidex=*/ true, + mainDexList); createCleanDexZipAction(ruleContext, classesDexIntermediate, classesDex); } return new DexingOutput(classesDex, binaryJar, ImmutableList.of(classesDex)); @@ -1095,8 +1124,7 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { mainDexList, dexopts.contains(DX_MINIMAL_MAIN_DEX_OPTION), inclusionFilterJar); - Artifact multidexShards = - createTemplatedMergerActions(ruleContext, shardsToMerge, dexopts); + Artifact multidexShards = createTemplatedMergerActions(ruleContext, shardsToMerge, dexopts); // TODO(b/69431301): avoid this action and give the files to apk build action directly createZipMergeAction(ruleContext, multidexShards, classesDex); } @@ -1124,8 +1152,8 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { if (isBinaryProguarded && override == TriState.YES && config.incrementalDexingShardsAfterProguard() <= 0) { - ruleContext.attributeError("incremental_dexing", - "target cannot be incrementally dexed because it uses Proguard"); + ruleContext.attributeError( + "incremental_dexing", "target cannot be incrementally dexed because it uses Proguard"); return false; } @@ -1151,8 +1179,10 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { Iterables.filter( blacklistedDexopts, Predicates.not(Predicates.in(config.getDexoptsSupportedInIncrementalDexing()))); - ruleContext.attributeWarning("incremental_dexing", - String.format("Using incremental dexing even though dexopts %s indicate this target " + ruleContext.attributeWarning( + "incremental_dexing", + String.format( + "Using incremental dexing even though dexopts %s indicate this target " + "may be unsuitable for incremental dexing for the moment.%s", blacklistedDexopts, Iterables.isEmpty(ignored) ? "" : " Ignored dexopts: " + ignored)); @@ -1188,8 +1218,8 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { new SpawnAction.Builder() .useDefaultShellEnvironment() .setMnemonic("ShardForMultidex") - .setProgressMessage("Assembling dex files for %s", - ruleContext.getLabel().getCanonicalForm()) + .setProgressMessage( + "Assembling dex files for %s", ruleContext.getLabel().getCanonicalForm()) .setExecutable(ruleContext.getExecutablePrerequisite("$dexsharder", Mode.HOST)) .addInputs(dexArchives) .addOutput(outputTree); @@ -1228,9 +1258,7 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { * @return Tree artifact containing zips with final dex files named for inclusion in an APK. */ private static Artifact createTemplatedMergerActions( - RuleContext ruleContext, - Artifact inputTree, - Collection<String> dexopts) { + RuleContext ruleContext, Artifact inputTree, Collection<String> dexopts) { Artifact outputTree = ruleContext.getTreeArtifact( ruleContext.getUniqueDirectory("dexfiles"), ruleContext.getBinOrGenfilesDirectory()); @@ -1257,14 +1285,15 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { private static void createZipMergeAction( RuleContext ruleContext, Artifact inputTree, Artifact outputZip) { - CustomCommandLine args = CustomCommandLine.builder() - .add("--exclude_build_data") - .add("--dont_change_compression") - .add("--sources") - .addExpandedTreeArtifactExecPaths(inputTree) - .addExecPath("--output", outputZip) - .add("--no_duplicates") // safety: expect distinct entry names in all inputs - .build(); + CustomCommandLine args = + CustomCommandLine.builder() + .add("--exclude_build_data") + .add("--dont_change_compression") + .add("--sources") + .addExpandedTreeArtifactExecPaths(inputTree) + .addExecPath("--output", outputZip) + .add("--no_duplicates") // safety: expect distinct entry names in all inputs + .build(); // Must use params file as otherwise expanding the input tree artifact doesn't work Artifact paramFile = ruleContext.getDerivedArtifact( @@ -1520,10 +1549,13 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { // dependencies that incremental dexing would need to be extended to (b/34949364). // Typically the fix for the latter involves propagating DexArchiveAspect along the // attribute defining the new implicit dependency. - ruleContext.throwWithAttributeError("deps", "Dependencies on .jar artifacts are not " - + "allowed in Android binaries, please use a java_import to depend on " - + jar.prettyPrint() + ". If this is an implicit dependency then the rule that " - + "introduces it will need to be fixed to account for it correctly."); + ruleContext.throwWithAttributeError( + "deps", + "Dependencies on .jar artifacts are not " + + "allowed in Android binaries, please use a java_import to depend on " + + jar.prettyPrint() + + ". If this is an implicit dependency then the rule that " + + "introduces it will need to be fixed to account for it correctly."); } dexedClasspath.add(dexArchive != null ? dexArchive : jar); } @@ -1572,9 +1604,9 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { } /** - * Creates an action that generates a list of classes to be passed to the dexer's - * --main-dex-list flag (which specifies the classes that need to be directly in classes.dex). - * Returns the file containing the list. + * Creates an action that generates a list of classes to be passed to the dexer's --main-dex-list + * flag (which specifies the classes that need to be directly in classes.dex). Returns the file + * containing the list. */ static Artifact createMainDexListAction( RuleContext ruleContext, @@ -1630,9 +1662,10 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { // Create the main dex classes list. Artifact mainDexList = AndroidBinary.getDxArtifact(ruleContext, "main_dex_list.txt"); - SpawnAction.Builder builder = new SpawnAction.Builder() - .setMnemonic("MainDexClasses") - .setProgressMessage("Generating main dex classes list"); + SpawnAction.Builder builder = + new SpawnAction.Builder() + .setMnemonic("MainDexClasses") + .setProgressMessage("Generating main dex classes list"); ruleContext.registerAction( builder @@ -1647,7 +1680,9 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { .addExecPath(jar) .addAll( ruleContext - .getExpander().withDataLocations().tokenized("main_dex_list_opts")) + .getExpander() + .withDataLocations() + .tokenized("main_dex_list_opts")) .build()) .build(ruleContext)); return mainDexList; @@ -1661,22 +1696,21 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { * Tests if the resources need to be regenerated. * * <p>The resources should be regenerated (using aapt) if any of the following are true: + * * <ul> - * <li>There is more than one resource container - * <li>There are resource filters. - * <li>There are extensions that should be compressed. + * <li>There is more than one resource container + * <li>There are resource filters. + * <li>There are extensions that should be compressed. * </ul> */ - public static boolean shouldRegenerate(RuleContext ruleContext, - ResourceDependencies resourceDeps) { + public static boolean shouldRegenerate( + RuleContext ruleContext, ResourceDependencies resourceDeps) { return Iterables.size(resourceDeps.getResourceContainers()) > 1 || ResourceFilterFactory.hasFilters(ruleContext) || ruleContext.attributes().isAttributeValueExplicitlySpecified("nocompress_extensions"); } - /** - * Returns the multidex mode to apply to this target. - */ + /** Returns the multidex mode to apply to this target. */ public static MultidexMode getMultidexMode(RuleContext ruleContext) { if (ruleContext.getRule().isAttrDefined("multidex", Type.STRING)) { return Preconditions.checkNotNull( @@ -1717,12 +1751,10 @@ public abstract class AndroidBinary implements RuleConfiguredTargetFactory { return true; } - /** - * Returns an intermediate artifact used to support dex generation. - */ + /** Returns an intermediate artifact used to support dex generation. */ public static Artifact getDxArtifact(RuleContext ruleContext, String baseName) { - return ruleContext.getUniqueDirectoryArtifact("_dx", baseName, - ruleContext.getBinOrGenfilesDirectory()); + return ruleContext.getUniqueDirectoryArtifact( + "_dx", baseName, ruleContext.getBinOrGenfilesDirectory()); } /** Returns true if this android_binary target is an instrumentation binary */ diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidBinaryMobileInstall.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidBinaryMobileInstall.java index 07678c9f6b..cd60236ef2 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidBinaryMobileInstall.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidBinaryMobileInstall.java @@ -42,21 +42,16 @@ import com.google.devtools.build.lib.rules.java.ProguardHelper; import com.google.devtools.build.lib.syntax.Type; import java.util.Map; -/** - * Encapsulates the logic for creating actions for mobile-install. - */ +/** Encapsulates the logic for creating actions for mobile-install. */ public final class AndroidBinaryMobileInstall { - /** - * Data class for the resource apks created for mobile-install. - */ + /** Data class for the resource apks created for mobile-install. */ public static final class MobileInstallResourceApks { final ResourceApk incrementalResourceApk; final ResourceApk splitResourceApk; public MobileInstallResourceApks( - ResourceApk incrementalResourceApk, - ResourceApk splitResourceApk) { + ResourceApk incrementalResourceApk, ResourceApk splitResourceApk) { this.incrementalResourceApk = incrementalResourceApk; this.splitResourceApk = splitResourceApk; } @@ -65,7 +60,8 @@ public final class AndroidBinaryMobileInstall { static MobileInstallResourceApks createMobileInstallResourceApks( RuleContext ruleContext, ApplicationManifest applicationManifest, - ResourceDependencies resourceDeps) throws RuleErrorException, InterruptedException { + ResourceDependencies resourceDeps) + throws RuleErrorException, InterruptedException { ResourceApk incrementalResourceApk; ResourceApk splitResourceApk; @@ -98,26 +94,29 @@ public final class AndroidBinaryMobileInstall { } else { - incrementalResourceApk = applicationManifest - .addMobileInstallStubApplication(ruleContext) - .packWithResources( - ruleContext.getImplicitOutputArtifact( - AndroidRuleClasses.ANDROID_INCREMENTAL_RESOURCES_APK), - ruleContext, - resourceDeps, - false, /* createSource */ - ProguardHelper.getProguardConfigArtifact(ruleContext, "incremental"), - null /* mainDexProguardConfig */); + incrementalResourceApk = + applicationManifest + .addMobileInstallStubApplication(ruleContext) + .packWithResources( + ruleContext.getImplicitOutputArtifact( + AndroidRuleClasses.ANDROID_INCREMENTAL_RESOURCES_APK), + ruleContext, + resourceDeps, + false, /* createSource */ + ProguardHelper.getProguardConfigArtifact(ruleContext, "incremental"), + null /* mainDexProguardConfig */); ruleContext.assertNoErrors(); - splitResourceApk = applicationManifest - .createSplitManifest(ruleContext, "android_resources", false) - .packWithResources(getMobileInstallArtifact(ruleContext, "android_resources.ap_"), - ruleContext, - resourceDeps, - false, /* createSource */ - ProguardHelper.getProguardConfigArtifact(ruleContext, "incremental_split"), - null /* mainDexProguardConfig */); + splitResourceApk = + applicationManifest + .createSplitManifest(ruleContext, "android_resources", false) + .packWithResources( + getMobileInstallArtifact(ruleContext, "android_resources.ap_"), + ruleContext, + resourceDeps, + false, /* createSource */ + ProguardHelper.getProguardConfigArtifact(ruleContext, "incremental_split"), + null /* mainDexProguardConfig */); ruleContext.assertNoErrors(); } @@ -169,8 +168,9 @@ public final class AndroidBinaryMobileInstall { ParamFileInfo.builder(ParameterFileType.UNQUOTED).build()) .build(ruleContext)); - Artifact stubData = ruleContext.getImplicitOutputArtifact( - AndroidRuleClasses.MOBILE_INSTALL_STUB_APPLICATION_DATA); + Artifact stubData = + ruleContext.getImplicitOutputArtifact( + AndroidRuleClasses.MOBILE_INSTALL_STUB_APPLICATION_DATA); Artifact stubDex = getStubDex(ruleContext, javaSemantics, false); ruleContext.assertNoErrors(); @@ -192,8 +192,7 @@ public final class AndroidBinaryMobileInstall { Artifact argsArtifact = ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.MOBILE_INSTALL_ARGS); - ruleContext.registerAction( - new WriteAdbArgsAction(ruleContext.getActionOwner(), argsArtifact)); + ruleContext.registerAction(new WriteAdbArgsAction(ruleContext.getActionOwner(), argsArtifact)); createInstallAction( ruleContext, @@ -235,8 +234,8 @@ public final class AndroidBinaryMobileInstall { for (int i = 0; i < dexingOutput.shardDexZips.size(); i++) { String splitName = "dex" + (i + 1); - Artifact splitApkResources = createSplitApkResources( - ruleContext, applicationManifest, splitName, true); + Artifact splitApkResources = + createSplitApkResources(ruleContext, applicationManifest, splitName, true); Artifact splitApk = getMobileInstallArtifact(ruleContext, splitName + ".apk"); ApkActionsBuilder.create("split dex apk " + (i + 1)) .setClassesDex(dexingOutput.shardDexZips.get(i)) @@ -247,8 +246,8 @@ public final class AndroidBinaryMobileInstall { splitApkSetBuilder.add(splitApk); } - Artifact nativeSplitApkResources = createSplitApkResources( - ruleContext, applicationManifest, "native", false); + Artifact nativeSplitApkResources = + createSplitApkResources(ruleContext, applicationManifest, "native", false); Artifact nativeSplitApk = getMobileInstallArtifact(ruleContext, "native.apk"); ApkActionsBuilder.create("split native apk") .addInputZip(nativeSplitApkResources) @@ -258,8 +257,8 @@ public final class AndroidBinaryMobileInstall { .registerActions(ruleContext); splitApkSetBuilder.add(nativeSplitApk); - Artifact javaSplitApkResources = createSplitApkResources( - ruleContext, applicationManifest, "java_resources", false); + Artifact javaSplitApkResources = + createSplitApkResources(ruleContext, applicationManifest, "java_resources", false); Artifact javaSplitApk = getMobileInstallArtifact(ruleContext, "java_resources.apk"); ApkActionsBuilder.create("split Java resource apk") .addInputZip(javaSplitApkResources) @@ -299,19 +298,20 @@ public final class AndroidBinaryMobileInstall { splitApkSetBuilder.add(splitMainApk); NestedSet<Artifact> allSplitApks = splitApkSetBuilder.build(); - createSplitInstallAction(ruleContext, splitDeployMarker, argsArtifact, splitMainApk, - splitApks, stubData); + createSplitInstallAction( + ruleContext, splitDeployMarker, argsArtifact, splitMainApk, splitApks, stubData); - Artifact incrementalDeployInfo = ruleContext.getImplicitOutputArtifact( - AndroidRuleClasses.DEPLOY_INFO_INCREMENTAL); - AndroidDeployInfoAction.createDeployInfoAction(ruleContext, + Artifact incrementalDeployInfo = + ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.DEPLOY_INFO_INCREMENTAL); + AndroidDeployInfoAction.createDeployInfoAction( + ruleContext, incrementalDeployInfo, resourceApk.getManifest(), additionalMergedManifests, ImmutableList.<Artifact>of()); - Artifact splitDeployInfo = ruleContext.getImplicitOutputArtifact( - AndroidRuleClasses.DEPLOY_INFO_SPLIT); + Artifact splitDeployInfo = + ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.DEPLOY_INFO_SPLIT); AndroidDeployInfoAction.createDeployInfoAction( ruleContext, splitDeployInfo, @@ -319,21 +319,24 @@ public final class AndroidBinaryMobileInstall { additionalMergedManifests, ImmutableList.<Artifact>of()); - NestedSet<Artifact> fullInstallOutputGroup = NestedSetBuilder.<Artifact>stableOrder() - .add(fullDeployMarker) - .add(incrementalDeployInfo) - .build(); - - NestedSet<Artifact> incrementalInstallOutputGroup = NestedSetBuilder.<Artifact>stableOrder() - .add(incrementalDeployMarker) - .add(incrementalDeployInfo) - .build(); - - NestedSet<Artifact> splitInstallOutputGroup = NestedSetBuilder.<Artifact>stableOrder() - .addTransitive(allSplitApks) - .add(splitDeployMarker) - .add(splitDeployInfo) - .build(); + NestedSet<Artifact> fullInstallOutputGroup = + NestedSetBuilder.<Artifact>stableOrder() + .add(fullDeployMarker) + .add(incrementalDeployInfo) + .build(); + + NestedSet<Artifact> incrementalInstallOutputGroup = + NestedSetBuilder.<Artifact>stableOrder() + .add(incrementalDeployMarker) + .add(incrementalDeployInfo) + .build(); + + NestedSet<Artifact> splitInstallOutputGroup = + NestedSetBuilder.<Artifact>stableOrder() + .addTransitive(allSplitApks) + .add(splitDeployMarker) + .add(splitDeployInfo) + .build(); ruleConfiguredTargetBuilder .addOutputGroup("mobile_install_full" + INTERNAL_SUFFIX, fullInstallOutputGroup) @@ -362,9 +365,10 @@ public final class AndroidBinaryMobileInstall { return null; } - JavaTargetAttributes attributes = new JavaTargetAttributes.Builder(javaSemantics) - .addRuntimeClassPathEntries(provider.getJavaCompilationArgs().getRuntimeJars()) - .build(); + JavaTargetAttributes attributes = + new JavaTargetAttributes.Builder(javaSemantics) + .addRuntimeClassPathEntries(provider.getJavaCompilationArgs().getRuntimeJars()) + .build(); Function<Artifact, Artifact> desugaredJars = Functions.identity(); if (AndroidCommon.getAndroidConfig(ruleContext).desugarJava8()) { @@ -373,8 +377,8 @@ public final class AndroidBinaryMobileInstall { .build() .collapseToFunction(); } - Artifact stubDeployJar = getMobileInstallArtifact(ruleContext, - split ? "split_stub_deploy.jar" : "stub_deploy.jar"); + Artifact stubDeployJar = + getMobileInstallArtifact(ruleContext, split ? "split_stub_deploy.jar" : "stub_deploy.jar"); new DeployArchiveBuilder(javaSemantics, ruleContext) .setOutputJar(stubDeployJar) .setAttributes(attributes) @@ -387,12 +391,7 @@ public final class AndroidBinaryMobileInstall { ruleContext, split ? "split_stub_application/classes.dex" : "stub_application/classes.dex"); AndroidCommon.createDexAction( - ruleContext, - stubDeployJar, - stubDex, - ImmutableList.<String>of(), - false, - null); + ruleContext, stubDeployJar, stubDex, ImmutableList.<String>of(), false, null); return stubDex; } @@ -455,8 +454,12 @@ public final class AndroidBinaryMobileInstall { ruleContext.registerAction(builder.build(ruleContext)); } - private static void createSplitInstallAction(RuleContext ruleContext, - Artifact marker, Artifact argsArtifact, Artifact splitMainApk, NestedSet<Artifact> splitApks, + private static void createSplitInstallAction( + RuleContext ruleContext, + Artifact marker, + Artifact argsArtifact, + Artifact splitMainApk, + NestedSet<Artifact> splitApks, Artifact stubDataFile) { FilesToRunProvider adb = AndroidSdkProvider.fromRuleContext(ruleContext).getAdb(); SpawnAction.Builder builder = @@ -490,10 +493,13 @@ public final class AndroidBinaryMobileInstall { ruleContext.registerAction(builder.build(ruleContext)); } - private static Artifact createSplitApkResources(RuleContext ruleContext, - ApplicationManifest mainManifest, String splitName, boolean hasCode) { - Artifact splitManifest = mainManifest.createSplitManifest(ruleContext, splitName, hasCode) - .getManifest(); + private static Artifact createSplitApkResources( + RuleContext ruleContext, + ApplicationManifest mainManifest, + String splitName, + boolean hasCode) { + Artifact splitManifest = + mainManifest.createSplitManifest(ruleContext, splitName, hasCode).getManifest(); Artifact splitResources = getMobileInstallArtifact(ruleContext, "split_" + splitName + ".ap_"); AndroidSdkProvider sdk = AndroidSdkProvider.fromRuleContext(ruleContext); ruleContext.registerAction( @@ -517,11 +523,9 @@ public final class AndroidBinaryMobileInstall { return splitResources; } - /** - * Returns an intermediate artifact used to support mobile-install. - */ + /** Returns an intermediate artifact used to support mobile-install. */ private static Artifact getMobileInstallArtifact(RuleContext ruleContext, String baseName) { - return ruleContext.getUniqueDirectoryArtifact("_mobile_install", baseName, - ruleContext.getBinOrGenfilesDirectory()); + return ruleContext.getUniqueDirectoryArtifact( + "_mobile_install", baseName, ruleContext.getBinOrGenfilesDirectory()); } } diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidCommon.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidCommon.java index ce41580a31..659bf5e985 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidCommon.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidCommon.java @@ -85,8 +85,9 @@ import java.util.List; */ public class AndroidCommon { - public static final InstrumentationSpec ANDROID_COLLECTION_SPEC = JavaCommon.JAVA_COLLECTION_SPEC - .withDependencyAttributes("deps", "data", "exports", "runtime_deps", "binary_under_test"); + public static final InstrumentationSpec ANDROID_COLLECTION_SPEC = + JavaCommon.JAVA_COLLECTION_SPEC.withDependencyAttributes( + "deps", "data", "exports", "runtime_deps", "binary_under_test"); public static final ImmutableSet<String> TRANSITIVE_ATTRIBUTES = ImmutableSet.of("deps", "exports"); @@ -153,9 +154,10 @@ public class AndroidCommon { /** * Creates a new AndroidCommon. + * * @param common the JavaCommon instance - * @param asNeverLink Boolean to indicate if this rule should be treated as a compile time dep - * by consuming rules. + * @param asNeverLink Boolean to indicate if this rule should be treated as a compile time dep by + * consuming rules. * @param exportDeps Boolean to indicate if the dependencies should be treated as "exported" deps. */ public AndroidCommon(JavaCommon common, boolean asNeverLink, boolean exportDeps) { @@ -171,16 +173,16 @@ public class AndroidCommon { * @param ruleContext the context of the rule neverlink deps are to be computed for * @param deps the targets to be treated as dependencies * @param runtimeJars the runtime jars produced by the rule (non-transitive) - * * @return a nested set of the neverlink deps. */ public static NestedSet<Artifact> collectTransitiveNeverlinkLibraries( - RuleContext ruleContext, Iterable<? extends TransitiveInfoCollection> deps, + RuleContext ruleContext, + Iterable<? extends TransitiveInfoCollection> deps, ImmutableList<Artifact> runtimeJars) { NestedSetBuilder<Artifact> builder = NestedSetBuilder.naiveLinkOrder(); - for (AndroidNeverLinkLibrariesProvider provider : AnalysisUtils.getProviders(deps, - AndroidNeverLinkLibrariesProvider.class)) { + for (AndroidNeverLinkLibrariesProvider provider : + AnalysisUtils.getProviders(deps, AndroidNeverLinkLibrariesProvider.class)) { builder.addTransitive(provider.getTransitiveNeverLinkLibraries()); } @@ -201,7 +203,10 @@ public class AndroidCommon { */ public static void createDexAction( RuleContext ruleContext, - Artifact jarToDex, Artifact classesDex, List<String> dexOptions, boolean multidex, + Artifact jarToDex, + Artifact classesDex, + List<String> dexOptions, + boolean multidex, Artifact mainDexList) { CustomCommandLine.Builder commandLine = CustomCommandLine.builder(); commandLine.add("--dex"); @@ -324,8 +329,8 @@ public class AndroidCommon { } /** - * Finds the rightmost occurrence of the needle and returns subfragment of the haystack from - * left to the end of the occurrence inclusive of the needle. + * Finds the rightmost occurrence of the needle and returns subfragment of the haystack from left + * to the end of the occurrence inclusive of the needle. * * <pre> * `Example: @@ -381,8 +386,8 @@ public class AndroidCommon { public static NestedSetBuilder<Artifact> collectTransitiveNativeLibsZips( RuleContext ruleContext) { NestedSetBuilder<Artifact> transitiveAarNativeLibs = NestedSetBuilder.naiveLinkOrder(); - Iterable<NativeLibsZipsProvider> providers = getTransitivePrerequisites( - ruleContext, Mode.TARGET, NativeLibsZipsProvider.class); + Iterable<NativeLibsZipsProvider> providers = + getTransitivePrerequisites(ruleContext, Mode.TARGET, NativeLibsZipsProvider.class); for (NativeLibsZipsProvider nativeLibsZipsProvider : providers) { transitiveAarNativeLibs.addTransitive(nativeLibsZipsProvider.getAarNativeLibs()); } @@ -434,19 +439,21 @@ public class AndroidCommon { } private void compileResourceJar( - JavaSemantics javaSemantics, ResourceApk resourceApk, Artifact resourcesJar, + JavaSemantics javaSemantics, + ResourceApk resourceApk, + Artifact resourcesJar, boolean useRClassGenerator) throws InterruptedException, RuleErrorException { - resourceSourceJar = ruleContext.getImplicitOutputArtifact( - AndroidRuleClasses.ANDROID_RESOURCES_SOURCE_JAR); - resourceClassJar = ruleContext.getImplicitOutputArtifact( - AndroidRuleClasses.ANDROID_RESOURCES_CLASS_JAR); + resourceSourceJar = + ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_RESOURCES_SOURCE_JAR); + resourceClassJar = + ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_RESOURCES_CLASS_JAR); JavaCompilationArtifacts.Builder javaArtifactsBuilder = new JavaCompilationArtifacts.Builder(); - JavaTargetAttributes.Builder javacAttributes = new JavaTargetAttributes.Builder(javaSemantics) - .addSourceJar(resourcesJar); - JavaCompilationHelper javacHelper = new JavaCompilationHelper( - ruleContext, javaSemantics, getJavacOpts(), javacAttributes); + JavaTargetAttributes.Builder javacAttributes = + new JavaTargetAttributes.Builder(javaSemantics).addSourceJar(resourcesJar); + JavaCompilationHelper javacHelper = + new JavaCompilationHelper(ruleContext, javaSemantics, getJavacOpts(), javacAttributes); // Only build the class jar if it's not already generated internally by resource processing. if (resourceApk.getResourceJavaClassJar() == null) { if (useRClassGenerator) { @@ -469,9 +476,11 @@ public class AndroidCommon { } else { // Otherwise, it should have been the AndroidRuleClasses.ANDROID_RESOURCES_CLASS_JAR. Preconditions.checkArgument( - resourceApk.getResourceJavaClassJar().equals( - ruleContext.getImplicitOutputArtifact( - AndroidRuleClasses.ANDROID_RESOURCES_CLASS_JAR))); + resourceApk + .getResourceJavaClassJar() + .equals( + ruleContext.getImplicitOutputArtifact( + AndroidRuleClasses.ANDROID_RESOURCES_CLASS_JAR))); } javacHelper.createSourceJarAction(resourceSourceJar, null); } @@ -495,16 +504,15 @@ public class AndroidCommon { // their local resource constants attributes.addRuntimeClassPathEntry(resourcesJar); - Artifact jarJarRuleFile = createResourceJarArtifact( - ruleContext, otherContainer, ".jar_jarjar_rules.txt"); + Artifact jarJarRuleFile = + createResourceJarArtifact(ruleContext, otherContainer, ".jar_jarjar_rules.txt"); - String jarJarRule = String.format("rule %s.* %s.@1", - originalPackage, otherContainer.getJavaPackage()); + String jarJarRule = + String.format("rule %s.* %s.@1", originalPackage, otherContainer.getJavaPackage()); ruleContext.registerAction( FileWriteAction.create(ruleContext, jarJarRuleFile, jarJarRule, false)); - FilesToRunProvider jarjar = - ruleContext.getExecutablePrerequisite("$jarjar_bin", Mode.HOST); + FilesToRunProvider jarjar = ruleContext.getExecutablePrerequisite("$jarjar_bin", Mode.HOST); ruleContext.registerAction( new SpawnAction.Builder() @@ -527,17 +535,19 @@ public class AndroidCommon { } } - private static Artifact createResourceJarArtifact(RuleContext ruleContext, - ResourceContainer container, String fileNameSuffix) { + private static Artifact createResourceJarArtifact( + RuleContext ruleContext, ResourceContainer container, String fileNameSuffix) { String artifactName = container.getLabel().getName() + fileNameSuffix; // Since the Java sources are generated by combining all resources with the // ones included in the binary, the path of the artifact has to be unique // per binary and per library (not only per library). - Artifact artifact = ruleContext.getUniqueDirectoryArtifact("resource_jars", - container.getLabel().getPackageIdentifier().getSourceRoot().getRelative(artifactName), - ruleContext.getBinOrGenfilesDirectory()); + Artifact artifact = + ruleContext.getUniqueDirectoryArtifact( + "resource_jars", + container.getLabel().getPackageIdentifier().getSourceRoot().getRelative(artifactName), + ruleContext.getBinOrGenfilesDirectory()); return artifact; } @@ -554,15 +564,17 @@ public class AndroidCommon { classJar = ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_LIBRARY_CLASS_JAR); idlHelper = new AndroidIdlHelper(ruleContext, classJar); - ImmutableList<Artifact> bootclasspath; if (getAndroidConfig(ruleContext).desugarJava8()) { - bootclasspath = ImmutableList.<Artifact>builder() - .addAll(ruleContext.getPrerequisite("$desugar_java8_extra_bootclasspath", Mode.HOST) - .getProvider(FileProvider.class) - .getFilesToBuild()) - .add(AndroidSdkProvider.fromRuleContext(ruleContext).getAndroidJar()) - .build(); + bootclasspath = + ImmutableList.<Artifact>builder() + .addAll( + ruleContext + .getPrerequisite("$desugar_java8_extra_bootclasspath", Mode.HOST) + .getProvider(FileProvider.class) + .getFilesToBuild()) + .add(AndroidSdkProvider.fromRuleContext(ruleContext).getAndroidJar()) + .build(); } else { bootclasspath = ImmutableList.of(AndroidSdkProvider.fromRuleContext(ruleContext).getAndroidJar()); @@ -594,8 +606,14 @@ public class AndroidCommon { // a bottleneck. For legacy resources, the srcjar and R class compiler don't match up // (the legacy srcjar requires the createJarJar step below). boolean useRClassGenerator = isBinary && !resourceApk.isLegacy(); - compileResources(javaSemantics, resourceApk, resourcesJar, artifactsBuilder, attributes, - filesBuilder, useRClassGenerator); + compileResources( + javaSemantics, + resourceApk, + resourcesJar, + artifactsBuilder, + attributes, + filesBuilder, + useRClassGenerator); // Combined resource constants needs to come even before our own classes that may contain // local resource constants. @@ -605,9 +623,12 @@ public class AndroidCommon { if (resourceApk.isLegacy()) { // Repackages the R.java for each dependency package and places the resultant jars before // the dependency libraries to ensure that the generated resource ids are correct. - createJarJarActions(attributes, jarsProducedForRuntime, + createJarJarActions( + attributes, + jarsProducedForRuntime, resourceApk.getResourceDependencies().getResourceContainers(), - resourceApk.getPrimaryResource().getJavaPackage(), resourceClassJar); + resourceApk.getPrimaryResource().getJavaPackage(), + resourceClassJar); } } @@ -617,8 +638,8 @@ public class AndroidCommon { } if (addCoverageSupport) { - androidSemantics.addCoverageSupport(ruleContext, this, javaSemantics, true, - attributes, artifactsBuilder); + androidSemantics.addCoverageSupport( + ruleContext, this, javaSemantics, true, attributes, artifactsBuilder); if (ruleContext.hasErrors()) { return null; } @@ -644,28 +665,33 @@ public class AndroidCommon { private JavaCompilationHelper initAttributes( JavaTargetAttributes.Builder attributes, JavaSemantics semantics) { boolean useDataBinding = DataBinding.isEnabled(ruleContext); - JavaCompilationHelper helper = new JavaCompilationHelper(ruleContext, semantics, - javaCommon.getJavacOpts(), attributes, - useDataBinding ? DataBinding.processDeps(ruleContext) : ImmutableList.<Artifact>of(), - // We have to disable strict deps checking with data binding because data binding propagates - // layout XML up the dependency chain. Say a library's XML references a Java class, - // e.g.: "<variable type="some.package.SomeClass" />". Data binding's annotation processor - // triggers a compile against SomeClass. Because data binding reprocesses bindings - // each step up the dependency chain (via merged resources), that means this compile also - // happens at the top-level binary. Since SomeClass.java is declared in the library, this - // creates a strict deps violation. - // - // This weakening of strict deps is unfortunate and deserves to be fixed. Once data - // binding integrates with aapt2 this problem should naturally go away (since reprocessing - // will no longer happen). - /*disableStrictDeps=*/useDataBinding); + JavaCompilationHelper helper = + new JavaCompilationHelper( + ruleContext, + semantics, + javaCommon.getJavacOpts(), + attributes, + useDataBinding ? DataBinding.processDeps(ruleContext) : ImmutableList.<Artifact>of(), + /* We have to disable strict deps checking with data binding because data binding + * propagates layout XML up the dependency chain. Say a library's XML references a Java + * class, e.g.: "<variable type="some.package.SomeClass" />". Data binding's annotation + * processor triggers a compile against SomeClass. Because data binding reprocesses + * bindings each step up the dependency chain (via merged resources), that means this + * compile also happens at the top-level binary. Since SomeClass.java is declared in the + * library, this creates a strict deps violation. + * + * This weakening of strict deps is unfortunate and deserves to be fixed. Once data + * binding integrates with aapt2 this problem should naturally go away (since + * reprocessing will no longer happen). + */ + /*disableStrictDeps=*/ useDataBinding); helper.addLibrariesToAttributes(javaCommon.targetsTreatedAsDeps(ClasspathType.COMPILE_ONLY)); attributes.setRuleKind(ruleContext.getRule().getRuleClass()); attributes.setTargetLabel(ruleContext.getLabel()); - JavaCommon.validateConstraint(ruleContext, "android", - javaCommon.targetsTreatedAsDeps(ClasspathType.BOTH)); + JavaCommon.validateConstraint( + ruleContext, "android", javaCommon.targetsTreatedAsDeps(ClasspathType.BOTH)); ruleContext.checkSrcsSamePackage(true); return helper; } @@ -712,8 +738,8 @@ public class AndroidCommon { helper.createSourceJarAction(srcJar, genSourceJar); outputDepsProto = helper.createOutputDepsProtoArtifact(classJar, javaArtifactsBuilder); - helper.createCompileActionWithInstrumentation(classJar, manifestProtoOutput, genSourceJar, - outputDepsProto, javaArtifactsBuilder); + helper.createCompileActionWithInstrumentation( + classJar, manifestProtoOutput, genSourceJar, outputDepsProto, javaArtifactsBuilder); if (isBinary) { generatedExtensionRegistryProvider = @@ -745,16 +771,16 @@ public class AndroidCommon { asNeverLink, helper.getBootclasspathOrDefault())); - transitiveNeverlinkLibraries = collectTransitiveNeverlinkLibraries( - ruleContext, - javaCommon.getDependencies(), - javaCommon.getJavaCompilationArtifacts().getRuntimeJars()); + transitiveNeverlinkLibraries = + collectTransitiveNeverlinkLibraries( + ruleContext, + javaCommon.getDependencies(), + javaCommon.getJavaCompilationArtifacts().getRuntimeJars()); if (collectJavaCompilationArgs) { boolean hasSources = attributes.hasSources(); - this.javaCompilationArgs = - collectJavaCompilationArgs(exportDeps, asNeverLink, hasSources); - this.recursiveJavaCompilationArgs = collectJavaCompilationArgs( - true, asNeverLink, /* hasSources */ true); + this.javaCompilationArgs = collectJavaCompilationArgs(exportDeps, asNeverLink, hasSources); + this.recursiveJavaCompilationArgs = + collectJavaCompilationArgs(true, asNeverLink, /* hasSources */ true); } } @@ -800,11 +826,12 @@ public class AndroidCommon { javaCommon.addGenJarsProvider(builder, javaInfoBuilder, genClassJar, genSourceJar); DataBinding.maybeAddProvider(builder, ruleContext); - JavaInfo javaInfo = javaInfoBuilder - .addProvider(JavaCompilationArgsProvider.class, compilationArgsProvider) - .addProvider(JavaRuleOutputJarsProvider.class, ruleOutputJarsProvider) - .addProvider(JavaSourceJarsProvider.class, sourceJarsProvider) - .build(); + JavaInfo javaInfo = + javaInfoBuilder + .addProvider(JavaCompilationArgsProvider.class, compilationArgsProvider) + .addProvider(JavaRuleOutputJarsProvider.class, ruleOutputJarsProvider) + .addProvider(JavaSourceJarsProvider.class, sourceJarsProvider) + .build(); return builder .setFilesToBuild(filesToBuild) @@ -841,19 +868,21 @@ public class AndroidCommon { // TODO(bazel-team): why return any Runfiles in the neverlink case? if (asNeverLink) { return new Runfiles.Builder( - ruleContext.getWorkspaceName(), ruleContext.getConfiguration().legacyExternalRunfiles()) + ruleContext.getWorkspaceName(), + ruleContext.getConfiguration().legacyExternalRunfiles()) .addRunfiles(ruleContext, RunfilesProvider.DEFAULT_RUNFILES) .build(); } return JavaCommon.getRunfiles( - ruleContext, javaCommon.getJavaSemantics(), javaCommon.getJavaCompilationArtifacts(), + ruleContext, + javaCommon.getJavaSemantics(), + javaCommon.getJavaCompilationArtifacts(), asNeverLink); } public static PathFragment getAssetDir(RuleContext ruleContext) { - return PathFragment.create(ruleContext.attributes().get( - ResourceType.ASSETS.getAttribute() + "_dir", - Type.STRING)); + return PathFragment.create( + ruleContext.attributes().get(ResourceType.ASSETS.getAttribute() + "_dir", Type.STRING)); } public static AndroidResourcesProvider getAndroidResources(RuleContext ruleContext) { @@ -891,10 +920,13 @@ public class AndroidCommon { * @param isNeverLink Whether the target has the 'neverlink' attr. * @param hasSrcs If false, deps are exported (deprecated behaviour) */ - private JavaCompilationArgs collectJavaCompilationArgs(boolean recursive, boolean isNeverLink, - boolean hasSrcs) { - boolean exportDeps = !hasSrcs - && ruleContext.getFragment(AndroidConfiguration.class).allowSrcsLessAndroidLibraryDeps(); + private JavaCompilationArgs collectJavaCompilationArgs( + boolean recursive, boolean isNeverLink, boolean hasSrcs) { + boolean exportDeps = + !hasSrcs + && ruleContext + .getFragment(AndroidConfiguration.class) + .allowSrcsLessAndroidLibraryDeps(); return javaCommon.collectJavaCompilationArgs(recursive, isNeverLink, exportDeps); } @@ -911,8 +943,8 @@ public class AndroidCommon { } /** - * Returns Jars produced by this rule that may go into the runtime classpath. By contrast - * {@link #getRuntimeJars()} returns the complete runtime classpath needed by this rule, including + * Returns Jars produced by this rule that may go into the runtime classpath. By contrast {@link + * #getRuntimeJars()} returns the complete runtime classpath needed by this rule, including * dependencies. */ public NestedSet<Artifact> getJarsProducedForRuntime() { @@ -955,9 +987,7 @@ public class AndroidCommon { }; } - /** - * Returns {@link AndroidConfiguration} in given context. - */ + /** Returns {@link AndroidConfiguration} in given context. */ static AndroidConfiguration getAndroidConfig(RuleContext context) { return context.getConfiguration().getFragment(AndroidConfiguration.class); } @@ -980,8 +1010,8 @@ public class AndroidCommon { * * <p>No rule needs <i>any</i> support if data binding is disabled. */ - static JavaCommon createJavaCommonWithAndroidDataBinding(RuleContext ruleContext, - JavaSemantics semantics, boolean isLibrary) { + static JavaCommon createJavaCommonWithAndroidDataBinding( + RuleContext ruleContext, JavaSemantics semantics, boolean isLibrary) { boolean useDataBinding = DataBinding.isEnabled(ruleContext); ImmutableList<Artifact> srcs = @@ -1012,8 +1042,9 @@ public class AndroidCommon { bothDeps = JavaCommon.defaultDeps(ruleContext, semantics, ClasspathType.BOTH); } else { // Binary: - compileDeps = ImmutableList.copyOf( - ruleContext.getPrerequisites("deps", RuleConfiguredTarget.Mode.TARGET)); + compileDeps = + ImmutableList.copyOf( + ruleContext.getPrerequisites("deps", RuleConfiguredTarget.Mode.TARGET)); runtimeDeps = compileDeps; bothDeps = compileDeps; } diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidConfiguration.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidConfiguration.java index bcb5cb7a99..09c4254648 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidConfiguration.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidConfiguration.java @@ -247,9 +247,9 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { // mobile-install v1 is going away, and this flag does not apply to v2 documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, effectTags = { - OptionEffectTag.AFFECTS_OUTPUTS, - OptionEffectTag.EXECUTION, - OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.AFFECTS_OUTPUTS, + OptionEffectTag.EXECUTION, + OptionEffectTag.LOADING_AND_ANALYSIS, }, metadataTags = OptionMetadataTag.EXPERIMENTAL ) @@ -262,10 +262,10 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { converter = EmptyToNullLabelConverter.class, documentationCategory = OptionDocumentationCategory.TOOLCHAIN, effectTags = { - OptionEffectTag.AFFECTS_OUTPUTS, - OptionEffectTag.CHANGES_INPUTS, - OptionEffectTag.LOADING_AND_ANALYSIS, - OptionEffectTag.LOSES_INCREMENTAL_STATE, + OptionEffectTag.AFFECTS_OUTPUTS, + OptionEffectTag.CHANGES_INPUTS, + OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.LOSES_INCREMENTAL_STATE, }, help = "The location of the C++ compiler used for Android builds." ) @@ -277,9 +277,9 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { category = "semantics", documentationCategory = OptionDocumentationCategory.OUTPUT_PARAMETERS, effectTags = { - OptionEffectTag.AFFECTS_OUTPUTS, - OptionEffectTag.LOADING_AND_ANALYSIS, - OptionEffectTag.LOSES_INCREMENTAL_STATE, + OptionEffectTag.AFFECTS_OUTPUTS, + OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.LOSES_INCREMENTAL_STATE, }, help = "The Android target CPU." ) @@ -291,9 +291,9 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { category = "semantics", documentationCategory = OptionDocumentationCategory.TOOLCHAIN, effectTags = { - OptionEffectTag.AFFECTS_OUTPUTS, - OptionEffectTag.LOADING_AND_ANALYSIS, - OptionEffectTag.LOSES_INCREMENTAL_STATE, + OptionEffectTag.AFFECTS_OUTPUTS, + OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.LOSES_INCREMENTAL_STATE, }, help = "The Android target compiler." ) @@ -306,9 +306,9 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { category = "semantics", documentationCategory = OptionDocumentationCategory.TOOLCHAIN, effectTags = { - OptionEffectTag.CHANGES_INPUTS, - OptionEffectTag.LOADING_AND_ANALYSIS, - OptionEffectTag.LOSES_INCREMENTAL_STATE, + OptionEffectTag.CHANGES_INPUTS, + OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.LOSES_INCREMENTAL_STATE, }, help = "The Android target grte_top." ) @@ -320,8 +320,8 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { converter = DynamicModeConverter.class, documentationCategory = OptionDocumentationCategory.OUTPUT_PARAMETERS, effectTags = { - OptionEffectTag.AFFECTS_OUTPUTS, - OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.AFFECTS_OUTPUTS, + OptionEffectTag.LOADING_AND_ANALYSIS, }, help = "Determines whether C++ deps of Android rules will be linked dynamically when a " @@ -341,9 +341,9 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { converter = LabelConverter.class, documentationCategory = OptionDocumentationCategory.TOOLCHAIN, effectTags = { - OptionEffectTag.CHANGES_INPUTS, - OptionEffectTag.LOADING_AND_ANALYSIS, - OptionEffectTag.LOSES_INCREMENTAL_STATE, + OptionEffectTag.CHANGES_INPUTS, + OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.LOSES_INCREMENTAL_STATE, }, help = "Specifies Android SDK/platform that is used to build Android applications." ) @@ -357,9 +357,9 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { category = "semantics", documentationCategory = OptionDocumentationCategory.OUTPUT_PARAMETERS, effectTags = { - OptionEffectTag.AFFECTS_OUTPUTS, - OptionEffectTag.LOADING_AND_ANALYSIS, - OptionEffectTag.LOSES_INCREMENTAL_STATE, + OptionEffectTag.AFFECTS_OUTPUTS, + OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.LOSES_INCREMENTAL_STATE, }, help = "Setting this option enables fat APKs, which contain native binaries for all " @@ -378,9 +378,9 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { defaultValue = "true", documentationCategory = OptionDocumentationCategory.INPUT_STRICTNESS, effectTags = { - OptionEffectTag.AFFECTS_OUTPUTS, - OptionEffectTag.LOADING_AND_ANALYSIS, - OptionEffectTag.LOSES_INCREMENTAL_STATE, + OptionEffectTag.AFFECTS_OUTPUTS, + OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.LOSES_INCREMENTAL_STATE, }, help = "Whether to desugar Java 8 bytecode before dexing." ) @@ -392,8 +392,8 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { defaultValue = "false", documentationCategory = OptionDocumentationCategory.INPUT_STRICTNESS, effectTags = { - OptionEffectTag.EAGERNESS_TO_EXIT, - OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.EAGERNESS_TO_EXIT, + OptionEffectTag.LOADING_AND_ANALYSIS, }, metadataTags = OptionMetadataTag.EXPERIMENTAL, help = "Whether to double-check correct desugaring at Android binary level." @@ -406,9 +406,9 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { category = "semantics", documentationCategory = OptionDocumentationCategory.BUILD_TIME_OPTIMIZATION, effectTags = { - OptionEffectTag.AFFECTS_OUTPUTS, - OptionEffectTag.LOADING_AND_ANALYSIS, - OptionEffectTag.LOSES_INCREMENTAL_STATE, + OptionEffectTag.AFFECTS_OUTPUTS, + OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.LOSES_INCREMENTAL_STATE, }, help = "Does most of the work for dexing separately for each Jar file." ) @@ -433,8 +433,8 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { category = "experimental", documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, effectTags = { - OptionEffectTag.ACTION_COMMAND_LINES, - OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.ACTION_COMMAND_LINES, + OptionEffectTag.LOADING_AND_ANALYSIS, }, help = "Do not use." ) @@ -450,9 +450,9 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { category = "experimental", documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, effectTags = { - OptionEffectTag.ACTION_COMMAND_LINES, - OptionEffectTag.EAGERNESS_TO_EXIT, - OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.ACTION_COMMAND_LINES, + OptionEffectTag.EAGERNESS_TO_EXIT, + OptionEffectTag.LOADING_AND_ANALYSIS, }, help = "Do not use." ) @@ -476,8 +476,8 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { metadataTags = {OptionMetadataTag.EXPERIMENTAL}, documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, effectTags = { - OptionEffectTag.ACTION_COMMAND_LINES, - OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.ACTION_COMMAND_LINES, + OptionEffectTag.LOADING_AND_ANALYSIS, }, help = "When enabled, the minSdkVersion is parsed from the merged AndroidManifest and used to " @@ -508,8 +508,8 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { category = "semantics", documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, effectTags = { - OptionEffectTag.LOADING_AND_ANALYSIS, - OptionEffectTag.LOSES_INCREMENTAL_STATE, + OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.LOSES_INCREMENTAL_STATE, }, help = "dx flags that that prevent incremental dexing for binary targets that list any of " @@ -529,8 +529,8 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { defaultValue = "--no-optimize,--no-locals", documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, effectTags = { - OptionEffectTag.ACTION_COMMAND_LINES, - OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.ACTION_COMMAND_LINES, + OptionEffectTag.LOADING_AND_ANALYSIS, }, help = "dx flags supported when converting Jars to dex archives incrementally." ) @@ -544,8 +544,8 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { defaultValue = "--minimal-main-dex,--set-max-idx-number", documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, effectTags = { - OptionEffectTag.ACTION_COMMAND_LINES, - OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.ACTION_COMMAND_LINES, + OptionEffectTag.LOADING_AND_ANALYSIS, }, help = "dx flags supported in tool that merges dex archives into final classes.dex files." ) @@ -565,9 +565,9 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { defaultValue = "false", documentationCategory = OptionDocumentationCategory.OUTPUT_PARAMETERS, effectTags = { - OptionEffectTag.AFFECTS_OUTPUTS, - OptionEffectTag.LOADING_AND_ANALYSIS, - OptionEffectTag.LOSES_INCREMENTAL_STATE, + OptionEffectTag.AFFECTS_OUTPUTS, + OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.LOSES_INCREMENTAL_STATE, }, metadataTags = OptionMetadataTag.EXPERIMENTAL, help = "use rex tool to rewrite dex files" @@ -579,8 +579,8 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { defaultValue = "false", documentationCategory = OptionDocumentationCategory.INPUT_STRICTNESS, effectTags = { - OptionEffectTag.EAGERNESS_TO_EXIT, - OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.EAGERNESS_TO_EXIT, + OptionEffectTag.LOADING_AND_ANALYSIS, }, help = "Flag to help transition from allowing to disallowing srcs-less android_library" @@ -593,8 +593,8 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { defaultValue = "false", documentationCategory = OptionDocumentationCategory.OUTPUT_PARAMETERS, effectTags = { - OptionEffectTag.AFFECTS_OUTPUTS, - OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.AFFECTS_OUTPUTS, + OptionEffectTag.LOADING_AND_ANALYSIS, }, help = "Enables resource shrinking for android_binary APKs that use ProGuard." ) @@ -606,8 +606,8 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { category = "semantics", documentationCategory = OptionDocumentationCategory.OUTPUT_PARAMETERS, effectTags = { - OptionEffectTag.AFFECTS_OUTPUTS, - OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.AFFECTS_OUTPUTS, + OptionEffectTag.LOADING_AND_ANALYSIS, }, help = "Enables resource shrinking for android_binary APKs that use ProGuard." ) @@ -619,8 +619,8 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { category = "semantics", documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, effectTags = { - OptionEffectTag.AFFECTS_OUTPUTS, - OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.AFFECTS_OUTPUTS, + OptionEffectTag.LOADING_AND_ANALYSIS, }, metadataTags = OptionMetadataTag.EXPERIMENTAL, help = @@ -636,9 +636,9 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { converter = AndroidManifestMergerConverter.class, documentationCategory = OptionDocumentationCategory.TOOLCHAIN, effectTags = { - OptionEffectTag.AFFECTS_OUTPUTS, - OptionEffectTag.LOADING_AND_ANALYSIS, - OptionEffectTag.LOSES_INCREMENTAL_STATE, + OptionEffectTag.AFFECTS_OUTPUTS, + OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.LOSES_INCREMENTAL_STATE, }, help = "Selects the manifest merger to use for android_binary rules. Flag to help the" @@ -652,9 +652,9 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { category = "semantics", documentationCategory = OptionDocumentationCategory.TOOLCHAIN, effectTags = { - OptionEffectTag.AFFECTS_OUTPUTS, - OptionEffectTag.LOADING_AND_ANALYSIS, - OptionEffectTag.LOSES_INCREMENTAL_STATE, + OptionEffectTag.AFFECTS_OUTPUTS, + OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.LOSES_INCREMENTAL_STATE, }, converter = AndroidAaptConverter.class, help = @@ -669,9 +669,9 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { defaultValue = "v1_v2", documentationCategory = OptionDocumentationCategory.SIGNING, effectTags = { - OptionEffectTag.ACTION_COMMAND_LINES, - OptionEffectTag.AFFECTS_OUTPUTS, - OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.ACTION_COMMAND_LINES, + OptionEffectTag.AFFECTS_OUTPUTS, + OptionEffectTag.LOADING_AND_ANALYSIS, }, help = "Implementation to use to sign APKs" ) @@ -692,9 +692,9 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { defaultValue = "filter_in_execution", documentationCategory = OptionDocumentationCategory.BUILD_TIME_OPTIMIZATION, effectTags = { - OptionEffectTag.CHANGES_INPUTS, - OptionEffectTag.LOADING_AND_ANALYSIS, - OptionEffectTag.LOSES_INCREMENTAL_STATE, + OptionEffectTag.CHANGES_INPUTS, + OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.LOSES_INCREMENTAL_STATE, }, metadataTags = {OptionMetadataTag.EXPERIMENTAL}, help = @@ -718,8 +718,8 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { defaultValue = "false", documentationCategory = OptionDocumentationCategory.OUTPUT_PARAMETERS, effectTags = { - OptionEffectTag.AFFECTS_OUTPUTS, - OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.AFFECTS_OUTPUTS, + OptionEffectTag.LOADING_AND_ANALYSIS, }, metadataTags = OptionMetadataTag.EXPERIMENTAL, help = "Compress Java resources in APKs" @@ -731,9 +731,9 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { defaultValue = "false", documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, effectTags = { - OptionEffectTag.AFFECTS_OUTPUTS, - OptionEffectTag.LOADING_AND_ANALYSIS, - OptionEffectTag.LOSES_INCREMENTAL_STATE, + OptionEffectTag.AFFECTS_OUTPUTS, + OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.LOSES_INCREMENTAL_STATE, }, help = "The default value of the exports_manifest attribute on android_library." ) @@ -744,8 +744,8 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { defaultValue = "false", documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, effectTags = { - OptionEffectTag.AFFECTS_OUTPUTS, - OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.AFFECTS_OUTPUTS, + OptionEffectTag.LOADING_AND_ANALYSIS, }, metadataTags = {OptionMetadataTag.EXPERIMENTAL}, help = "If true, robolectric resources will be packaged using aapt2 if available." @@ -757,8 +757,8 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { defaultValue = "false", documentationCategory = OptionDocumentationCategory.INPUT_STRICTNESS, effectTags = { - OptionEffectTag.EAGERNESS_TO_EXIT, - OptionEffectTag.LOADING_AND_ANALYSIS, + OptionEffectTag.EAGERNESS_TO_EXIT, + OptionEffectTag.LOADING_AND_ANALYSIS, }, help = "If passed, resource merge conflicts will be treated as errors instead of warnings" ) @@ -798,13 +798,14 @@ public class AndroidConfiguration extends BuildConfiguration.Fragment { public boolean skipParsingAction; @Option( - name = "android_fixed_resource_neverlinking", - defaultValue = "false", - documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, - effectTags = {OptionEffectTag.LOADING_AND_ANALYSIS}, - help = "If true, resources will properly not get propagated through neverlinked libraries." - + " Otherwise, the old behavior of propagating those resources if no resource-related" - + " attributes are specified in the neverlink library will be preserved." + name = "android_fixed_resource_neverlinking", + defaultValue = "false", + documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, + effectTags = {OptionEffectTag.LOADING_AND_ANALYSIS}, + help = + "If true, resources will properly not get propagated through neverlinked libraries." + + " Otherwise, the old behavior of propagating those resources if no resource-related" + + " attributes are specified in the neverlink library will be preserved." ) public boolean fixedResourceNeverlinking; diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidDeployInfoAction.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidDeployInfoAction.java index ef2a4c99c4..573d9046f7 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidDeployInfoAction.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidDeployInfoAction.java @@ -34,8 +34,8 @@ import java.io.IOException; import java.io.InputStream; /** - * Writes AndroidDeployInfo proto message. This proto describes how - * to deploy and launch an android_binary/android_test. + * Writes AndroidDeployInfo proto message. This proto describes how to deploy and launch an + * android_binary/android_test. */ @Immutable public final class AndroidDeployInfoAction extends AbstractFileWriteAction { @@ -64,8 +64,11 @@ public final class AndroidDeployInfoAction extends AbstractFileWriteAction { Artifact mergedManifest, ImmutableList<Artifact> additionalMergedManifests, ImmutableList<Artifact> apksToDeploy) { - super(owner, makeInputs(mergedManifest, additionalMergedManifests, apksToDeploy), - outputFile, false); + super( + owner, + makeInputs(mergedManifest, additionalMergedManifests, apksToDeploy), + outputFile, + false); this.mergedManifest = mergedManifest; this.additionalMergedManifests = additionalMergedManifests; this.apksToDeploy = apksToDeploy; @@ -90,8 +93,13 @@ public final class AndroidDeployInfoAction extends AbstractFileWriteAction { Artifact mergedManifest, ImmutableList<Artifact> additionalMergedManifests, ImmutableList<Artifact> apksToDeploy) { - Action action = new AndroidDeployInfoAction(ruleContext.getActionOwner(), - deployInfo, mergedManifest, additionalMergedManifests, apksToDeploy); + Action action = + new AndroidDeployInfoAction( + ruleContext.getActionOwner(), + deployInfo, + mergedManifest, + additionalMergedManifests, + apksToDeploy); ruleContext.registerAction(action); } @@ -107,8 +115,7 @@ public final class AndroidDeployInfoAction extends AbstractFileWriteAction { @Override protected String computeKey(ActionKeyContext actionKeyContext) { - Fingerprint f = new Fingerprint() - .addString(GUID); + Fingerprint f = new Fingerprint().addString(GUID); try (InputStream in = getByteString().newInput()) { byte[] buffer = new byte[512]; diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidDevice.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidDevice.java index e87c524686..fbe66747c2 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidDevice.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidDevice.java @@ -52,9 +52,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -/** - * An implementation for the "android_device" rule. - */ +/** An implementation for the "android_device" rule. */ public class AndroidDevice implements RuleConfiguredTargetFactory { private static final Template STUB_SCRIPT = @@ -80,17 +78,18 @@ public class AndroidDevice implements RuleConfiguredTargetFactory { private static final Predicate<Artifact> SOURCE_PROPERTIES_SELECTOR = (Artifact artifact) -> "source.properties".equals(artifact.getPath().getBaseName()); - private static final Predicate<Artifact> SOURCE_PROPERTIES_FILTER = Predicates.not( - SOURCE_PROPERTIES_SELECTOR); + private static final Predicate<Artifact> SOURCE_PROPERTIES_FILTER = + Predicates.not(SOURCE_PROPERTIES_SELECTOR); + @Override public ConfiguredTarget create(RuleContext ruleContext) throws InterruptedException, RuleErrorException { checkWhitelist(ruleContext); Artifact executable = ruleContext.createOutputArtifact(); - Artifact metadata = ruleContext.getImplicitOutputArtifact( - AndroidRuleClasses.ANDROID_DEVICE_EMULATOR_METADATA); - Artifact images = ruleContext.getImplicitOutputArtifact( - AndroidRuleClasses.ANDROID_DEVICE_USERDATA_IMAGES); + Artifact metadata = + ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_DEVICE_EMULATOR_METADATA); + Artifact images = + ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_DEVICE_USERDATA_IMAGES); NestedSetBuilder<Artifact> filesBuilder = NestedSetBuilder.stableOrder(); filesBuilder.add(executable); @@ -99,8 +98,8 @@ public class AndroidDevice implements RuleConfiguredTargetFactory { NestedSet<Artifact> filesToBuild = filesBuilder.build(); Map<String, String> executionInfo = TargetUtils.getExecutionInfo(ruleContext.getRule()); - AndroidDeviceRuleAttributes deviceAttributes = new AndroidDeviceRuleAttributes( - ruleContext, ImmutableMap.copyOf(executionInfo)); + AndroidDeviceRuleAttributes deviceAttributes = + new AndroidDeviceRuleAttributes(ruleContext, ImmutableMap.copyOf(executionInfo)); if (ruleContext.hasErrors()) { return null; } @@ -111,15 +110,16 @@ public class AndroidDevice implements RuleConfiguredTargetFactory { deviceAttributes.createStubScriptAction(metadata, images, executable, ruleContext); deviceAttributes.createBootAction(metadata, images); - Runfiles runfiles = new Runfiles.Builder(ruleContext.getWorkspaceName()) - .addTransitiveArtifacts(filesToBuild) - .addArtifacts(commonDependencyArtifacts) - .addRunfiles(ruleContext, RunfilesProvider.DEFAULT_RUNFILES) - .merge( - ruleContext - .getExecutablePrerequisite("$unified_launcher", Mode.HOST) - .getRunfilesSupport()) - .build(); + Runfiles runfiles = + new Runfiles.Builder(ruleContext.getWorkspaceName()) + .addTransitiveArtifacts(filesToBuild) + .addArtifacts(commonDependencyArtifacts) + .addRunfiles(ruleContext, RunfilesProvider.DEFAULT_RUNFILES) + .merge( + ruleContext + .getExecutablePrerequisite("$unified_launcher", Mode.HOST) + .getRunfilesSupport()) + .build(); RunfilesSupport runfilesSupport = RunfilesSupport.withExecutable(ruleContext, runfiles, executable); NestedSet<Artifact> extraFilesToRun = @@ -189,8 +189,9 @@ public class AndroidDevice implements RuleConfiguredTargetFactory { cache = ruleContext.attributes().get("cache", Type.INTEGER); vmHeap = ruleContext.attributes().get("vm_heap", Type.INTEGER); - defaultProperties = Optional.fromNullable( - ruleContext.getPrerequisiteArtifact("default_properties", Mode.HOST)); + defaultProperties = + Optional.fromNullable( + ruleContext.getPrerequisiteArtifact("default_properties", Mode.HOST)); adb = ruleContext.getPrerequisiteArtifact("$adb", Mode.HOST); emulatorArm = ruleContext.getPrerequisiteArtifact("$emulator_arm", Mode.HOST); emulatorX86 = ruleContext.getPrerequisiteArtifact("$emulator_x86", Mode.HOST); @@ -229,34 +230,43 @@ public class AndroidDevice implements RuleConfiguredTargetFactory { systemImages = Iterables.filter(files, SOURCE_PROPERTIES_FILTER); validateAttributes(); if (sourcePropertiesFile == null) { - ruleContext.attributeError("system_image", "No source.properties files exist in this " - + "filegroup (" + systemImagesAndSourceProperties.getLabel() + ")"); + ruleContext.attributeError( + "system_image", + "No source.properties files exist in this " + + "filegroup (" + + systemImagesAndSourceProperties.getLabel() + + ")"); } int numberOfSourceProperties = Iterables.size(files) - Iterables.size(systemImages); if (numberOfSourceProperties > 1) { - ruleContext.attributeError("system_image", "Multiple source.properties files exist in " - + "this filegroup (" + systemImagesAndSourceProperties.getLabel() + ")"); + ruleContext.attributeError( + "system_image", + "Multiple source.properties files exist in " + + "this filegroup (" + + systemImagesAndSourceProperties.getLabel() + + ")"); } if (ruleContext.hasErrors()) { return; } - commonDependencies = ImmutableList.<Artifact>builder() - .add(adb) - .add(sourcePropertiesFile) - .addAll(systemImages) - .add(emulatorArm) - .add(emulatorX86) - .add(adbStatic) - .addAll(emulatorX86Bios) - .addAll(xvfbSupportFiles) - .add(mksdcard) - .add(snapshotFs) - .addAll(unifiedLauncher.getFilesToRun()) - .addAll(androidRuntestDeps) - .addAll(testingShbaseDeps) - .addAll(platformApks) - .build(); + commonDependencies = + ImmutableList.<Artifact>builder() + .add(adb) + .add(sourcePropertiesFile) + .addAll(systemImages) + .add(emulatorArm) + .add(emulatorX86) + .add(adbStatic) + .addAll(emulatorX86Bios) + .addAll(xvfbSupportFiles) + .add(mksdcard) + .add(snapshotFs) + .addAll(unifiedLauncher.getFilesToRun()) + .addAll(androidRuntestDeps) + .addAll(testingShbaseDeps) + .addAll(platformApks) + .build(); } /* @@ -268,8 +278,9 @@ public class AndroidDevice implements RuleConfiguredTargetFactory { Artifact metadata, Artifact images, Artifact executable, RuleContext ruleContext) { List<Substitution> arguments = new ArrayList<>(); arguments.add(Substitution.of("%workspace%", ruleContext.getWorkspaceName())); - arguments.add(Substitution.of("%unified_launcher%", - unifiedLauncher.getExecutable().getRunfilesPathString())); + arguments.add( + Substitution.of( + "%unified_launcher%", unifiedLauncher.getExecutable().getRunfilesPathString())); arguments.add(Substitution.of("%adb%", adb.getRunfilesPathString())); arguments.add(Substitution.of("%adb_static%", adbStatic.getRunfilesPathString())); arguments.add(Substitution.of("%emulator_x86%", emulatorX86.getRunfilesPathString())); @@ -286,16 +297,18 @@ public class AndroidDevice implements RuleConfiguredTargetFactory { Substitution.of( "%bios_files%", emulatorX86Bios.stream().map(Artifact::getRunfilesPathString).collect(joining(" ")))); - arguments.add(Substitution.of("%source_properties_file%", - sourcePropertiesFile.getRunfilesPathString())); + arguments.add( + Substitution.of( + "%source_properties_file%", sourcePropertiesFile.getRunfilesPathString())); arguments.add(Substitution.of("%image_input_file%", images.getRunfilesPathString())); arguments.add(Substitution.of("%emulator_metadata_path%", metadata.getRunfilesPathString())); arguments.add(Substitution.of("%android_runtest%", androidRuntest.getRunfilesPathString())); arguments.add(Substitution.of("%testing_shbase%", testingShbase.getRunfilesPathString())); arguments.add(Substitution.of("%sdk_path%", sdkPath.getRunfilesPathString())); - ruleContext.registerAction(new TemplateExpansionAction( - ruleContext.getActionOwner(), executable, STUB_SCRIPT, arguments, true)); + ruleContext.registerAction( + new TemplateExpansionAction( + ruleContext.getActionOwner(), executable, STUB_SCRIPT, arguments, true)); } public void createBootAction(Artifact metadata, Artifact images) { @@ -303,44 +316,46 @@ public class AndroidDevice implements RuleConfiguredTargetFactory { // strings to find all dependent artifacts (there is no nicely created runfiles // folder we're executing in). - SpawnAction.Builder spawnBuilder = new SpawnAction.Builder() - .addOutput(metadata) - .addOutput(images) - .addInputs(commonDependencies) - .setMnemonic("AndroidDeviceBoot") - .setProgressMessage("creating android images...") - .setExecutionInfo(constraints) - .setExecutable(unifiedLauncher) - // Boot resource estimation: - // CPU: 100% - the emulator will peg a single cpu during boot because it's a very - // computation intensive part of the lifecycle. - // RAM: the emulator will use as much ram as has been requested in the device rule - // (there is a slight overhead for qemu's internals, but this is miniscule). - // IO: 15% Process is IO light until the very end when the booted files are flushed to - // disk. - .setResources(ResourceSet.createWithRamCpuIo(ram, 1, .0)) - .addExecutableArguments( - "--action=boot", - "--density=" + density, - "--memory=" + ram, - "--cache=" + cache, - "--vm_size=" + vmHeap, - "--generate_output_dir=" + images.getExecPath().getParentDirectory().getPathString(), - "--skin=" + getScreenSize(), - "--source_properties_file=" + sourcePropertiesFile.getExecPathString(), - "--system_images=" + Artifact.joinExecPaths(" ", systemImages), - "--flag_configured_android_tools", - "--adb=" + adb.getExecPathString(), - "--emulator_x86=" + emulatorX86.getExecPathString(), - "--emulator_arm=" + emulatorArm.getExecPathString(), - "--adb_static=" + adbStatic.getExecPathString(), - "--mksdcard=" + mksdcard.getExecPathString(), - "--empty_snapshot_fs=" + snapshotFs.getExecPathString(), - "--bios_files=" + Artifact.joinExecPaths(",", emulatorX86Bios), - "--nocopy_system_images", - "--single_image_file", - "--android_sdk_path=" + sdkPath.getExecPathString(), - "--platform_apks=" + Artifact.joinExecPaths(",", platformApks)); + SpawnAction.Builder spawnBuilder = + new SpawnAction.Builder() + .addOutput(metadata) + .addOutput(images) + .addInputs(commonDependencies) + .setMnemonic("AndroidDeviceBoot") + .setProgressMessage("creating android images...") + .setExecutionInfo(constraints) + .setExecutable(unifiedLauncher) + // Boot resource estimation: + // CPU: 100% - the emulator will peg a single cpu during boot because it's a very + // computation intensive part of the lifecycle. + // RAM: the emulator will use as much ram as has been requested in the device rule + // (there is a slight overhead for qemu's internals, but this is miniscule). + // IO: 15% Process is IO light until the very end when the booted files are flushed to + // disk. + .setResources(ResourceSet.createWithRamCpuIo(ram, 1, .0)) + .addExecutableArguments( + "--action=boot", + "--density=" + density, + "--memory=" + ram, + "--cache=" + cache, + "--vm_size=" + vmHeap, + "--generate_output_dir=" + + images.getExecPath().getParentDirectory().getPathString(), + "--skin=" + getScreenSize(), + "--source_properties_file=" + sourcePropertiesFile.getExecPathString(), + "--system_images=" + Artifact.joinExecPaths(" ", systemImages), + "--flag_configured_android_tools", + "--adb=" + adb.getExecPathString(), + "--emulator_x86=" + emulatorX86.getExecPathString(), + "--emulator_arm=" + emulatorArm.getExecPathString(), + "--adb_static=" + adbStatic.getExecPathString(), + "--mksdcard=" + mksdcard.getExecPathString(), + "--empty_snapshot_fs=" + snapshotFs.getExecPathString(), + "--bios_files=" + Artifact.joinExecPaths(",", emulatorX86Bios), + "--nocopy_system_images", + "--single_image_file", + "--android_sdk_path=" + sdkPath.getExecPathString(), + "--platform_apks=" + Artifact.joinExecPaths(",", platformApks)); CustomCommandLine.Builder commandLine = CustomCommandLine.builder(); if (defaultProperties.isPresent()) { diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidDeviceRule.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidDeviceRule.java index 23f2efb350..a033c67cfb 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidDeviceRule.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidDeviceRule.java @@ -27,9 +27,7 @@ import com.google.devtools.build.lib.analysis.whitelisting.Whitelist; import com.google.devtools.build.lib.packages.RuleClass; import com.google.devtools.build.lib.rules.java.JavaSemantics; -/** - * Rule definition for android_device. - */ +/** Rule definition for android_device. */ public final class AndroidDeviceRule implements RuleDefinition { @Override public RuleClass build(RuleClass.Builder builder, RuleDefinitionEnvironment env) { @@ -97,38 +95,64 @@ public final class AndroidDeviceRule implements RuleDefinition { a specific device). The properties in this file will override read only properties typically set by the emulator such as ro.product.model. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ - .add(attr("default_properties", LABEL).cfg(HOST) - .allowedFileTypes(JavaSemantics.PROPERTIES)) + .add(attr("default_properties", LABEL).cfg(HOST).allowedFileTypes(JavaSemantics.PROPERTIES)) /* <!-- #BLAZE_RULE(android_device).ATTRIBUTE(platform_apks) --> A list of apks to be installed on the device at boot time. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("platform_apks", LABEL_LIST).legacyAllowAnyFileType()) - .add(attr("$adb_static", LABEL).cfg(HOST).value( - env.getToolsLabel("//tools/android:adb_static"))) - .add(attr("$adb", LABEL).cfg(HOST).value( - env.getToolsLabel("//tools/android:adb"))) - .add(attr("$emulator_arm", LABEL).cfg(HOST).value( - env.getToolsLabel("//tools/android/emulator:emulator_arm"))) - .add(attr("$emulator_x86", LABEL).cfg(HOST).value( - env.getToolsLabel("//tools/android/emulator:emulator_x86"))) - .add(attr("$emulator_x86_bios", LABEL).cfg(HOST).value( - env.getToolsLabel("//tools/android/emulator:emulator_x86_bios"))) - .add(attr("$mksd", LABEL).cfg(HOST).exec().value( - env.getToolsLabel("//tools/android/emulator:mksd"))) - .add(attr("$empty_snapshot_fs", LABEL).cfg(HOST).value( - env.getToolsLabel("//tools/android/emulator:empty_snapshot_fs"))) - .add(attr("$xvfb_support", LABEL).cfg(HOST).value( - env.getToolsLabel("//tools/android/emulator:xvfb_support"))) - .add(attr("$unified_launcher", LABEL).cfg(HOST).exec().value( - env.getToolsLabel("//tools/android/emulator:unified_launcher"))) - .add(attr("$android_runtest", LABEL).cfg(HOST).exec().value( - env.getToolsLabel("//tools/android:android_runtest"))) - .add(attr("$testing_shbase", LABEL).cfg(HOST).value( - env.getToolsLabel("//tools/android/emulator:shbase"))) - .add(attr("$sdk_path", LABEL).cfg(HOST).exec().value( - env.getToolsLabel("//tools/android/emulator:sdk_path"))) - .add(attr("$is_executable", BOOLEAN).value(true) - .nonconfigurable("Called from RunCommand.isExecutable, which takes a Target")) + .add( + attr("$adb_static", LABEL) + .cfg(HOST) + .value(env.getToolsLabel("//tools/android:adb_static"))) + .add(attr("$adb", LABEL).cfg(HOST).value(env.getToolsLabel("//tools/android:adb"))) + .add( + attr("$emulator_arm", LABEL) + .cfg(HOST) + .value(env.getToolsLabel("//tools/android/emulator:emulator_arm"))) + .add( + attr("$emulator_x86", LABEL) + .cfg(HOST) + .value(env.getToolsLabel("//tools/android/emulator:emulator_x86"))) + .add( + attr("$emulator_x86_bios", LABEL) + .cfg(HOST) + .value(env.getToolsLabel("//tools/android/emulator:emulator_x86_bios"))) + .add( + attr("$mksd", LABEL) + .cfg(HOST) + .exec() + .value(env.getToolsLabel("//tools/android/emulator:mksd"))) + .add( + attr("$empty_snapshot_fs", LABEL) + .cfg(HOST) + .value(env.getToolsLabel("//tools/android/emulator:empty_snapshot_fs"))) + .add( + attr("$xvfb_support", LABEL) + .cfg(HOST) + .value(env.getToolsLabel("//tools/android/emulator:xvfb_support"))) + .add( + attr("$unified_launcher", LABEL) + .cfg(HOST) + .exec() + .value(env.getToolsLabel("//tools/android/emulator:unified_launcher"))) + .add( + attr("$android_runtest", LABEL) + .cfg(HOST) + .exec() + .value(env.getToolsLabel("//tools/android:android_runtest"))) + .add( + attr("$testing_shbase", LABEL) + .cfg(HOST) + .value(env.getToolsLabel("//tools/android/emulator:shbase"))) + .add( + attr("$sdk_path", LABEL) + .cfg(HOST) + .exec() + .value(env.getToolsLabel("//tools/android/emulator:sdk_path"))) + .add( + attr("$is_executable", BOOLEAN) + .value(true) + .nonconfigurable("Called from RunCommand.isExecutable, which takes a Target")) .add( Whitelist.getAttributeFromWhitelistName(AndroidDevice.WHITELIST_NAME) .value(env.getToolsLabel("//tools/android:android_device_whitelist"))) diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidFeatureFlagSetProvider.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidFeatureFlagSetProvider.java index ecfdcb65b2..3746a85c8d 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidFeatureFlagSetProvider.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidFeatureFlagSetProvider.java @@ -88,8 +88,7 @@ public abstract class AndroidFeatureFlagSetProvider implements TransitiveInfoPro FEATURE_FLAG_ATTR, String.format( "the %s attribute is not available in package '%s'", - FEATURE_FLAG_ATTR, - ruleContext.getLabel().getPackageIdentifier())); + FEATURE_FLAG_ATTR, ruleContext.getLabel().getPackageIdentifier())); throw new RuleErrorException(); } diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidIdeInfoProvider.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidIdeInfoProvider.java index 2ff220d584..5779df4100 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidIdeInfoProvider.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidIdeInfoProvider.java @@ -34,12 +34,10 @@ import java.util.Objects; import java.util.Set; import javax.annotation.Nullable; -/** - * An Android target provider to provide Android-specific info to IDEs. - */ +/** An Android target provider to provide Android-specific info to IDEs. */ @Immutable public final class AndroidIdeInfoProvider implements TransitiveInfoProvider { - /** Represents a directory that contains sources, generated or otherwise, for an IDE.*/ + /** Represents a directory that contains sources, generated or otherwise, for an IDE. */ @Immutable public static class SourceDirectory { final PathFragment relativePath; @@ -48,9 +46,7 @@ public final class AndroidIdeInfoProvider implements TransitiveInfoProvider { final boolean isSource; @VisibleForTesting - public static SourceDirectory fromSourceRoot( - PathFragment rootPath, - PathFragment relativePath) { + public static SourceDirectory fromSourceRoot(PathFragment rootPath, PathFragment relativePath) { return new SourceDirectory(rootPath, PathFragment.EMPTY_FRAGMENT, relativePath, true); } @@ -70,23 +66,19 @@ public final class AndroidIdeInfoProvider implements TransitiveInfoProvider { this.isSource = isSource; } - /** - * The root relative path, {@link Artifact#getRootRelativePath()}. - */ + /** The root relative path, {@link Artifact#getRootRelativePath()}. */ public PathFragment getRelativePath() { return relativePath; } - /** - * The absolute path of the root that contains this directory, {@link Root#getPath()}. - */ + /** The absolute path of the root that contains this directory, {@link Root#getPath()}. */ public PathFragment getRootPath() { return rootPath; } /** - * The path from the execution root to the actual root. For source roots, this returns - * the empty fragment, {@link Root#getExecPath()}. + * The path from the execution root to the actual root. For source roots, this returns the empty + * fragment, {@link Root#getExecPath()}. */ public PathFragment getRootExecutionPathFragment() { return rootExecutionPathFragment; @@ -116,14 +108,19 @@ public final class AndroidIdeInfoProvider implements TransitiveInfoProvider { @Override public String toString() { - return "SourceDirectory [relativePath=" + relativePath + ", rootPath=" + rootPath - + ", executionRootPrefix=" + rootExecutionPathFragment + ", isSource=" + isSource + "]"; + return "SourceDirectory [relativePath=" + + relativePath + + ", rootPath=" + + rootPath + + ", executionRootPrefix=" + + rootExecutionPathFragment + + ", isSource=" + + isSource + + "]"; } } - /** - * Builder for {@link AndroidIdeInfoProvider} - */ + /** Builder for {@link AndroidIdeInfoProvider} */ public static class Builder { private Artifact manifest = null; private Artifact generatedManifest = null; @@ -228,32 +225,25 @@ public final class AndroidIdeInfoProvider implements TransitiveInfoProvider { return this; } - public Builder addIdlImportRoot(String idlImportRoot) { this.idlImportRoot = idlImportRoot; return this; } - /** - * Add "idl_srcs" contents. - */ + /** Add "idl_srcs" contents. */ public Builder addIdlSrcs(Collection<Artifact> idlSrcs) { this.idlSrcs.addAll(idlSrcs); addIdlDirs(idlSrcs); return this; } - /** - * Add the java files generated from "idl_srcs". - */ + /** Add the java files generated from "idl_srcs". */ public Builder addIdlGeneratedJavaFiles(Collection<Artifact> idlGeneratedJavaFiles) { this.idlGeneratedJavaFiles.addAll(idlGeneratedJavaFiles); return this; } - /** - * Add "idl_parcelables" contents. - */ + /** Add "idl_parcelables" contents. */ public Builder addIdlParcelables(Collection<Artifact> idlParcelables) { addIdlDirs(idlParcelables); return this; @@ -263,8 +253,7 @@ public final class AndroidIdeInfoProvider implements TransitiveInfoProvider { for (Artifact idl : idlArtifacts) { this.idlDirs.add( SourceDirectory.fromRoot( - idl.getRoot(), - idl.getRootRelativePath().getParentDirectory())); + idl.getRoot(), idl.getRootRelativePath().getParentDirectory())); } } @@ -389,8 +378,8 @@ public final class AndroidIdeInfoProvider implements TransitiveInfoProvider { } /** - * Returns true if the target defined Android resources. - * Exposes {@link LocalResourceContainer#definesAndroidResources(AttributeMap)} + * Returns true if the target defined Android resources. Exposes {@link + * LocalResourceContainer#definesAndroidResources(AttributeMap)} */ public boolean definesAndroidResources() { return this.definesAndroidResources; diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidIdlHelper.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidIdlHelper.java index 977455f85a..1fe6a2ec4e 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidIdlHelper.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidIdlHelper.java @@ -43,9 +43,7 @@ import java.util.Map.Entry; import java.util.Set; import javax.annotation.Nullable; -/** - * Helper class for Android IDL processing. - */ +/** Helper class for Android IDL processing. */ public class AndroidIdlHelper { /** @@ -84,30 +82,33 @@ public class AndroidIdlHelper { idlSourceJar = null; } - androidIdlProvider = createAndroidIdlProvider( - ruleContext, idlClassJar, idlSourceJar); + androidIdlProvider = createAndroidIdlProvider(ruleContext, idlClassJar, idlSourceJar); } /** * Adds the necessary providers to the {@code builder}. * - * Adds an {@link AndroidIdlProvider} to the target, and adds the transitive generated IDL jars to - * the IDL_JARS_OUTPUT_GROUP. This also generates the actions to compile the .aidl files to .java, - * as well as the .jar and .srcjar files consisting of only the IDL-generated source and class - * files. + * <p>Adds an {@link AndroidIdlProvider} to the target, and adds the transitive generated IDL jars + * to the IDL_JARS_OUTPUT_GROUP. This also generates the actions to compile the .aidl files to + * .java, as well as the .jar and .srcjar files consisting of only the IDL-generated source and + * class files. * * @param builder The target builder to add the providers to. * @param classJar The class jar to be separated into the IDL class jar. * @param manifestProtoOutput The manifest generated by JavaBuilder, for identifying IDL-generated * class files in the class jar. */ - public void addTransitiveInfoProviders(RuleConfiguredTargetBuilder builder, - Artifact classJar, Artifact manifestProtoOutput) { + public void addTransitiveInfoProviders( + RuleConfiguredTargetBuilder builder, Artifact classJar, Artifact manifestProtoOutput) { if (!translatedIdlSources.isEmpty()) { - generateAndroidIdlCompilationActions( - ruleContext, androidIdlProvider, translatedIdlSources); - createIdlClassJarAction(ruleContext, classJar, translatedIdlSources.values(), - manifestProtoOutput, idlClassJar, idlSourceJar); + generateAndroidIdlCompilationActions(ruleContext, androidIdlProvider, translatedIdlSources); + createIdlClassJarAction( + ruleContext, + classJar, + translatedIdlSources.values(), + manifestProtoOutput, + idlClassJar, + idlSourceJar); } builder .addProvider(AndroidIdlProvider.class, androidIdlProvider) @@ -121,16 +122,12 @@ public class AndroidIdlHelper { return hasExplicitlySpecifiedIdlImportRoot(ruleContext) ? getIdlImportRoot(ruleContext) : null; } - /** - * Returns the raw (non-processed) idl_srcs, not including parcelable marker files. - */ + /** Returns the raw (non-processed) idl_srcs, not including parcelable marker files. */ public Collection<Artifact> getIdlSources() { return translatedIdlSources.keySet(); } - /** - * Returns the idl_parcelables, consisting of parcelable marker files defined on this rule. - */ + /** Returns the idl_parcelables, consisting of parcelable marker files defined on this rule. */ public Collection<Artifact> getIdlParcelables() { return getIdlParcelables(ruleContext); } @@ -140,9 +137,7 @@ public class AndroidIdlHelper { return getIdlPreprocessed(ruleContext); } - /** - * Returns the generated Java sources created from the idl_srcs. - */ + /** Returns the generated Java sources created from the idl_srcs. */ public Collection<Artifact> getIdlGeneratedJavaSources() { return translatedIdlSources.values(); } @@ -174,8 +169,8 @@ public class AndroidIdlHelper { /** * Returns a new list with the idl libs added to the given list if necessary, or the same list. */ - public static ImmutableList<TransitiveInfoCollection> maybeAddSupportLibs(RuleContext ruleContext, - ImmutableList<TransitiveInfoCollection> deps) { + public static ImmutableList<TransitiveInfoCollection> maybeAddSupportLibs( + RuleContext ruleContext, ImmutableList<TransitiveInfoCollection> deps) { if (!hasIdlSrcs(ruleContext)) { return deps; } @@ -183,14 +178,11 @@ public class AndroidIdlHelper { if (aidlLib == null) { return deps; } - return ImmutableList.<TransitiveInfoCollection>builder() - .addAll(deps) - .add(aidlLib) - .build(); + return ImmutableList.<TransitiveInfoCollection>builder().addAll(deps).add(aidlLib).build(); } - public static void maybeAddSupportLibProguardConfigs(RuleContext ruleContext, - NestedSetBuilder<Artifact> proguardConfigsBuilder) { + public static void maybeAddSupportLibProguardConfigs( + RuleContext ruleContext, NestedSetBuilder<Artifact> proguardConfigsBuilder) { if (!hasIdlSrcs(ruleContext)) { return; } @@ -205,35 +197,34 @@ public class AndroidIdlHelper { proguardConfigsBuilder.addTransitive(provider.getTransitiveProguardSpecs()); } - /** - * Generates an artifact by replacing the extension of the input with the suffix. - */ + /** Generates an artifact by replacing the extension of the input with the suffix. */ private Artifact createIdlJar(Artifact baseArtifact, String suffix) { return ruleContext.getDerivedArtifact( FileSystemUtils.replaceExtension(baseArtifact.getRootRelativePath(), suffix), baseArtifact.getRoot()); } - /** - * Returns the idl_parcelables defined on the given rule. - */ + /** Returns the idl_parcelables defined on the given rule. */ private static ImmutableList<Artifact> getIdlParcelables(RuleContext ruleContext) { return ruleContext.getRule().isAttrDefined("idl_parcelables", BuildType.LABEL_LIST) - ? ImmutableList.copyOf(ruleContext.getPrerequisiteArtifacts( - "idl_parcelables", Mode.TARGET).filter(AndroidRuleClasses.ANDROID_IDL).list()) + ? ImmutableList.copyOf( + ruleContext + .getPrerequisiteArtifacts("idl_parcelables", Mode.TARGET) + .filter(AndroidRuleClasses.ANDROID_IDL) + .list()) : ImmutableList.<Artifact>of(); } - /** - * Returns the idl_srcs defined on the given rule. - */ + /** Returns the idl_srcs defined on the given rule. */ private static Collection<Artifact> getIdlSrcs(RuleContext ruleContext) { if (!ruleContext.getRule().isAttrDefined("idl_srcs", BuildType.LABEL_LIST)) { return ImmutableList.of(); } checkIdlSrcsSamePackage(ruleContext); - return ruleContext.getPrerequisiteArtifacts( - "idl_srcs", Mode.TARGET).filter(AndroidRuleClasses.ANDROID_IDL).list(); + return ruleContext + .getPrerequisiteArtifacts("idl_srcs", Mode.TARGET) + .filter(AndroidRuleClasses.ANDROID_IDL) + .list(); } /** @@ -241,16 +232,21 @@ public class AndroidIdlHelper { */ private static void checkIdlSrcsSamePackage(RuleContext ruleContext) { PathFragment packageName = ruleContext.getLabel().getPackageFragment(); - Collection<Artifact> idls = ruleContext - .getPrerequisiteArtifacts("idl_srcs", Mode.TARGET) - .filter(AndroidRuleClasses.ANDROID_IDL) - .list(); + Collection<Artifact> idls = + ruleContext + .getPrerequisiteArtifacts("idl_srcs", Mode.TARGET) + .filter(AndroidRuleClasses.ANDROID_IDL) + .list(); for (Artifact idl : idls) { Label idlLabel = idl.getOwner(); if (!packageName.equals(idlLabel.getPackageFragment())) { - ruleContext.attributeError("idl_srcs", "do not import '" + idlLabel + "' directly. " - + "You should either move the file to this package or depend on " - + "an appropriate rule there"); + ruleContext.attributeError( + "idl_srcs", + "do not import '" + + idlLabel + + "' directly. " + + "You should either move the file to this package or depend on " + + "an appropriate rule there"); } } } @@ -268,9 +264,10 @@ public class AndroidIdlHelper { for (Artifact idl : idls) { // Reconstruct the package tree under <rule>_aidl to avoid a name conflict // if the same AIDL files are used in multiple targets. - PathFragment javaOutputPath = FileSystemUtils.replaceExtension( - PathFragment.create(ruleName + "_aidl").getRelative(idl.getRootRelativePath()), - ".java"); + PathFragment javaOutputPath = + FileSystemUtils.replaceExtension( + PathFragment.create(ruleName + "_aidl").getRelative(idl.getRootRelativePath()), + ".java"); Artifact output = ruleContext.getGenfilesArtifact(javaOutputPath.getPathString()); outputJavaSources.put(idl, output); } @@ -303,9 +300,12 @@ public class AndroidIdlHelper { } for (Entry<Artifact, Artifact> entry : translatedIdlSources.entrySet()) { - createAndroidIdlAction(ruleContext, entry.getKey(), + createAndroidIdlAction( + ruleContext, + entry.getKey(), transitiveIdlImportData.getTransitiveIdlImports(), - entry.getValue(), preprocessedArgs); + entry.getValue(), + preprocessedArgs); } } @@ -328,11 +328,13 @@ public class AndroidIdlHelper { Artifact idlClassJar, Artifact idlSourceJar) { String basename = FileSystemUtils.removeExtension(classJar.getExecPath().getBaseName()); - PathFragment idlTempDir = ruleContext.getConfiguration() - .getBinDirectory(ruleContext.getRule().getRepository()) - .getExecPath() - .getRelative(ruleContext.getUniqueDirectory("_idl")) - .getRelative(basename + "_temp"); + PathFragment idlTempDir = + ruleContext + .getConfiguration() + .getBinDirectory(ruleContext.getRule().getRepository()) + .getExecPath() + .getRelative(ruleContext.getUniqueDirectory("_idl")) + .getRelative(basename + "_temp"); ruleContext.registerAction( new SpawnAction.Builder() .addInput(manifestProtoOutput) @@ -366,9 +368,12 @@ public class AndroidIdlHelper { * @param output The .java file where the .aidl file will be converted to. * @param importArgs The arguments defining the import roots and framework .aidl. */ - private static void createAndroidIdlAction(RuleContext ruleContext, - Artifact idl, NestedSet<Artifact> idlImports, - Artifact output, List<String> importArgs) { + private static void createAndroidIdlAction( + RuleContext ruleContext, + Artifact idl, + NestedSet<Artifact> idlImports, + Artifact output, + List<String> importArgs) { AndroidSdkProvider sdk = AndroidSdkProvider.fromRuleContext(ruleContext); ruleContext.registerAction( new SpawnAction.Builder() @@ -391,8 +396,8 @@ public class AndroidIdlHelper { } /** - * Returns the union of "idl_srcs" and "idl_parcelables", i.e. all .aidl files - * provided by this library that contribute to .aidl --> .java compilation. + * Returns the union of "idl_srcs" and "idl_parcelables", i.e. all .aidl files provided by this + * library that contribute to .aidl --> .java compilation. */ private static Collection<Artifact> getIdlImports(RuleContext ruleContext) { return ImmutableList.<Artifact>builder() @@ -413,8 +418,8 @@ public class AndroidIdlHelper { * one does not exist. * @return A provider containing the collected data, suitable to be provided by this rule. */ - private static AndroidIdlProvider createAndroidIdlProvider(RuleContext ruleContext, - @Nullable Artifact idlClassJar, @Nullable Artifact idlSourceJar) { + private static AndroidIdlProvider createAndroidIdlProvider( + RuleContext ruleContext, @Nullable Artifact idlClassJar, @Nullable Artifact idlSourceJar) { NestedSetBuilder<String> rootsBuilder = NestedSetBuilder.naiveLinkOrder(); NestedSetBuilder<Artifact> importsBuilder = NestedSetBuilder.naiveLinkOrder(); NestedSetBuilder<Artifact> jarsBuilder = NestedSetBuilder.stableOrder(); @@ -426,8 +431,9 @@ public class AndroidIdlHelper { jarsBuilder.add(idlSourceJar); } - for (AndroidIdlProvider dep : AndroidCommon.getTransitivePrerequisites( - ruleContext, Mode.TARGET, AndroidIdlProvider.class)) { + for (AndroidIdlProvider dep : + AndroidCommon.getTransitivePrerequisites( + ruleContext, Mode.TARGET, AndroidIdlProvider.class)) { rootsBuilder.addTransitive(dep.getTransitiveIdlImportRoots()); importsBuilder.addTransitive(dep.getTransitiveIdlImports()); preprocessedBuilder.addTransitive(dep.getTransitiveIdlPreprocessed()); @@ -439,8 +445,8 @@ public class AndroidIdlHelper { for (Artifact idlImport : idlImports) { PathFragment javaRoot = JavaUtil.getJavaRoot(idlImport.getExecPath()); if (javaRoot == null) { - ruleContext.ruleError("Cannot determine java/javatests root for import " - + idlImport.getExecPathString()); + ruleContext.ruleError( + "Cannot determine java/javatests root for import " + idlImport.getExecPathString()); } else { rootsBuilder.add(javaRoot.toString()); } @@ -449,9 +455,12 @@ public class AndroidIdlHelper { PathFragment pkgFragment = ruleContext.getLabel().getPackageFragment(); Set<PathFragment> idlImportRoots = new HashSet<>(); for (Artifact idlImport : idlImports) { - idlImportRoots.add(idlImport.getRoot().getExecPath() - .getRelative(pkgFragment) - .getRelative(getIdlImportRoot(ruleContext))); + idlImportRoots.add( + idlImport + .getRoot() + .getExecPath() + .getRelative(pkgFragment) + .getRelative(getIdlImportRoot(ruleContext))); } for (PathFragment idlImportRoot : idlImportRoots) { rootsBuilder.add(idlImportRoot.toString()); @@ -469,13 +478,12 @@ public class AndroidIdlHelper { preprocessedBuilder.build()); } - /** - * Checks that idl_import_root is only set if idl_srcs or idl_parcelables was. - */ + /** Checks that idl_import_root is only set if idl_srcs or idl_parcelables was. */ private static void checkIdlRootImport(RuleContext ruleContext) { if (hasExplicitlySpecifiedIdlImportRoot(ruleContext) && !hasExplicitlySpecifiedIdlSrcsOrParcelables(ruleContext)) { - ruleContext.attributeError("idl_import_root", + ruleContext.attributeError( + "idl_import_root", "Neither idl_srcs nor idl_parcelables were specified, " + "but 'idl_import_root' attribute was set"); } diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidInstrumentationTest.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidInstrumentationTest.java index 20e9f4bbb8..30e26d1803 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidInstrumentationTest.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidInstrumentationTest.java @@ -294,9 +294,7 @@ public class AndroidInstrumentationTest implements RuleConfiguredTargetFactory { private static Iterable<AndroidDeviceScriptFixtureInfoProvider> getDeviceScriptFixtures( RuleContext ruleContext) { return ruleContext.getPrerequisites( - "fixtures", - Mode.TARGET, - AndroidDeviceScriptFixtureInfoProvider.SKYLARK_CONSTRUCTOR); + "fixtures", Mode.TARGET, AndroidDeviceScriptFixtureInfoProvider.SKYLARK_CONSTRUCTOR); } private static String getDeviceBrokerType(RuleContext ruleContext) { @@ -315,8 +313,8 @@ public class AndroidInstrumentationTest implements RuleConfiguredTargetFactory { private static String getTestSuitePropertyName(RuleContext ruleContext) throws RuleErrorException { try { - return ResourceFileLoader - .loadResource(AndroidInstrumentationTest.class, TEST_SUITE_PROPERTY_NAME_FILE) + return ResourceFileLoader.loadResource( + AndroidInstrumentationTest.class, TEST_SUITE_PROPERTY_NAME_FILE) .trim(); } catch (IOException e) { ruleContext.throwWithRuleError("Cannot load test suite property name: " + e.getMessage()); @@ -333,12 +331,9 @@ public class AndroidInstrumentationTest implements RuleConfiguredTargetFactory { */ private static ExecutionInfo getExecutionInfoProvider(RuleContext ruleContext) { ExecutionInfo executionInfo = - ruleContext.getPrerequisite( - "target_device", Mode.HOST, ExecutionInfo.PROVIDER); + ruleContext.getPrerequisite("target_device", Mode.HOST, ExecutionInfo.PROVIDER); ImmutableMap<String, String> executionRequirements = - (executionInfo != null) - ? executionInfo.getExecutionInfo() - : ImmutableMap.of(); + (executionInfo != null) ? executionInfo.getExecutionInfo() : ImmutableMap.of(); return new ExecutionInfo(executionRequirements); } } diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLibrary.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLibrary.java index eeefaddcc7..bcc8fdcaf0 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLibrary.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLibrary.java @@ -41,23 +41,21 @@ import com.google.devtools.build.lib.rules.java.ProguardLibrary; import com.google.devtools.build.lib.rules.java.ProguardSpecProvider; import com.google.devtools.build.lib.syntax.Type; -/** - * An implementation for the "android_library" rule. - */ +/** An implementation for the "android_library" rule. */ public abstract class AndroidLibrary implements RuleConfiguredTargetFactory { protected abstract JavaSemantics createJavaSemantics(); + protected abstract AndroidSemantics createAndroidSemantics(); - /** - * Checks expected rule invariants, throws rule errors if anything is set wrong. - */ + /** Checks expected rule invariants, throws rule errors if anything is set wrong. */ private static void validateRuleContext(RuleContext ruleContext) throws InterruptedException, RuleErrorException { if (ruleContext.attributes().isAttributeValueExplicitlySpecified("resources") - && DataBinding.isEnabled(ruleContext)) { - ruleContext.throwWithRuleError("Data binding doesn't work with the \"resources\" attribute. " - + "Use \"resource_files\" instead."); + && DataBinding.isEnabled(ruleContext)) { + ruleContext.throwWithRuleError( + "Data binding doesn't work with the \"resources\" attribute. " + + "Use \"resource_files\" instead."); } AndroidCommon.validateResourcesAttribute(ruleContext); @@ -65,12 +63,12 @@ public abstract class AndroidLibrary implements RuleConfiguredTargetFactory { /** * TODO(b/14473160): Remove when deps are no longer implicitly exported. * - * Warn if android_library rule contains deps without srcs or locally-used resources. - * Such deps are implicitly exported (deprecated behavior), and will soon be disallowed - * entirely. + * <p>Warn if android_library rule contains deps without srcs or locally-used resources. Such + * deps are implicitly exported (deprecated behavior), and will soon be disallowed entirely. */ if (usesDeprecatedImplicitExport(ruleContext)) { - String message = "android_library will be deprecating the use of deps to export " + String message = + "android_library will be deprecating the use of deps to export " + "targets implicitly. Please use android_library.exports to explicitly specify " + "targets this rule exports"; AndroidConfiguration androidConfig = ruleContext.getFragment(AndroidConfiguration.class); @@ -85,14 +83,13 @@ public abstract class AndroidLibrary implements RuleConfiguredTargetFactory { /** * TODO(b/14473160): Remove when deps are no longer implicitly exported. * - * Returns true if the rule (possibly) relies on the implicit dep exports behavior. + * <p>Returns true if the rule (possibly) relies on the implicit dep exports behavior. * - * If this returns true, then the rule *is* exporting deps implicitly, and does not have - * any srcs or locally-used resources consuming the deps. + * <p>If this returns true, then the rule *is* exporting deps implicitly, and does not have any + * srcs or locally-used resources consuming the deps. * - * Else, this rule either: - * 1) is not using deps - * 2) has another deps-consuming attribute (src, locally-used resources) + * <p>Else, this rule either is not using deps or has another deps-consuming attribute (src, + * locally-used resources) */ private static boolean usesDeprecatedImplicitExport(RuleContext ruleContext) throws RuleErrorException { @@ -103,7 +100,7 @@ public abstract class AndroidLibrary implements RuleConfiguredTargetFactory { return false; } - String[] labelListAttrs = { "srcs", "idl_srcs", "assets", "resource_files" }; + String[] labelListAttrs = {"srcs", "idl_srcs", "assets", "resource_files"}; for (String attr : labelListAttrs) { if (attrs.isAttributeValueExplicitlySpecified(attr) && !attrs.get(attr, BuildType.LABEL_LIST).isEmpty()) { @@ -199,8 +196,10 @@ public abstract class AndroidLibrary implements RuleConfiguredTargetFactory { final ResourceApk resourceApk; if (definesLocalResources) { - ApplicationManifest applicationManifest = androidSemantics.getManifestForRule(ruleContext) - .renamePackage(ruleContext, AndroidCommon.getJavaPackage(ruleContext)); + ApplicationManifest applicationManifest = + androidSemantics + .getManifestForRule(ruleContext) + .renamePackage(ruleContext, AndroidCommon.getJavaPackage(ruleContext)); resourceApk = applicationManifest.packLibraryWithDataAndResources( ruleContext, @@ -224,22 +223,22 @@ public abstract class AndroidLibrary implements RuleConfiguredTargetFactory { && JavaCommon.isNeverLink(ruleContext))); } - JavaTargetAttributes javaTargetAttributes = androidCommon.init( - javaSemantics, - androidSemantics, - resourceApk, - false /* addCoverageSupport */, - true /* collectJavaCompilationArgs */, - false /* isBinary */, - null /* excludedRuntimeArtifacts */); + JavaTargetAttributes javaTargetAttributes = + androidCommon.init( + javaSemantics, + androidSemantics, + resourceApk, + false /* addCoverageSupport */, + true /* collectJavaCompilationArgs */, + false /* isBinary */, + null /* excludedRuntimeArtifacts */); if (javaTargetAttributes == null) { return null; } Artifact classesJar = ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_LIBRARY_CLASS_JAR); - Artifact aarOut = ruleContext.getImplicitOutputArtifact( - AndroidRuleClasses.ANDROID_LIBRARY_AAR); + Artifact aarOut = ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_LIBRARY_AAR); final ResourceContainer primaryResources; final Aar aar; @@ -252,15 +251,17 @@ public abstract class AndroidLibrary implements RuleConfiguredTargetFactory { aar = Aar.create(aarOut, applicationManifest.getManifest()); addAarToProvider(aar, transitiveAars, transitiveAarArtifacts); } else if (AndroidCommon.getAndroidResources(ruleContext) != null) { - primaryResources = Iterables.getOnlyElement( - AndroidCommon.getAndroidResources(ruleContext).getDirectAndroidResources()); + primaryResources = + Iterables.getOnlyElement( + AndroidCommon.getAndroidResources(ruleContext).getDirectAndroidResources()); aar = Aar.create(aarOut, primaryResources.getManifest()); addAarToProvider(aar, transitiveAars, transitiveAarArtifacts); } else { // there are no local resources and resources attribute was not specified either aar = null; - ApplicationManifest applicationManifest = ApplicationManifest.generatedManifest(ruleContext) - .renamePackage(ruleContext, AndroidCommon.getJavaPackage(ruleContext)); + ApplicationManifest applicationManifest = + ApplicationManifest.generatedManifest(ruleContext) + .renamePackage(ruleContext, AndroidCommon.getJavaPackage(ruleContext)); String javaPackage = AndroidCommon.getJavaPackage(ruleContext); @@ -275,30 +276,32 @@ public abstract class AndroidLibrary implements RuleConfiguredTargetFactory { .setRTxt(ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_R_TXT)) .build(); - primaryResources = new AndroidResourcesProcessorBuilder(ruleContext) - .setLibrary(true) - .setRTxtOut(resourceContainer.getRTxt()) - .setManifestOut(ruleContext.getImplicitOutputArtifact( - AndroidRuleClasses.ANDROID_PROCESSED_MANIFEST)) - .setSourceJarOut(resourceContainer.getJavaSourceJar()) - .setJavaPackage(resourceContainer.getJavaPackage()) - .withPrimary(resourceContainer) - .withDependencies(resourceApk.getResourceDependencies()) - .setDebug(ruleContext.getConfiguration().getCompilationMode() != CompilationMode.OPT) - .setThrowOnResourceConflict( - ruleContext.getFragment(AndroidConfiguration.class).throwOnResourceConflict()) - .build(ruleContext); + primaryResources = + new AndroidResourcesProcessorBuilder(ruleContext) + .setLibrary(true) + .setRTxtOut(resourceContainer.getRTxt()) + .setManifestOut( + ruleContext.getImplicitOutputArtifact( + AndroidRuleClasses.ANDROID_PROCESSED_MANIFEST)) + .setSourceJarOut(resourceContainer.getJavaSourceJar()) + .setJavaPackage(resourceContainer.getJavaPackage()) + .withPrimary(resourceContainer) + .withDependencies(resourceApk.getResourceDependencies()) + .setDebug(ruleContext.getConfiguration().getCompilationMode() != CompilationMode.OPT) + .setThrowOnResourceConflict( + ruleContext.getFragment(AndroidConfiguration.class).throwOnResourceConflict()) + .build(ruleContext); } new AarGeneratorBuilder(ruleContext) - .withPrimary(primaryResources) - .withManifest(aar != null ? aar.getManifest() : primaryResources.getManifest()) - .withRtxt(primaryResources.getRTxt()) - .withClasses(classesJar) - .setAAROut(aarOut) - .setThrowOnResourceConflict( - ruleContext.getFragment(AndroidConfiguration.class).throwOnResourceConflict()) - .build(ruleContext); + .withPrimary(primaryResources) + .withManifest(aar != null ? aar.getManifest() : primaryResources.getManifest()) + .withRtxt(primaryResources.getRTxt()) + .withClasses(classesJar) + .setAAROut(aarOut) + .setThrowOnResourceConflict( + ruleContext.getFragment(AndroidConfiguration.class).throwOnResourceConflict()) + .build(ruleContext); boolean isResourcesOnly = true; for (String attr : ruleContext.attributes().getAttributeNames()) { @@ -375,13 +378,14 @@ public abstract class AndroidLibrary implements RuleConfiguredTargetFactory { return; } - ResourceContainer container = Iterables.getOnlyElement( - resources.getDirectAndroidResources()); + ResourceContainer container = Iterables.getOnlyElement(resources.getDirectAndroidResources()); if (container.getConstantsInlined() && !container.getArtifacts(ResourceType.RESOURCES).isEmpty()) { - ruleContext.ruleError("This android library has some resources assigned, so the target '" - + resources.getLabel() + "' should have the attribute inline_constants set to 0"); + ruleContext.ruleError( + "This android library has some resources assigned, so the target '" + + resources.getLabel() + + "' should have the attribute inline_constants set to 0"); } } @@ -389,8 +393,9 @@ public abstract class AndroidLibrary implements RuleConfiguredTargetFactory { RuleContext ruleContext, NestedSetBuilder<Aar> transitiveAars, NestedSetBuilder<Artifact> transitiveAarArtifacts) { - for (AndroidLibraryAarProvider library : AndroidCommon.getTransitivePrerequisites( - ruleContext, Mode.TARGET, AndroidLibraryAarProvider.class)) { + for (AndroidLibraryAarProvider library : + AndroidCommon.getTransitivePrerequisites( + ruleContext, Mode.TARGET, AndroidLibraryAarProvider.class)) { transitiveAars.addTransitive(library.getTransitiveAars()); transitiveAarArtifacts.addTransitive(library.getTransitiveAarArtifacts()); } @@ -407,4 +412,3 @@ public abstract class AndroidLibrary implements RuleConfiguredTargetFactory { return builder; } } - diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLibraryAarProvider.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLibraryAarProvider.java index d4a8a8afdd..2c9df75b3f 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLibraryAarProvider.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLibraryAarProvider.java @@ -35,7 +35,8 @@ public abstract class AndroidLibraryAarProvider implements TransitiveInfoProvide return new AutoValue_AndroidLibraryAarProvider(aar, transitiveAars, transitiveAarArtifacts); } - @Nullable public abstract Aar getAar(); + @Nullable + public abstract Aar getAar(); public abstract NestedSet<Aar> getTransitiveAars(); diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLibraryBaseRule.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLibraryBaseRule.java index 4ccd2967b8..78ffb0693e 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLibraryBaseRule.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLibraryBaseRule.java @@ -33,9 +33,7 @@ import com.google.devtools.build.lib.rules.java.JavaSemantics; import com.google.devtools.build.lib.rules.java.ProguardLibraryRule; import com.google.devtools.build.lib.util.FileTypeSet; -/** - * Rule definition for the android_library rule. - */ +/** Rule definition for the android_library rule. */ public final class AndroidLibraryBaseRule implements RuleDefinition { private final AndroidNeverlinkAspect androidNeverlinkAspect; diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLocalTestBase.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLocalTestBase.java index 391408a59b..91bf58001c 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLocalTestBase.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLocalTestBase.java @@ -315,7 +315,8 @@ public abstract class AndroidLocalTestBase implements RuleConfiguredTargetFactor NestedSet<Artifact> extraFilesToRun = NestedSetBuilder.create(Order.STABLE_ORDER, runfilesSupport.getRunfilesMiddleman()); - JavaInfo javaInfo = javaInfoBuilder + JavaInfo javaInfo = + javaInfoBuilder .addProvider(JavaSourceJarsProvider.class, sourceJarsProvider) .addProvider(JavaRuleOutputJarsProvider.class, ruleOutputJarsProvider) .build(); @@ -366,6 +367,7 @@ public abstract class AndroidLocalTestBase implements RuleConfiguredTargetFactor * Returns a merged {@link ApplicationManifest} for the rule. The final merged manifest will be * merged into the manifest provided on the rule, or into a placeholder manifest if one is not * provided + * * @throws InterruptedException * @throws RuleErrorException */ @@ -388,8 +390,10 @@ public abstract class AndroidLocalTestBase implements RuleConfiguredTargetFactor return applicationManifest; } - /** Returns the transitive closure of resource dependencies, including those specified on the rule - * if present. */ + /** + * Returns the transitive closure of resource dependencies, including those specified on the rule + * if present. + */ private ResourceDependencies getResourceDependencies(RuleContext ruleContext) { return LocalResourceContainer.definesAndroidResources(ruleContext.attributes()) ? ResourceDependencies.fromRuleDeps(ruleContext, false /* neverlink */) @@ -545,6 +549,7 @@ public abstract class AndroidLocalTestBase implements RuleConfiguredTargetFactor /** * Add compilation dependencies to the java compilation helper. + * * @throws RuleErrorException */ protected abstract JavaCompilationHelper getJavaCompilationHelperWithDependencies( diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLocalTestBaseRule.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLocalTestBaseRule.java index ef13513cda..49c5dba321 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLocalTestBaseRule.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidLocalTestBaseRule.java @@ -165,4 +165,4 @@ public class AndroidLocalTestBaseRule implements RuleDefinition { .type(RuleClassType.ABSTRACT) .build(); } -}
\ No newline at end of file +} diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidManifestMergeHelper.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidManifestMergeHelper.java index 01fdbf174c..567ef49401 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidManifestMergeHelper.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidManifestMergeHelper.java @@ -24,9 +24,12 @@ public final class AndroidManifestMergeHelper { private AndroidManifestMergeHelper() {} - public static void createMergeManifestAction(RuleContext ruleContext, - Artifact merger, Iterable<Artifact> mergees, - Collection<String> excludePermissions, Artifact mergedManifest) { + public static void createMergeManifestAction( + RuleContext ruleContext, + Artifact merger, + Iterable<Artifact> mergees, + Collection<String> excludePermissions, + Artifact mergedManifest) { CustomCommandLine.Builder commandLine = CustomCommandLine.builder(); commandLine.addPrefixedExecPath("--merger=", merger); for (Artifact mergee : mergees) { @@ -51,4 +54,3 @@ public final class AndroidManifestMergeHelper { .build(ruleContext)); } } - diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourceMergingActionBuilder.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourceMergingActionBuilder.java index 0399c577d0..14635e626a 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourceMergingActionBuilder.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourceMergingActionBuilder.java @@ -110,8 +110,9 @@ public class AndroidResourceMergingActionBuilder { /** * The output zip for resource-processed data binding expressions (i.e. a zip of .xml files). - * If null, data binding processing is skipped (and data binding expressions aren't allowed in - * layout resources). + * + * <p>If null, data binding processing is skipped (and data binding expressions aren't allowed in + * layout resources). */ public AndroidResourceMergingActionBuilder setDataBindingInfoZip(Artifact zip) { this.dataBindingInfoZip = zip; @@ -129,8 +130,7 @@ public class AndroidResourceMergingActionBuilder { return this; } - public AndroidResourceMergingActionBuilder setUseCompiledMerge( - boolean useCompiledMerge) { + public AndroidResourceMergingActionBuilder setUseCompiledMerge(boolean useCompiledMerge) { this.useCompiledMerge = useCompiledMerge; return this; } @@ -166,14 +166,13 @@ public class AndroidResourceMergingActionBuilder { NestedSetBuilder<Artifact> inputs = createInputsForBuilder(builder); Preconditions.checkNotNull(primary); - builder.add("--primaryData", - RESOURCE_CONTAINER_TO_ARG_FOR_COMPILED.apply(primary)); + builder.add("--primaryData", RESOURCE_CONTAINER_TO_ARG_FOR_COMPILED.apply(primary)); inputs.addAll(primary.getArtifacts()); inputs.add(primary.getCompiledSymbols()); if (dependencies != null) { - ResourceContainerConverter.addToCommandLine(dependencies, builder, - RESOURCE_CONTAINER_TO_ARG_FOR_COMPILED); + ResourceContainerConverter.addToCommandLine( + dependencies, builder, RESOURCE_CONTAINER_TO_ARG_FOR_COMPILED); inputs.addTransitive(dependencies.getTransitiveResources()); inputs.addTransitive(dependencies.getTransitiveAssets()); inputs.addTransitive(dependencies.getTransitiveCompiledSymbols()); @@ -191,13 +190,11 @@ public class AndroidResourceMergingActionBuilder { .addCommandLine(builder.build(), compiledParamFileInfo.build()) .setExecutable( ruleContext.getExecutablePrerequisite("$android_resources_busybox", Mode.HOST)) - .setProgressMessage("Merging compiled Android resources for %s", - ruleContext.getLabel()) + .setProgressMessage("Merging compiled Android resources for %s", ruleContext.getLabel()) .setMnemonic("AndroidCompiledResourceMerger") .build(context)); } - private void buildParsedResourceMergingAction( CustomCommandLine.Builder builder, List<Artifact> outputs, @@ -263,13 +260,9 @@ public class AndroidResourceMergingActionBuilder { } CustomCommandLine.Builder jarAndManifestBuilder = - useCompiledMerge - ? compiledMergeBuilder - : parsedMergeBuilder; + useCompiledMerge ? compiledMergeBuilder : parsedMergeBuilder; List<Artifact> jarAndManifestOutputs = - useCompiledMerge - ? compiledMergeOutputs - : parsedMergeOutputs; + useCompiledMerge ? compiledMergeOutputs : parsedMergeOutputs; if (classJarOut != null) { jarAndManifestBuilder.addExecPath("--classJarOutput", classJarOut); diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourceParsingActionBuilder.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourceParsingActionBuilder.java index 84ab6f9161..ffcb6b773b 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourceParsingActionBuilder.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourceParsingActionBuilder.java @@ -54,25 +54,19 @@ public class AndroidResourceParsingActionBuilder { private Artifact compiledSymbols; private Artifact dataBindingInfoZip; - /** - * @param ruleContext The RuleContext that was used to create the SpawnAction.Builder. - */ + /** @param ruleContext The RuleContext that was used to create the SpawnAction.Builder. */ public AndroidResourceParsingActionBuilder(RuleContext ruleContext) { this.ruleContext = ruleContext; this.sdk = AndroidSdkProvider.fromRuleContext(ruleContext); } - /** - * Set the resource container to parse. - */ + /** Set the resource container to parse. */ public AndroidResourceParsingActionBuilder setParse(LocalResourceContainer primary) { this.primary = primary; return this; } - /** - * Set the artifact location for the output protobuf. - */ + /** Set the artifact location for the output protobuf. */ public AndroidResourceParsingActionBuilder setOutput(Artifact output) { this.output = output; return this; @@ -97,8 +91,7 @@ public class AndroidResourceParsingActionBuilder { private static class ResourceContainerToArg implements Function<LocalResourceContainer, String> { - public ResourceContainerToArg() { - } + public ResourceContainerToArg() {} @Override public String apply(LocalResourceContainer container) { @@ -113,8 +106,7 @@ public class AndroidResourceParsingActionBuilder { private static class ResourceContainerToArtifacts implements Function<LocalResourceContainer, NestedSet<Artifact>> { - public ResourceContainerToArtifacts() { - } + public ResourceContainerToArtifacts() {} @Override public NestedSet<Artifact> apply(LocalResourceContainer container) { diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourceValidatorActionBuilder.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourceValidatorActionBuilder.java index af55c61526..251813a66f 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourceValidatorActionBuilder.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourceValidatorActionBuilder.java @@ -175,11 +175,10 @@ public class AndroidResourceValidatorActionBuilder { } if (!resourceDeps.getTransitiveCompiledSymbols().isEmpty()) { - builder - .addExecPaths( - "--compiledDep", - VectorArg.join(context.getConfiguration().getHostPathSeparator()) - .each(resourceDeps.getTransitiveCompiledSymbols())); + builder.addExecPaths( + "--compiledDep", + VectorArg.join(context.getConfiguration().getHostPathSeparator()) + .each(resourceDeps.getTransitiveCompiledSymbols())); inputs.addAll(resourceDeps.getTransitiveCompiledSymbols()); } @@ -283,9 +282,6 @@ public class AndroidResourceValidatorActionBuilder { .build(context)); // Return the full set of validated transitive dependencies. - return primary.toBuilder() - .setJavaSourceJar(sourceJarOut) - .setRTxt(rTxtOut) - .build(); + return primary.toBuilder().setJavaSourceJar(sourceJarOut).setRTxt(rTxtOut).build(); } } diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourcesProcessorBuilder.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourcesProcessorBuilder.java index feda3f6a47..2275c57462 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourcesProcessorBuilder.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourcesProcessorBuilder.java @@ -33,9 +33,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -/** - * Builder for creating resource processing action. - */ +/** Builder for creating resource processing action. */ public class AndroidResourcesProcessorBuilder { private static final ResourceContainerConverter.ToArg AAPT2_RESOURCE_DEP_TO_ARG = @@ -106,9 +104,7 @@ public class AndroidResourcesProcessorBuilder { private boolean useCompiledResourcesForMerge; private boolean isTestWithResources = false; - /** - * @param ruleContext The RuleContext that was used to create the SpawnAction.Builder. - */ + /** @param ruleContext The RuleContext that was used to create the SpawnAction.Builder. */ public AndroidResourcesProcessorBuilder(RuleContext ruleContext) { this.sdk = AndroidSdkProvider.fromRuleContext(ruleContext); this.ruleContext = ruleContext; @@ -116,8 +112,8 @@ public class AndroidResourcesProcessorBuilder { } /** - * The primary resource for merging. This resource will overwrite any resource or data - * value in the transitive closure. + * The primary resource for merging. This resource will overwrite any resource or data value in + * the transitive closure. */ public AndroidResourcesProcessorBuilder withPrimary(ResourceContainer primary) { this.primary = primary; @@ -126,7 +122,8 @@ public class AndroidResourcesProcessorBuilder { /** * The output zip for resource-processed data binding expressions (i.e. a zip of .xml files). - * If null, data binding processing is skipped (and data binding expressions aren't allowed in + * + * <p>If null, data binding processing is skipped (and data binding expressions aren't allowed in * layout resources). */ public AndroidResourcesProcessorBuilder setDataBindingInfoZip(Artifact zip) { @@ -277,7 +274,6 @@ public class AndroidResourcesProcessorBuilder { return this; } - private ResourceContainer createAapt2ApkAction(ActionConstructionContext context) { List<Artifact> outs = new ArrayList<>(); // TODO(corysmith): Convert to an immutable list builder, as there is no benefit to a NestedSet diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourcesProvider.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourcesProvider.java index 66671dc5d8..45539aef6a 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourcesProvider.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourcesProvider.java @@ -82,7 +82,7 @@ public abstract class AndroidResourcesProvider implements TransitiveInfoProvider * Returns whether the targets contained within this provider only represent android resources or * also contain other information. * - * TODO(b/30307842): Remove this once android_resources is fully removed. + * <p>TODO(b/30307842): Remove this once android_resources is fully removed. */ public abstract boolean getIsResourcesOnly(); diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidRuntimeJarProvider.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidRuntimeJarProvider.java index 1c949850ca..5985833bc4 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidRuntimeJarProvider.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidRuntimeJarProvider.java @@ -36,17 +36,14 @@ public class AndroidRuntimeJarProvider implements TransitiveInfoProvider { new AndroidRuntimeJarProvider( NestedSetBuilder.<ImmutableMap<Artifact, Artifact>>emptySet(STABLE_ORDER)); - /** - * Builder for {@link AndroidRuntimeJarProvider}. - */ + /** Builder for {@link AndroidRuntimeJarProvider}. */ public static class Builder { private final ImmutableMap.Builder<Artifact, Artifact> newlyDesugared = ImmutableMap.builder(); private final NestedSetBuilder<ImmutableMap<Artifact, Artifact>> transitiveMappings = NestedSetBuilder.stableOrder(); - public Builder() { - } + public Builder() {} /** * Copies all mappings from the given providers, which is useful to aggregate providers from @@ -65,9 +62,7 @@ public class AndroidRuntimeJarProvider implements TransitiveInfoProvider { return this; } - /** - * Returns the finished {@link AndroidRuntimeJarProvider}. - */ + /** Returns the finished {@link AndroidRuntimeJarProvider}. */ public AndroidRuntimeJarProvider build() { return new AndroidRuntimeJarProvider(transitiveMappings.add(newlyDesugared.build()).build()); } diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidSdk.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidSdk.java index d44353e5e9..9f79e3a752 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidSdk.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidSdk.java @@ -28,9 +28,7 @@ import com.google.devtools.build.lib.packages.AggregatingAttributeMapper; import com.google.devtools.build.lib.rules.java.JavaConfiguration; import com.google.devtools.build.lib.syntax.Type; -/** - * Implementation of the {@code android_sdk} rule. - */ +/** Implementation of the {@code android_sdk} rule. */ public class AndroidSdk implements RuleConfiguredTargetFactory { @Override public ConfiguredTarget create(RuleContext ruleContext) @@ -42,19 +40,19 @@ public class AndroidSdk implements RuleConfiguredTargetFactory { ? ruleContext.getExecutablePrerequisite("proguard", Mode.HOST) : ruleContext.getExecutablePrerequisite(":proguard", Mode.HOST); - String buildToolsVersion = AggregatingAttributeMapper.of(ruleContext.getRule()) - .get("build_tools_version", Type.STRING); + String buildToolsVersion = + AggregatingAttributeMapper.of(ruleContext.getRule()) + .get("build_tools_version", Type.STRING); FilesToRunProvider aidl = ruleContext.getExecutablePrerequisite("aidl", Mode.HOST); FilesToRunProvider aapt = ruleContext.getExecutablePrerequisite("aapt", Mode.HOST); FilesToRunProvider aapt2 = ruleContext.getExecutablePrerequisite("aapt2", Mode.HOST); - FilesToRunProvider apkBuilder = ruleContext.getExecutablePrerequisite( - "apkbuilder", Mode.HOST); + FilesToRunProvider apkBuilder = ruleContext.getExecutablePrerequisite("apkbuilder", Mode.HOST); FilesToRunProvider apkSigner = ruleContext.getExecutablePrerequisite("apksigner", Mode.HOST); FilesToRunProvider adb = ruleContext.getExecutablePrerequisite("adb", Mode.HOST); FilesToRunProvider dx = ruleContext.getExecutablePrerequisite("dx", Mode.HOST); - FilesToRunProvider mainDexListCreator = ruleContext.getExecutablePrerequisite( - "main_dex_list_creator", Mode.HOST); + FilesToRunProvider mainDexListCreator = + ruleContext.getExecutablePrerequisite("main_dex_list_creator", Mode.HOST); FilesToRunProvider zipalign = ruleContext.getExecutablePrerequisite("zipalign", Mode.HOST); Artifact frameworkAidl = ruleContext.getPrerequisiteArtifact("framework_aidl", Mode.HOST); TransitiveInfoCollection aidlLib = ruleContext.getPrerequisite("aidl_lib", Mode.TARGET); diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidSdkProvider.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidSdkProvider.java index 741f17d23a..f4667fb305 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidSdkProvider.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidSdkProvider.java @@ -77,15 +77,13 @@ public abstract class AndroidSdkProvider implements TransitiveInfoProvider { public static AndroidSdkProvider fromRuleContext(RuleContext ruleContext) { TransitiveInfoCollection androidSdkDep = ruleContext.getPrerequisite(":android_sdk", Mode.TARGET); - AndroidSdkProvider androidSdk = androidSdkDep == null - ? null : androidSdkDep.getProvider(AndroidSdkProvider.class); + AndroidSdkProvider androidSdk = + androidSdkDep == null ? null : androidSdkDep.getProvider(AndroidSdkProvider.class); return androidSdk; } - /** - * Throws an error if the Android SDK cannot be found. - */ + /** Throws an error if the Android SDK cannot be found. */ public static void verifyPresence(RuleContext ruleContext) throws RuleErrorException { if (fromRuleContext(ruleContext) == null) { throw ruleContext.throwWithRuleError( diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidSemantics.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidSemantics.java index 1a42e03aed..84d64e3b45 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidSemantics.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidSemantics.java @@ -47,6 +47,7 @@ public interface AndroidSemantics { /** * Returns the manifest to be used when compiling a given rule. + * * @throws InterruptedException */ default ApplicationManifest getManifestForRule(RuleContext ruleContext) @@ -70,9 +71,7 @@ public interface AndroidSemantics { } } - /** - * Returns the name of the file in which the file names of native dependencies are listed. - */ + /** Returns the name of the file in which the file names of native dependencies are listed. */ String getNativeDepsFileName(); /** @@ -101,14 +100,18 @@ public interface AndroidSemantics { /** * Add coverage instrumentation to the Java compilation of an Android binary. + * * @throws InterruptedException */ - void addCoverageSupport(RuleContext ruleContext, AndroidCommon common, - JavaSemantics javaSemantics, boolean forAndroidTest, JavaTargetAttributes.Builder attributes, - JavaCompilationArtifacts.Builder artifactsBuilder) throws InterruptedException; + void addCoverageSupport( + RuleContext ruleContext, + AndroidCommon common, + JavaSemantics javaSemantics, + boolean forAndroidTest, + JavaTargetAttributes.Builder attributes, + JavaCompilationArtifacts.Builder artifactsBuilder) + throws InterruptedException; - /** - * Returns the list of attributes that may contribute Java runtime dependencies. - */ + /** Returns the list of attributes that may contribute Java runtime dependencies. */ ImmutableList<String> getAttributesWithJavaRuntimeDeps(RuleContext ruleContext); } diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidSkylarkApiProvider.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidSkylarkApiProvider.java index 3269b0a998..b9e9d70968 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidSkylarkApiProvider.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidSkylarkApiProvider.java @@ -117,10 +117,10 @@ public class AndroidSkylarkApiProvider extends SkylarkApiProvider { } @SkylarkCallable( - name = "apks_under_test", - structField = true, - allowReturnNones = true, - doc = "Returns a collection of APKs that this target tests." + name = "apks_under_test", + structField = true, + allowReturnNones = true, + doc = "Returns a collection of APKs that this target tests." ) public ImmutableCollection<Artifact> getApksUnderTest() { return getIdeInfoProvider().getApksUnderTest(); @@ -135,11 +135,10 @@ public class AndroidSkylarkApiProvider extends SkylarkApiProvider { return getIdeInfoProvider().definesAndroidResources(); } - @SkylarkCallable( - name = "idl", - structField = true, - doc = "Returns information about IDL files associated with this target." + name = "idl", + structField = true, + doc = "Returns information about IDL files associated with this target." ) public IdlInfo getIdlInfo() { return idlInfo; @@ -155,10 +154,10 @@ public class AndroidSkylarkApiProvider extends SkylarkApiProvider { } @SkylarkCallable( - name = "resource_jar", - structField = true, - allowReturnNones = true, - doc = "Returns a jar file for classes generated from resources." + name = "resource_jar", + structField = true, + allowReturnNones = true, + doc = "Returns a jar file for classes generated from resources." ) @Nullable public JavaRuleOutputJarsProvider.OutputJar getResourceJar() { @@ -166,10 +165,10 @@ public class AndroidSkylarkApiProvider extends SkylarkApiProvider { } @SkylarkCallable( - name = "aar", - structField = true, - allowReturnNones = true, - doc = "Returns the aar output of this target." + name = "aar", + structField = true, + allowReturnNones = true, + doc = "Returns the aar output of this target." ) public Artifact getAar() { return getIdeInfoProvider().getAar(); @@ -200,36 +199,34 @@ public class AndroidSkylarkApiProvider extends SkylarkApiProvider { @Immutable public class IdlInfo { @SkylarkCallable( - name = "import_root", - structField = true, - allowReturnNones = true, - doc = "Returns the root of IDL packages if not the java root." + name = "import_root", + structField = true, + allowReturnNones = true, + doc = "Returns the root of IDL packages if not the java root." ) public String getImportRoot() { return getIdeInfoProvider().getIdlImportRoot(); } - @SkylarkCallable( - name = "sources", - structField = true, - doc = "Returns a list of IDL files." - ) + + @SkylarkCallable(name = "sources", structField = true, doc = "Returns a list of IDL files.") public ImmutableCollection<Artifact> getSources() { return getIdeInfoProvider().getIdlSrcs(); } + @SkylarkCallable( - name = "generated_java_files", - structField = true, - doc = "Returns a list Java files generated from IDL sources." + name = "generated_java_files", + structField = true, + doc = "Returns a list Java files generated from IDL sources." ) public ImmutableCollection<Artifact> getIdlGeneratedJavaFiles() { return getIdeInfoProvider().getIdlGeneratedJavaFiles(); } @SkylarkCallable( - name = "output", - structField = true, - allowReturnNones = true, - doc = "Returns a jar file for classes generated from IDL sources." + name = "output", + structField = true, + allowReturnNones = true, + doc = "Returns a jar file for classes generated from IDL sources." ) @Nullable public JavaRuleOutputJarsProvider.OutputJar getIdlOutput() { @@ -241,8 +238,7 @@ public class AndroidSkylarkApiProvider extends SkylarkApiProvider { return new OutputJar( getIdeInfoProvider().getIdlClassJar(), null, - idlSourceJar == null ? ImmutableList.<Artifact>of() : ImmutableList.of(idlSourceJar) - ); + idlSourceJar == null ? ImmutableList.<Artifact>of() : ImmutableList.of(idlSourceJar)); } } } diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidSkylarkCommon.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidSkylarkCommon.java index 1024b074e9..fe8a9dd36d 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidSkylarkCommon.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidSkylarkCommon.java @@ -20,9 +20,7 @@ import com.google.devtools.build.lib.skylarkinterface.SkylarkCallable; import com.google.devtools.build.lib.skylarkinterface.SkylarkModule; import com.google.devtools.build.lib.vfs.PathFragment; -/** - * Common utilities for Skylark rules related to Android. - */ +/** Common utilities for Skylark rules related to Android. */ @SkylarkModule( name = "android_common", doc = "Common utilities and fucntionality related to Android rules." @@ -43,10 +41,11 @@ public class AndroidSkylarkCommon { } @SkylarkCallable( - name = "multi_cpu_configuration", - doc = "A configuration for rule attributes that compiles native code according to " - + "the --fat_apk_cpu and --android_crosstool_top flags.", - structField = true + name = "multi_cpu_configuration", + doc = + "A configuration for rule attributes that compiles native code according to " + + "the --fat_apk_cpu and --android_crosstool_top flags.", + structField = true ) public SplitTransition<BuildOptions> getAndroidSplitTransition() { return AndroidRuleClasses.ANDROID_SPLIT_TRANSITION; diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidToolsDefaultsJar.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidToolsDefaultsJar.java index e7325dcf6b..817e0a2bc9 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidToolsDefaultsJar.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidToolsDefaultsJar.java @@ -30,10 +30,10 @@ import java.util.regex.Pattern; /** * Implementation for the {@code android_tools_defaults_jar} rule. * - * <p>This rule is a sad, sad way to let people depend on {@code android.jar} when an - * {@code android_sdk} rule is used. In an ideal world, people would say "depend on - * the android_jar output group of $config.android_sdk", but, alas, neither depending on labels in - * the configuration nor depending on a specified output group works. + * <p>This rule is a sad, sad way to let people depend on {@code android.jar} when an {@code + * android_sdk} rule is used. In an ideal world, people would say "depend on the android_jar output + * group of $config.android_sdk", but, alas, neither depending on labels in the configuration nor + * depending on a specified output group works. * * <p>So all this needs to be implemented manually. This rule is injected into the defaults package * from {@link AndroidConfiguration.Options#getDefaultsRules()}. @@ -47,20 +47,23 @@ public class AndroidToolsDefaultsJar implements RuleConfiguredTargetFactory { throws InterruptedException, RuleErrorException { if (!ruleContext.getLabel().getPackageName().equals("tools/defaults")) { // Guard against extraordinarily inquisitive individuals. - ruleContext.ruleError("The android_tools_defaults_jar rule should not be used in BUILD files." - + " It is a rule internal to the build tool."); + ruleContext.ruleError( + "The android_tools_defaults_jar rule should not be used in BUILD files." + + " It is a rule internal to the build tool."); return null; } TransitiveInfoCollection androidSdk = ruleContext.getPrerequisite(":android_sdk", Mode.TARGET); - AndroidSdkProvider sdkProvider = androidSdk.getProvider(AndroidSdkProvider.class); - Artifact androidJar = sdkProvider != null - ? sdkProvider.getAndroidJar() - : findAndroidJar(androidSdk.getProvider(FileProvider.class).getFilesToBuild()); + AndroidSdkProvider sdkProvider = androidSdk.getProvider(AndroidSdkProvider.class); + Artifact androidJar = + sdkProvider != null + ? sdkProvider.getAndroidJar() + : findAndroidJar(androidSdk.getProvider(FileProvider.class).getFilesToBuild()); - NestedSet<Artifact> filesToBuild = androidJar == null - ? NestedSetBuilder.<Artifact>emptySet(Order.STABLE_ORDER) - : NestedSetBuilder.create(Order.STABLE_ORDER, androidJar); + NestedSet<Artifact> filesToBuild = + androidJar == null + ? NestedSetBuilder.<Artifact>emptySet(Order.STABLE_ORDER) + : NestedSetBuilder.create(Order.STABLE_ORDER, androidJar); return new RuleConfiguredTargetBuilder(ruleContext) .add(RunfilesProvider.class, RunfilesProvider.EMPTY) diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/ApkActionsBuilder.java b/src/main/java/com/google/devtools/build/lib/rules/android/ApkActionsBuilder.java index ebdf48d23d..51e5f6524c 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/ApkActionsBuilder.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/ApkActionsBuilder.java @@ -340,8 +340,9 @@ public class ApkActionsBuilder { } List<String> noCompressExtensions; - if (ruleContext.getRule().isAttrDefined( - AndroidRuleClasses.NOCOMPRESS_EXTENSIONS_ATTR, Type.STRING_LIST)) { + if (ruleContext + .getRule() + .isAttrDefined(AndroidRuleClasses.NOCOMPRESS_EXTENSIONS_ATTR, Type.STRING_LIST)) { noCompressExtensions = ruleContext .getExpander() @@ -434,8 +435,8 @@ public class ApkActionsBuilder { private Artifact getApkArtifact(RuleContext ruleContext, String baseName) { if (artifactLocation != null) { - return ruleContext.getUniqueDirectoryArtifact(artifactLocation, baseName, - ruleContext.getBinOrGenfilesDirectory()); + return ruleContext.getUniqueDirectoryArtifact( + artifactLocation, baseName, ruleContext.getBinOrGenfilesDirectory()); } else { return AndroidBinary.getDxArtifact(ruleContext, baseName); } diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/ApplicationManifest.java b/src/main/java/com/google/devtools/build/lib/rules/android/ApplicationManifest.java index 8b406cb82d..0cb02c5942 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/ApplicationManifest.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/ApplicationManifest.java @@ -240,8 +240,7 @@ public final class ApplicationManifest { public ApplicationManifest mergeWith( RuleContext ruleContext, ResourceDependencies resourceDeps, boolean legacy) { - Map<Artifact, Label> mergeeManifests = - getMergeeManifests(resourceDeps.getResourceContainers()); + Map<Artifact, Label> mergeeManifests = getMergeeManifests(resourceDeps.getResourceContainers()); if (legacy) { if (!mergeeManifests.isEmpty()) { @@ -620,8 +619,8 @@ public final class ApplicationManifest { // have checked its dependencies. ruleContext); - AndroidConfiguration androidConfiguration = ruleContext.getConfiguration() - .getFragment(AndroidConfiguration.class); + AndroidConfiguration androidConfiguration = + ruleContext.getConfiguration().getFragment(AndroidConfiguration.class); boolean skipParsingAction = targetAaptVersion == AndroidAaptVersion.AAPT2 && androidConfiguration.skipParsingAction(); @@ -734,8 +733,8 @@ public final class ApplicationManifest { Artifact rJavaClassJar = ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_RESOURCES_CLASS_JAR); - AndroidConfiguration androidConfiguration = ruleContext.getConfiguration() - .getFragment(AndroidConfiguration.class); + AndroidConfiguration androidConfiguration = + ruleContext.getConfiguration().getFragment(AndroidConfiguration.class); boolean skipParsingAction = targetAaptVersion == AndroidAaptVersion.AAPT2 && androidConfiguration.skipParsingAction(); @@ -902,8 +901,9 @@ public final class ApplicationManifest { ResourceFilterFactory.fromRuleContext(ruleContext); List<String> uncompressedExtensions; - if (ruleContext.getRule().isAttrDefined( - AndroidRuleClasses.NOCOMPRESS_EXTENSIONS_ATTR, Type.STRING_LIST)) { + if (ruleContext + .getRule() + .isAttrDefined(AndroidRuleClasses.NOCOMPRESS_EXTENSIONS_ATTR, Type.STRING_LIST)) { uncompressedExtensions = ruleContext .getExpander() diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/DataBinding.java b/src/main/java/com/google/devtools/build/lib/rules/android/DataBinding.java index ad6a97c733..65027087e2 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/DataBinding.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/DataBinding.java @@ -33,22 +33,23 @@ import java.util.ArrayList; import java.util.List; /** - * Support logic for Bazel's - * <a href="https://developer.android.com/topic/libraries/data-binding/index.html">data binding</a> + * Support logic for Bazel's <a + * href="https://developer.android.com/topic/libraries/data-binding/index.html">data binding</a> * integration. * * <p>In short, data binding in Bazel works as follows: + * * <ol> * <li>If a rule enables data binding and has layout resources with data binding expressions, - * resource processing invokes the data binding library to preprocess these expressions, then - * strips them out before feeding the resources into aapt. A separate "layout info" XML file - * gets produced that contains the bindings.</li> + * resource processing invokes the data binding library to preprocess these expressions, then + * strips them out before feeding the resources into aapt. A separate "layout info" XML file + * gets produced that contains the bindings. * <li>The data binding annotation processor gets activated on Java compilation. This processor - * reads a custom-generated <code>DataBindingInfo.java</code> which specifies the path to the - * layout info file (as an annotation). The processor reads that file and produces the - * corresponding Java classes that end-user code uses to access the resources.</li> + * reads a custom-generated <code>DataBindingInfo.java</code> which specifies the path to the + * layout info file (as an annotation). The processor reads that file and produces the + * corresponding Java classes that end-user code uses to access the resources. * <li>The data binding compile-time and runtime support libraries get linked into the binary's - * deploy jar.</li> + * deploy jar. * </ol> * * <p>For data binding to work, the corresponding support libraries must be checked into the depot @@ -56,12 +57,9 @@ import java.util.List; * * <p>Unless otherwise specified, all methods in this class assume the current rule applies data * binding. Callers can intelligently trigger this logic by checking {@link #isEnabled}. - * */ public final class DataBinding { - /** - * The rule attribute supplying data binding's annotation processor. - */ + /** The rule attribute supplying data binding's annotation processor. */ public static final String DATABINDING_ANNOTATION_PROCESSOR_ATTR = "$databinding_annotation_processor"; @@ -69,81 +67,74 @@ public final class DataBinding { * Annotation processing creates the following metadata files that describe how data binding is * applied. The full file paths include prefixes as implemented in {@link #getMetadataOutputs}. */ - private static final ImmutableList<String> METADATA_OUTPUT_SUFFIXES = ImmutableList.<String>of( - "setter_store.bin", "layoutinfo.bin", "br.bin"); + private static final ImmutableList<String> METADATA_OUTPUT_SUFFIXES = + ImmutableList.<String>of("setter_store.bin", "layoutinfo.bin", "br.bin"); - /** - * The directory where the annotation processor looks for dep metadata. - */ + /** The directory where the annotation processor looks for dep metadata. */ private static final String DEP_METADATA_INPUT_DIR = "dependent-lib-artifacts"; - /** - * The directory where the annotation processor write metadata output for the current rule. - */ + /** The directory where the annotation processor write metadata output for the current rule. */ private static final String METADATA_OUTPUT_DIR = "bin-files"; /** * Should data binding support be enabled for this rule? * * <p>Data binding incurs additional resource processing and compilation work as well as - * additional compile/runtime dependencies. But rules with data binding disabled will fail if - * data binding expressions appear in their layout resources. + * additional compile/runtime dependencies. But rules with data binding disabled will fail if data + * binding expressions appear in their layout resources. */ public static boolean isEnabled(RuleContext ruleContext) { return ruleContext.attributes().has("enable_data_binding", Type.BOOLEAN) && ruleContext.attributes().get("enable_data_binding", Type.BOOLEAN); } - /** - * Returns this rule's data binding base output dir (as an execroot-relative path). - */ + /** Returns this rule's data binding base output dir (as an execroot-relative path). */ private static PathFragment getDataBindingExecPath(RuleContext ruleContext) { - return ruleContext.getBinOrGenfilesDirectory().getExecPath().getRelative( - ruleContext.getUniqueDirectory("databinding")); + return ruleContext + .getBinOrGenfilesDirectory() + .getExecPath() + .getRelative(ruleContext.getUniqueDirectory("databinding")); } - /** - * Returns an artifact for the specified output under a standardized data binding base dir. - */ + /** Returns an artifact for the specified output under a standardized data binding base dir. */ private static Artifact getDataBindingArtifact(RuleContext ruleContext, String relativePath) { - PathFragment binRelativeBasePath = getDataBindingExecPath(ruleContext) - .relativeTo(ruleContext.getBinOrGenfilesDirectory().getExecPath()); - return ruleContext.getDerivedArtifact(binRelativeBasePath.getRelative(relativePath), - ruleContext.getBinOrGenfilesDirectory()); + PathFragment binRelativeBasePath = + getDataBindingExecPath(ruleContext) + .relativeTo(ruleContext.getBinOrGenfilesDirectory().getExecPath()); + return ruleContext.getDerivedArtifact( + binRelativeBasePath.getRelative(relativePath), ruleContext.getBinOrGenfilesDirectory()); } /** - * Returns the file where data binding's resource processing produces binding xml. For - * example, given: + * Returns the file where data binding's resource processing produces binding xml. For example, + * given: * * <pre>{@code - * <layout> - * <data> - * <variable name="foo" type="String" /> - * </data> - * </layout> - * <LinearLayout> - * ... - * </LinearLayout> - * } - * </pre> + * <layout> + * <data> + * <variable name="foo" type="String" /> + * </data> + * </layout> + * <LinearLayout> + * ... + * </LinearLayout> + * }</pre> * * <p>data binding strips out and processes this part: * * <pre>{@code - * <data> - * <variable name="foo" type="String" /> - * </data> - * } - * </pre> + * <data> + * <variable name="foo" type="String" /> + * </data> + * }</pre> * - * for each layout file with data binding expressions. Since this may produce multiple - * files, outputs are zipped up into a single container. + * for each layout file with data binding expressions. Since this may produce multiple files, + * outputs are zipped up into a single container. */ static Artifact getLayoutInfoFile(RuleContext ruleContext) { // The data binding library expects this to be called "layout-info.zip". - return ruleContext.getUniqueDirectoryArtifact("databinding", "layout-info.zip", - ruleContext.getBinOrGenfilesDirectory()); + return ruleContext.getUniqueDirectoryArtifact( + "databinding", "layout-info.zip", ruleContext.getBinOrGenfilesDirectory()); } /** @@ -173,9 +164,7 @@ public final class DataBinding { attributes.addAdditionalOutputs(getMetadataOutputs(ruleContext)); } - /** - * The javac flags that are needed to configure data binding's annotation processor. - */ + /** The javac flags that are needed to configure data binding's annotation processor. */ static ImmutableList<String> getJavacopts(RuleContext ruleContext, boolean isBinary) { ImmutableList.Builder<String> flags = ImmutableList.builder(); String metadataOutputDir = getDataBindingExecPath(ruleContext).getPathString(); @@ -211,26 +200,24 @@ public final class DataBinding { return flags.build(); } - /** - * Turns a key/value pair into a javac annotation processor flag received by data binding. - */ + /** Turns a key/value pair into a javac annotation processor flag received by data binding. */ private static String createProcessorFlag(String flag, String value) { return String.format("-Aandroid.databinding.%s=%s", flag, value); } /** - * Creates and returns the generated Java source that data binding's annotation processor - * reads to translate layout info xml (from {@link #getLayoutInfoFile} into the classes that - * end user code consumes. + * Creates and returns the generated Java source that data binding's annotation processor reads to + * translate layout info xml (from {@link #getLayoutInfoFile} into the classes that end user code + * consumes. * - * <p>This mostly just triggers the annotation processor. Annotation processor settings - * are configured separately in {@link #getJavacopts}. + * <p>This mostly just triggers the annotation processor. Annotation processor settings are + * configured separately in {@link #getJavacopts}. */ static Artifact createAnnotationFile(RuleContext ruleContext) { String contents; try { - contents = ResourceFileLoader.loadResource(DataBinding.class, - "databinding_annotation_template.txt"); + contents = + ResourceFileLoader.loadResource(DataBinding.class, "databinding_annotation_template.txt"); } catch (IOException e) { ruleContext.ruleError("Cannot load annotation processor template: " + e.getMessage()); return null; @@ -243,11 +230,11 @@ public final class DataBinding { /** * Adds the appropriate {@link UsesDataBindingProvider} for a rule if it should expose one. * - * <p>A rule exposes {@link UsesDataBindingProvider} if either it or its deps set - * {@code enable_data_binding = 1}. + * <p>A rule exposes {@link UsesDataBindingProvider} if either it or its deps set {@code + * enable_data_binding = 1}. */ - public static void maybeAddProvider(RuleConfiguredTargetBuilder builder, - RuleContext ruleContext) { + public static void maybeAddProvider( + RuleConfiguredTargetBuilder builder, RuleContext ruleContext) { // Expose the data binding provider if this rule either applies data binding or exports a dep // that applies it. List<Artifact> dataBindingMetadataOutputs = new ArrayList<>(); @@ -262,19 +249,18 @@ public final class DataBinding { dataBindingMetadataOutputs.addAll(getTransitiveMetadata(ruleContext, "deps")); } if (!dataBindingMetadataOutputs.isEmpty()) { - builder.addProvider(UsesDataBindingProvider.class, - new UsesDataBindingProvider(dataBindingMetadataOutputs)); + builder.addProvider( + UsesDataBindingProvider.class, new UsesDataBindingProvider(dataBindingMetadataOutputs)); } } - /** - * Returns the data binding resource processing output from deps under the given attribute. - */ + /** Returns the data binding resource processing output from deps under the given attribute. */ private static List<Artifact> getTransitiveMetadata(RuleContext ruleContext, String attr) { ImmutableList.Builder<Artifact> dataBindingMetadataOutputs = ImmutableList.builder(); if (ruleContext.attributes().has(attr, BuildType.LABEL_LIST)) { - for (UsesDataBindingProvider provider : ruleContext.getPrerequisites(attr, - RuleConfiguredTarget.Mode.TARGET, UsesDataBindingProvider.class)) { + for (UsesDataBindingProvider provider : + ruleContext.getPrerequisites( + attr, RuleConfiguredTarget.Mode.TARGET, UsesDataBindingProvider.class)) { dataBindingMetadataOutputs.addAll(provider.getMetadataOutputs()); } } @@ -285,13 +271,12 @@ public final class DataBinding { * Returns metadata outputs from this rule's annotation processing that describe what it did with * data binding. This is used by parent rules to ensure consistent binding patterns. * - * <p>>For example, if {@code foo.AndroidBinary} depends on {@code foo.lib.AndroidLibrary} and - * the library defines data binding expression {@code Bar}, compiling the library produces Java - * class {@code foo.lib.Bar}. But since the binary applies data binding over the merged resources - * of its deps, that means the binary also sees {@code Bar}, so it compiles it into - * {@code foo.Bar}. This would be a class redefinition conflict. But by feeding the library's - * metadata outputs into the binary's compilation, enough information is available to only use the - * first version. + * <p>>For example, if {@code foo.AndroidBinary} depends on {@code foo.lib.AndroidLibrary} and the + * library defines data binding expression {@code Bar}, compiling the library produces Java class + * {@code foo.lib.Bar}. But since the binary applies data binding over the merged resources of its + * deps, that means the binary also sees {@code Bar}, so it compiles it into {@code foo.Bar}. This + * would be a class redefinition conflict. But by feeding the library's metadata outputs into the + * binary's compilation, enough information is available to only use the first version. */ private static List<Artifact> getMetadataOutputs(RuleContext ruleContext) { if (!LocalResourceContainer.definesAndroidResources(ruleContext.attributes())) { @@ -304,8 +289,10 @@ public final class DataBinding { for (String suffix : METADATA_OUTPUT_SUFFIXES) { // The annotation processor automatically creates files with this naming pattern under the // {@code -Aandroid.databinding.generationalFileOutDir} base directory. - outputs.add(getDataBindingArtifact(ruleContext, String.format("%s/%s-%s-%s", - METADATA_OUTPUT_DIR, javaPackage, javaPackage, suffix))); + outputs.add( + getDataBindingArtifact( + ruleContext, + String.format("%s/%s-%s-%s", METADATA_OUTPUT_DIR, javaPackage, javaPackage, suffix))); } return outputs.build(); } @@ -330,24 +317,28 @@ public final class DataBinding { } /** - * * Data binding's annotation processor reads the transitive metadata outputs of the target's deps - * (see {@link #getMetadataOutputs(RuleContext)}) in the directory specified by the processor - * flag {@code -Aandroid.databinding.bindingBuildFolder}. Since dependencies don't generate - * their outputs under a common directory, we symlink them into a common place here. + * (see {@link #getMetadataOutputs(RuleContext)}) in the directory specified by the processor flag + * {@code -Aandroid.databinding.bindingBuildFolder}. Since dependencies don't generate their + * outputs under a common directory, we symlink them into a common place here. * * @return the symlink paths of the transitive dep metadata outputs for this rule */ - private static Artifact symlinkDepsMetadataIntoOutputTree(RuleContext ruleContext, - Artifact depMetadata) { + private static Artifact symlinkDepsMetadataIntoOutputTree( + RuleContext ruleContext, Artifact depMetadata) { Label ruleLabel = ruleContext.getRule().getLabel(); - Artifact symlink = getDataBindingArtifact(ruleContext, - String.format("%s/%s", DEP_METADATA_INPUT_DIR, depMetadata.getRootRelativePathString())); + Artifact symlink = + getDataBindingArtifact( + ruleContext, + String.format( + "%s/%s", DEP_METADATA_INPUT_DIR, depMetadata.getRootRelativePathString())); ruleContext.registerAction( - new SymlinkAction(ruleContext.getActionOwner(), depMetadata, symlink, - String.format("Symlinking dep metadata output %s for %s", - depMetadata.getFilename(), ruleLabel))); + new SymlinkAction( + ruleContext.getActionOwner(), + depMetadata, + symlink, + String.format( + "Symlinking dep metadata output %s for %s", depMetadata.getFilename(), ruleLabel))); return symlink; } } - diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/DeviceBrokerTypeProvider.java b/src/main/java/com/google/devtools/build/lib/rules/android/DeviceBrokerTypeProvider.java index 377ba360cc..7a0b926741 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/DeviceBrokerTypeProvider.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/DeviceBrokerTypeProvider.java @@ -27,8 +27,8 @@ public final class DeviceBrokerTypeProvider implements TransitiveInfoProvider { } /** - * Returns the type of device broker that is appropriate to use to interact with - * devices obtained by this artifact. + * Returns the type of device broker that is appropriate to use to interact with devices obtained + * by this artifact. */ public String getDeviceBrokerType() { return deviceBrokerType; diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/DexArchiveAspect.java b/src/main/java/com/google/devtools/build/lib/rules/android/DexArchiveAspect.java index 90c2e69336..ac7e914b47 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/DexArchiveAspect.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/DexArchiveAspect.java @@ -73,9 +73,7 @@ import java.util.Map; import java.util.Set; import java.util.TreeSet; -/** - * Aspect to {@link DexArchiveProvider build .dex Archives} from Jars. - */ +/** Aspect to {@link DexArchiveProvider build .dex Archives} from Jars. */ public final class DexArchiveAspect extends NativeAspectClass implements ConfiguredAspectFactory { public static final String NAME = "DexArchiveAspect"; /** @@ -104,13 +102,20 @@ public final class DexArchiveAspect extends NativeAspectClass implements Configu private static final String ASPECT_DEXBUILDER_PREREQ = "$dex_archive_dexbuilder"; /** Aspect-only label for desugaring executable, to avoid name clashes with labels on rules. */ private static final String ASPECT_DESUGAR_PREREQ = "$aspect_desugar"; + private static final ImmutableList<String> TRANSITIVE_ATTRIBUTES_EXCEPT_FOR_PROTOS = - ImmutableList.of("deps", "exports", "runtime_deps", - ":android_sdk", "aidl_lib"); // for the aidl runtime in the android_sdk rule + ImmutableList.of( + "deps", + "exports", + "runtime_deps", + ":android_sdk", + "aidl_lib"); // for the aidl runtime in the android_sdk rule private static final ImmutableList<String> TRANSITIVE_ATTRIBUTES = - ImmutableList.<String>builder().addAll(TRANSITIVE_ATTRIBUTES_EXCEPT_FOR_PROTOS) + ImmutableList.<String>builder() + .addAll(TRANSITIVE_ATTRIBUTES_EXCEPT_FOR_PROTOS) // To get from proto_library through proto_lang_toolchain rule to proto runtime library. - .add(JavaLiteProtoAspect.PROTO_TOOLCHAIN_ATTR, "runtime").build(); + .add(JavaLiteProtoAspect.PROTO_TOOLCHAIN_ATTR, "runtime") + .build(); private static final FlagMatcher DEXOPTS_SUPPORTED_IN_DEXBUILDER = new FlagMatcher( ImmutableList.of("--no-locals", "--no-optimize", "--no-warnings", "--positions")); @@ -156,8 +161,11 @@ public final class DexArchiveAspect extends NativeAspectClass implements Configu .requireAspectsWithNativeProviders(JavaProtoLibraryAspectProvider.class); if (TriState.valueOf(params.getOnlyValueOfAttribute("incremental_dexing")) != TriState.NO) { // Marginally improves "query2" precision for targets that disable incremental dexing - result.add(attr(ASPECT_DEXBUILDER_PREREQ, LABEL).cfg(HOST).exec() - .value(Label.parseAbsoluteUnchecked(toolsRepository + "//tools/android:dexbuilder"))); + result.add( + attr(ASPECT_DEXBUILDER_PREREQ, LABEL) + .cfg(HOST) + .exec() + .value(Label.parseAbsoluteUnchecked(toolsRepository + "//tools/android:dexbuilder"))); } for (String attr : TRANSITIVE_ATTRIBUTES) { result.propagateAlongAttribute(attr); @@ -166,11 +174,11 @@ public final class DexArchiveAspect extends NativeAspectClass implements Configu } @Override - public ConfiguredAspect create(ConfiguredTarget base, RuleContext ruleContext, - AspectParameters params) throws InterruptedException { + public ConfiguredAspect create( + ConfiguredTarget base, RuleContext ruleContext, AspectParameters params) + throws InterruptedException { ConfiguredAspect.Builder result = new ConfiguredAspect.Builder(this, params, ruleContext); - Function<Artifact, Artifact> desugaredJars = - desugarJarsIfRequested(base, ruleContext, result); + Function<Artifact, Artifact> desugaredJars = desugarJarsIfRequested(base, ruleContext, result); TriState incrementalAttr = TriState.valueOf(params.getOnlyValueOfAttribute("incremental_dexing")); @@ -185,8 +193,9 @@ public final class DexArchiveAspect extends NativeAspectClass implements Configu return result.addProvider(DexArchiveProvider.NEVERLINK).build(); } - DexArchiveProvider.Builder dexArchives = new DexArchiveProvider.Builder() - .addTransitiveProviders(collectPrerequisites(ruleContext, DexArchiveProvider.class)); + DexArchiveProvider.Builder dexArchives = + new DexArchiveProvider.Builder() + .addTransitiveProviders(collectPrerequisites(ruleContext, DexArchiveProvider.class)); Iterable<Artifact> runtimeJars = getProducedRuntimeJars(base, ruleContext); if (runtimeJars != null) { boolean basenameClash = checkBasenameClash(runtimeJars); @@ -199,7 +208,8 @@ public final class DexArchiveAspect extends NativeAspectClass implements Configu // their filenames. String uniqueFilename = (basenameClash ? jar.getRootRelativePathString() : jar.getFilename()) - + Joiner.on("").join(incrementalDexopts) + ".dex.zip"; + + Joiner.on("").join(incrementalDexopts) + + ".dex.zip"; Artifact dexArchive = createDexArchiveAction( ruleContext, @@ -229,8 +239,10 @@ public final class DexArchiveAspect extends NativeAspectClass implements Configu result.addProvider(AndroidRuntimeJarProvider.NEVERLINK); return Functions.forMap(newlyDesugared); } - AndroidRuntimeJarProvider.Builder desugaredJars = new AndroidRuntimeJarProvider.Builder() - .addTransitiveProviders(collectPrerequisites(ruleContext, AndroidRuntimeJarProvider.class)); + AndroidRuntimeJarProvider.Builder desugaredJars = + new AndroidRuntimeJarProvider.Builder() + .addTransitiveProviders( + collectPrerequisites(ruleContext, AndroidRuntimeJarProvider.class)); if (isProtoLibrary(ruleContext)) { // TODO(b/33557068): Desugar protos if needed instead of assuming they don't need desugaring result.addProvider(desugaredJars.build()); @@ -249,8 +261,9 @@ public final class DexArchiveAspect extends NativeAspectClass implements Configu boolean basenameClash = checkBasenameClash(jarProvider.getRuntimeJars()); for (Artifact jar : jarProvider.getRuntimeJars()) { - Artifact desugared = createDesugarAction(ruleContext, basenameClash, jar, bootclasspath, - compileTimeClasspath); + Artifact desugared = + createDesugarAction( + ruleContext, basenameClash, jar, bootclasspath, compileTimeClasspath); newlyDesugared.put(jar, desugared); desugaredJars.addDesugaredJar(jar, desugared); } @@ -259,8 +272,8 @@ public final class DexArchiveAspect extends NativeAspectClass implements Configu return Functions.forMap(newlyDesugared); } - private static Iterable<Artifact> getProducedRuntimeJars(ConfiguredTarget base, - RuleContext ruleContext) { + private static Iterable<Artifact> getProducedRuntimeJars( + ConfiguredTarget base, RuleContext ruleContext) { if (isProtoLibrary(ruleContext) && getAndroidConfig(ruleContext).incrementalDexingForLiteProtos()) { if (!ruleContext.getPrerequisites("srcs", Mode.TARGET).isEmpty()) { @@ -280,8 +293,8 @@ public final class DexArchiveAspect extends NativeAspectClass implements Configu return null; } - private static JavaCompilationArgsProvider getJavaCompilationArgsProvider(ConfiguredTarget base, - RuleContext ruleContext) { + private static JavaCompilationArgsProvider getJavaCompilationArgsProvider( + ConfiguredTarget base, RuleContext ruleContext) { JavaCompilationArgsProvider provider = JavaInfo.getProvider(JavaCompilationArgsProvider.class, base); if (provider != null) { @@ -309,8 +322,10 @@ public final class DexArchiveAspect extends NativeAspectClass implements Configu private static <T extends TransitiveInfoProvider> IterablesChain<T> collectPrerequisites( RuleContext ruleContext, Class<T> classType) { - ImmutableList<String> attrs = getAndroidConfig(ruleContext).incrementalDexingForLiteProtos() - ? TRANSITIVE_ATTRIBUTES : TRANSITIVE_ATTRIBUTES_EXCEPT_FOR_PROTOS; + ImmutableList<String> attrs = + getAndroidConfig(ruleContext).incrementalDexingForLiteProtos() + ? TRANSITIVE_ATTRIBUTES + : TRANSITIVE_ATTRIBUTES_EXCEPT_FOR_PROTOS; IterablesChain.Builder<T> result = IterablesChain.builder(); for (String attr : attrs) { if (ruleContext.attributes().getAttributeType(attr) != null) { @@ -320,8 +335,8 @@ public final class DexArchiveAspect extends NativeAspectClass implements Configu return result.build(); } - private static ImmutableList<Artifact> getBootclasspath(ConfiguredTarget base, - RuleContext ruleContext) { + private static ImmutableList<Artifact> getBootclasspath( + ConfiguredTarget base, RuleContext ruleContext) { JavaCompilationInfoProvider compilationInfo = base.getProvider(JavaCompilationInfoProvider.class); if (compilationInfo == null || compilationInfo.getBootClasspath().isEmpty()) { @@ -346,15 +361,16 @@ public final class DexArchiveAspect extends NativeAspectClass implements Configu jar, bootclasspath, compileTimeClasspath, - AndroidBinary.getDxArtifact(ruleContext, + AndroidBinary.getDxArtifact( + ruleContext, (disambiguateBasenames ? jar.getRootRelativePathString() : jar.getFilename()) - + "_desugared.jar")); + + "_desugared.jar")); } /** - * Desugars the given Jar using an executable prerequisite {@code "$desugar"}. - * Rules calling this method must declare the appropriate prerequisite, similar to how - * {@link #getDefinition} does it for {@link DexArchiveAspect} under a different name. + * Desugars the given Jar using an executable prerequisite {@code "$desugar"}. Rules calling this + * method must declare the appropriate prerequisite, similar to how {@link #getDefinition} does it + * for {@link DexArchiveAspect} under a different name. * * <p>It's useful to have this action separately since callers need to look up classpath and * bootclasspath in a different way than this aspect does it. @@ -415,24 +431,28 @@ public final class DexArchiveAspect extends NativeAspectClass implements Configu } /** - * Creates a dex archive using an executable prerequisite called {@code "$dexbuilder"}. Rules - * calling this method must declare the appropriate prerequisite, similar to how - * {@link #getDefinition} does it for {@link DexArchiveAspect} under a different name. + * Creates a dex archive using an executable prerequisite called {@code "$dexbuilder"}. Rules + * calling this method must declare the appropriate prerequisite, similar to how {@link + * #getDefinition} does it for {@link DexArchiveAspect} under a different name. * * @return the artifact given as {@code result}, which can simplify calling code */ // Package-private method for use in AndroidBinary - static Artifact createDexArchiveAction(RuleContext ruleContext, Artifact jar, - Set<String> tokenizedDexopts, Artifact result) { + static Artifact createDexArchiveAction( + RuleContext ruleContext, Artifact jar, Set<String> tokenizedDexopts, Artifact result) { return createDexArchiveAction(ruleContext, "$dexbuilder", jar, tokenizedDexopts, result); } /** - * Creates a dexbuilder action with the given input, output, and flags. Flags must have been + * Creates a dexbuilder action with the given input, output, and flags. Flags must have been * filtered and normalized to a set that the dexbuilder tool can understand. */ - private static Artifact createDexArchiveAction(RuleContext ruleContext, String dexbuilderPrereq, - Artifact jar, Set<String> incrementalDexopts, Artifact dexArchive) { + private static Artifact createDexArchiveAction( + RuleContext ruleContext, + String dexbuilderPrereq, + Artifact jar, + Set<String> incrementalDexopts, + Artifact dexArchive) { // Write command line arguments into a params file for compatibility with WorkerSpawnStrategy CustomCommandLine args = new Builder() @@ -477,12 +497,12 @@ public final class DexArchiveAspect extends NativeAspectClass implements Configu /** * Derives options to use in incremental dexing actions from the given context and dx flags, where - * the latter typically come from a {@code dexopts} attribute on a top-level target. This method - * only works reliably if the given dexopts were tokenized, e.g., using - * {@link RuleContext#getTokenizedStringListAttr}. + * the latter typically come from a {@code dexopts} attribute on a top-level target. This method + * only works reliably if the given dexopts were tokenized, e.g., using {@link + * RuleContext#getTokenizedStringListAttr}. */ - static ImmutableSet<String> incrementalDexopts(RuleContext ruleContext, - Iterable<String> tokenizedDexopts) { + static ImmutableSet<String> incrementalDexopts( + RuleContext ruleContext, Iterable<String> tokenizedDexopts) { if (ruleContext.getConfiguration().isCodeCoverageEnabled()) { // TODO(b/27382165): Still needed? No longer done in AndroidCommon.createDexAction tokenizedDexopts = Iterables.concat(tokenizedDexopts, ImmutableList.of("--no-locals")); @@ -495,11 +515,10 @@ public final class DexArchiveAspect extends NativeAspectClass implements Configu } /** - * Returns the subset of the given dexopts that are blacklisted from using incremental dexing - * by default. + * Returns the subset of the given dexopts that are blacklisted from using incremental dexing by + * default. */ - static Iterable<String> blacklistedDexopts( - RuleContext ruleContext, List<String> dexopts) { + static Iterable<String> blacklistedDexopts(RuleContext ruleContext, List<String> dexopts) { return Iterables.filter( dexopts, new FlagMatcher( @@ -508,8 +527,8 @@ public final class DexArchiveAspect extends NativeAspectClass implements Configu /** * Derives options to use in DexBuilder actions from the given context and dx flags, where the - * latter typically come from a {@code dexopts} attribute on a top-level target. This should be - * a superset of {@link #incrementalDexopts}. + * latter typically come from a {@code dexopts} attribute on a top-level target. This should be a + * superset of {@link #incrementalDexopts}. */ static ImmutableSet<String> topLevelDexbuilderDexopts( RuleContext ruleContext, Iterable<String> tokenizedDexopts) { @@ -525,8 +544,8 @@ public final class DexArchiveAspect extends NativeAspectClass implements Configu * Derives options to use in DexFileMerger actions from the given context and dx flags, where the * latter typically come from a {@code dexopts} attribute on a top-level target. */ - static ImmutableSet<String> mergerDexopts(RuleContext ruleContext, - Iterable<String> tokenizedDexopts) { + static ImmutableSet<String> mergerDexopts( + RuleContext ruleContext, Iterable<String> tokenizedDexopts) { // We don't need an ordered set but might as well. Note we don't need to worry about coverage // builds since the merger doesn't use --no-locals. return normalizeDexopts( diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/DexArchiveProvider.java b/src/main/java/com/google/devtools/build/lib/rules/android/DexArchiveProvider.java index 5b981283d9..f06f56f3f6 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/DexArchiveProvider.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/DexArchiveProvider.java @@ -31,7 +31,7 @@ import java.util.Map; import java.util.Set; /** - * Provider of transitively available dex archives corresponding to Jars. A dex archive is a zip of + * Provider of transitively available dex archives corresponding to Jars. A dex archive is a zip of * {@code .dex} files that each encode exactly one {@code .class} file in an Android-readable form. * The file names in a dex archive should match the file names in the originating Jar file, except * with {@code .dex} appended, i.e., {@code <package/for/ClassName[$Inner].class.dex}. @@ -44,14 +44,12 @@ public class DexArchiveProvider implements TransitiveInfoProvider { /** * Provider that doesn't provide any dex archives, which is what any neverlink target should use. - * It's not strictly necessary to handle neverlink specially, but doing so reduces the amount - * of processing done for targets that won't be used for dexing anyway. + * It's not strictly necessary to handle neverlink specially, but doing so reduces the amount of + * processing done for targets that won't be used for dexing anyway. */ public static final DexArchiveProvider NEVERLINK = new DexArchiveProvider.Builder().build(); - /** - * Builder for {@link DexArchiveProvider}. - */ + /** Builder for {@link DexArchiveProvider}. */ public static class Builder { private final Table<ImmutableSet<String>, Artifact, Artifact> dexArchives = @@ -59,8 +57,7 @@ public class DexArchiveProvider implements TransitiveInfoProvider { private final NestedSetBuilder<ImmutableTable<ImmutableSet<String>, Artifact, Artifact>> transitiveDexArchives = NestedSetBuilder.stableOrder(); - public Builder() { - } + public Builder() {} /** * Adds all dex archives from the given providers, which is useful to aggregate providers from @@ -75,11 +72,14 @@ public class DexArchiveProvider implements TransitiveInfoProvider { /** * Adds the given dex archive as a replacement for the given Jar. + * * @param dexopts */ public Builder addDexArchive(Set<String> dexopts, Artifact dexArchive, Artifact dexedJar) { - checkArgument(dexArchive.getFilename().endsWith(".dex.zip"), - "Doesn't look like a dex archive: %s", dexArchive); + checkArgument( + dexArchive.getFilename().endsWith(".dex.zip"), + "Doesn't look like a dex archive: %s", + dexArchive); // Adding this artifact will fail iff dexArchive already appears as the value of another jar. // It's ok and expected to put the same pair multiple times. Note that ImmutableBiMap fails // in that situation, which is why we're not using it here. @@ -87,15 +87,17 @@ public class DexArchiveProvider implements TransitiveInfoProvider { Artifact old = dexArchives.put( ImmutableSet.copyOf(dexopts), checkNotNull(dexedJar, "dexedJar"), dexArchive); - checkArgument(old == null || old.equals(dexArchive), + checkArgument( + old == null || old.equals(dexArchive), "We already had mapping %s-%s for dexopts %s, so we don't also need %s", - dexedJar, old, dexopts, dexArchive); + dexedJar, + old, + dexopts, + dexArchive); return this; } - /** - * Returns the finished {@link DexArchiveProvider}. - */ + /** Returns the finished {@link DexArchiveProvider}. */ public DexArchiveProvider build() { return new DexArchiveProvider( transitiveDexArchives.add(ImmutableTable.copyOf(dexArchives)).build()); @@ -110,9 +112,7 @@ public class DexArchiveProvider implements TransitiveInfoProvider { this.dexArchives = dexArchives; } - /** - * Returns a flat map from Jars to dex archives transitively produced for the given dexopts. - */ + /** Returns a flat map from Jars to dex archives transitively produced for the given dexopts. */ public Map<Artifact, Artifact> archivesForDexopts(ImmutableSet<String> dexopts) { // Can't use ImmutableMap because we can encounter the same key-value pair multiple times. // Use LinkedHashMap in case someone tries to iterate this map (not the case as of 2/2017). diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/LocalResourceContainer.java b/src/main/java/com/google/devtools/build/lib/rules/android/LocalResourceContainer.java index 084306048d..68c10576d4 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/LocalResourceContainer.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/LocalResourceContainer.java @@ -43,15 +43,16 @@ import javax.annotation.Nullable; */ @Immutable public final class LocalResourceContainer { - public static final String[] RESOURCES_ATTRIBUTES = new String[] { - "manifest", - "resource_files", - "local_resource_files", - "assets", - "assets_dir", - "inline_constants", - "exports_manifest" - }; + public static final String[] RESOURCES_ATTRIBUTES = + new String[] { + "manifest", + "resource_files", + "local_resource_files", + "assets", + "assets_dir", + "inline_constants", + "exports_manifest" + }; /** Set of allowable android directories prefixes. */ public static final ImmutableSet<String> RESOURCE_DIRECTORY_TYPES = @@ -65,9 +66,7 @@ public final class LocalResourceContainer { + "<resource directory>/{%s}/<file>", Joiner.on(',').join(RESOURCE_DIRECTORY_TYPES)); - /** - * Determines if the attributes contain resource and asset attributes. - */ + /** Determines if the attributes contain resource and asset attributes. */ public static boolean definesAndroidResources(AttributeMap attributes) { for (String attribute : RESOURCES_ATTRIBUTES) { if (attributes.isAttributeValueExplicitlySpecified(attribute)) { @@ -79,7 +78,7 @@ public final class LocalResourceContainer { /** * Checks validity of a RuleContext to produce an AndroidData. - * + * * @throws RuleErrorException if the RuleContext is invalid. Accumulated errors will be available * via {@code ruleContext} */ @@ -99,14 +98,14 @@ public final class LocalResourceContainer { } } - /** - * Validates that there are no resources defined if there are resource attributes defined. - */ + /** Validates that there are no resources defined if there are resource attributes defined. */ private static void validateNoResourcesAttribute(RuleContext ruleContext) throws RuleErrorException { if (ruleContext.attributes().isAttributeValueExplicitlySpecified("resources")) { - ruleContext.throwWithAttributeError("resources", - String.format("resources cannot be set when any of %s are defined.", + ruleContext.throwWithAttributeError( + "resources", + String.format( + "resources cannot be set when any of %s are defined.", Joiner.on(", ").join(RESOURCES_ATTRIBUTES))); } } @@ -120,15 +119,16 @@ public final class LocalResourceContainer { Iterable<AndroidResourcesProvider> resources = ruleContext.getPrerequisites("srcs", Mode.TARGET, AndroidResourcesProvider.class); for (AndroidResourcesProvider provider : resources) { - ruleContext.throwWithAttributeError("srcs", + ruleContext.throwWithAttributeError( + "srcs", String.format("srcs should not contain android_resource label %s", provider.getLabel())); } } private static void validateManifest(RuleContext ruleContext) throws RuleErrorException { if (ruleContext.getPrerequisiteArtifact("manifest", Mode.TARGET) == null) { - ruleContext.throwWithAttributeError("manifest", - "manifest is required when resource_files or assets are defined."); + ruleContext.throwWithAttributeError( + "manifest", "manifest is required when resource_files or assets are defined."); } } @@ -364,10 +364,10 @@ public final class LocalResourceContainer { ImmutableList<PathFragment> resourceRoots, ImmutableList<Artifact> assets, ImmutableList<PathFragment> assetRoots) { - this.resources = resources; - this.resourceRoots = resourceRoots; - this.assets = assets; - this.assetRoots = assetRoots; + this.resources = resources; + this.resourceRoots = resourceRoots; + this.assets = assets; + this.assetRoots = assetRoots; } public ImmutableList<Artifact> getResources() { diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/ManifestMergerActionBuilder.java b/src/main/java/com/google/devtools/build/lib/rules/android/ManifestMergerActionBuilder.java index 0df89bf3a8..798b1867a3 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/ManifestMergerActionBuilder.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/ManifestMergerActionBuilder.java @@ -32,9 +32,7 @@ import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; -/** - * Builder for creating manifest merger actions. - */ +/** Builder for creating manifest merger actions. */ public class ManifestMergerActionBuilder { private final RuleContext ruleContext; private final SpawnAction.Builder spawnActionBuilder; @@ -163,7 +161,8 @@ public class ManifestMergerActionBuilder { return mapToDictionaryString(map, Functions.toStringFunction(), Functions.toStringFunction()); } - private <K, V> String mapToDictionaryString(Map<K, V> map, + private <K, V> String mapToDictionaryString( + Map<K, V> map, Function<? super K, String> keyConverter, Function<? super V, String> valueConverter) { if (keyConverter == null) { @@ -187,4 +186,3 @@ public class ManifestMergerActionBuilder { return sb.toString(); } } - diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/NativeLibs.java b/src/main/java/com/google/devtools/build/lib/rules/android/NativeLibs.java index cfe19e1323..f499541d31 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/NativeLibs.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/NativeLibs.java @@ -102,9 +102,9 @@ public final class NativeLibs { // The native deps name file must be the only file in its directory because ApkBuilder does // not have an option to add a particular file to the .apk, only one to add every file in a // particular directory. - Artifact nativeDepsName = ruleContext.getUniqueDirectoryArtifact( - "nativedeps_filename", nativeDepsFileName, - ruleContext.getBinOrGenfilesDirectory()); + Artifact nativeDepsName = + ruleContext.getUniqueDirectoryArtifact( + "nativedeps_filename", nativeDepsFileName, ruleContext.getBinOrGenfilesDirectory()); ruleContext.registerAction( FileWriteAction.create(ruleContext, nativeDepsName, nativeDepsLibraryBasename, false)); @@ -154,9 +154,13 @@ public final class NativeLibs { } Artifact inputManifest = AndroidBinary.getDxArtifact(ruleContext, "native_symlinks.manifest"); - SourceManifestAction sourceManifestAction = new SourceManifestAction.Builder( - ruleContext.getWorkspaceName(), ManifestType.SOURCE_SYMLINKS, ruleContext.getActionOwner(), - inputManifest, ruleContext.getConfiguration().legacyExternalRunfiles()) + SourceManifestAction sourceManifestAction = + new SourceManifestAction.Builder( + ruleContext.getWorkspaceName(), + ManifestType.SOURCE_SYMLINKS, + ruleContext.getActionOwner(), + inputManifest, + ruleContext.getConfiguration().legacyExternalRunfiles()) .addRootSymlinks(symlinks) .build(); ruleContext.registerAction(sourceManifestAction); diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/RClassGeneratorActionBuilder.java b/src/main/java/com/google/devtools/build/lib/rules/android/RClassGeneratorActionBuilder.java index f6cf02e841..876bc1d9a8 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/RClassGeneratorActionBuilder.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/RClassGeneratorActionBuilder.java @@ -34,9 +34,7 @@ import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; -/** - * Builds up the spawn action for $android_rclass_generator. - */ +/** Builds up the spawn action for $android_rclass_generator. */ public class RClassGeneratorActionBuilder { private final RuleContext ruleContext; @@ -47,9 +45,7 @@ public class RClassGeneratorActionBuilder { private AndroidAaptVersion version; - /** - * @param ruleContext The RuleContext that is used to create a SpawnAction.Builder. - */ + /** @param ruleContext The RuleContext that is used to create a SpawnAction.Builder. */ public RClassGeneratorActionBuilder(RuleContext ruleContext) { this.ruleContext = ruleContext; } diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/ResourceApk.java b/src/main/java/com/google/devtools/build/lib/rules/android/ResourceApk.java index 4f244bd683..a4980cf040 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/ResourceApk.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/ResourceApk.java @@ -27,12 +27,12 @@ public final class ResourceApk { // TODO(bazel-team): The only fields that are legitimately nullable are javaSrcJar and // mainDexProguardConfig. The rest are marked as such due to .fromTransitiveResources(). // It seems like there should be a better way to do this. - @Nullable private final Artifact resourceApk; // The .ap_ file - @Nullable private final Artifact resourceJavaSrcJar; // Source jar containing R.java and friends - @Nullable private final Artifact resourceJavaClassJar; // Class jar containing R.class files + @Nullable private final Artifact resourceApk; // The .ap_ file + @Nullable private final Artifact resourceJavaSrcJar; // Source jar containing R.java and friends + @Nullable private final Artifact resourceJavaClassJar; // Class jar containing R.class files private final ResourceDependencies resourceDeps; @Nullable private final ResourceContainer primaryResource; - @Nullable private final Artifact manifest; // The non-binary XML version of AndroidManifest.xml + @Nullable private final Artifact manifest; // The non-binary XML version of AndroidManifest.xml @Nullable private final Artifact resourceProguardConfig; @Nullable private final Artifact mainDexProguardConfig; private final boolean legacy; @@ -82,8 +82,7 @@ public final class ResourceApk { return legacy; } - public static ResourceApk fromTransitiveResources( - ResourceDependencies resourceDeps) { + public static ResourceApk fromTransitiveResources(ResourceDependencies resourceDeps) { return new ResourceApk(null, null, null, resourceDeps, null, null, null, null, false); } @@ -109,8 +108,8 @@ public final class ResourceApk { * <p>If the ResourceApk was generated from a "resources" attribute, it will contain the * "resources" container in the direct dependencies and the rest as transitive. * - * <p>If the ResourceApk was generated from local resources, that will be the direct dependencies and - * the rest will be transitive. + * <p>If the ResourceApk was generated from local resources, that will be the direct dependencies + * and the rest will be transitive. */ public AndroidResourcesProvider toResourceProvider(Label label, boolean isResourcesOnly) { if (primaryResource == null) { diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/ResourceContainer.java b/src/main/java/com/google/devtools/build/lib/rules/android/ResourceContainer.java index fa76544120..89d110f4d4 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/ResourceContainer.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/ResourceContainer.java @@ -87,7 +87,7 @@ public abstract class ResourceContainer { /** * Gets the directories containing the assets. * - * TODO(b/30308041): Stop using these directories, and remove this code. + * <p>TODO(b/30308041): Stop using these directories, and remove this code. * * @deprecated We are moving towards passing around the actual artifacts, rather than the * directories that contain them. If the resources were provided with a glob() that excludes @@ -100,7 +100,7 @@ public abstract class ResourceContainer { /** * Gets the directories containing the resources. * - * TODO(b/30308041): Stop using these directories, and remove this code. + * <p>TODO(b/30308041): Stop using these directories, and remove this code. * * @deprecated We are moving towards passing around the actual artifacts, rather than the * directories that contain them. If the resources were provided with a glob() that excludes @@ -113,7 +113,7 @@ public abstract class ResourceContainer { /** * Gets the directories containing the resources of a specific type. * - * TODO(b/30308041): Stop using these directories, and remove this code. + * <p>TODO(b/30308041): Stop using these directories, and remove this code. * * @deprecated We are moving towards passing around the actual artifacts, rather than the * directories that contain them. If the resources were provided with a glob() that excludes @@ -233,9 +233,9 @@ public abstract class ResourceContainer { */ MANIFEST, /** - * Uses the package from the path to the source jar (or, if the rule context has it set, - * the {@code custom_package} attribute). If the source jar is not under a valid Java root, - * this will result in an error being added to the rule context. This can only be used if the + * Uses the package from the path to the source jar (or, if the rule context has it set, the + * {@code custom_package} attribute). If the source jar is not under a valid Java root, this + * will result in an error being added to the rule context. This can only be used if the * builder was created by {@link ResourceContainer#builderFromRule(RuleContext)}. */ SOURCE_JAR_PATH @@ -256,13 +256,13 @@ public abstract class ResourceContainer { } /** - * Sets the Java package from the given source. Overrides earlier calls to - * {@link #setJavaPackageFrom(JavaPackageSource)} or {@link #setJavaPackageFromString(String)}. + * Sets the Java package from the given source. Overrides earlier calls to {@link + * #setJavaPackageFrom(JavaPackageSource)} or {@link #setJavaPackageFromString(String)}. * * <p>To set the package from {@link JavaPackageSource#SOURCE_JAR_PATH}, this instance must have * been created using {@link ResourceContainer#builderFromRule(RuleContext)}. Also in this case, - * the source jar must be set non-{@code null} when the {@link #build()} method is called. - * It defaults to the source jar implicit output when creating a builder out of a rule context. + * the source jar must be set non-{@code null} when the {@link #build()} method is called. It + * defaults to the source jar implicit output when creating a builder out of a rule context. */ public Builder setJavaPackageFrom(JavaPackageSource javaPackageSource) { Preconditions.checkNotNull(javaPackageSource); @@ -274,11 +274,11 @@ public abstract class ResourceContainer { } /** - * Sets the Java package from the given string. Overrides earlier calls to - * {@link #setJavaPackageFrom(JavaPackageSource)} or {@link #setJavaPackageFromString(String)}. + * Sets the Java package from the given string. Overrides earlier calls to {@link + * #setJavaPackageFrom(JavaPackageSource)} or {@link #setJavaPackageFromString(String)}. * - * <p>To make {@link ResourceContainer#getJavaPackage()} return {@code null}, call - * {@code setJavaPackageFrom(MANIFEST)} instead. + * <p>To make {@link ResourceContainer#getJavaPackage()} return {@code null}, call {@code + * setJavaPackageFrom(MANIFEST)} instead. */ public Builder setJavaPackageFromString(String javaPackageOverride) { Preconditions.checkNotNull(javaPackageOverride); diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/ResourceContainerConverter.java b/src/main/java/com/google/devtools/build/lib/rules/android/ResourceContainerConverter.java index a1bbf2269b..bb1ddc5510 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/ResourceContainerConverter.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/ResourceContainerConverter.java @@ -55,14 +55,12 @@ public class ResourceContainerConverter { private Joiner argJoiner; private Function<String, String> escaper = Functions.identity(); - enum SeparatorType { COLON_COMMA, SEMICOLON_AMPERSAND } - Builder() { - } + Builder() {} Builder includeAapt2RTxt() { includeAapt2RTxt = true; diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/ResourceDependencies.java b/src/main/java/com/google/devtools/build/lib/rules/android/ResourceDependencies.java index e7ad609c6c..80ff7c823a 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/ResourceDependencies.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/ResourceDependencies.java @@ -34,9 +34,9 @@ import javax.annotation.Nullable; * abstraction simplifies the process of managing and exporting the direct and transitive resource * dependencies of an android rule, as well as providing type safety. * - * <p>The transitive and direct dependencies are not guaranteed to be disjoint. If a - * library is included in both the transitive and direct dependencies, it will appear twice. This - * requires consumers to manage duplicated resources gracefully. + * <p>The transitive and direct dependencies are not guaranteed to be disjoint. If a library is + * included in both the transitive and direct dependencies, it will appear twice. This requires + * consumers to manage duplicated resources gracefully. */ @Immutable public final class ResourceDependencies { @@ -66,13 +66,11 @@ public final class ResourceDependencies { /** * Transitive resource files for this target. * - * We keep them separate from the {@code transitiveAssets} so that we can filter them. + * <p>We keep them separate from the {@code transitiveAssets} so that we can filter them. */ private final NestedSet<Artifact> transitiveResources; - /** - * Transitive asset files for this target. - */ + /** Transitive asset files for this target. */ private final NestedSet<Artifact> transitiveAssets; private final NestedSet<Artifact> transitiveManifests; @@ -170,8 +168,8 @@ public final class ResourceDependencies { transitiveRTxt.build()); } - public static ResourceDependencies fromRuleResourceAndDeps(RuleContext ruleContext, - boolean neverlink) { + public static ResourceDependencies fromRuleResourceAndDeps( + RuleContext ruleContext, boolean neverlink) { NestedSetBuilder<ResourceContainer> transitiveDependencies = NestedSetBuilder.naiveLinkOrder(); NestedSetBuilder<ResourceContainer> directDependencies = NestedSetBuilder.naiveLinkOrder(); NestedSetBuilder<Artifact> transitiveResources = NestedSetBuilder.naiveLinkOrder(); @@ -310,8 +308,8 @@ public final class ResourceDependencies { } /** - * Creates an empty ResourceDependencies instance. This is used when an AndroidResources rule - * is the only resource dependency. The most common case is the AndroidTest rule. + * Creates an empty ResourceDependencies instance. This is used when an AndroidResources rule is + * the only resource dependency. The most common case is the AndroidTest rule. */ public static ResourceDependencies empty() { return new ResourceDependencies( @@ -453,9 +451,8 @@ public final class ResourceDependencies { * the resource merging as if this library didn't exist. * * @param label The label of the library exporting this provider. - * @param isResourcesOnly if the direct dependency is either an android_resources - * target or an android_library target with no fields that android_resources targets do not - * provide. + * @param isResourcesOnly if the direct dependency is either an android_resources target or an + * android_library target with no fields that android_resources targets do not provide. * @return A provider with the current resources and label. */ public AndroidResourcesProvider toProvider(Label label, boolean isResourcesOnly) { @@ -530,8 +527,8 @@ public final class ResourceDependencies { } /** - * @return The transitive closure of compiled symbols. - * Compiled symbols are zip files containing the compiled resource output of aapt2 compile + * @return The transitive closure of compiled symbols. Compiled symbols are zip files containing + * the compiled resource output of aapt2 compile */ public NestedSet<Artifact> getTransitiveCompiledSymbols() { return transitiveCompiledSymbols; diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/ResourceShrinkerActionBuilder.java b/src/main/java/com/google/devtools/build/lib/rules/android/ResourceShrinkerActionBuilder.java index fb1fb56d67..251672c981 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/ResourceShrinkerActionBuilder.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/ResourceShrinkerActionBuilder.java @@ -32,9 +32,7 @@ import com.google.devtools.build.lib.util.OS; import java.util.Collections; import java.util.List; -/** - * Builder for creating resource shrinker actions. - */ +/** Builder for creating resource shrinker actions. */ public class ResourceShrinkerActionBuilder { private AndroidAaptVersion targetAaptVersion; private Artifact resourceFilesZip; @@ -74,25 +72,19 @@ public class ResourceShrinkerActionBuilder { return this; } - /** - * @param resourceFilesZip A zip file containing the merged assets and resources to be shrunk. - */ + /** @param resourceFilesZip A zip file containing the merged assets and resources to be shrunk. */ public ResourceShrinkerActionBuilder withResourceFiles(Artifact resourceFilesZip) { this.resourceFilesZip = resourceFilesZip; return this; } - /** - * @param shrunkJar The deploy jar of the rule after a dead code removal Proguard pass. - */ + /** @param shrunkJar The deploy jar of the rule after a dead code removal Proguard pass. */ public ResourceShrinkerActionBuilder withShrunkJar(Artifact shrunkJar) { this.shrunkJar = shrunkJar; return this; } - /** - * @param proguardMapping The Proguard mapping between obfuscated and original code. - */ + /** @param proguardMapping The Proguard mapping between obfuscated and original code. */ public ResourceShrinkerActionBuilder withProguardMapping(Artifact proguardMapping) { this.proguardMapping = proguardMapping; return this; @@ -110,41 +102,31 @@ public class ResourceShrinkerActionBuilder { return this; } - /** - * @param resourceDeps The full dependency tree of {@link ResourceContainer}s. - */ + /** @param resourceDeps The full dependency tree of {@link ResourceContainer}s. */ public ResourceShrinkerActionBuilder withDependencies(ResourceDependencies resourceDeps) { this.dependencyResources = resourceDeps; return this; } - /** - * @param resourceApkOut The location to write the shrunk resource ap_ package. - */ + /** @param resourceApkOut The location to write the shrunk resource ap_ package. */ public ResourceShrinkerActionBuilder setResourceApkOut(Artifact resourceApkOut) { this.resourceApkOut = resourceApkOut; return this; } - /** - * @param shrunkResourcesOut The location to write the shrunk resource files zip. - */ + /** @param shrunkResourcesOut The location to write the shrunk resource files zip. */ public ResourceShrinkerActionBuilder setShrunkResourcesOut(Artifact shrunkResourcesOut) { this.shrunkResourcesOut = shrunkResourcesOut; return this; } - /** - * @param logOut The location to write the shrinker log. - */ + /** @param logOut The location to write the shrinker log. */ public ResourceShrinkerActionBuilder setLogOut(Artifact logOut) { this.logOut = logOut; return this; } - /** - * @param androidAaptVersion The aapt version to target with this action. - */ + /** @param androidAaptVersion The aapt version to target with this action. */ public ResourceShrinkerActionBuilder setTargetAaptVersion(AndroidAaptVersion androidAaptVersion) { this.targetAaptVersion = androidAaptVersion; return this; @@ -275,4 +257,3 @@ public class ResourceShrinkerActionBuilder { return resourcePackages.build(); } } - diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/UsesDataBindingProvider.java b/src/main/java/com/google/devtools/build/lib/rules/android/UsesDataBindingProvider.java index 7f69dac2bd..2f6ddd3c03 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/UsesDataBindingProvider.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/UsesDataBindingProvider.java @@ -19,9 +19,9 @@ import com.google.devtools.build.lib.analysis.TransitiveInfoProvider; import java.util.Collection; /** - * An Android rule that exposes this enables - * <a href="https://developer.android.com/topic/libraries/data-binding/index.html">data binding</a> - * on its resource processing and Java compilation. + * An Android rule that exposes this enables <a + * href="https://developer.android.com/topic/libraries/data-binding/index.html">data binding</a> on + * its resource processing and Java compilation. */ public final class UsesDataBindingProvider implements TransitiveInfoProvider { private final ImmutableList<Artifact> metadataOutputs; diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/WriteAdbArgsAction.java b/src/main/java/com/google/devtools/build/lib/rules/android/WriteAdbArgsAction.java index ea9f554c28..02d46b59a3 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/WriteAdbArgsAction.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/WriteAdbArgsAction.java @@ -40,9 +40,7 @@ import java.util.List; public final class WriteAdbArgsAction extends AbstractFileWriteAction { private static final String GUID = "16720416-3c01-4b0a-a543-ead7e563a1ca"; - /** - * Options of the {@code mobile-install} command pertaining to the way {@code adb} is invoked. - */ + /** Options of the {@code mobile-install} command pertaining to the way {@code adb} is invoked. */ public static final class Options extends OptionsBase { @Option( name = "adb", @@ -149,7 +147,7 @@ public final class WriteAdbArgsAction extends AbstractFileWriteAction { ps.printf("--adb=%s\n", adb); } - if (!device.isEmpty()){ + if (!device.isEmpty()) { args.add("-s"); args.add(device); } @@ -189,9 +187,7 @@ public final class WriteAdbArgsAction extends AbstractFileWriteAction { @Override protected String computeKey(ActionKeyContext actionKeyContext) { - return new Fingerprint() - .addString(GUID) - .hexDigestAndReset(); + return new Fingerprint().addString(GUID).hexDigestAndReset(); } /** Specifies how the app should be started/stopped. */ diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/WriteAdbArgsActionContext.java b/src/main/java/com/google/devtools/build/lib/rules/android/WriteAdbArgsActionContext.java index fcdb81cc79..9c0f355f45 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/WriteAdbArgsActionContext.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/WriteAdbArgsActionContext.java @@ -17,9 +17,7 @@ import com.google.devtools.build.lib.actions.ActionContext; import com.google.devtools.build.lib.actions.ExecutionStrategy; import javax.annotation.Nullable; -/** - * {@link ActionContext} for {@link WriteAdbArgsAction}. - */ +/** {@link ActionContext} for {@link WriteAdbArgsAction}. */ @ExecutionStrategy(contextType = WriteAdbArgsActionContext.class) public final class WriteAdbArgsActionContext implements ActionContext { @@ -31,7 +29,7 @@ public final class WriteAdbArgsActionContext implements ActionContext { /** * @return The user's home directory as set in the environment in which the Blaze client is called - * or null if the HOME environment variable has not been set. + * or null if the HOME environment variable has not been set. */ @Nullable public String getUserHomeDirectory() { diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/ZipFilterBuilder.java b/src/main/java/com/google/devtools/build/lib/rules/android/ZipFilterBuilder.java index 37e1af0b38..37d57186a2 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/ZipFilterBuilder.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/ZipFilterBuilder.java @@ -21,13 +21,9 @@ import com.google.devtools.build.lib.analysis.actions.CustomCommandLine.VectorAr import com.google.devtools.build.lib.analysis.actions.SpawnAction; import com.google.devtools.build.lib.analysis.configuredtargets.RuleConfiguredTarget.Mode; -/** - * Builder for creating a zip filter action. - */ +/** Builder for creating a zip filter action. */ public class ZipFilterBuilder { - /** - * Type of compression to apply to output archive. - */ + /** Type of compression to apply to output archive. */ public enum Compression { /** Output should be compressed. */ COMPRESSED, diff --git a/src/tools/android/java/com/google/devtools/build/android/Aapt2ResourcePackagingAction.java b/src/tools/android/java/com/google/devtools/build/android/Aapt2ResourcePackagingAction.java index c2ddb7cd9f..90487a3c42 100644 --- a/src/tools/android/java/com/google/devtools/build/android/Aapt2ResourcePackagingAction.java +++ b/src/tools/android/java/com/google/devtools/build/android/Aapt2ResourcePackagingAction.java @@ -120,8 +120,7 @@ public class Aapt2ResourcePackagingAction { dataDeserializer, options.throwOnResourceConflict) .filter( - new DensitySpecificResourceFilter( - densities, filteredResources, mergedResources), + new DensitySpecificResourceFilter(densities, filteredResources, mergedResources), new DensitySpecificManifestProcessor(densities, densityManifest)); profiler.recordEndOf("merging"); diff --git a/src/tools/android/java/com/google/devtools/build/android/AaptCommandBuilder.java b/src/tools/android/java/com/google/devtools/build/android/AaptCommandBuilder.java index 4a7e711b0a..094d13622c 100644 --- a/src/tools/android/java/com/google/devtools/build/android/AaptCommandBuilder.java +++ b/src/tools/android/java/com/google/devtools/build/android/AaptCommandBuilder.java @@ -127,9 +127,10 @@ public class AaptCommandBuilder { if (values.size() > 200) { add( flag, - "@" + Files.write( - Files.createDirectories(workingDirectory).resolve("params" + flag), - ImmutableList.of(values.stream().collect(Collectors.joining(" "))))); + "@" + + Files.write( + Files.createDirectories(workingDirectory).resolve("params" + flag), + ImmutableList.of(values.stream().collect(Collectors.joining(" "))))); } else { addRepeated(flag, values); } diff --git a/src/tools/android/java/com/google/devtools/build/android/AarGeneratorAction.java b/src/tools/android/java/com/google/devtools/build/android/AarGeneratorAction.java index 6e57cc58dc..20e9e6c9d7 100644 --- a/src/tools/android/java/com/google/devtools/build/android/AarGeneratorAction.java +++ b/src/tools/android/java/com/google/devtools/build/android/AarGeneratorAction.java @@ -53,6 +53,7 @@ import java.util.zip.ZipOutputStream; * Action to generate an AAR archive for an Android library. * * <p> + * * <pre> * Example Usage: * java/com/google/build/android/AarGeneratorAction\ @@ -128,12 +129,14 @@ public class AarGeneratorAction { ) public Path aarOutput; - @Option(name = "throwOnResourceConflict", - defaultValue = "false", - category = "config", - documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, - effectTags = {OptionEffectTag.UNKNOWN}, - help = "If passed, resource merge conflicts will be treated as errors instead of warnings") + @Option( + name = "throwOnResourceConflict", + defaultValue = "false", + category = "config", + documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, + effectTags = {OptionEffectTag.UNKNOWN}, + help = "If passed, resource merge conflicts will be treated as errors instead of warnings" + ) public boolean throwOnResourceConflict; } @@ -167,8 +170,7 @@ public class AarGeneratorAction { VariantType.LIBRARY, null, /* filteredResources= */ ImmutableList.<String>of(), - options.throwOnResourceConflict - ); + options.throwOnResourceConflict); logger.fine(String.format("Merging finished at %dms", timer.elapsed(TimeUnit.MILLISECONDS))); writeAar(options.aarOutput, mergedData, options.manifest, options.rtxt, options.classes); @@ -200,8 +202,7 @@ public class AarGeneratorAction { throw new IllegalArgumentException( String.format( "%s must be specified. Building an .aar without %s is unsupported.", - Joiner.on(", ").join(nullFlags), - Joiner.on(", ").join(nullFlags))); + Joiner.on(", ").join(nullFlags), Joiner.on(", ").join(nullFlags))); } } @@ -209,8 +210,8 @@ public class AarGeneratorAction { static void writeAar( Path aar, final MergedAndroidData data, Path manifest, Path rtxt, Path classes) throws IOException { - try (final ZipOutputStream zipOut = new ZipOutputStream( - new BufferedOutputStream(Files.newOutputStream(aar)))) { + try (final ZipOutputStream zipOut = + new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(aar)))) { ZipEntry manifestEntry = new ZipEntry("AndroidManifest.xml"); manifestEntry.setTime(EPOCH); zipOut.putNextEntry(manifestEntry); diff --git a/src/tools/android/java/com/google/devtools/build/android/AndroidCompiledDataDeserializer.java b/src/tools/android/java/com/google/devtools/build/android/AndroidCompiledDataDeserializer.java index 020d2cf78d..6ca066d06d 100644 --- a/src/tools/android/java/com/google/devtools/build/android/AndroidCompiledDataDeserializer.java +++ b/src/tools/android/java/com/google/devtools/build/android/AndroidCompiledDataDeserializer.java @@ -49,7 +49,7 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** Deserializes {@link DataKey}, {@link DataValue} entries from compiled resource files. */ -public class AndroidCompiledDataDeserializer implements AndroidDataDeserializer{ +public class AndroidCompiledDataDeserializer implements AndroidDataDeserializer { private static final Logger logger = Logger.getLogger(AndroidCompiledDataDeserializer.class.getName()); @@ -105,11 +105,7 @@ public class AndroidCompiledDataDeserializer implements AndroidDataDeserializer{ List<ConfigValue> configValues = resource.getConfigValueList(); Preconditions.checkArgument(configValues.size() == 1); - int sourceIndex = - configValues.get(0) - .getValue() - .getSource() - .getPathIdx(); + int sourceIndex = configValues.get(0).getValue().getSource().getPathIdx(); String source = sourcePool.get(sourceIndex); @@ -120,8 +116,8 @@ public class AndroidCompiledDataDeserializer implements AndroidDataDeserializer{ new SimpleEntry<FullyQualifiedName, Boolean>(fqn, packageName.isEmpty())); if (packageName.isEmpty()) { - DataResourceXml dataResourceXml = DataResourceXml - .from(resourceValue, dataSource, resourceType, fullyQualifiedNames); + DataResourceXml dataResourceXml = + DataResourceXml.from(resourceValue, dataSource, resourceType, fullyQualifiedNames); if (resourceType == ResourceType.ID || resourceType == ResourceType.PUBLIC || resourceType == ResourceType.STYLEABLE) { @@ -137,10 +133,11 @@ public class AndroidCompiledDataDeserializer implements AndroidDataDeserializer{ /** * Reads compiled resource data files and adds them to consumers - * @param compiledFileStream First byte is number of compiled files represented in this file. - * Next 8 bytes is a long indicating the length of the metadata describing the compiled file. - * Next N bytes is the metadata describing the compiled file. - * The remaining bytes are the actual original file. + * + * @param compiledFileStream First byte is number of compiled files represented in this file. Next + * 8 bytes is a long indicating the length of the metadata describing the compiled file. Next + * N bytes is the metadata describing the compiled file. The remaining bytes are the actual + * original file. * @param consumers * @param fqnFactory * @throws IOException @@ -192,10 +189,13 @@ public class AndroidCompiledDataDeserializer implements AndroidDataDeserializer{ String fileZipPath = resourceFile.getName(); int resourceSubdirectoryIndex = fileZipPath.indexOf('_', fileZipPath.lastIndexOf('/')); - Path filePath = Paths.get(String.format("%s%c%s", - fileZipPath.substring(0, resourceSubdirectoryIndex), - '/', - fileZipPath.substring(resourceSubdirectoryIndex + 1))); + Path filePath = + Paths.get( + String.format( + "%s%c%s", + fileZipPath.substring(0, resourceSubdirectoryIndex), + '/', + fileZipPath.substring(resourceSubdirectoryIndex + 1))); String shortPath = filePath.getParent().getFileName() + "/" + filePath.getFileName(); @@ -206,8 +206,8 @@ public class AndroidCompiledDataDeserializer implements AndroidDataDeserializer{ continue; } - final String[] dirNameAndQualifiers = filePath.getParent().getFileName().toString() - .split(SdkConstants.RES_QUALIFIER_SEP); + final String[] dirNameAndQualifiers = + filePath.getParent().getFileName().toString().split(SdkConstants.RES_QUALIFIER_SEP); Factory fqnFactory = Factory.fromDirectoryName(dirNameAndQualifiers); LittleEndianDataInputStream dataInputStream = @@ -241,7 +241,7 @@ public class AndroidCompiledDataDeserializer implements AndroidDataDeserializer{ int stringCount = byteBuffer.getInt(8); boolean isUtf8 = (byteBuffer.getInt(16) & (1 << 8)) != 0; int stringsStart = byteBuffer.getInt(20); - //Position the ByteBuffer after the metadata + // Position the ByteBuffer after the metadata byteBuffer.position(28); List<String> strings = new ArrayList<>(); @@ -288,5 +288,4 @@ public class AndroidCompiledDataDeserializer implements AndroidDataDeserializer{ return strings; } - } diff --git a/src/tools/android/java/com/google/devtools/build/android/AndroidCompiledResourceMergingAction.java b/src/tools/android/java/com/google/devtools/build/android/AndroidCompiledResourceMergingAction.java index 88ae2be56b..155d7b39d7 100644 --- a/src/tools/android/java/com/google/devtools/build/android/AndroidCompiledResourceMergingAction.java +++ b/src/tools/android/java/com/google/devtools/build/android/AndroidCompiledResourceMergingAction.java @@ -34,10 +34,9 @@ import java.util.logging.Logger; /** * Provides an entry point for the compiled resource merging action. * - * <p>This action merges compiled intermediate resource files from aapt2 - * and reports merge conflicts. It also provides a merged manifest file - * to {@link ValidateAndLinkResourcesAction} and builds the resource class - * jar for the lib jar + * <p>This action merges compiled intermediate resource files from aapt2 and reports merge + * conflicts. It also provides a merged manifest file to {@link ValidateAndLinkResourcesAction} and + * builds the resource class jar for the lib jar */ public class AndroidCompiledResourceMergingAction { @@ -92,14 +91,15 @@ public class AndroidCompiledResourceMergingAction { AndroidResourceOutputs.createClassJar(generatedSources, options.classJarOutput); logger.fine( - String.format( - "Create classJar finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); + String.format("Create classJar finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); // Until enough users with manifest placeholders migrate to the new manifest merger, // we need to replace ${applicationId} and ${packageName} with options.packageForR to make // the manifests compatible with the old manifest merger. - processedManifest = AndroidManifestProcessor.with(stdLogger) - .processLibraryManifest(options.packageForR, options.primaryManifest, processedManifest); + processedManifest = + AndroidManifestProcessor.with(stdLogger) + .processLibraryManifest( + options.packageForR, options.primaryManifest, processedManifest); Files.createDirectories(options.manifestOutput.getParent()); Files.copy(processedManifest, options.manifestOutput); @@ -117,5 +117,4 @@ public class AndroidCompiledResourceMergingAction { } logger.fine(String.format("Resources merged in %sms", timer.elapsed(TimeUnit.MILLISECONDS))); } - } diff --git a/src/tools/android/java/com/google/devtools/build/android/AndroidDataDeserializer.java b/src/tools/android/java/com/google/devtools/build/android/AndroidDataDeserializer.java index 60212bdb20..400c9032f4 100644 --- a/src/tools/android/java/com/google/devtools/build/android/AndroidDataDeserializer.java +++ b/src/tools/android/java/com/google/devtools/build/android/AndroidDataDeserializer.java @@ -15,8 +15,9 @@ package com.google.devtools.build.android; import java.nio.file.Path; -/** Represents a deserializer to deserialize {@link DataKey} - * and {@link DataValue} from a path and feed to it consumers. +/** + * Represents a deserializer to deserialize {@link DataKey} and {@link DataValue} from a path and + * feed to it consumers. */ public interface AndroidDataDeserializer { diff --git a/src/tools/android/java/com/google/devtools/build/android/AndroidDataMerger.java b/src/tools/android/java/com/google/devtools/build/android/AndroidDataMerger.java index 16b43b848e..2a8c298335 100644 --- a/src/tools/android/java/com/google/devtools/build/android/AndroidDataMerger.java +++ b/src/tools/android/java/com/google/devtools/build/android/AndroidDataMerger.java @@ -232,8 +232,7 @@ class AndroidDataMerger { * the ultimate source of truth, provided it doesn't conflict with itself. * @return An UnwrittenMergedAndroidData, containing DataResource objects that can be written to * disk for aapt processing or serialized for future merge passes. - * @throws MergingException if there are issues with parsing resources from - * primaryData. + * @throws MergingException if there are issues with parsing resources from primaryData. * @throws MergeConflictException if there are merge conflicts */ UnwrittenMergedAndroidData merge( diff --git a/src/tools/android/java/com/google/devtools/build/android/AndroidDataSerializer.java b/src/tools/android/java/com/google/devtools/build/android/AndroidDataSerializer.java index f43bc7b7ef..cb19f78dca 100644 --- a/src/tools/android/java/com/google/devtools/build/android/AndroidDataSerializer.java +++ b/src/tools/android/java/com/google/devtools/build/android/AndroidDataSerializer.java @@ -31,9 +31,7 @@ import java.util.TreeMap; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; -/** - * Serializes {@link DataKey},{@link DataValue} entries to a binary file. - */ +/** Serializes {@link DataKey},{@link DataValue} entries to a binary file. */ public class AndroidDataSerializer { private static final Logger logger = Logger.getLogger(AndroidDataSerializer.class.getName()); @@ -48,7 +46,9 @@ public class AndroidDataSerializer { /** * Writes all of the collected DataKey -> DataValue. * - * The binary format will be: <pre> + * <p>The binary format will be: + * + * <pre> * {@link Header} * {@link com.google.devtools.build.android.proto.SerializeFormat.DataKey} keys... * {@link com.google.devtools.build.android.proto.SerializeFormat.DataValue} entries... @@ -68,22 +68,19 @@ public class AndroidDataSerializer { Files.newOutputStream(out, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE))) { // Set the header for the deserialization process. - SerializeFormat.Header.Builder headerBuilder = Header.newBuilder() - .setEntryCount(entries.size()); + SerializeFormat.Header.Builder headerBuilder = + Header.newBuilder().setEntryCount(entries.size()); // Create table of source paths to allow references in the serialization format via an index. ByteArrayOutputStream sourceTableOutputStream = new ByteArrayOutputStream(2048); DataSourceTable sourceTable = DataSourceTable.createAndWrite(entries, sourceTableOutputStream, headerBuilder); - headerBuilder - .build() - .writeDelimitedTo(outStream); + headerBuilder.build().writeDelimitedTo(outStream); writeKeyValuesTo(entries, outStream, sourceTable, sourceTableOutputStream.toByteArray()); } - logger.fine( - String.format("Serialized merged in %sms", timer.elapsed(TimeUnit.MILLISECONDS))); + logger.fine(String.format("Serialized merged in %sms", timer.elapsed(TimeUnit.MILLISECONDS))); } private void writeKeyValuesTo( @@ -100,8 +97,8 @@ public class AndroidDataSerializer { // TODO(corysmith): Tune the size of the byte array. ByteArrayOutputStream valuesOutputStream = new ByteArrayOutputStream(2048); for (Map.Entry<DataKey, DataValue> entry : entries) { - orderedValueSizes[valueSizeIndex++] = entry.getValue() - .serializeTo(entry.getKey(), sourceTable, valuesOutputStream); + orderedValueSizes[valueSizeIndex++] = + entry.getValue().serializeTo(entry.getKey(), sourceTable, valuesOutputStream); } // Serialize all the keys in sorted order valueSizeIndex = 0; diff --git a/src/tools/android/java/com/google/devtools/build/android/AndroidDataWriter.java b/src/tools/android/java/com/google/devtools/build/android/AndroidDataWriter.java index 91de790772..38d38f3aa0 100644 --- a/src/tools/android/java/com/google/devtools/build/android/AndroidDataWriter.java +++ b/src/tools/android/java/com/google/devtools/build/android/AndroidDataWriter.java @@ -189,7 +189,7 @@ public class AndroidDataWriter implements AndroidDataWritingVisitor { /** * Creates a new, naive writer for testing. * - * This writer has "assets" and a "res" directory from the destination directory, as well as a + * <p>This writer has "assets" and a "res" directory from the destination directory, as well as a * noop png cruncher and a {@link ExecutorService} of 1 thread. * * @param destination The base directory to derive all paths. @@ -212,7 +212,7 @@ public class AndroidDataWriter implements AndroidDataWritingVisitor { * @param resourceDirectory The directory to copy resources into. * @param assetsDirectory The directory to copy assets into. * @param cruncher The cruncher for png files. If the cruncher is null, it will be replaced with a - * noop cruncher. + * noop cruncher. * @param executorService An execution service for multi-threaded writing. * @return A new {@link AndroidDataWriter}. */ @@ -268,9 +268,7 @@ public class AndroidDataWriter implements AndroidDataWritingVisitor { writeTasks.add(executorService.submit(new CopyTask(sourcePath, destinationPath))); } - /** - * Finalizes all operations and flushes the buffers. - */ + /** Finalizes all operations and flushes the buffers. */ @Override public void flush() throws IOException { for (Entry<String, ResourceValuesDefinitions> entry : valueTags.entrySet()) { @@ -312,9 +310,7 @@ public class AndroidDataWriter implements AndroidDataWritingVisitor { valueTags.get(valuesPath).addAllNamespaces(namespaces); } - /** - * A container for the {@linkplain Segment}s of a values.xml file. - */ + /** A container for the {@linkplain Segment}s of a values.xml file. */ private static class ResourceValuesDefinitions { private static final class WritingTask implements Callable<Boolean> { @@ -589,8 +585,8 @@ public class AndroidDataWriter implements AndroidDataWritingVisitor { @Override public ValuesResourceDefinition endTag() { - Preconditions.checkArgument(!tagStack.isEmpty(), - "Unable to endTag, as no tag has been started."); + Preconditions.checkArgument( + !tagStack.isEmpty(), "Unable to endTag, as no tag has been started."); mapper.add("</" + tagStack.pop() + ">"); return this; } @@ -685,8 +681,11 @@ public class AndroidDataWriter implements AndroidDataWritingVisitor { @Override public Path write(Path previousSource, Writer writer) throws IOException { Path source = previousSource; - Preconditions.checkArgument(segmentsByName.containsKey(fqn), "%s has no segment in %s", - fqn.toPrettyString(), segmentsByName.keySet()); + Preconditions.checkArgument( + segmentsByName.containsKey(fqn), + "%s has no segment in %s", + fqn.toPrettyString(), + segmentsByName.keySet()); for (Segment s : segmentsByName.get(fqn)) { // not recording the source source = s.write(source, writer); diff --git a/src/tools/android/java/com/google/devtools/build/android/AndroidDataWritingVisitor.java b/src/tools/android/java/com/google/devtools/build/android/AndroidDataWritingVisitor.java index cbc60364b8..1ada80c1c1 100644 --- a/src/tools/android/java/com/google/devtools/build/android/AndroidDataWritingVisitor.java +++ b/src/tools/android/java/com/google/devtools/build/android/AndroidDataWritingVisitor.java @@ -26,9 +26,7 @@ import javax.xml.namespace.QName; /** An interface for visiting android data for writing. */ public interface AndroidDataWritingVisitor extends Flushable { - /** - * Copies the AndroidManifest to the destination directory. - */ + /** Copies the AndroidManifest to the destination directory. */ Path copyManifest(Path sourceManifest) throws IOException; /** @@ -71,8 +69,7 @@ public interface AndroidDataWritingVisitor extends Flushable { /** * Provides a fluent interface to generate an xml resource for the values directory. * - * <p>Example usage: - * <code> + * <p>Example usage: <code> * writer.define(key) * .derivedFrom(source) * .startTag(tagName) @@ -112,8 +109,8 @@ public interface AndroidDataWritingVisitor extends Flushable { * Takes another values xml resource and writes it as a child tag here. * * <p>This allows xml elements from other {@link XmlResourceValue} to be moved in the stream. - * Currently, this is only necessary for {@link StyleableXmlResourceValue} which can have - * {@link AttrXmlResourceValue} defined as child elements (yet, they are merged and treated as + * Currently, this is only necessary for {@link StyleableXmlResourceValue} which can have {@link + * AttrXmlResourceValue} defined as child elements (yet, they are merged and treated as * independent resources.) * * @param fqn The {@link FullyQualifiedName} of the {@link XmlResourceValue} to be adopted. This diff --git a/src/tools/android/java/com/google/devtools/build/android/AndroidFrameworkAttrIdProvider.java b/src/tools/android/java/com/google/devtools/build/android/AndroidFrameworkAttrIdProvider.java index 522dca5974..1ff8039e53 100644 --- a/src/tools/android/java/com/google/devtools/build/android/AndroidFrameworkAttrIdProvider.java +++ b/src/tools/android/java/com/google/devtools/build/android/AndroidFrameworkAttrIdProvider.java @@ -13,16 +13,12 @@ // limitations under the License. package com.google.devtools.build.android; -/** - * Provides the android.R.attr field IDs. - */ +/** Provides the android.R.attr field IDs. */ public interface AndroidFrameworkAttrIdProvider { int getAttrId(String attrName) throws AttrLookupException; - /** - * Exception thrown when lookup fails. - */ + /** Exception thrown when lookup fails. */ final class AttrLookupException extends Exception { AttrLookupException(Throwable t) { diff --git a/src/tools/android/java/com/google/devtools/build/android/AndroidManifestProcessor.java b/src/tools/android/java/com/google/devtools/build/android/AndroidManifestProcessor.java index 490d24587a..f870d6c7df 100644 --- a/src/tools/android/java/com/google/devtools/build/android/AndroidManifestProcessor.java +++ b/src/tools/android/java/com/google/devtools/build/android/AndroidManifestProcessor.java @@ -131,7 +131,8 @@ public class AndroidManifestProcessor { Map<String, String> values, String customPackage, Path output, - Path logFile) throws ManifestProcessingException { + Path logFile) + throws ManifestProcessingException { if (mergeeManifests.isEmpty() && values.isEmpty() && Strings.isNullOrEmpty(customPackage)) { return manifest; } @@ -253,7 +254,11 @@ public class AndroidManifestProcessor { if (versionCode != -1 || versionName != null || applicationId != null) { processManifest( - versionCode, versionName, manifest, processedManifest, MergeType.APPLICATION, + versionCode, + versionName, + manifest, + processedManifest, + MergeType.APPLICATION, applicationId); return processedManifest; } @@ -262,9 +267,7 @@ public class AndroidManifestProcessor { /** Processes the manifest for a library and return the manifest Path. */ public Path processLibraryManifest( - String newManifestPackage, - Path manifest, - Path processedManifest) { + String newManifestPackage, Path manifest, Path processedManifest) { if (newManifestPackage != null) { processManifest( @@ -402,11 +405,15 @@ public class AndroidManifestProcessor { public static Path writeDummyManifestForAapt(Path dummyManifest, String packageForR) { try { Files.createDirectories(dummyManifest.getParent()); - return Files.write(dummyManifest, String.format( - "<?xml version=\"1.0\" encoding=\"utf-8\"?>" - + "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"" - + " package=\"%s\">" - + "</manifest>", packageForR).getBytes(UTF_8)); + return Files.write( + dummyManifest, + String.format( + "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + + "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"" + + " package=\"%s\">" + + "</manifest>", + packageForR) + .getBytes(UTF_8)); } catch (IOException e) { throw new ManifestProcessingException(e); } diff --git a/src/tools/android/java/com/google/devtools/build/android/AndroidParsedDataDeserializer.java b/src/tools/android/java/com/google/devtools/build/android/AndroidParsedDataDeserializer.java index 71787b4b39..e704c06552 100644 --- a/src/tools/android/java/com/google/devtools/build/android/AndroidParsedDataDeserializer.java +++ b/src/tools/android/java/com/google/devtools/build/android/AndroidParsedDataDeserializer.java @@ -122,10 +122,7 @@ public class AndroidParsedDataDeserializer implements AndroidDataDeserializer { } private void readEntriesSegment( - KeyValueConsumers consumers, - InputStream in, - FileSystem currentFileSystem, - Header header) + KeyValueConsumers consumers, InputStream in, FileSystem currentFileSystem, Header header) throws IOException { int numberOfEntries = header.getEntryCount(); Map<DataKey, KeyValueConsumer<DataKey, ? extends DataValue>> keys = @@ -211,5 +208,3 @@ public class AndroidParsedDataDeserializer implements AndroidDataDeserializer { return builder.build(); } } - - diff --git a/src/tools/android/java/com/google/devtools/build/android/AndroidResourceClassWriter.java b/src/tools/android/java/com/google/devtools/build/android/AndroidResourceClassWriter.java index ec7a3286c9..b9458fb05b 100644 --- a/src/tools/android/java/com/google/devtools/build/android/AndroidResourceClassWriter.java +++ b/src/tools/android/java/com/google/devtools/build/android/AndroidResourceClassWriter.java @@ -33,7 +33,7 @@ import java.util.Map; * class files. */ public class AndroidResourceClassWriter implements Flushable, AndroidResourceSymbolSink { - + /** Create a new class writer. */ public static AndroidResourceClassWriter createWith( Path androidJar, Path out, String javaPackage) { @@ -46,7 +46,7 @@ public class AndroidResourceClassWriter implements Flushable, AndroidResourceSym return new AndroidResourceClassWriter( PlaceholderIdFieldInitializerBuilder.from(androidIdProvider), outputBasePath, packageName); } - + private final Path outputBasePath; private final String packageName; private boolean includeClassFile = true; diff --git a/src/tools/android/java/com/google/devtools/build/android/AndroidResourceMerger.java b/src/tools/android/java/com/google/devtools/build/android/AndroidResourceMerger.java index 2013617964..1257def88a 100644 --- a/src/tools/android/java/com/google/devtools/build/android/AndroidResourceMerger.java +++ b/src/tools/android/java/com/google/devtools/build/android/AndroidResourceMerger.java @@ -204,8 +204,8 @@ public class AndroidResourceMerger { } /** - * Merges all secondary compiled resources with the primary compiled resources, - * given that the primary resources have been separately compiled + * Merges all secondary compiled resources with the primary compiled resources, given that the + * primary resources have been separately compiled */ public static void mergeCompiledData( final SerializedAndroidData primary, @@ -245,5 +245,3 @@ public class AndroidResourceMerger { } } } - - diff --git a/src/tools/android/java/com/google/devtools/build/android/AndroidResourceMergingAction.java b/src/tools/android/java/com/google/devtools/build/android/AndroidResourceMergingAction.java index 454f056f8b..ceda631537 100644 --- a/src/tools/android/java/com/google/devtools/build/android/AndroidResourceMergingAction.java +++ b/src/tools/android/java/com/google/devtools/build/android/AndroidResourceMergingAction.java @@ -184,12 +184,14 @@ public class AndroidResourceMergingAction { ) public Path dataBindingInfoOut; - @Option(name = "throwOnResourceConflict", - defaultValue = "false", - category = "config", - documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, - effectTags = {OptionEffectTag.UNKNOWN}, - help = "If passed, resource merge conflicts will be treated as errors instead of warnings") + @Option( + name = "throwOnResourceConflict", + defaultValue = "false", + category = "config", + documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, + effectTags = {OptionEffectTag.UNKNOWN}, + help = "If passed, resource merge conflicts will be treated as errors instead of warnings" + ) public boolean throwOnResourceConflict; } @@ -328,8 +330,6 @@ public class AndroidResourceMergingAction { } @Override - public void end(int key) { - } - + public void end(int key) {} } } diff --git a/src/tools/android/java/com/google/devtools/build/android/AndroidResourceOutputs.java b/src/tools/android/java/com/google/devtools/build/android/AndroidResourceOutputs.java index 82001c6065..9b9cd2f317 100644 --- a/src/tools/android/java/com/google/devtools/build/android/AndroidResourceOutputs.java +++ b/src/tools/android/java/com/google/devtools/build/android/AndroidResourceOutputs.java @@ -216,7 +216,6 @@ public class AndroidResourceOutputs { paths.add(dir); return FileVisitResult.CONTINUE; } - } /** A FileVisitor that will add all files to be stored in a zip archive. */ diff --git a/src/tools/android/java/com/google/devtools/build/android/AndroidResourceParsingAction.java b/src/tools/android/java/com/google/devtools/build/android/AndroidResourceParsingAction.java index 9b72728ad0..e2a98e4f13 100644 --- a/src/tools/android/java/com/google/devtools/build/android/AndroidResourceParsingAction.java +++ b/src/tools/android/java/com/google/devtools/build/android/AndroidResourceParsingAction.java @@ -39,9 +39,7 @@ public class AndroidResourceParsingAction { private static final Logger logger = Logger.getLogger(AndroidResourceParsingAction.class.getName()); - /** - * Flag specifications for this action. - */ + /** Flag specifications for this action. */ public static final class Options extends OptionsBase { @Option( @@ -83,15 +81,13 @@ public class AndroidResourceParsingAction { final Stopwatch timer = Stopwatch.createStarted(); ParsedAndroidData parsedPrimary = ParsedAndroidData.from(options.primaryData); logger.fine(String.format("Walked XML tree at %dms", timer.elapsed(TimeUnit.MILLISECONDS))); - UnwrittenMergedAndroidData unwrittenData = UnwrittenMergedAndroidData.of( - null, - parsedPrimary, - ParsedAndroidData.from(ImmutableList.<DependencyAndroidData>of())); + UnwrittenMergedAndroidData unwrittenData = + UnwrittenMergedAndroidData.of( + null, parsedPrimary, ParsedAndroidData.from(ImmutableList.<DependencyAndroidData>of())); AndroidDataSerializer serializer = AndroidDataSerializer.create(); unwrittenData.serializeTo(serializer); serializer.flushTo(options.output); - logger.fine(String.format( - "Finished parse + serialize in %dms", timer.elapsed(TimeUnit.MILLISECONDS))); + logger.fine( + String.format("Finished parse + serialize in %dms", timer.elapsed(TimeUnit.MILLISECONDS))); } - } diff --git a/src/tools/android/java/com/google/devtools/build/android/AndroidResourceProcessingAction.java b/src/tools/android/java/com/google/devtools/build/android/AndroidResourceProcessingAction.java index 13b1c9aa46..86e5ec4d82 100644 --- a/src/tools/android/java/com/google/devtools/build/android/AndroidResourceProcessingAction.java +++ b/src/tools/android/java/com/google/devtools/build/android/AndroidResourceProcessingAction.java @@ -364,8 +364,8 @@ public class AndroidResourceProcessingAction { public static void main(String[] args) throws Exception { final Stopwatch timer = Stopwatch.createStarted(); - OptionsParser optionsParser = OptionsParser.newOptionsParser( - Options.class, AaptConfigOptions.class); + OptionsParser optionsParser = + OptionsParser.newOptionsParser(Options.class, AaptConfigOptions.class); optionsParser.enableParamsFileSupport( new ShellQuotedParamsFilePreProcessor(FileSystems.getDefault())); optionsParser.parseAndExitUponError(args); @@ -384,9 +384,7 @@ public class AndroidResourceProcessingAction { final Path dummyManifest = tmp.resolve("manifest-aapt-dummy/AndroidManifest.xml"); Path generatedSources = null; - if (options.srcJarOutput != null - || options.rOutput != null - || options.symbolsOut != null) { + if (options.srcJarOutput != null || options.rOutput != null || options.symbolsOut != null) { generatedSources = tmp.resolve("generated_resources"); } @@ -419,9 +417,7 @@ public class AndroidResourceProcessingAction { ? options.densities : Collections.<String>emptyList(); final List<String> densitiesForManifest = - densitiesToFilter.isEmpty() - ? options.densitiesForManifest - : densitiesToFilter; + densitiesToFilter.isEmpty() ? options.densitiesForManifest : densitiesToFilter; final DensityFilteredAndroidData filteredData = mergedData.filter( @@ -457,14 +453,13 @@ public class AndroidResourceProcessingAction { } if (hasConflictWithPackageUnderTest( - options.packageUnderTest, - processedData.getManifest(), - timer)) { + options.packageUnderTest, processedData.getManifest(), timer)) { logger.log( Level.SEVERE, "Android resources cannot be provided if the instrumentation package is the same as " + "the package under test, but the instrumentation package (in the manifest) and " - + "the package under test both had the same package: " + options.packageUnderTest); + + "the package under test both had the same package: " + + options.packageUnderTest); System.exit(1); } @@ -531,26 +526,23 @@ public class AndroidResourceProcessingAction { /** * Checks if there is a conflict between the package under test and the package being built. * - * When testing Android code, the test can be run in the same or a different process as the code - * being tested. If it's in the same process, we do not allow Android resources to be used by the - * test, as they could overwrite the resources used by the code being tested. If this APK won't - * be testing another APK, the test and code under test are in different processes, or no + * <p>When testing Android code, the test can be run in the same or a different process as the + * code being tested. If it's in the same process, we do not allow Android resources to be used by + * the test, as they could overwrite the resources used by the code being tested. If this APK + * won't be testing another APK, the test and code under test are in different processes, or no * resources are being used, this isn't a concern. * - * To determine whether the test and code under test are run in the same process, we check the + * <p>To determine whether the test and code under test are run in the same process, we check the * package of the code under test, passed into this function, against the target packages of any * <code>instrumentation</code> tags in this APK's manifest. * * @param packageUnderTest the package of the code under test, or null if no code is under test * @param processedManifest the processed manifest for this APK - * * @return true if there is a conflict, false otherwise */ @VisibleForTesting static boolean hasConflictWithPackageUnderTest( - @Nullable String packageUnderTest, - Path processedManifest, - Stopwatch timer) + @Nullable String packageUnderTest, Path processedManifest, Stopwatch timer) throws SAXException, StreamException, ParserConfigurationException, IOException { if (packageUnderTest == null) { return false; diff --git a/src/tools/android/java/com/google/devtools/build/android/AndroidResourceProcessor.java b/src/tools/android/java/com/google/devtools/build/android/AndroidResourceProcessor.java index 6c8b86b3e1..25e9f39c73 100644 --- a/src/tools/android/java/com/google/devtools/build/android/AndroidResourceProcessor.java +++ b/src/tools/android/java/com/google/devtools/build/android/AndroidResourceProcessor.java @@ -68,15 +68,11 @@ import java.util.concurrent.Executors; import java.util.logging.Logger; import javax.xml.xpath.XPathExpressionException; -/** - * Provides a wrapper around the AOSP build tools for resource processing. - */ +/** Provides a wrapper around the AOSP build tools for resource processing. */ public class AndroidResourceProcessor { static final Logger logger = Logger.getLogger(AndroidResourceProcessor.class.getName()); - /** - * Options class containing flags for Aapt setup. - */ + /** Options class containing flags for Aapt setup. */ public static final class AaptConfigOptions extends OptionsBase { @Option( name = "buildToolsVersion", @@ -204,7 +200,7 @@ public class AndroidResourceProcessor { private static final String ANDROID_SPLIT_DOCUMENTATION_URL = "https://developer.android.com/guide/topics/resources/providing-resources.html" - + "#QualifierRules"; + + "#QualifierRules"; @Option( name = "split", @@ -229,9 +225,7 @@ public class AndroidResourceProcessor { public List<String> splits; } - /** - * {@link AaptOptions} backed by an {@link AaptConfigOptions}. - */ + /** {@link AaptOptions} backed by an {@link AaptConfigOptions}. */ public static final class FlagAaptOptions implements AaptOptions { private final AaptConfigOptions options; @@ -264,16 +258,15 @@ public class AndroidResourceProcessor { public List<String> getAdditionalParameters() { List<String> params = new java.util.ArrayList<String>(); if (options.featureOf != null) { - params.add("--feature-of"); - params.add(options.featureOf.toString()); + params.add("--feature-of"); + params.add(options.featureOf.toString()); } if (options.featureAfter != null) { - params.add("--feature-after"); - params.add(options.featureAfter.toString()); + params.add("--feature-after"); + params.add(options.featureAfter.toString()); } return ImmutableList.copyOf(params); } - } private final StdLogger stdLogger; @@ -580,8 +573,8 @@ public class AndroidResourceProcessor { // (on a shared system). On the other hand, a lot of the work is I/O, so it's not completely // CPU bound. As a compromise, divide by 2 the reported availableProcessors. int numThreads = Math.max(1, Runtime.getRuntime().availableProcessors() / 2); - ListeningExecutorService executorService = MoreExecutors.listeningDecorator( - Executors.newFixedThreadPool(numThreads)); + ListeningExecutorService executorService = + MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(numThreads)); try (Closeable closeable = ExecutorServiceCloser.createWith(executorService)) { for (Entry<String, ListenableFuture<ResourceSymbols>> entry : ResourceSymbols.loadFrom(libraries, executorService, appPackageName).entries()) { @@ -600,7 +593,8 @@ public class AndroidResourceProcessor { List<DependencyAndroidData> dependencyData, String customPackageForR, Path androidManifest, - Path sourceOut) throws IOException { + Path sourceOut) + throws IOException { List<SymbolFileProvider> libraries = new ArrayList<>(); for (DependencyAndroidData dataDep : dependencyData) { SymbolFileProvider library = dataDep.asSymbolFileProvider(); @@ -691,9 +685,7 @@ public class AndroidResourceProcessor { AndroidManifestProcessor.writeDummyManifestForAapt(dummyManifest, packageForR); } - /** - * Shutdown AOSP utilized thread-pool. - */ + /** Shutdown AOSP utilized thread-pool. */ public void shutdown() { FullyQualifiedName.logCacheUsage(logger); // AOSP code never shuts down its singleton executor and leaves the process hanging. diff --git a/src/tools/android/java/com/google/devtools/build/android/Converters.java b/src/tools/android/java/com/google/devtools/build/android/Converters.java index 26d918b278..e58dd2d29b 100644 --- a/src/tools/android/java/com/google/devtools/build/android/Converters.java +++ b/src/tools/android/java/com/google/devtools/build/android/Converters.java @@ -321,8 +321,10 @@ public final class Converters { public static <T> List<T> concatLists( @Nullable List<? extends T> a, @Nullable List<? extends T> b) { - @SuppressWarnings("unchecked") List<T> la = (List<T>) a; - @SuppressWarnings("unchecked") List<T> lb = (List<T>) b; + @SuppressWarnings("unchecked") + List<T> la = (List<T>) a; + @SuppressWarnings("unchecked") + List<T> lb = (List<T>) b; if (la == null || la.isEmpty()) { return (lb == null || lb.isEmpty()) ? ImmutableList.of() : lb; } diff --git a/src/tools/android/java/com/google/devtools/build/android/DataAsset.java b/src/tools/android/java/com/google/devtools/build/android/DataAsset.java index b78b07fd30..c4ffbfe3b4 100644 --- a/src/tools/android/java/com/google/devtools/build/android/DataAsset.java +++ b/src/tools/android/java/com/google/devtools/build/android/DataAsset.java @@ -15,16 +15,12 @@ package com.google.devtools.build.android; import java.io.IOException; -/** - * Represents an Asset created from a binary file. - */ +/** Represents an Asset created from a binary file. */ public interface DataAsset extends DataValue { - /** - * Write the asset value to mergedDataWriter. - */ + /** Write the asset value to mergedDataWriter. */ void writeAsset(RelativeAssetPath key, AndroidDataWritingVisitor mergedDataWriter) throws IOException; - + /** Overwrite another {@link DataAsset}. */ DataAsset overwrite(DataAsset other); } diff --git a/src/tools/android/java/com/google/devtools/build/android/DataKey.java b/src/tools/android/java/com/google/devtools/build/android/DataKey.java index 0fbbd1f9ed..02f193c0f7 100644 --- a/src/tools/android/java/com/google/devtools/build/android/DataKey.java +++ b/src/tools/android/java/com/google/devtools/build/android/DataKey.java @@ -19,12 +19,12 @@ import java.io.OutputStream; /** * A general interface for resource and asset keys. * - * Resource and Assets are merged on the basis of a key value: + * <p>Resource and Assets are merged on the basis of a key value: * - * For Resources, this is the fully qualified name, consisting of the resource package, name, type, - * and qualifiers. + * <p>For Resources, this is the fully qualified name, consisting of the resource package, name, + * type, and qualifiers. * - * For Assets, it is the asset path from the assets directory. + * <p>For Assets, it is the asset path from the assets directory. */ public interface DataKey extends Comparable<DataKey> { @@ -33,18 +33,14 @@ public interface DataKey extends Comparable<DataKey> { * * @param output The destination stream to serialize the key. * @param valueSize The size, in bytes, of the serialized output for this key. The value size can - * be used for calculating offsets of the value in the stream. + * be used for calculating offsets of the value in the stream. */ void serializeTo(OutputStream output, int valueSize) throws IOException; - /** - * Returns a human readable string representation of the key. - */ + /** Returns a human readable string representation of the key. */ String toPrettyString(); - /** - * Defines a total ordering on the different key types to assist in compareTo operations. - */ + /** Defines a total ordering on the different key types to assist in compareTo operations. */ enum KeyType { ASSET_PATH, FULL_QUALIFIED_NAME diff --git a/src/tools/android/java/com/google/devtools/build/android/DataResource.java b/src/tools/android/java/com/google/devtools/build/android/DataResource.java index 1295f60192..16053923e1 100644 --- a/src/tools/android/java/com/google/devtools/build/android/DataResource.java +++ b/src/tools/android/java/com/google/devtools/build/android/DataResource.java @@ -15,9 +15,7 @@ package com.google.devtools.build.android; import com.google.devtools.build.android.AndroidResourceMerger.MergingException; -/** - * Represents an Android Resource parsed from an xml or binary file. - */ +/** Represents an Android Resource parsed from an xml or binary file. */ public interface DataResource extends DataValue { /** Write as a resource using the supplied {@link AndroidDataWritingVisitor}. */ void writeResource(FullyQualifiedName key, AndroidDataWritingVisitor writer) @@ -25,7 +23,7 @@ public interface DataResource extends DataValue { /** * Combines these resource together and returns a single resource. - * + * * @param resource Another resource to be combined with this one. * @return A union of the values of these two resources. * @throws IllegalArgumentException if either resource cannot combine with the other. @@ -34,7 +32,7 @@ public interface DataResource extends DataValue { /** Queue up writing the resource to the given {@link AndroidResourceSymbolSink}. */ void writeResourceToClass(FullyQualifiedName key, AndroidResourceSymbolSink sink); - + /** Overwrite another {@link DataResource}. */ DataResource overwrite(DataResource other); } diff --git a/src/tools/android/java/com/google/devtools/build/android/DataResourceXml.java b/src/tools/android/java/com/google/devtools/build/android/DataResourceXml.java index 145725f941..e26a7a87bd 100644 --- a/src/tools/android/java/com/google/devtools/build/android/DataResourceXml.java +++ b/src/tools/android/java/com/google/devtools/build/android/DataResourceXml.java @@ -58,9 +58,8 @@ import javax.xml.stream.events.StartElement; /** * Represents an Android Resource defined in the xml and value folder. * - * <p> - * Basically, if the resource is defined inside a <resources> tag, this class will handle it. - * Layouts are treated separately as they don't declare anything besides ids. + * <p>Basically, if the resource is defined inside a <resources> tag, this class will handle + * it. Layouts are treated separately as they don't declare anything besides ids. */ public class DataResourceXml implements DataResource { @@ -88,8 +87,7 @@ public class DataResourceXml implements DataResource { throws XMLStreamException, FactoryConfigurationError, IOException { XMLEventReader eventReader = xmlInputFactory.createXMLEventReader( - new BufferedInputStream(Files.newInputStream(path)), - StandardCharsets.UTF_8.toString()); + new BufferedInputStream(Files.newInputStream(path)), StandardCharsets.UTF_8.toString()); try { // TODO(corysmith): Make the xml parsing more readable. for (StartElement resources = XmlResourceValues.moveToResources(eventReader); @@ -104,15 +102,12 @@ public class DataResourceXml implements DataResource { attribute.getName().getNamespaceURI().isEmpty() ? attribute.getName().getLocalPart() : attribute.getName().getPrefix() + ":" + attribute.getName().getLocalPart(); - FullyQualifiedName fqn = fqnFactory.create( - VirtualType.RESOURCES_ATTRIBUTE, - attribute.getName().toString()); + FullyQualifiedName fqn = + fqnFactory.create(VirtualType.RESOURCES_ATTRIBUTE, attribute.getName().toString()); ResourcesAttribute resourceAttribute = ResourcesAttribute.of(fqn, attributeName, attribute.getValue()); - DataResourceXml resource = DataResourceXml.createWithNamespaces( - path, - resourceAttribute, - namespaces); + DataResourceXml resource = + DataResourceXml.createWithNamespaces(path, resourceAttribute, namespaces); if (resourceAttribute.isCombining()) { combiningConsumer.accept(fqn, resource); } else { @@ -172,9 +167,7 @@ public class DataResourceXml implements DataResource { throws InvalidProtocolBufferException { DataValueXml xmlValue = protoValue.getXmlValue(); return createWithNamespaces( - source, - valueFromProto(xmlValue), - Namespaces.from(xmlValue.getNamespace())); + source, valueFromProto(xmlValue), Namespaces.from(xmlValue.getNamespace())); } private static XmlResourceValue valueFromProto(SerializeFormat.DataValueXml proto) @@ -210,10 +203,11 @@ public class DataResourceXml implements DataResource { ResourceType resourceType, Map<String, Entry<FullyQualifiedName, Boolean>> fullyQualifiedNames) throws InvalidProtocolBufferException { - DataResourceXml dataResourceXml = createWithNamespaces( - source, - valueFromProto(protoValue, resourceType, fullyQualifiedNames), - Namespaces.empty()); + DataResourceXml dataResourceXml = + createWithNamespaces( + source, + valueFromProto(protoValue, resourceType, fullyQualifiedNames), + Namespaces.empty()); return dataResourceXml; } @@ -335,12 +329,11 @@ public class DataResourceXml implements DataResource { Path sourcePath, XmlResourceValue xml, ImmutableMap<String, String> prefixToUri) { return createWithNamespaces(sourcePath, xml, Namespaces.from(prefixToUri)); } - + public static DataResourceXml createWithNoNamespace(DataSource source, XmlResourceValue xml) { return new DataResourceXml(source, xml, Namespaces.empty()); } - public static DataResourceXml createWithNamespaces( DataSource source, XmlResourceValue xml, Namespaces namespaces) { return new DataResourceXml(source, xml, namespaces); @@ -418,7 +411,7 @@ public class DataResourceXml implements DataResource { } return createWithNamespaces(source.overwrite(resource.source()), xml, namespaces); } - + @Override public DataValue update(DataSource source) { return createWithNamespaces(source, xml, namespaces); diff --git a/src/tools/android/java/com/google/devtools/build/android/DataValue.java b/src/tools/android/java/com/google/devtools/build/android/DataValue.java index b399b106ae..ce86664a09 100644 --- a/src/tools/android/java/com/google/devtools/build/android/DataValue.java +++ b/src/tools/android/java/com/google/devtools/build/android/DataValue.java @@ -19,7 +19,7 @@ import java.io.OutputStream; /** * Represents the value associated with DataKey interface for resource and asset values. * - * A DataValue is either an android resource or asset derived from a Path. + * <p>A DataValue is either an android resource or asset derived from a Path. */ public interface DataValue { @@ -28,12 +28,9 @@ public interface DataValue { */ DataSource source(); - /** - * Serializes to a supplied stream and returns the number of bytes written. - */ - int serializeTo( - DataKey key, DataSourceTable sourceTable, OutputStream output) throws IOException; - + /** Serializes to a supplied stream and returns the number of bytes written. */ + int serializeTo(DataKey key, DataSourceTable sourceTable, OutputStream output) throws IOException; + DataValue update(DataSource source); /** Provides a representation of the value suitable for a conflict message. */ diff --git a/src/tools/android/java/com/google/devtools/build/android/DataValueFile.java b/src/tools/android/java/com/google/devtools/build/android/DataValueFile.java index 61c569c217..e45545f97a 100644 --- a/src/tools/android/java/com/google/devtools/build/android/DataValueFile.java +++ b/src/tools/android/java/com/google/devtools/build/android/DataValueFile.java @@ -25,7 +25,7 @@ import java.util.Objects; /** * Represents a file based android resource or asset. * - * These include all resource types except those found in values, as well as all assets. + * <p>These include all resource types except those found in values, as well as all assets. */ public class DataValueFile implements DataResource, DataAsset { diff --git a/src/tools/android/java/com/google/devtools/build/android/DensityFilteredAndroidData.java b/src/tools/android/java/com/google/devtools/build/android/DensityFilteredAndroidData.java index ae2db68eca..ff39e921d6 100644 --- a/src/tools/android/java/com/google/devtools/build/android/DensityFilteredAndroidData.java +++ b/src/tools/android/java/com/google/devtools/build/android/DensityFilteredAndroidData.java @@ -15,9 +15,7 @@ package com.google.devtools.build.android; import java.nio.file.Path; -/** - * Represents a MergedData that has been filtered for density content. - */ +/** Represents a MergedData that has been filtered for density content. */ public class DensityFilteredAndroidData extends MergedAndroidData { public DensityFilteredAndroidData(Path resources, Path assets, Path manifest) { diff --git a/src/tools/android/java/com/google/devtools/build/android/DensitySpecificManifestProcessor.java b/src/tools/android/java/com/google/devtools/build/android/DensitySpecificManifestProcessor.java index 8a08978f94..a5c5632505 100644 --- a/src/tools/android/java/com/google/devtools/build/android/DensitySpecificManifestProcessor.java +++ b/src/tools/android/java/com/google/devtools/build/android/DensitySpecificManifestProcessor.java @@ -38,46 +38,52 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; -/** - * Modifies a {@link MergedAndroidData} manifest for the specified densities. - */ +/** Modifies a {@link MergedAndroidData} manifest for the specified densities. */ public class DensitySpecificManifestProcessor { - static final ImmutableList<String> SCREEN_SIZES = ImmutableList.of( - "small", "normal", "large", "xlarge"); + static final ImmutableList<String> SCREEN_SIZES = + ImmutableList.of("small", "normal", "large", "xlarge"); static final ImmutableBiMap<String, String> PLAY_STORE_SUPPORTED_DENSITIES = ImmutableBiMap.<String, String>builder() - .put("ldpi", "ldpi") - .put("mdpi", "mdpi") - .put("tvdpi", "213") - .put("hdpi", "hdpi") - .put("280dpi", "280") - .put("xhdpi", "xhdpi") - .put("400dpi", "400") - .put("420dpi", "420") - .put("xxhdpi", "480") - .put("560dpi", "560") - .put("xxxhdpi", "640").build(); - - private static final ImmutableMap<String, Boolean> SECURE_XML_FEATURES = ImmutableMap.of( - XMLConstants.FEATURE_SECURE_PROCESSING, true, - "http://xml.org/sax/features/external-general-entities", false, - "http://xml.org/sax/features/external-parameter-entities", false, - "http://apache.org/xml/features/nonvalidating/load-external-dtd", false); + .put("ldpi", "ldpi") + .put("mdpi", "mdpi") + .put("tvdpi", "213") + .put("hdpi", "hdpi") + .put("280dpi", "280") + .put("xhdpi", "xhdpi") + .put("400dpi", "400") + .put("420dpi", "420") + .put("xxhdpi", "480") + .put("560dpi", "560") + .put("xxxhdpi", "640") + .build(); + + private static final ImmutableMap<String, Boolean> SECURE_XML_FEATURES = + ImmutableMap.of( + XMLConstants.FEATURE_SECURE_PROCESSING, + true, + "http://xml.org/sax/features/external-general-entities", + false, + "http://xml.org/sax/features/external-parameter-entities", + false, + "http://apache.org/xml/features/nonvalidating/load-external-dtd", + false); private static DocumentBuilder getSecureDocumentBuilder() throws ParserConfigurationException { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance( - "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl", null); + DocumentBuilderFactory factory = + DocumentBuilderFactory.newInstance( + "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl", null); factory.setValidating(false); factory.setXIncludeAware(false); for (Map.Entry<String, Boolean> featureAndValue : SECURE_XML_FEATURES.entrySet()) { - try { - factory.setFeature(featureAndValue.getKey(), featureAndValue.getValue()); - } catch (ParserConfigurationException e) { - throw new FactoryConfigurationError(e, - "Xerces DocumentBuilderFactory doesn't support the required security features: " - + e.getMessage()); - } + try { + factory.setFeature(featureAndValue.getKey(), featureAndValue.getValue()); + } catch (ParserConfigurationException e) { + throw new FactoryConfigurationError( + e, + "Xerces DocumentBuilderFactory doesn't support the required security features: " + + e.getMessage()); + } } return factory.newDocumentBuilder(); } @@ -122,8 +128,10 @@ public class DensitySpecificManifestProcessor { NodeList screenElements = doc.getElementsByTagName("screen"); for (int i = 0; i < screenElements.getLength(); i++) { Node screen = screenElements.item(i); - existingDensities.add(PLAY_STORE_SUPPORTED_DENSITIES.inverse().get( - screen.getAttributes().getNamedItem("android:screenDensity").getNodeValue())); + existingDensities.add( + PLAY_STORE_SUPPORTED_DENSITIES + .inverse() + .get(screen.getAttributes().getNamedItem("android:screenDensity").getNodeValue())); } if (existingDensities.containsAll(densities)) { return manifest; @@ -157,8 +165,8 @@ public class DensitySpecificManifestProcessor { for (String screenSize : SCREEN_SIZES) { Element screen = doc.createElement("screen"); screen.setAttribute("android:screenSize", screenSize); - screen.setAttribute("android:screenDensity", - PLAY_STORE_SUPPORTED_DENSITIES.get(density)); + screen.setAttribute( + "android:screenDensity", PLAY_STORE_SUPPORTED_DENSITIES.get(density)); compatibleScreens.appendChild(screen); } } @@ -166,8 +174,9 @@ public class DensitySpecificManifestProcessor { Files.createDirectories(out.getParent()); TransformerFactory transformerFactory = TransformerFactory.newInstance(); - transformerFactory.newTransformer().transform( - new DOMSource(doc), new StreamResult(Files.newOutputStream(out))); + transformerFactory + .newTransformer() + .transform(new DOMSource(doc), new StreamResult(Files.newOutputStream(out))); return out; } catch (ParserConfigurationException | SAXException | IOException | TransformerException e) { diff --git a/src/tools/android/java/com/google/devtools/build/android/DensitySpecificResourceFilter.java b/src/tools/android/java/com/google/devtools/build/android/DensitySpecificResourceFilter.java index 70180c1ccd..431169d2c2 100644 --- a/src/tools/android/java/com/google/devtools/build/android/DensitySpecificResourceFilter.java +++ b/src/tools/android/java/com/google/devtools/build/android/DensitySpecificResourceFilter.java @@ -42,20 +42,19 @@ import java.util.EnumSet; import java.util.List; import javax.annotation.Nullable; -/** - * Filters a {@link MergedAndroidData} resource drawables to the specified densities. - */ +/** Filters a {@link MergedAndroidData} resource drawables to the specified densities. */ public class DensitySpecificResourceFilter { private static class ResourceInfo { /** Path to an actual file resource, instead of a directory. */ private Path resource; + private String restype; private String qualifiers; private String density; private String resid; - public ResourceInfo(Path resource, String restype, String qualifiers, String density, - String resid) { + public ResourceInfo( + Path resource, String restype, String qualifiers, String density, String resid) { this.resource = resource; this.restype = restype; this.qualifiers = qualifiers; @@ -184,38 +183,43 @@ public class DensitySpecificResourceFilter { @VisibleForTesting List<Path> getResourceToRemove(List<Path> resourcePaths) { - Predicate<ResourceInfo> requestedDensityFilter = new Predicate<ResourceInfo>() { - @Override - public boolean apply(@Nullable ResourceInfo info) { - return !densities.contains(info.getDensity()); - } - }; + Predicate<ResourceInfo> requestedDensityFilter = + new Predicate<ResourceInfo>() { + @Override + public boolean apply(@Nullable ResourceInfo info) { + return !densities.contains(info.getDensity()); + } + }; List<ResourceInfo> resourceInfos = getResourceInfos(resourcePaths); List<ResourceInfo> densityResourceInfos = filterDensityResourceInfos(resourceInfos); List<ResourceInfo> resourceInfoToRemove = new ArrayList<>(); - Multimap<String, ResourceInfo> fileGroups = groupResourceInfos(densityResourceInfos, - GET_RESOURCE_ID); + Multimap<String, ResourceInfo> fileGroups = + groupResourceInfos(densityResourceInfos, GET_RESOURCE_ID); for (String key : fileGroups.keySet()) { - Multimap<String, ResourceInfo> qualifierGroups = groupResourceInfos(fileGroups.get(key), - GET_RESOURCE_QUALIFIERS); + Multimap<String, ResourceInfo> qualifierGroups = + groupResourceInfos(fileGroups.get(key), GET_RESOURCE_QUALIFIERS); for (String qualifiers : qualifierGroups.keySet()) { Collection<ResourceInfo> qualifierResourceInfos = qualifierGroups.get(qualifiers); if (qualifierResourceInfos.size() != 1) { - List<ResourceInfo> sortedResourceInfos = Ordering.natural().onResultOf( - new Function<ResourceInfo, Double>() { - @Override - public Double apply(ResourceInfo info) { - return matchScore(info, densities); - } - }).immutableSortedCopy(qualifierResourceInfos); - resourceInfoToRemove.addAll(Collections2.filter( - sortedResourceInfos.subList(1, sortedResourceInfos.size()), - requestedDensityFilter)); + List<ResourceInfo> sortedResourceInfos = + Ordering.natural() + .onResultOf( + new Function<ResourceInfo, Double>() { + @Override + public Double apply(ResourceInfo info) { + return matchScore(info, densities); + } + }) + .immutableSortedCopy(qualifierResourceInfos); + resourceInfoToRemove.addAll( + Collections2.filter( + sortedResourceInfos.subList(1, sortedResourceInfos.size()), + requestedDensityFilter)); } } } @@ -256,10 +260,13 @@ public class DensitySpecificResourceFilter { String[] qualifierArray = qualifiers.split("-"); String restype = qualifierArray[0]; - qualifiers = (qualifierArray.length) > 0 ? Joiner.on("-").join(Arrays.copyOfRange( - qualifierArray, 1, qualifierArray.length)) : ""; - resourceInfos.add(new ResourceInfo(resourcePath, restype, qualifiers, density, - resourcePath.getFileName().toString())); + qualifiers = + (qualifierArray.length) > 0 + ? Joiner.on("-").join(Arrays.copyOfRange(qualifierArray, 1, qualifierArray.length)) + : ""; + resourceInfos.add( + new ResourceInfo( + resourcePath, restype, qualifiers, density, resourcePath.getFileName().toString())); } return ImmutableList.copyOf(resourceInfos); @@ -270,8 +277,10 @@ public class DensitySpecificResourceFilter { List<ResourceInfo> densityResourceInfos = new ArrayList<>(); for (ResourceInfo info : resourceInfos) { - if (info.getRestype().equals("drawable") && !info.getDensity().equals("") - && !info.getDensity().equals("nodpi") && !info.getResid().endsWith(".xml")) { + if (info.getRestype().equals("drawable") + && !info.getDensity().equals("") + && !info.getDensity().equals("nodpi") + && !info.getResid().endsWith(".xml")) { densityResourceInfos.add(info); } } @@ -312,13 +321,15 @@ public class DensitySpecificResourceFilter { if (densities.isEmpty()) { return unFilteredResourceDir; } - final Path filteredResourceDir = - out.resolve(working.relativize(unFilteredResourceDir)); + final Path filteredResourceDir = out.resolve(working.relativize(unFilteredResourceDir)); RecursiveFileCopier fileVisitor = new RecursiveFileCopier(filteredResourceDir, unFilteredResourceDir); try { - Files.walkFileTree(unFilteredResourceDir, EnumSet.of(FileVisitOption.FOLLOW_LINKS), - Integer.MAX_VALUE, fileVisitor); + Files.walkFileTree( + unFilteredResourceDir, + EnumSet.of(FileVisitOption.FOLLOW_LINKS), + Integer.MAX_VALUE, + fileVisitor); } catch (IOException e) { throw new RuntimeException(e); } diff --git a/src/tools/android/java/com/google/devtools/build/android/DependencyAndroidData.java b/src/tools/android/java/com/google/devtools/build/android/DependencyAndroidData.java index f59267d23e..b4d4b99b3f 100644 --- a/src/tools/android/java/com/google/devtools/build/android/DependencyAndroidData.java +++ b/src/tools/android/java/com/google/devtools/build/android/DependencyAndroidData.java @@ -62,12 +62,11 @@ class DependencyAndroidData extends SerializedAndroidData { compiledSymbols = CompiledResources.from(exists(fileSystem.getPath(parts[4]))); symbolsBin = exists(fileSystem.getPath(parts[5])); } else if (parts.length == 5) { - //This is either symbols bin or compiled symbols depending on "useCompiledResourcesForMerge" + // This is either symbols bin or compiled symbols depending on "useCompiledResourcesForMerge" compiledSymbols = CompiledResources.from(exists(fileSystem.getPath(parts[4]))); symbolsBin = exists(fileSystem.getPath(parts[4])); } - return new DependencyAndroidData( splitPaths(parts[0], fileSystem), assetDirs, diff --git a/src/tools/android/java/com/google/devtools/build/android/DependencySymbolFileProvider.java b/src/tools/android/java/com/google/devtools/build/android/DependencySymbolFileProvider.java index b6f86bd636..f5f1977d81 100644 --- a/src/tools/android/java/com/google/devtools/build/android/DependencySymbolFileProvider.java +++ b/src/tools/android/java/com/google/devtools/build/android/DependencySymbolFileProvider.java @@ -21,9 +21,7 @@ import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; -/** - * Represents the R.txt symbol file and AndroidManifest (provides Java package) of libraries. - */ +/** Represents the R.txt symbol file and AndroidManifest (provides Java package) of libraries. */ class DependencySymbolFileProvider implements SymbolFileProvider { private final File symbolFile; @@ -91,5 +89,4 @@ class DependencySymbolFileProvider implements SymbolFileProvider { public String toString() { return String.format("%s, %s", symbolFile, manifest); } - } diff --git a/src/tools/android/java/com/google/devtools/build/android/FailedFutureAggregator.java b/src/tools/android/java/com/google/devtools/build/android/FailedFutureAggregator.java index 06f49036e2..b95684d0f3 100644 --- a/src/tools/android/java/com/google/devtools/build/android/FailedFutureAggregator.java +++ b/src/tools/android/java/com/google/devtools/build/android/FailedFutureAggregator.java @@ -19,9 +19,7 @@ import java.io.IOException; import java.util.List; import java.util.concurrent.ExecutionException; -/** - * Aggregates a list of failed {@link ListenableFuture} and throws it as an exception. - */ +/** Aggregates a list of failed {@link ListenableFuture} and throws it as an exception. */ class FailedFutureAggregator<T extends Throwable> { private ExceptionFactory<T> exceptionFactory; diff --git a/src/tools/android/java/com/google/devtools/build/android/GenerateRobolectricResourceSymbolsAction.java b/src/tools/android/java/com/google/devtools/build/android/GenerateRobolectricResourceSymbolsAction.java index fa71b5f3e1..d6010bf0e9 100644 --- a/src/tools/android/java/com/google/devtools/build/android/GenerateRobolectricResourceSymbolsAction.java +++ b/src/tools/android/java/com/google/devtools/build/android/GenerateRobolectricResourceSymbolsAction.java @@ -46,9 +46,7 @@ import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; -/** - * This action generates consistent ids R.class files for use in robolectric tests. - */ +/** This action generates consistent ids R.class files for use in robolectric tests. */ public class GenerateRobolectricResourceSymbolsAction { private static final Logger logger = diff --git a/src/tools/android/java/com/google/devtools/build/android/KeyValueConsumers.java b/src/tools/android/java/com/google/devtools/build/android/KeyValueConsumers.java index 63b0a3a036..d3733a33ac 100644 --- a/src/tools/android/java/com/google/devtools/build/android/KeyValueConsumers.java +++ b/src/tools/android/java/com/google/devtools/build/android/KeyValueConsumers.java @@ -18,7 +18,8 @@ import com.google.devtools.build.android.ParsedAndroidData.KeyValueConsumer; /** * A group of {@link KeyValueConsumer}s for each DataValue type. * - * This class acts as a parameter object for organizing the common grouping of consumer instances. + * <p>This class acts as a parameter object for organizing the common grouping of consumer + * instances. */ class KeyValueConsumers { static KeyValueConsumers of( diff --git a/src/tools/android/java/com/google/devtools/build/android/ManifestMergerAction.java b/src/tools/android/java/com/google/devtools/build/android/ManifestMergerAction.java index e7a3ac6d55..a7301f1030 100644 --- a/src/tools/android/java/com/google/devtools/build/android/ManifestMergerAction.java +++ b/src/tools/android/java/com/google/devtools/build/android/ManifestMergerAction.java @@ -178,9 +178,9 @@ public class ManifestMergerAction { // Write resulting manifest to the output directory, maintaining full path to prevent collisions Path output = outputDir.resolve(manifest.toString().replaceFirst("^/", "")); Files.createDirectories(output.getParent()); - TransformerFactory.newInstance().newTransformer().transform( - new DOMSource(doc), - new StreamResult(output.toFile())); + TransformerFactory.newInstance() + .newTransformer() + .transform(new DOMSource(doc), new StreamResult(output.toFile())); return output; } @@ -201,8 +201,7 @@ public class ManifestMergerAction { ImmutableMap.Builder<Path, String> mergeeManifests = ImmutableMap.builder(); for (Entry<Path, String> mergeeManifest : options.mergeeManifests.entrySet()) { mergeeManifests.put( - removePermissions(mergeeManifest.getKey(), tmp), - mergeeManifest.getValue()); + removePermissions(mergeeManifest.getKey(), tmp), mergeeManifest.getValue()); } mergedManifest = @@ -229,4 +228,3 @@ public class ManifestMergerAction { } } } - diff --git a/src/tools/android/java/com/google/devtools/build/android/ManifestProcessingException.java b/src/tools/android/java/com/google/devtools/build/android/ManifestProcessingException.java index 24e16c206c..1530959068 100644 --- a/src/tools/android/java/com/google/devtools/build/android/ManifestProcessingException.java +++ b/src/tools/android/java/com/google/devtools/build/android/ManifestProcessingException.java @@ -13,9 +13,7 @@ // limitations under the License. package com.google.devtools.build.android; -/** - * Indicates an error parsing or modifying an AndroidManifest.xml. - */ +/** Indicates an error parsing or modifying an AndroidManifest.xml. */ public class ManifestProcessingException extends Exception { public ManifestProcessingException() { diff --git a/src/tools/android/java/com/google/devtools/build/android/MergeConflict.java b/src/tools/android/java/com/google/devtools/build/android/MergeConflict.java index 958c1e8456..5a98086bbb 100644 --- a/src/tools/android/java/com/google/devtools/build/android/MergeConflict.java +++ b/src/tools/android/java/com/google/devtools/build/android/MergeConflict.java @@ -24,11 +24,12 @@ import java.util.Objects; /** * Represents a conflict of two DataResources or DataAssets. * - * For resources, the dataKey is the FullyQualifiedName; Assets use the RelativeAssetPath. + * <p>For resources, the dataKey is the FullyQualifiedName; Assets use the RelativeAssetPath. */ @Immutable public class MergeConflict { - private static final String CONFLICT_MESSAGE = "\n\u001B[31mCONFLICT:\u001B[0m" + private static final String CONFLICT_MESSAGE = + "\n\u001B[31mCONFLICT:\u001B[0m" + " %s is provided with ambiguous priority from:\n\t%s\n\t%s"; private final DataKey dataKey; diff --git a/src/tools/android/java/com/google/devtools/build/android/MergedAndroidData.java b/src/tools/android/java/com/google/devtools/build/android/MergedAndroidData.java index 431d205e12..8483e8dcd3 100644 --- a/src/tools/android/java/com/google/devtools/build/android/MergedAndroidData.java +++ b/src/tools/android/java/com/google/devtools/build/android/MergedAndroidData.java @@ -53,8 +53,8 @@ class MergedAndroidData implements ManifestContainer { public DensityFilteredAndroidData filter( DensitySpecificResourceFilter resourceFilter, DensitySpecificManifestProcessor manifestProcessor) - throws ManifestProcessingException { - return new DensityFilteredAndroidData(resourceFilter.filter(resourceDir), - assetDir, manifestProcessor.process(manifest)); + throws ManifestProcessingException { + return new DensityFilteredAndroidData( + resourceFilter.filter(resourceDir), assetDir, manifestProcessor.process(manifest)); } } diff --git a/src/tools/android/java/com/google/devtools/build/android/NinePatchOnlyCruncher.java b/src/tools/android/java/com/google/devtools/build/android/NinePatchOnlyCruncher.java index 99fcbcb86d..d497b0d2d6 100644 --- a/src/tools/android/java/com/google/devtools/build/android/NinePatchOnlyCruncher.java +++ b/src/tools/android/java/com/google/devtools/build/android/NinePatchOnlyCruncher.java @@ -22,9 +22,7 @@ import com.google.common.io.Files; import java.io.File; import java.io.IOException; -/** - * A wrapper around a PNG cruncher that only processes nine-patch PNGs. - */ +/** A wrapper around a PNG cruncher that only processes nine-patch PNGs. */ public class NinePatchOnlyCruncher extends AaptCruncher { public NinePatchOnlyCruncher( diff --git a/src/tools/android/java/com/google/devtools/build/android/RClassGeneratorAction.java b/src/tools/android/java/com/google/devtools/build/android/RClassGeneratorAction.java index 3cf3a9d9f0..bcfdb5fdb3 100644 --- a/src/tools/android/java/com/google/devtools/build/android/RClassGeneratorAction.java +++ b/src/tools/android/java/com/google/devtools/build/android/RClassGeneratorAction.java @@ -56,14 +56,11 @@ import java.util.logging.Logger; */ public class RClassGeneratorAction { - private static final StdLogger STD_LOGGER = - new StdLogger(StdLogger.Level.WARNING); + private static final StdLogger STD_LOGGER = new StdLogger(StdLogger.Level.WARNING); private static final Logger logger = Logger.getLogger(RClassGeneratorAction.class.getName()); - /** - * Flag specifications for this action. - */ + /** Flag specifications for this action. */ public static final class Options extends OptionsBase { @Option( @@ -164,8 +161,8 @@ public class RClassGeneratorAction { if (options.primaryRTxt != null) { String appPackageName = options.packageForR; if (appPackageName == null) { - appPackageName = VariantConfiguration - .getManifestPackage(options.primaryManifest.toFile()); + appPackageName = + VariantConfiguration.getManifestPackage(options.primaryManifest.toFile()); } Multimap<String, ResourceSymbols> libSymbolMap = ArrayListMultimap.create(); ResourceSymbols fullSymbolValues = diff --git a/src/tools/android/java/com/google/devtools/build/android/RelativeAssetPath.java b/src/tools/android/java/com/google/devtools/build/android/RelativeAssetPath.java index 9940d13d27..1801026c96 100644 --- a/src/tools/android/java/com/google/devtools/build/android/RelativeAssetPath.java +++ b/src/tools/android/java/com/google/devtools/build/android/RelativeAssetPath.java @@ -25,16 +25,14 @@ import java.util.Objects; /** * Represents a DataKey for assets. * - * Assets are added to a single directory inside an apk by aapt. Therefore, to determine overwritten - * and conflicting assets we take the relative from the asset directory and turn it into a DataKey. - * This serves as the unique identifier for each apk stored asset. + * <p>Assets are added to a single directory inside an apk by aapt. Therefore, to determine + * overwritten and conflicting assets we take the relative from the asset directory and turn it into + * a DataKey. This serves as the unique identifier for each apk stored asset. * - * Note: Assets have no qualifiers or packages. + * <p>Note: Assets have no qualifiers or packages. */ public class RelativeAssetPath implements DataKey { - /** - * A Factory that creates RelativeAssetsPath objects whose paths are relative to a given path. - */ + /** A Factory that creates RelativeAssetsPath objects whose paths are relative to a given path. */ public static class Factory { private final Path assetRoot; @@ -42,9 +40,7 @@ public class RelativeAssetPath implements DataKey { this.assetRoot = assetRoot; } - /** - * Creates a new factory with the asset directory that contains assets. - */ + /** Creates a new factory with the asset directory that contains assets. */ public static Factory of(Path assetRoot) { return new Factory(Preconditions.checkNotNull(assetRoot)); } @@ -58,9 +54,7 @@ public class RelativeAssetPath implements DataKey { } } - /** - * Reconstitutes the relative asset path from a protocol buffer and {@link FileSystem}. - */ + /** Reconstitutes the relative asset path from a protocol buffer and {@link FileSystem}. */ static RelativeAssetPath fromProto(SerializeFormat.DataKey serialized, FileSystem fileSystem) { return of(fileSystem.getPath(serialized.getKeyValue())); } diff --git a/src/tools/android/java/com/google/devtools/build/android/ResourceShrinkerAction.java b/src/tools/android/java/com/google/devtools/build/android/ResourceShrinkerAction.java index ff38cac35f..7d9f59fb0d 100644 --- a/src/tools/android/java/com/google/devtools/build/android/ResourceShrinkerAction.java +++ b/src/tools/android/java/com/google/devtools/build/android/ResourceShrinkerAction.java @@ -239,7 +239,7 @@ public class ResourceShrinkerAction { } private static Set<String> getManifestPackages(Path primaryManifest, List<Path> otherManifests) - throws SAXException, IOException, StreamException, ParserConfigurationException { + throws SAXException, IOException, StreamException, ParserConfigurationException { Set<String> manifestPackages = new HashSet<>(); manifestPackages.add(getManifestPackage(primaryManifest)); for (Path manifest : otherManifests) { @@ -251,8 +251,8 @@ public class ResourceShrinkerAction { public static void main(String[] args) throws Exception { final Stopwatch timer = Stopwatch.createStarted(); // Parse arguments. - OptionsParser optionsParser = OptionsParser.newOptionsParser( - Options.class, AaptConfigOptions.class); + OptionsParser optionsParser = + OptionsParser.newOptionsParser(Options.class, AaptConfigOptions.class); optionsParser.enableParamsFileSupport( new ShellQuotedParamsFilePreProcessor(FileSystems.getDefault())); optionsParser.parseAndExitUponError(args); @@ -271,13 +271,13 @@ public class ResourceShrinkerAction { final Path shrunkResources = working.resolve("shrunk_resources"); // Gather package list from manifests. - Set<String> resourcePackages = getManifestPackages( - options.primaryManifest, options.dependencyManifests); + Set<String> resourcePackages = + getManifestPackages(options.primaryManifest, options.dependencyManifests); resourcePackages.addAll(options.resourcePackages); // Expand resource files zip into working directory. - try (ZipInputStream zin = new ZipInputStream( - new FileInputStream(options.resourcesZip.toFile()))) { + try (ZipInputStream zin = + new ZipInputStream(new FileInputStream(options.resourcesZip.toFile()))) { ZipEntry entry; while ((entry = zin.getNextEntry()) != null) { if (!entry.isDirectory()) { @@ -291,18 +291,20 @@ public class ResourceShrinkerAction { } // Shrink resources. - ResourceUsageAnalyzer resourceShrinker = new ResourceUsageAnalyzer( - resourcePackages, - options.rTxt, - options.shrunkJar, - options.primaryManifest, - options.proguardMapping, - resourceFiles.resolve("res"), - options.log); + ResourceUsageAnalyzer resourceShrinker = + new ResourceUsageAnalyzer( + resourcePackages, + options.rTxt, + options.shrunkJar, + options.primaryManifest, + options.proguardMapping, + resourceFiles.resolve("res"), + options.log); resourceShrinker.shrink(shrunkResources); - logger.fine(String.format("Shrinking resources finished at %sms", - timer.elapsed(TimeUnit.MILLISECONDS))); + logger.fine( + String.format( + "Shrinking resources finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); Path generatedSources = null; if (options.rTxtOutput != null) { @@ -338,8 +340,9 @@ public class ResourceShrinkerAction { AndroidResourceOutputs.copyRToOutput( generatedSources, options.rTxtOutput, options.packageType == VariantType.LIBRARY); } - logger.fine(String.format("Packing resources finished at %sms", - timer.elapsed(TimeUnit.MILLISECONDS))); + logger.fine( + String.format( + "Packing resources finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); } catch (Exception e) { logger.log(Level.SEVERE, "Error shrinking resources", e); throw e; diff --git a/src/tools/android/java/com/google/devtools/build/android/SplitConfigurationFilter.java b/src/tools/android/java/com/google/devtools/build/android/SplitConfigurationFilter.java index c1454e4d76..4103b800a2 100644 --- a/src/tools/android/java/com/google/devtools/build/android/SplitConfigurationFilter.java +++ b/src/tools/android/java/com/google/devtools/build/android/SplitConfigurationFilter.java @@ -40,10 +40,10 @@ import java.util.regex.Pattern; * API version, if any, then by other specifiers (case-insensitive), with ties broken by the * filename or split flag originally used to create the instance (case-sensitive). * - * <p>This has the following useful property:<br/> - * Given two sets of {@link SplitConfigurationFilter}s, one from the input split flags, and - * one from aapt's outputs... Each member of the output set can be matched to the greatest member - * of the input set for which {@code input.matchesFilterFromFilename(output)} is true. + * <p>This has the following useful property:<br> + * Given two sets of {@link SplitConfigurationFilter}s, one from the input split flags, and one from + * aapt's outputs... Each member of the output set can be matched to the greatest member of the + * input set for which {@code input.matchesFilterFromFilename(output)} is true. */ final class SplitConfigurationFilter implements Comparable<SplitConfigurationFilter> { @@ -181,10 +181,10 @@ final class SplitConfigurationFilter implements Comparable<SplitConfigurationFil * <p>Order of whole configurations doesn't matter, as aapt will reorder the configurations * according to complicated internal logic (yes, logic even more complicated than this!). * - * <p>Care is needed with API version specifiers because aapt may add or change minimum - * API version specifiers to configurations according to whether they had specifiers which are - * only supported in certain versions of Android. It will only ever increase the minimum version - * or leave it the same. + * <p>Care is needed with API version specifiers because aapt may add or change minimum API + * version specifiers to configurations according to whether they had specifiers which are only + * supported in certain versions of Android. It will only ever increase the minimum version or + * leave it the same. * * <p>The other (non-wildcard) specifiers should be case-insensitive identical, including order; * aapt will not allow parts of a single configuration to be parsed out of order. @@ -262,10 +262,10 @@ final class SplitConfigurationFilter implements Comparable<SplitConfigurationFil * <p>The natural ordering of this class sorts by required API version, if any, then by other * specifiers. * - * <p>This has the following useful property:<br/> - * Given two sets of {@link ResourceConfiguration}s, one from an input split flag, and - * one from aapt's output... Each member of the output set can be matched to the greatest member - * of the input set for which {@code input.matchesConfigurationFromFilename(output)} is true. + * <p>This has the following useful property:<br> + * Given two sets of {@link ResourceConfiguration}s, one from an input split flag, and one from + * aapt's output... Each member of the output set can be matched to the greatest member of the + * input set for which {@code input.matchesConfigurationFromFilename(output)} is true. */ static final class ResourceConfiguration implements Comparable<ResourceConfiguration> { /** diff --git a/src/tools/android/java/com/google/devtools/build/android/UnvalidatedAndroidDirectories.java b/src/tools/android/java/com/google/devtools/build/android/UnvalidatedAndroidDirectories.java index 8be10be0fb..49fdb18296 100644 --- a/src/tools/android/java/com/google/devtools/build/android/UnvalidatedAndroidDirectories.java +++ b/src/tools/android/java/com/google/devtools/build/android/UnvalidatedAndroidDirectories.java @@ -23,9 +23,7 @@ import java.nio.file.Path; import java.util.Objects; import java.util.regex.Pattern; -/** - * Android resource and asset directories that can be parsed. - */ +/** Android resource and asset directories that can be parsed. */ public class UnvalidatedAndroidDirectories { private static final Pattern VALID_REGEX = Pattern.compile(".*:.*"); @@ -39,8 +37,7 @@ public class UnvalidatedAndroidDirectories { @VisibleForTesting static UnvalidatedAndroidDirectories valueOf(String text, FileSystem fileSystem) { if (!VALID_REGEX.matcher(text).find()) { - throw new IllegalArgumentException( - text + " is not in the format '" + EXPECTED_FORMAT + "'"); + throw new IllegalArgumentException(text + " is not in the format '" + EXPECTED_FORMAT + "'"); } String[] parts = text.split(":"); return new UnvalidatedAndroidDirectories( diff --git a/src/tools/android/java/com/google/devtools/build/android/UnwrittenMergedAndroidData.java b/src/tools/android/java/com/google/devtools/build/android/UnwrittenMergedAndroidData.java index 1f0fe68355..4668887a40 100644 --- a/src/tools/android/java/com/google/devtools/build/android/UnwrittenMergedAndroidData.java +++ b/src/tools/android/java/com/google/devtools/build/android/UnwrittenMergedAndroidData.java @@ -21,9 +21,7 @@ import java.nio.file.Path; import java.util.Map.Entry; import java.util.Objects; -/** - * Merged Android Data that has yet to written into a {@link MergedAndroidData}. - */ +/** Merged Android Data that has yet to written into a {@link MergedAndroidData}. */ public class UnwrittenMergedAndroidData { private final Path manifest; diff --git a/src/tools/android/java/com/google/devtools/build/android/XmlResourceValue.java b/src/tools/android/java/com/google/devtools/build/android/XmlResourceValue.java index 0c0edd92a5..f24d6b271a 100644 --- a/src/tools/android/java/com/google/devtools/build/android/XmlResourceValue.java +++ b/src/tools/android/java/com/google/devtools/build/android/XmlResourceValue.java @@ -17,9 +17,7 @@ import com.google.devtools.build.android.xml.Namespaces; import java.io.IOException; import java.io.OutputStream; -/** - * An {@link XmlResourceValue} is extracted from xml files in the resource 'values' directory. - */ +/** An {@link XmlResourceValue} is extracted from xml files in the resource 'values' directory. */ public interface XmlResourceValue { /** * Each XmlValue is expected to write a valid representation in xml to the writer. @@ -35,7 +33,7 @@ public interface XmlResourceValue { /** * Combines these xml values together and returns a single value. - * + * * @param value Another resource to be combined with this one. * @return A union of the values of these two values. * @throws IllegalArgumentException if either value cannot combine with the other. diff --git a/src/tools/android/java/com/google/devtools/build/android/XmlResourceValues.java b/src/tools/android/java/com/google/devtools/build/android/XmlResourceValues.java index 432cfc7495..1ea38826bf 100644 --- a/src/tools/android/java/com/google/devtools/build/android/XmlResourceValues.java +++ b/src/tools/android/java/com/google/devtools/build/android/XmlResourceValues.java @@ -80,6 +80,7 @@ public class XmlResourceValues { private static final XMLOutputFactory XML_OUTPUT_FACTORY = XMLOutputFactory.newInstance(); private static XMLInputFactory inputFactoryInstance = null; + public static XMLInputFactory getXmlInputFactory() { if (inputFactoryInstance == null) { inputFactoryInstance = XMLInputFactory.newInstance(); @@ -130,8 +131,7 @@ public class XmlResourceValues { // <Parent> // And, in the resource name <parent>.<resource name> // Here, we take a garbage in, garbage out approach and just read the xml value raw. - return StyleXmlResourceValue.of(getElementAttributeByName(start, ATTR_PARENT), - values); + return StyleXmlResourceValue.of(getElementAttributeByName(start, ATTR_PARENT), values); } static void parseDeclareStyleable( @@ -281,7 +281,7 @@ public class XmlResourceValues { } // TODO(corysmith): Replace this with real escaping system, preferably a performant high level xml - //writing library. See AndroidDataWritingVisitor TODO. + // writing library. See AndroidDataWritingVisitor TODO. private static String escapeXmlValues(String data) { return data.replace("&", "&").replace("<", "<").replace(">", ">"); } diff --git a/src/tools/android/java/com/google/devtools/build/android/ZipFilterAction.java b/src/tools/android/java/com/google/devtools/build/android/ZipFilterAction.java index e8aae6bad0..c774ec22f6 100644 --- a/src/tools/android/java/com/google/devtools/build/android/ZipFilterAction.java +++ b/src/tools/android/java/com/google/devtools/build/android/ZipFilterAction.java @@ -53,9 +53,12 @@ import java.util.regex.Pattern; * extension of '.*' was specified. * * <p>Assuming each Zip as a set of entries, the result is: + * * <pre> outputZip = inputZip - union[x intersect filterTypes for x in filterZips]</pre> * - * <p><pre> + * <p> + * + * <pre> * Example Usage: * java/com/google/build/android/ZipFilterAction\ * --inputZip path/to/inputZip diff --git a/src/tools/android/java/com/google/devtools/build/android/aapt2/Aapt2ConfigOptions.java b/src/tools/android/java/com/google/devtools/build/android/aapt2/Aapt2ConfigOptions.java index 6d8d614116..1b402eaf90 100644 --- a/src/tools/android/java/com/google/devtools/build/android/aapt2/Aapt2ConfigOptions.java +++ b/src/tools/android/java/com/google/devtools/build/android/aapt2/Aapt2ConfigOptions.java @@ -63,29 +63,28 @@ public class Aapt2ConfigOptions extends OptionsBase { public Path androidJar; @Option( - name = "annotationJar", - defaultValue = "null", - converter = ExistingPathConverter.class, - category = "tool", - documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, - effectTags = {OptionEffectTag.UNKNOWN}, - help = "Path to the android jar for resource packaging and building apks." + name = "annotationJar", + defaultValue = "null", + converter = ExistingPathConverter.class, + category = "tool", + documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, + effectTags = {OptionEffectTag.UNKNOWN}, + help = "Path to the android jar for resource packaging and building apks." ) public Path annotationJar; - @Option( - name = "useAaptCruncher", - defaultValue = "auto", - category = "config", - documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, - effectTags = {OptionEffectTag.UNKNOWN}, - help = - "Use the legacy aapt cruncher, defaults to true for non-LIBRARY packageTypes. " - + " LIBRARY packages do not benefit from the additional processing as the resources" - + " will need to be reprocessed during the generation of the final apk. See" - + " https://code.google.com/p/android/issues/detail?id=67525 for a discussion of the" - + " different png crunching methods." + name = "useAaptCruncher", + defaultValue = "auto", + category = "config", + documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, + effectTags = {OptionEffectTag.UNKNOWN}, + help = + "Use the legacy aapt cruncher, defaults to true for non-LIBRARY packageTypes. " + + " LIBRARY packages do not benefit from the additional processing as the resources" + + " will need to be reprocessed during the generation of the final apk. See" + + " https://code.google.com/p/android/issues/detail?id=67525 for a discussion of the" + + " different png crunching methods." ) public TriState useAaptCruncher; @@ -100,45 +99,45 @@ public class Aapt2ConfigOptions extends OptionsBase { public TriState conditionalKeepRules; @Option( - name = "uncompressedExtensions", - defaultValue = "", - converter = CommaSeparatedOptionListConverter.class, - category = "config", - documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, - effectTags = {OptionEffectTag.UNKNOWN}, - help = "A list of file extensions not to compress." + name = "uncompressedExtensions", + defaultValue = "", + converter = CommaSeparatedOptionListConverter.class, + category = "config", + documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, + effectTags = {OptionEffectTag.UNKNOWN}, + help = "A list of file extensions not to compress." ) public List<String> uncompressedExtensions; @Option( - name = "assetsToIgnore", - defaultValue = "", - converter = CommaSeparatedOptionListConverter.class, - category = "config", - documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, - effectTags = {OptionEffectTag.UNKNOWN}, - help = "A list of assets extensions to ignore." + name = "assetsToIgnore", + defaultValue = "", + converter = CommaSeparatedOptionListConverter.class, + category = "config", + documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, + effectTags = {OptionEffectTag.UNKNOWN}, + help = "A list of assets extensions to ignore." ) public List<String> assetsToIgnore; @Option( - name = "debug", - defaultValue = "false", - category = "config", - documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, - effectTags = {OptionEffectTag.UNKNOWN}, - help = "Indicates if it is a debug build." + name = "debug", + defaultValue = "false", + category = "config", + documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, + effectTags = {OptionEffectTag.UNKNOWN}, + help = "Indicates if it is a debug build." ) public boolean debug; @Option( - name = "resourceConfigs", - defaultValue = "", - converter = CommaSeparatedOptionListConverter.class, - category = "config", - documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, - effectTags = {OptionEffectTag.UNKNOWN}, - help = "A list of resource config filters to pass to aapt." + name = "resourceConfigs", + defaultValue = "", + converter = CommaSeparatedOptionListConverter.class, + category = "config", + documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, + effectTags = {OptionEffectTag.UNKNOWN}, + help = "A list of resource config filters to pass to aapt." ) public List<String> resourceConfigs; @@ -147,34 +146,34 @@ public class Aapt2ConfigOptions extends OptionsBase { + "#QualifierRules"; @Option( - name = "split", - defaultValue = "required but ignored due to allowMultiple", - category = "config", - documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, - effectTags = {OptionEffectTag.UNKNOWN}, - allowMultiple = true, - help = - "An individual split configuration to pass to aapt." - + " Each split is a list of configuration filters separated by commas." - + " Configuration filters are lists of configuration qualifiers separated by dashes," - + " as used in resource directory names and described on the Android developer site: " - + ANDROID_SPLIT_DOCUMENTATION_URL - + " For example, a split might be 'en-television,en-xxhdpi', containing English" - + " assets which either are for TV screens or are extra extra high resolution." - + " Multiple splits can be specified by passing this flag multiple times." - + " Each split flag will produce an additional output file, named by replacing the" - + " commas in the split specification with underscores, and appending the result to" - + " the output package name following an underscore." + name = "split", + defaultValue = "required but ignored due to allowMultiple", + category = "config", + documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, + effectTags = {OptionEffectTag.UNKNOWN}, + allowMultiple = true, + help = + "An individual split configuration to pass to aapt." + + " Each split is a list of configuration filters separated by commas." + + " Configuration filters are lists of configuration qualifiers separated by dashes," + + " as used in resource directory names and described on the Android developer site: " + + ANDROID_SPLIT_DOCUMENTATION_URL + + " For example, a split might be 'en-television,en-xxhdpi', containing English" + + " assets which either are for TV screens or are extra extra high resolution." + + " Multiple splits can be specified by passing this flag multiple times." + + " Each split flag will produce an additional output file, named by replacing the" + + " commas in the split specification with underscores, and appending the result to" + + " the output package name following an underscore." ) public List<String> splits; @Option( - name = "useCompiledResourcesForMerge", - defaultValue = "false", - category = "config", - documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, - effectTags = {OptionEffectTag.UNKNOWN}, - help = "Use compiled resources for merging rather than parsed symbols binary." + name = "useCompiledResourcesForMerge", + defaultValue = "false", + category = "config", + documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, + effectTags = {OptionEffectTag.UNKNOWN}, + help = "Use compiled resources for merging rather than parsed symbols binary." ) public boolean useCompiledResourcesForMerge; } diff --git a/src/tools/android/java/com/google/devtools/build/android/aapt2/CompiledResources.java b/src/tools/android/java/com/google/devtools/build/android/aapt2/CompiledResources.java index 2e96319a81..65200f6b52 100644 --- a/src/tools/android/java/com/google/devtools/build/android/aapt2/CompiledResources.java +++ b/src/tools/android/java/com/google/devtools/build/android/aapt2/CompiledResources.java @@ -65,9 +65,7 @@ public class CompiledResources implements ManifestContainer { resources, manifest, assetDirs != null ? assetDirs : ImmutableList.of(), Optional.empty()); } - /** - * This zip file contains resource flat files that are the result of aapt2 compile - */ + /** This zip file contains resource flat files that are the result of aapt2 compile */ public Path getZip() { return resources; } diff --git a/src/tools/android/java/com/google/devtools/build/android/aapt2/StaticLibrary.java b/src/tools/android/java/com/google/devtools/build/android/aapt2/StaticLibrary.java index 142d7fefb1..a8b27e9e8c 100644 --- a/src/tools/android/java/com/google/devtools/build/android/aapt2/StaticLibrary.java +++ b/src/tools/android/java/com/google/devtools/build/android/aapt2/StaticLibrary.java @@ -57,13 +57,8 @@ public class StaticLibrary { return new StaticLibrary(library, rTxt, assets, sourceJar); } - public static StaticLibrary from( - Path library, Path rTxt, ImmutableList<Path> assetDirs) { - return of( - library, - Optional.ofNullable(rTxt), - Optional.ofNullable(assetDirs), - Optional.empty()); + public static StaticLibrary from(Path library, Path rTxt, ImmutableList<Path> assetDirs) { + return of(library, Optional.ofNullable(rTxt), Optional.ofNullable(assetDirs), Optional.empty()); } public static StaticLibrary from( diff --git a/src/tools/android/java/com/google/devtools/build/android/desugar/BitFlags.java b/src/tools/android/java/com/google/devtools/build/android/desugar/BitFlags.java index bb32c452e2..8be228801d 100644 --- a/src/tools/android/java/com/google/devtools/build/android/desugar/BitFlags.java +++ b/src/tools/android/java/com/google/devtools/build/android/desugar/BitFlags.java @@ -15,14 +15,12 @@ package com.google.devtools.build.android.desugar; import org.objectweb.asm.Opcodes; -/** - * Convenience method for working with {@code int} bitwise flags. - */ +/** Convenience method for working with {@code int} bitwise flags. */ class BitFlags { /** - * Returns {@code true} iff <b>all</b> bits in {@code bitmask} are set in {@code flags}. - * Trivially returns {@code true} if {@code bitmask} is 0. + * Returns {@code true} iff <b>all</b> bits in {@code bitmask} are set in {@code flags}. Trivially + * returns {@code true} if {@code bitmask} is 0. */ public static boolean isSet(int flags, int bitmask) { return (flags & bitmask) == bitmask; |