com.android.builder.core.VariantType Java Examples

The following examples show how to use com.android.builder.core.VariantType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MergeAwbAssets.java    From atlas with Apache License 2.0 6 votes vote down vote up
@Override
        public void execute(@NonNull MergeAwbAssets mergeAssetsTask) {
            BaseVariantData variantData = scope.getVariantData();
            VariantConfiguration variantConfig = variantData.getVariantConfiguration();

            mergeAssetsTask.setAndroidBuilder(scope.getGlobalScope().getAndroidBuilder());
            mergeAssetsTask.setVariantName(variantConfig.getFullName());
            mergeAssetsTask.setIncrementalFolder(scope.getIncrementalDir(getName()));
//            final Project project = scope.getGlobalScope().getProject();
//            final Function<SourceProvider, Collection<File>> assetDirFunction =
//                    SourceProvider::getJniLibsDirectories;
//            mergeAssetsTask.assetSetSupplier =
//                    () -> variantConfig.getSourceFilesAsAssetSets(assetDirFunction);
//            mergeAssetsTask.sourceFolderInputs =
//                    TaskInputHelper.bypassFileSupplier(
//                            () -> variantConfig.getSourceFiles(assetDirFunction));

            mergeAssetsTask.assetSetSupplier = () -> ImmutableList.of();
            mergeAssetsTask.sourceFolderInputs = ()-> ImmutableList.of();
            mergeAssetsTask.awbBundle = awbBundle;
            if (!variantConfig.getType().equals(VariantType.LIBRARY)) {
                mergeAssetsTask.libraries = awbBundle.getAndroidLibraries();
            }
            mergeAssetsTask.setOutputDir(variantContext.getAwbMergeNativeLibsOutputDir(awbBundle));
        }
 
Example #2
Source File: MergeAwbAssets.java    From atlas with Apache License 2.0 6 votes vote down vote up
@Override
        public void execute(@NonNull MergeAwbAssets mergeAssetsTask) {
            BaseVariantData variantData = scope.getVariantData();
            VariantConfiguration variantConfig = variantData.getVariantConfiguration();

            mergeAssetsTask.setAndroidBuilder(scope.getGlobalScope().getAndroidBuilder());
            mergeAssetsTask.setVariantName(variantConfig.getFullName());
            mergeAssetsTask.setIncrementalFolder(scope.getIncrementalDir(getName()));
            final Project project = scope.getGlobalScope().getProject();

            final Function<SourceProvider, Collection<File>> assetDirFunction =
                    SourceProvider::getShadersDirectories;
//            mergeAssetsTask.assetSetSupplier =
//                    () -> variantConfig.getSourceFilesAsAssetSets(assetDirFunction);
//            mergeAssetsTask.sourceFolderInputs =
//                    TaskInputHelper.bypassFileSupplier(
//                            () -> variantConfig.getSourceFiles(assetDirFunction));
            mergeAssetsTask.assetSetSupplier = () -> ImmutableList.of();
            mergeAssetsTask.sourceFolderInputs = () -> ImmutableList.of();

            mergeAssetsTask.awbBundle = awbBundle;
            if (!variantConfig.getType().equals(VariantType.LIBRARY)) {
                mergeAssetsTask.libraries = awbBundle.getAndroidLibraries();
            }
            mergeAssetsTask.setOutputDir(variantContext.getMergeShadersOutputDir(awbBundle));
        }
 
Example #3
Source File: ResourceLinker.java    From bazel with Apache License 2.0 6 votes vote down vote up
private Path optimize(CompiledResources compiled, Path binary) throws IOException {
  if (densities.size() < 2) {
    return binary;
  }

  profiler.startTask("optimize");
  final Path optimized = workingDirectory.resolve("optimized." + PROTO_EXTENSION);
  logger.fine(
      new AaptCommandBuilder(aapt2)
          .forBuildToolsVersion(buildToolsVersion)
          .forVariantType(VariantType.DEFAULT)
          .add("optimize")
          .when(Objects.equals(logger.getLevel(), Level.FINE))
          .thenAdd("-v")
          // TODO(b/138166830): Simplify behavior specific to number of densities. There's likely
          // little to lose in passing a single-element density list, which we would confirm in
          // the APK analyzer dashboard.
          .when(densities.size() >= 2)
          .thenAdd("--target-densities", densities.stream().collect(Collectors.joining(",")))
          .add("-o", optimized)
          .add(binary.toString())
          .execute(String.format("Optimizing %s", compiled.getManifest())));
  profiler.recordEndOf("optimize");
  return optimized;
}
 
Example #4
Source File: AaptCommandBuilderTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testWhenVariantIsDoesNotAddFlagsForUnspecifiedVariantType() {
  assertThat(
          new AaptCommandBuilder(aapt)
              .whenVariantIs(VariantType.LIBRARY)
              .thenAdd("--dontaddthisflag")
              .build())
      .doesNotContain("--dontaddthisflag");
}
 
Example #5
Source File: MergeAwbAssets.java    From atlas with Apache License 2.0 5 votes vote down vote up
@Override
        public void execute(@NonNull MergeAwbAssets mergeAssetsTask) {
            BaseVariantData variantData = scope.getVariantData();
            VariantConfiguration variantConfig = variantData.getVariantConfiguration();
            mergeAssetsTask.setAndroidBuilder(scope.getGlobalScope().getAndroidBuilder());
            mergeAssetsTask.setVariantName(variantConfig.getFullName());
            mergeAssetsTask.setIncrementalFolder(scope.getIncrementalDir(getName()));
            final Project project = scope.getGlobalScope().getProject();

            final Function<SourceProvider, Collection<File>> assetDirFunction =
                    SourceProvider::getAssetsDirectories;
//            mergeAssetsTask.assetSetSupplier =
//                    () -> variantConfig.getSourceFilesAsAssetSets(assetDirFunction);

            mergeAssetsTask.assetSetSupplier = ()-> ImmutableList.of();
            mergeAssetsTask.sourceFolderInputs = () -> ImmutableList.of();
//            mergeAssetsTask.sourceFolderInputs =
//                    TaskInputHelper.bypassFileSupplier(
//                            () -> variantConfig.getSourceFiles(assetDirFunction));

            mergeAssetsTask.shadersOutputDir = project.files(variantContext.getAwbShadersOutputDir(awbBundle));
            if (variantData.copyApkTask != null) {
                mergeAssetsTask.copyApk = project.files(variantData.copyApkTask.getDestinationDir());
            }

            AaptOptions options = scope.getGlobalScope().getExtension().getAaptOptions();
            if (options != null) {
                mergeAssetsTask.ignoreAssets = options.getIgnoreAssets();
            }

            if (!variantConfig.getType().equals(VariantType.LIBRARY)) {
                mergeAssetsTask.libraries = awbBundle.getAndroidLibraries();
            }

            mergeAssetsTask.awbBundle = awbBundle;
            mergeAssetsTask.variantContext = (AppVariantContext) this.variantContext;
            mergeAssetsTask.setOutputDir(outputDir);
        }
 
Example #6
Source File: AaptCommandBuilderTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testWhenVariantIsDoesNotAddFlagsForUnequalVariantType() {
  assertThat(
          new AaptCommandBuilder(aapt)
              .forVariantType(VariantType.DEFAULT)
              .whenVariantIs(VariantType.LIBRARY)
              .thenAdd("--dontaddthisflag")
              .build())
      .doesNotContain("--dontaddthisflag");
}
 
Example #7
Source File: AaptCommandBuilderTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testWhenVariantIsAddsFlagsForEqualVariantType() {
  assertThat(
          new AaptCommandBuilder(aapt)
              .forVariantType(VariantType.LIBRARY)
              .whenVariantIs(VariantType.LIBRARY)
              .thenAdd("--addthisflag")
              .build())
      .contains("--addthisflag");
}
 
Example #8
Source File: AndroidResourceMerger.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Merges all secondary resources with the primary resources, given that the primary resources
 * have been separately parsed and serialized.
 */
public static MergedAndroidData mergeDataAndWrite(
    final SerializedAndroidData primary,
    final Path primaryManifest,
    final List<? extends SerializedAndroidData> direct,
    final List<? extends SerializedAndroidData> transitive,
    final Path resourcesOut,
    final Path assetsOut,
    @Nullable final PngCruncher cruncher,
    final VariantType type,
    @Nullable final Path symbolsOut,
    @Nullable final AndroidResourceClassWriter rclassWriter,
    boolean throwOnResourceConflict,
    ListeningExecutorService executorService) {
  final ParsedAndroidData.Builder primaryBuilder = ParsedAndroidData.Builder.newBuilder();
  final AndroidParsedDataDeserializer deserializer = AndroidParsedDataDeserializer.create();
  primary.deserialize(
      DependencyInfo.DependencyType.PRIMARY, deserializer, primaryBuilder.consumers());
  ParsedAndroidData primaryData = primaryBuilder.build();
  return mergeDataAndWrite(
      primaryData,
      primaryManifest,
      direct,
      transitive,
      resourcesOut,
      assetsOut,
      cruncher,
      type,
      symbolsOut,
      rclassWriter,
      deserializer,
      throwOnResourceConflict,
      executorService);
}
 
Example #9
Source File: AndroidResourceMerger.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Merges all secondary resources with the primary resources, given that the primary resources
 * have not yet been parsed and serialized.
 */
public static MergedAndroidData mergeDataAndWrite(
    final UnvalidatedAndroidData primary,
    final List<? extends SerializedAndroidData> direct,
    final List<? extends SerializedAndroidData> transitive,
    final Path resourcesOut,
    final Path assetsOut,
    @Nullable final PngCruncher cruncher,
    final VariantType type,
    @Nullable final Path symbolsOut,
    final List<String> filteredResources,
    boolean throwOnResourceConflict) {
  try (ExecutorServiceCloser executorService = ExecutorServiceCloser.createWithFixedPoolOf(15)) {
    final ParsedAndroidData parsedPrimary = ParsedAndroidData.from(primary);
    return mergeDataAndWrite(
        parsedPrimary,
        primary.getManifest(),
        direct,
        transitive,
        resourcesOut,
        assetsOut,
        cruncher,
        type,
        symbolsOut,
        /* rclassWriter= */ null,
        AndroidParsedDataDeserializer.withFilteredResources(filteredResources),
        throwOnResourceConflict,
        executorService);
  } catch (IOException e) {
    throw MergingException.wrapException(e);
  }
}
 
Example #10
Source File: AndroidResourceMerger.java    From bazel with Apache License 2.0 5 votes vote down vote up
/** Performs a merge of compiled android data. */
static Path mergeDataToSymbols(
    ParsedAndroidData primary,
    Path manifest,
    ImmutableList<SerializedAndroidData> direct,
    ImmutableList<SerializedAndroidData> transitive,
    VariantType packageType,
    Path symbolsOut,
    AndroidCompiledDataDeserializer deserializer,
    boolean throwOnResourceConflict,
    ExecutorServiceCloser executorService)
    throws IOException {
  AndroidDataMerger merger =
      AndroidDataMerger.createWithPathDeduplictor(
          executorService, deserializer, AndroidDataMerger.NoopSourceChecker.create());
  final UnwrittenMergedAndroidData merged =
      merger.loadAndMerge(
          transitive,
          direct,
          primary,
          manifest,
          packageType.equals(VariantType.DEFAULT),
          throwOnResourceConflict);
  AndroidDataSerializer serializer = AndroidDataSerializer.create();
  merged.serializeTo(serializer);
  serializer.flushTo(symbolsOut);
  return symbolsOut;
}
 
Example #11
Source File: AaptCommandBuilder.java    From bazel with Apache License 2.0 5 votes vote down vote up
/** Sets the variant type to be used for {@link #whenVariantIs}. */
public AaptCommandBuilder forVariantType(VariantType variantType) {
  Preconditions.checkNotNull(variantType);
  Preconditions.checkState(this.variantType == null, "A variant type was already specified.");
  this.variantType = variantType;
  return this;
}
 
Example #12
Source File: ResourceCompiler.java    From bazel with Apache License 2.0 5 votes vote down vote up
private void compile(
    String type,
    String filename,
    List<Path> results,
    Path compileOutRoot,
    Path file,
    boolean generatePseudoLocale) {
  try {
    Path destination = CompilingVisitor.destinationPath(file, compileOutRoot);
    final Path compiledResourcePath = destination.resolve(type + "_" + filename + ".flat");

    logger.fine(
        new AaptCommandBuilder(aapt2)
            .forBuildToolsVersion(buildToolsVersion)
            .forVariantType(VariantType.LIBRARY)
            .add("compile")
            .add("-v")
            .add("--legacy")
            .when(USE_VISIBILITY_FROM_AAPT2)
            .thenAdd("--preserve-visibility-of-styleables")
            .when(generatePseudoLocale)
            .thenAdd("--pseudo-localize")
            .add("-o", destination.toString())
            .add(file.toString())
            .execute("Compiling " + file));

    Preconditions.checkArgument(
        Files.exists(compiledResourcePath),
        "%s does not exists after aapt2 ran.",
        compiledResourcePath);
    results.add(compiledResourcePath);
  } catch (IOException e) {
    throw new CompileError(e);
  }
}
 
Example #13
Source File: ResourceLinker.java    From bazel with Apache License 2.0 5 votes vote down vote up
/** Link a proto apk to produce an apk. */
public Path link(ProtoApk protoApk, Path resourceIds) {
  try {
    final Path protoApkPath = protoApk.asApkPath();
    final Path working =
        workingDirectory
            .resolve("link-proto")
            .resolve(replaceExtension(protoApkPath.getFileName().toString(), "working"));
    final Path manifest = protoApk.writeManifestAsXmlTo(working);
    final Path apk = working.resolve("binary.apk");
    logger.fine(
        new AaptCommandBuilder(aapt2)
            .forBuildToolsVersion(buildToolsVersion)
            .forVariantType(VariantType.DEFAULT)
            .add("link")
            .when(Objects.equals(logger.getLevel(), Level.FINE))
            .thenAdd("-v")
            .whenVersionIsAtLeast(new Revision(23))
            .thenAdd("--no-version-vectors")
            .add("--stable-ids", resourceIds)
            .add("--manifest", manifest)
            .addRepeated("-I", StaticLibrary.toPathStrings(linkAgainst))
            .add("-R", protoApk.asApkPath())
            .add("-o", apk.toString())
            .execute(String.format("Re-linking %s", protoApkPath)));
    return combineApks(protoApkPath, apk, working);
  } catch (IOException e) {
    throw new LinkError(e);
  }
}
 
Example #14
Source File: AndroidManifestProcessor.java    From bazel with Apache License 2.0 5 votes vote down vote up
/** Process a manifest for a library or a binary and return the merged android data. */
public MergedAndroidData processManifest(
    VariantType variantType,
    String customPackageForR,
    String applicationId,
    int versionCode,
    String versionName,
    MergedAndroidData primaryData,
    Path processedManifest,
    boolean logWarnings) {

  ManifestMerger2.MergeType mergeType =
      variantType == VariantType.DEFAULT
          ? ManifestMerger2.MergeType.APPLICATION
          : ManifestMerger2.MergeType.LIBRARY;

  String newManifestPackage =
      variantType == VariantType.DEFAULT ? applicationId : customPackageForR;

  if (versionCode != -1 || versionName != null || newManifestPackage != null) {
    processManifest(
        versionCode,
        versionName,
        primaryData.getManifest(),
        processedManifest,
        mergeType,
        newManifestPackage,
        logWarnings);
    return new MergedAndroidData(
        primaryData.getResourceDir(), primaryData.getAssetDir(), processedManifest);
  }
  return primaryData;
}
 
Example #15
Source File: AndroidAssetMergingAction.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
void run(Path tmp, ExecutorServiceCloser executorService) throws Exception {
  Options options = getOptions(Options.class);
  Path mergedAssets = tmp.resolve("merged_assets");
  Path ignored = tmp.resolve("ignored");

  Preconditions.checkNotNull(options.primary);

  MergedAndroidData mergedData =
      AndroidResourceMerger.mergeDataAndWrite(
          options.primary,
          /* primaryManifest = */ null,
          options.directData,
          options.transitiveData,
          /* resourcesOut = */ ignored,
          mergedAssets,
          /* cruncher = */ null,
          VariantType.LIBRARY,
          /* symbolsOut = */ null,
          /* rclassWriter = */ null,
          options.throwOnAssetConflict,
          executorService);

  logCompletion("Merging");

  Preconditions.checkState(
      !Files.exists(ignored),
      "The asset merging action should not produce non-asset merge results!");

  ResourcesZip.from(ignored, mergedData.getAssetDir())
      .writeTo(options.assetsOutput, /* compress= */ true);
  logCompletion("Create assets zip");
}
 
Example #16
Source File: GradleVariantConfiguration.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns whether the configuration has minification enabled.
 */
public boolean isMinifyEnabled() {
    VariantType type = getType();
    // if type == test then getTestedConfig always returns non-null
    //noinspection ConstantConditions
    return getBuildType().isMinifyEnabled();
}
 
Example #17
Source File: VariantManager.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Turns a string into a valid source set name for the given {@link VariantType}, e.g.
 * "fooBarUnitTest" becomes "testFooBar".
 */
@NonNull
private static String computeSourceSetName(
        @NonNull String name,
        @NonNull VariantType variantType) {
    if (name.endsWith(variantType.getSuffix())) {
        name = name.substring(0, name.length() - variantType.getSuffix().length());
    }

    if (!variantType.getPrefix().isEmpty()) {
        name = variantType.getPrefix() + StringHelper.capitalize(name);
    }

    return name;
}
 
Example #18
Source File: GradleVariantConfiguration.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a {@link GradleVariantConfiguration} for a normal (non-test) variant.
 */
public GradleVariantConfiguration(
        @NonNull CoreProductFlavor defaultConfig,
        @NonNull SourceProvider defaultSourceProvider,
        @NonNull CoreBuildType buildType,
        @Nullable SourceProvider buildTypeSourceProvider,
        @NonNull VariantType type,
        @Nullable SigningConfig signingConfigOverride) {
    super(defaultConfig, defaultSourceProvider, buildType, buildTypeSourceProvider, type,
            signingConfigOverride);
}
 
Example #19
Source File: VariantScope.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@NonNull
public File getMergeAssetsOutputDir() {
    return getVariantConfiguration().getType() == VariantType.LIBRARY ?
            new File(globalScope.getIntermediatesDir(),
                    DIR_BUNDLES + "/" + getVariantConfiguration().getDirName() +
                            "/assets") :
            new File(globalScope.getIntermediatesDir(),
                    "/assets/" + getVariantConfiguration().getDirName());
}
 
Example #20
Source File: AidlCompile.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void execute(AidlCompile compileTask) {
    final VariantConfiguration<?, ?, ?> variantConfiguration = scope.getVariantConfiguration();

    scope.getVariantData().aidlCompileTask = compileTask;

    compileTask.setAndroidBuilder(scope.getGlobalScope().getAndroidBuilder());
    compileTask.setVariantName(scope.getVariantConfiguration().getFullName());
    compileTask.setIncrementalFolder(scope.getAidlIncrementalDir());

    ConventionMappingHelper.map(compileTask, "sourceDirs", new Callable<List<File>>() {
        @Override
        public List<File> call() throws Exception {
            return variantConfiguration.getAidlSourceList();
        }
    });
    ConventionMappingHelper.map(compileTask, "importDirs", new Callable<List<File>>() {
        @Override
        public List<File> call() throws Exception {
            return variantConfiguration.getAidlImports();
        }
    });

    ConventionMappingHelper.map(compileTask, "sourceOutputDir", new Callable<File>() {
        @Override
        public File call() throws Exception {
            return scope.getAidlSourceOutputDir();
        }
    });

    if (variantConfiguration.getType() == VariantType.LIBRARY) {
        compileTask.setAidlParcelableDir(scope.getAidlParcelableDir());
    }
}
 
Example #21
Source File: ProcessAwbAndroidResources.java    From atlas with Apache License 2.0 4 votes vote down vote up
/**
 * Does not change between incremental builds, so does not need to be @Input.
 */
public VariantType getType() {
    return type;
}
 
Example #22
Source File: ProcessAwbAndroidResources.java    From atlas with Apache License 2.0 4 votes vote down vote up
public void setType(VariantType type) {
    this.type = type;
}
 
Example #23
Source File: AtlasDependencyGraph.java    From atlas with Apache License 2.0 4 votes vote down vote up
public static ArtifactCollection computeArtifactCollection(
        VariantScope variantScope,
        @NonNull AtlasAndroidArtifacts.ConsumedConfigType configType,
        @NonNull AndroidArtifacts.ArtifactScope scope,
        @NonNull AtlasAndroidArtifacts.AtlasArtifactType artifactType) {

    Configuration configuration;
    switch (configType) {
        case COMPILE_CLASSPATH:
            configuration = variantScope.getVariantData().getVariantDependency().getCompileClasspath();
            break;
        case RUNTIME_CLASSPATH:
            configuration = variantScope.getVariantData().getVariantDependency().getRuntimeClasspath();
            break;
        case BUNDLECOMPILE_CLASSPATH:
            configuration = variantScope.getGlobalScope().getProject().getConfigurations().maybeCreate(AtlasPlugin.BUNDLE_COMPILE);
            break;
        case ANNOTATION_PROCESSOR:
            configuration = variantScope.getVariantData()
                    .getVariantDependency()
                    .getAnnotationProcessorConfiguration();
            break;
        case METADATA_VALUES:
            configuration =
                    variantScope.getVariantData().getVariantDependency().getMetadataValuesConfiguration();
            break;
        default:
            throw new RuntimeException("unknown ConfigType value");
    }

    Action<AttributeContainer> attributes =
            container -> container.attribute(ARTIFACT_TYPE, artifactType.getType());

    Spec<ComponentIdentifier> filter = getComponentFilter(scope);

    boolean lenientMode =
            Boolean.TRUE.equals(
                    variantScope.getGlobalScope().getProjectOptions().get(BooleanOption.IDE_BUILD_MODEL_ONLY));

    ArtifactCollection artifacts =  configuration
            .getIncoming()
            .artifactView(
                    config -> {
                        config.attributes(attributes);
                        if (filter != null) {
                            config.componentFilter(filter);
                        }
                        // TODO somehow read the unresolved dependencies?
                        config.lenient(lenientMode);
                    })
            .getArtifacts();

    if (configType == AtlasAndroidArtifacts.ConsumedConfigType.RUNTIME_CLASSPATH
            && variantScope.getVariantConfiguration().getType() == VariantType.FEATURE
            && artifactType != AtlasAndroidArtifacts.AtlasArtifactType.FEATURE_TRANSITIVE_DEPS) {
        artifacts =
                new FilteredArtifactCollection(
                        variantScope.getGlobalScope().getProject(),
                        artifacts,
                        computeArtifactCollection(variantScope,
                                AtlasAndroidArtifacts.ConsumedConfigType.RUNTIME_CLASSPATH,
                                scope,
                                AtlasAndroidArtifacts.AtlasArtifactType.FEATURE_TRANSITIVE_DEPS)
                                .getArtifactFiles());
    }
    return artifacts;
}
 
Example #24
Source File: AndroidResourceMerger.java    From bazel with Apache License 2.0 4 votes vote down vote up
/** Merges all secondary resources with the primary resources. */
private static MergedAndroidData mergeDataAndWrite(
    final ParsedAndroidData primary,
    final Path primaryManifest,
    final List<? extends SerializedAndroidData> direct,
    final List<? extends SerializedAndroidData> transitive,
    final Path resourcesOut,
    final Path assetsOut,
    @Nullable final PngCruncher cruncher,
    final VariantType type,
    @Nullable final Path symbolsOut,
    @Nullable AndroidResourceClassWriter rclassWriter,
    AndroidParsedDataDeserializer deserializer,
    boolean throwOnResourceConflict,
    ListeningExecutorService executorService) {
  Stopwatch timer = Stopwatch.createStarted();
  try {
    UnwrittenMergedAndroidData merged =
        mergeData(
            executorService,
            transitive,
            direct,
            primary,
            primaryManifest,
            type != VariantType.LIBRARY,
            deserializer,
            throwOnResourceConflict,
            ContentComparingChecker.create());
    timer.reset().start();
    if (symbolsOut != null) {
      AndroidDataSerializer serializer = AndroidDataSerializer.create();
      merged.serializeTo(serializer);
      serializer.flushTo(symbolsOut);
      logger.fine(
          String.format(
              "serialize merge finished in %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
      timer.reset().start();
    }
    if (rclassWriter != null) {
      merged.writeResourceClass(rclassWriter);
      logger.fine(
          String.format("write classes finished in %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
      timer.reset().start();
    }
    AndroidDataWriter writer =
        AndroidDataWriter.createWith(
            resourcesOut.getParent(), resourcesOut, assetsOut, cruncher, executorService);
    return merged.write(writer);
  } catch (IOException e) {
    throw MergingException.wrapException(e);
  } finally {
    logger.fine(
        String.format("write merge finished in %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
  }
}
 
Example #25
Source File: ProcessAndroidResources.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
/** Does not change between incremental builds, so does not need to be @Input. */
public VariantType getType() {
    return type;
}
 
Example #26
Source File: ProcessAndroidResources.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
public void setType(VariantType type) {
    this.type = type;
}
 
Example #27
Source File: AaptCommandBuilder.java    From bazel with Apache License 2.0 4 votes vote down vote up
/** Adds the next flag to the builder only if the variant type is the passed-in type. */
public ConditionalAaptCommandBuilder whenVariantIs(VariantType variantType) {
  Preconditions.checkNotNull(variantType);
  return when(this.variantType == variantType);
}
 
Example #28
Source File: LibraryVariantFactory.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
@NonNull
@Override
public VariantType getVariantConfigurationType() {
    return VariantType.LIBRARY;
}
 
Example #29
Source File: AndroidResourceProcessor.java    From bazel with Apache License 2.0 4 votes vote down vote up
public void runAapt(
    Path tempRoot,
    Path aapt,
    Path androidJar,
    @Nullable Revision buildToolsVersion,
    VariantType variantType,
    boolean debug,
    String customPackageForR,
    AaptOptions aaptOptions,
    Collection<String> resourceConfigs,
    Path androidManifest,
    Path resourceDir,
    Path assetsDir,
    Path sourceOut,
    @Nullable Path packageOut,
    @Nullable Path proguardOut,
    @Nullable Path mainDexProguardOut,
    @Nullable Path publicResourcesOut)
    throws InterruptedException, LoggedErrorException, IOException {
  try (JunctionCreator junctions =
      System.getProperty("os.name").toLowerCase().startsWith("windows")
          ? new WindowsJunctionCreator(Files.createDirectories(tempRoot.resolve("juncts")))
          : new NoopJunctionCreator()) {
    sourceOut = junctions.create(sourceOut);
    AaptCommandBuilder commandBuilder =
        new AaptCommandBuilder(junctions.create(aapt))
            .forBuildToolsVersion(buildToolsVersion)
            .forVariantType(variantType)
            // first argument is the command to be executed, "package"
            .add("package")
            // If the logger is verbose, set aapt to be verbose
            .when(stdLogger.getLevel() == StdLogger.Level.VERBOSE)
            .thenAdd("-v")
            // Overwrite existing files, if they exist.
            .add("-f")
            // Resources are precrunched in the merge process.
            .add("--no-crunch")
            // Do not automatically generate versioned copies of vector XML resources.
            .whenVersionIsAtLeast(new Revision(23))
            .thenAdd("--no-version-vectors")
            // Add the android.jar as a base input.
            .add("-I", junctions.create(androidJar))
            // Add the manifest for validation.
            .add("-M", junctions.create(androidManifest.toAbsolutePath()))
            // Maybe add the resources if they exist
            .when(Files.isDirectory(resourceDir))
            .thenAdd("-S", junctions.create(resourceDir))
            // Maybe add the assets if they exist
            .when(Files.isDirectory(assetsDir))
            .thenAdd("-A", junctions.create(assetsDir))
            // Outputs
            .when(sourceOut != null)
            .thenAdd("-m")
            .add("-J", prepareOutputPath(sourceOut))
            .add("--output-text-symbols", prepareOutputPath(sourceOut))
            .add("-F", junctions.create(packageOut))
            .add("-G", junctions.create(proguardOut))
            .whenVersionIsAtLeast(new Revision(24))
            .thenAdd("-D", junctions.create(mainDexProguardOut))
            .add("-P", junctions.create(publicResourcesOut))
            .when(debug)
            .thenAdd("--debug-mode")
            .add("--custom-package", customPackageForR)
            // If it is a library, do not generate final java ids.
            .whenVariantIs(VariantType.LIBRARY)
            .thenAdd("--non-constant-id")
            .add("--ignore-assets", aaptOptions.getIgnoreAssets())
            .when(aaptOptions.getFailOnMissingConfigEntry())
            .thenAdd("--error-on-missing-config-entry")
            // Never compress apks.
            .add("-0", "apk")
            // Add custom no-compress extensions.
            .addRepeated("-0", aaptOptions.getNoCompress())
            // Filter by resource configuration type.
            .add("-c", Joiner.on(',').join(resourceConfigs));
    for (String additional : aaptOptions.getAdditionalParameters()) {
      commandBuilder.add(additional);
    }
    try {
      new CommandLineRunner(stdLogger).runCmdLine(commandBuilder.build(), null);
    } catch (LoggedErrorException e) {
      // Add context and throw the error to resume processing.
      throw new LoggedErrorException(
          e.getCmdLineError(), getOutputWithSourceContext(aapt, e.getOutput()), e.getCmdLine());
    }
  }
}
 
Example #30
Source File: AndroidResourceProcessor.java    From bazel with Apache License 2.0 4 votes vote down vote up
/**
 * Processes resources for generated sources, configs and packaging resources.
 *
 * <p>Returns a post-processed MergedAndroidData. Notably, the resources will be stripped of any
 * databinding expressions.
 */
public MergedAndroidData processResources(
    Path tempRoot,
    Path aapt,
    Path androidJar,
    @Nullable Revision buildToolsVersion,
    VariantType variantType,
    boolean debug,
    String customPackageForR,
    AaptOptions aaptOptions,
    Collection<String> resourceConfigs,
    MergedAndroidData primaryData,
    List<DependencyAndroidData> dependencyData,
    @Nullable Path sourceOut,
    @Nullable Path packageOut,
    @Nullable Path proguardOut,
    @Nullable Path mainDexProguardOut,
    @Nullable Path publicResourcesOut,
    @Nullable Path dataBindingInfoOut)
    throws IOException, InterruptedException, LoggedErrorException {
  Path androidManifest = primaryData.getManifest();
  final Path resourceDir =
      processDataBindings(
          primaryData.getResourceDir().resolveSibling("res_no_binding"),
          primaryData.getResourceDir(),
          dataBindingInfoOut,
          customPackageForR,
          /* shouldZipDataBindingInfo= */ true);

  final Path assetsDir = primaryData.getAssetDir();
  if (publicResourcesOut != null) {
    prepareOutputPath(publicResourcesOut.getParent());
  }
  runAapt(
      tempRoot,
      aapt,
      androidJar,
      buildToolsVersion,
      variantType,
      debug,
      customPackageForR,
      aaptOptions,
      resourceConfigs,
      androidManifest,
      resourceDir,
      assetsDir,
      sourceOut,
      packageOut,
      proguardOut,
      mainDexProguardOut,
      publicResourcesOut);
  // The R needs to be created for each library in the dependencies,
  // but only if the current project is not a library.
  if (sourceOut != null && variantType != VariantType.LIBRARY) {
    writeDependencyPackageRJavaFiles(
        dependencyData, customPackageForR, androidManifest, sourceOut);
  }
  return new MergedAndroidData(resourceDir, assetsDir, androidManifest);
}