use of com.facebook.buck.rules.BuildRuleParams in project buck by facebook.
the class AndroidAarDescription method createBuildRule.
@Override
public <A extends Arg> BuildRule createBuildRule(TargetGraph targetGraph, BuildRuleParams originalBuildRuleParams, BuildRuleResolver resolver, A args) throws NoSuchBuildTargetException {
UnflavoredBuildTarget originalBuildTarget = originalBuildRuleParams.getBuildTarget().checkUnflavored();
SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
ImmutableList.Builder<BuildRule> aarExtraDepsBuilder = ImmutableList.<BuildRule>builder().addAll(originalBuildRuleParams.getExtraDeps().get());
/* android_manifest */
AndroidManifestDescription.Arg androidManifestArgs = androidManifestDescription.createUnpopulatedConstructorArg();
androidManifestArgs.skeleton = args.manifestSkeleton;
androidManifestArgs.deps = args.deps;
BuildRuleParams androidManifestParams = originalBuildRuleParams.withBuildTarget(BuildTargets.createFlavoredBuildTarget(originalBuildTarget, AAR_ANDROID_MANIFEST_FLAVOR));
AndroidManifest manifest = androidManifestDescription.createBuildRule(targetGraph, androidManifestParams, resolver, androidManifestArgs);
aarExtraDepsBuilder.add(resolver.addToIndex(manifest));
final APKModuleGraph apkModuleGraph = new APKModuleGraph(targetGraph, originalBuildRuleParams.getBuildTarget(), Optional.empty());
/* assemble dirs */
AndroidPackageableCollector collector = new AndroidPackageableCollector(originalBuildRuleParams.getBuildTarget(), /* buildTargetsToExcludeFromDex */
ImmutableSet.of(), /* resourcesToExclude */
ImmutableSet.of(), apkModuleGraph);
collector.addPackageables(AndroidPackageableCollector.getPackageableRules(originalBuildRuleParams.getDeps()));
AndroidPackageableCollection packageableCollection = collector.build();
ImmutableSortedSet<BuildRule> androidResourceDeclaredDeps = AndroidResourceHelper.androidResOnly(originalBuildRuleParams.getDeclaredDeps().get());
ImmutableSortedSet<BuildRule> androidResourceExtraDeps = AndroidResourceHelper.androidResOnly(originalBuildRuleParams.getExtraDeps().get());
BuildRuleParams assembleAssetsParams = originalBuildRuleParams.withBuildTarget(BuildTargets.createFlavoredBuildTarget(originalBuildTarget, AAR_ASSEMBLE_ASSETS_FLAVOR)).copyReplacingDeclaredAndExtraDeps(Suppliers.ofInstance(androidResourceDeclaredDeps), Suppliers.ofInstance(androidResourceExtraDeps));
ImmutableCollection<SourcePath> assetsDirectories = packageableCollection.getAssetsDirectories();
AssembleDirectories assembleAssetsDirectories = new AssembleDirectories(assembleAssetsParams, assetsDirectories);
aarExtraDepsBuilder.add(resolver.addToIndex(assembleAssetsDirectories));
BuildRuleParams assembleResourceParams = originalBuildRuleParams.withBuildTarget(BuildTargets.createFlavoredBuildTarget(originalBuildTarget, AAR_ASSEMBLE_RESOURCE_FLAVOR)).copyReplacingDeclaredAndExtraDeps(Suppliers.ofInstance(androidResourceDeclaredDeps), Suppliers.ofInstance(androidResourceExtraDeps));
ImmutableCollection<SourcePath> resDirectories = packageableCollection.getResourceDetails().getResourceDirectories();
MergeAndroidResourceSources assembleResourceDirectories = new MergeAndroidResourceSources(assembleResourceParams, resDirectories);
aarExtraDepsBuilder.add(resolver.addToIndex(assembleResourceDirectories));
/* android_resource */
BuildRuleParams androidResourceParams = originalBuildRuleParams.withBuildTarget(BuildTargets.createFlavoredBuildTarget(originalBuildTarget, AAR_ANDROID_RESOURCE_FLAVOR)).copyReplacingDeclaredAndExtraDeps(Suppliers.ofInstance(ImmutableSortedSet.of(manifest, assembleAssetsDirectories, assembleResourceDirectories)), Suppliers.ofInstance(ImmutableSortedSet.of()));
AndroidResource androidResource = new AndroidResource(androidResourceParams, ruleFinder, /* deps */
ImmutableSortedSet.<BuildRule>naturalOrder().add(assembleAssetsDirectories).add(assembleResourceDirectories).addAll(originalBuildRuleParams.getDeclaredDeps().get()).build(), assembleResourceDirectories.getSourcePathToOutput(), /* resSrcs */
ImmutableSortedMap.of(), /* rDotJavaPackage */
null, assembleAssetsDirectories.getSourcePathToOutput(), /* assetsSrcs */
ImmutableSortedMap.of(), manifest.getSourcePathToOutput(), /* hasWhitelistedStrings */
false);
aarExtraDepsBuilder.add(resolver.addToIndex(androidResource));
ImmutableSortedSet.Builder<SourcePath> classpathToIncludeInAar = ImmutableSortedSet.naturalOrder();
classpathToIncludeInAar.addAll(packageableCollection.getClasspathEntriesToDex());
aarExtraDepsBuilder.addAll(BuildRules.toBuildRulesFor(originalBuildRuleParams.getBuildTarget(), resolver, packageableCollection.getJavaLibrariesToDex()));
if (!args.buildConfigValues.getNameToField().isEmpty() && !args.includeBuildConfigClass) {
throw new HumanReadableException("Rule %s has build_config_values set but does not set " + "include_build_config_class to True. Either indicate you want to include the " + "BuildConfig class in the final .aar or do not specify build config values.", originalBuildRuleParams.getBuildTarget());
}
if (args.includeBuildConfigClass) {
ImmutableSortedSet<JavaLibrary> buildConfigRules = AndroidBinaryGraphEnhancer.addBuildConfigDeps(originalBuildRuleParams, AndroidBinary.PackageType.RELEASE, EnumSet.noneOf(AndroidBinary.ExopackageMode.class), args.buildConfigValues, Optional.empty(), resolver, javacOptions, packageableCollection);
resolver.addAllToIndex(buildConfigRules);
aarExtraDepsBuilder.addAll(buildConfigRules);
classpathToIncludeInAar.addAll(buildConfigRules.stream().map(BuildRule::getSourcePathToOutput).collect(Collectors.toList()));
}
/* native_libraries */
AndroidNativeLibsPackageableGraphEnhancer packageableGraphEnhancer = new AndroidNativeLibsPackageableGraphEnhancer(resolver, originalBuildRuleParams, nativePlatforms, ImmutableSet.of(), cxxBuckConfig, /* nativeLibraryMergeMap */
Optional.empty(), /* nativeLibraryMergeGlue */
Optional.empty(), AndroidBinary.RelinkerMode.DISABLED, apkModuleGraph);
Optional<ImmutableMap<APKModule, CopyNativeLibraries>> nativeLibrariesOptional = packageableGraphEnhancer.enhance(packageableCollection).getCopyNativeLibraries();
if (nativeLibrariesOptional.isPresent() && nativeLibrariesOptional.get().containsKey(apkModuleGraph.getRootAPKModule())) {
aarExtraDepsBuilder.add(resolver.addToIndex(nativeLibrariesOptional.get().get(apkModuleGraph.getRootAPKModule())));
}
Optional<Path> assembledNativeLibsDir = nativeLibrariesOptional.map(input -> {
CopyNativeLibraries copyNativeLibraries = input.get(apkModuleGraph.getRootAPKModule());
if (copyNativeLibraries == null) {
throw new HumanReadableException("Native libraries are present but not in the root application module.");
}
return copyNativeLibraries.getPathToNativeLibsDir();
});
BuildRuleParams androidAarParams = originalBuildRuleParams.copyReplacingExtraDeps(Suppliers.ofInstance(ImmutableSortedSet.copyOf(aarExtraDepsBuilder.build())));
return new AndroidAar(androidAarParams, manifest, androidResource, assembleResourceDirectories.getSourcePathToOutput(), assembleAssetsDirectories.getSourcePathToOutput(), assembledNativeLibsDir, ImmutableSet.copyOf(packageableCollection.getNativeLibAssetsDirectories().values()), classpathToIncludeInAar.build());
}
use of com.facebook.buck.rules.BuildRuleParams in project buck by facebook.
the class AndroidBinaryDescription method createBuildRule.
@Override
public <A extends Arg> BuildRule createBuildRule(TargetGraph targetGraph, BuildRuleParams params, BuildRuleResolver resolver, A args) throws NoSuchBuildTargetException {
try (SimplePerfEvent.Scope ignored = SimplePerfEvent.scope(Optional.ofNullable(resolver.getEventBus()), PerfEventId.of("AndroidBinaryDescription"), "target", params.getBuildTarget().toString())) {
ResourceCompressionMode compressionMode = getCompressionMode(args);
BuildTarget target = params.getBuildTarget();
boolean isFlavored = target.isFlavored();
if (isFlavored) {
if (target.getFlavors().contains(PACKAGE_STRING_ASSETS_FLAVOR) && !compressionMode.isStoreStringsAsAssets()) {
throw new HumanReadableException("'package_string_assets' flavor does not exist for %s.", target.getUnflavoredBuildTarget());
}
params = params.withBuildTarget(BuildTarget.of(target.getUnflavoredBuildTarget()));
}
BuildRule keystore = resolver.getRule(args.keystore);
if (!(keystore instanceof Keystore)) {
throw new HumanReadableException("In %s, keystore='%s' must be a keystore() but was %s().", params.getBuildTarget(), keystore.getFullyQualifiedName(), keystore.getType());
}
APKModuleGraph apkModuleGraph = new APKModuleGraph(targetGraph, target, Optional.of(args.applicationModuleTargets));
ProGuardObfuscateStep.SdkProguardType androidSdkProguardConfig = args.androidSdkProguardConfig.orElse(ProGuardObfuscateStep.SdkProguardType.DEFAULT);
// was not specified, and allow the old form to override the default.
if (args.useAndroidProguardConfigWithOptimizations.isPresent()) {
Preconditions.checkArgument(!args.androidSdkProguardConfig.isPresent(), "The deprecated use_android_proguard_config_with_optimizations parameter" + " cannot be used with android_sdk_proguard_config.");
LOG.error("Target %s specified use_android_proguard_config_with_optimizations, " + "which is deprecated. Use android_sdk_proguard_config.", params.getBuildTarget());
androidSdkProguardConfig = args.useAndroidProguardConfigWithOptimizations.orElse(false) ? ProGuardObfuscateStep.SdkProguardType.OPTIMIZED : ProGuardObfuscateStep.SdkProguardType.DEFAULT;
}
EnumSet<ExopackageMode> exopackageModes = EnumSet.noneOf(ExopackageMode.class);
if (!args.exopackageModes.isEmpty()) {
exopackageModes = EnumSet.copyOf(args.exopackageModes);
} else if (args.exopackage.orElse(false)) {
LOG.error("Target %s specified exopackage=True, which is deprecated. Use exopackage_modes.", params.getBuildTarget());
exopackageModes = EnumSet.of(ExopackageMode.SECONDARY_DEX);
}
DexSplitMode dexSplitMode = createDexSplitMode(args, exopackageModes);
PackageType packageType = getPackageType(args);
boolean shouldPreDex = !args.disablePreDex && PackageType.DEBUG.equals(packageType) && !args.preprocessJavaClassesBash.isPresent();
ResourceFilter resourceFilter = new ResourceFilter(args.resourceFilter);
AndroidBinaryGraphEnhancer graphEnhancer = new AndroidBinaryGraphEnhancer(params, resolver, compressionMode, resourceFilter, args.getBannedDuplicateResourceTypes(), args.resourceUnionPackage, addFallbackLocales(args.locales), args.manifest, packageType, ImmutableSet.copyOf(args.cpuFilters), args.buildStringSourceMap, shouldPreDex, AndroidBinary.getPrimaryDexPath(params.getBuildTarget(), params.getProjectFilesystem()), dexSplitMode, ImmutableSet.copyOf(args.noDx.orElse(ImmutableSet.of())), /* resourcesToExclude */
ImmutableSet.of(), args.skipCrunchPngs, args.includesVectorDrawables, javacOptions, exopackageModes, args.buildConfigValues, args.buildConfigValuesFile, Optional.empty(), args.trimResourceIds, args.keepResourcePattern, nativePlatforms, Optional.of(args.nativeLibraryMergeMap), args.nativeLibraryMergeGlue, args.nativeLibraryMergeCodeGenerator, args.enableRelinker ? RelinkerMode.ENABLED : RelinkerMode.DISABLED, dxExecutorService, args.manifestEntries, cxxBuckConfig, apkModuleGraph, dxConfig);
AndroidGraphEnhancementResult result = graphEnhancer.createAdditionalBuildables();
if (target.getFlavors().contains(PACKAGE_STRING_ASSETS_FLAVOR)) {
Optional<PackageStringAssets> packageStringAssets = result.getPackageStringAssets();
Preconditions.checkState(packageStringAssets.isPresent());
return packageStringAssets.get();
}
// Build rules added to "no_dx" are only hints, not hard dependencies. Therefore, although a
// target may be mentioned in that parameter, it may not be present as a build rule.
ImmutableSortedSet.Builder<BuildRule> builder = ImmutableSortedSet.naturalOrder();
for (BuildTarget noDxTarget : args.noDx.orElse(ImmutableSet.of())) {
Optional<BuildRule> ruleOptional = resolver.getRuleOptional(noDxTarget);
if (ruleOptional.isPresent()) {
builder.add(ruleOptional.get());
} else {
LOG.info("%s: no_dx target not a dependency: %s", target, noDxTarget);
}
}
ImmutableSortedSet<BuildRule> buildRulesToExcludeFromDex = builder.build();
ImmutableSortedSet<JavaLibrary> rulesToExcludeFromDex = RichStream.from(buildRulesToExcludeFromDex).filter(JavaLibrary.class).collect(MoreCollectors.toImmutableSortedSet(Ordering.natural()));
SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
Optional<RedexOptions> redexOptions = getRedexOptions(params, resolver, args);
ImmutableSortedSet<BuildRule> redexExtraDeps = redexOptions.map(a -> a.getRedexExtraArgs().stream().flatMap(arg -> arg.getDeps(ruleFinder).stream()).collect(MoreCollectors.toImmutableSortedSet(Ordering.natural()))).orElse(ImmutableSortedSet.of());
return new AndroidBinary(params.copyReplacingExtraDeps(Suppliers.ofInstance(result.getFinalDeps())).copyAppendingExtraDeps(ruleFinder.filterBuildRuleInputs(result.getPackageableCollection().getProguardConfigs())).copyAppendingExtraDeps(rulesToExcludeFromDex).copyAppendingExtraDeps(redexExtraDeps), ruleFinder, proGuardConfig.getProguardJarOverride(), proGuardConfig.getProguardMaxHeapSize(), Optional.of(args.proguardJvmArgs), proGuardConfig.getProguardAgentPath(), (Keystore) keystore, packageType, dexSplitMode, args.noDx.orElse(ImmutableSet.of()), androidSdkProguardConfig, args.optimizationPasses, args.proguardConfig, args.skipProguard, redexOptions, compressionMode, args.cpuFilters, resourceFilter, exopackageModes, MACRO_HANDLER.getExpander(params.getBuildTarget(), params.getCellRoots(), resolver), args.preprocessJavaClassesBash, rulesToExcludeFromDex, result, args.reorderClassesIntraDex, args.dexReorderToolFile, args.dexReorderDataDumpFile, args.xzCompressionLevel, dxExecutorService, args.packageAssetLibraries, args.compressAssetLibraries, args.manifestEntries, javaOptions.getJavaRuntimeLauncher(), dxConfig.getDxMaxHeapSize());
}
}
use of com.facebook.buck.rules.BuildRuleParams in project buck by facebook.
the class AndroidBinaryGraphEnhancer method createPreDexMergeRule.
/**
* Creates/finds the set of build rules that correspond to pre-dex'd artifacts that should be
* merged to create the final classes.dex for the APK.
* <p>
* This method may modify {@code ruleResolver}, inserting new rules into its index.
*/
@VisibleForTesting
PreDexMerge createPreDexMergeRule(ImmutableMultimap<APKModule, DexProducedFromJavaLibrary> allPreDexDeps, DexProducedFromJavaLibrary dexForUberRDotJava) {
BuildRuleParams paramsForPreDexMerge = buildRuleParams.withAppendedFlavor(DEX_MERGE_FLAVOR).copyReplacingDeclaredAndExtraDeps(Suppliers.ofInstance(ImmutableSortedSet.<BuildRule>naturalOrder().addAll(getDexMergeDeps(dexForUberRDotJava, ImmutableSet.copyOf(allPreDexDeps.values()))).build()), Suppliers.ofInstance(ImmutableSortedSet.of()));
PreDexMerge preDexMerge = new PreDexMerge(paramsForPreDexMerge, primaryDexPath, dexSplitMode, apkModuleGraph, allPreDexDeps, dexForUberRDotJava, dxExecutorService, xzCompressionLevel, dxConfig.getDxMaxHeapSize());
ruleResolver.addToIndex(preDexMerge);
return preDexMerge;
}
use of com.facebook.buck.rules.BuildRuleParams in project buck by facebook.
the class AndroidBuildConfigDescription method createBuildRule.
/**
* @param values Collection whose entries identify fields for the generated
* {@code BuildConfig} class. The values for fields can be overridden by values from the
* {@code valuesFile} file, if present.
* @param valuesFile Path to a file with values to override those in {@code values}.
* @param ruleResolver Any intermediate rules introduced by this method will be added to this
* {@link BuildRuleResolver}.
*/
static AndroidBuildConfigJavaLibrary createBuildRule(BuildRuleParams params, String javaPackage, BuildConfigFields values, Optional<SourcePath> valuesFile, boolean useConstantExpressions, JavacOptions javacOptions, BuildRuleResolver ruleResolver) throws NoSuchBuildTargetException {
// Normally, the build target for an intermediate rule is a flavored version of the target for
// the original rule. For example, if the build target for an android_build_config() were
// //foo:bar, then the build target for the intermediate AndroidBuildConfig rule created by this
// method would be //foo:bar#gen_java_android_build_config.
//
// However, in the case of an android_binary() with multiple android_build_config() rules in its
// transitive deps, it must create one intermediate AndroidBuildConfigJavaLibrary for each
// android_build_config() dependency. The primary difference is that in each of the new versions
// of the AndroidBuildConfigJavaLibrary, constant expressions will be used so the values can be
// inlined (whereas non-constant-expressions were used in the original versions). Because there
// are multiple intermediate rules based on the same android_binary(), the flavor cannot just be
// #gen_java_android_build_config because that would lead to build target collisions, so the
// flavor must be parameterized by the java package to ensure it is unique.
//
// This fixes the issue, but deviates from the common pattern where a build rule has at most
// one flavored version of itself for a given flavor.
SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(ruleResolver);
SourcePathResolver pathResolver = new SourcePathResolver(ruleFinder);
BuildTarget buildConfigBuildTarget;
if (!params.getBuildTarget().isFlavored()) {
// android_build_config() case.
Preconditions.checkArgument(!useConstantExpressions);
buildConfigBuildTarget = params.getBuildTarget().withFlavors(GEN_JAVA_FLAVOR);
} else {
// android_binary() graph enhancement case.
Preconditions.checkArgument(useConstantExpressions);
buildConfigBuildTarget = params.getBuildTarget().withFlavors(InternalFlavor.of(GEN_JAVA_FLAVOR.getName() + '_' + javaPackage.replace('.', '_')));
}
// Create one build rule to generate BuildConfig.java.
BuildRuleParams buildConfigParams = params.withBuildTarget(buildConfigBuildTarget).copyAppendingExtraDeps(ruleFinder.filterBuildRuleInputs(OptionalCompat.asSet(valuesFile)));
AndroidBuildConfig androidBuildConfig = new AndroidBuildConfig(buildConfigParams, javaPackage, values, valuesFile, useConstantExpressions);
ruleResolver.addToIndex(androidBuildConfig);
// Create a second build rule to compile BuildConfig.java and expose it as a JavaLibrary.
BuildRuleParams javaLibraryParams = params.copyReplacingDeclaredAndExtraDeps(Suppliers.ofInstance(ImmutableSortedSet.of(androidBuildConfig)), Suppliers.ofInstance(ImmutableSortedSet.of()));
return new AndroidBuildConfigJavaLibrary(javaLibraryParams, pathResolver, ruleFinder, javacOptions, JavaLibraryRules.getAbiInputs(ruleResolver, javaLibraryParams.getDeps()), androidBuildConfig);
}
use of com.facebook.buck.rules.BuildRuleParams in project buck by facebook.
the class AndroidNativeLibsPackageableGraphEnhancer method generateStripRules.
// Note: this method produces rules that will be shared between multiple apps,
// so be careful not to let information about this particular app slip into the definitions.
private static ImmutableMap<StripLinkable, StrippedObjectDescription> generateStripRules(BuildRuleParams buildRuleParams, SourcePathRuleFinder ruleFinder, BuildRuleResolver ruleResolver, BuildTarget appRuleTarget, ImmutableMap<NdkCxxPlatforms.TargetCpuType, NdkCxxPlatform> nativePlatforms, ImmutableMap<Pair<NdkCxxPlatforms.TargetCpuType, String>, SourcePath> libs) {
ImmutableMap.Builder<StripLinkable, StrippedObjectDescription> result = ImmutableMap.builder();
for (Map.Entry<Pair<NdkCxxPlatforms.TargetCpuType, String>, SourcePath> entry : libs.entrySet()) {
SourcePath sourcePath = entry.getValue();
NdkCxxPlatforms.TargetCpuType targetCpuType = entry.getKey().getFirst();
NdkCxxPlatform platform = Preconditions.checkNotNull(nativePlatforms.get(targetCpuType));
// To be safe, default to using the app rule target as the base for the strip rule.
// This will be used for stripping the C++ runtime. We could use something more easily
// shareable (like just using the app's containing directory, or even the repo root),
// but stripping the C++ runtime is pretty fast, so just keep the safe old behavior for now.
BuildTarget baseBuildTarget = appRuleTarget;
// to allow sharing the rule between all apps that depend on it.
if (sourcePath instanceof BuildTargetSourcePath) {
baseBuildTarget = ((BuildTargetSourcePath<?>) sourcePath).getTarget();
}
String sharedLibrarySoName = entry.getKey().getSecond();
BuildTarget targetForStripRule = BuildTarget.builder(baseBuildTarget).addFlavors(InternalFlavor.of("android-strip")).addFlavors(InternalFlavor.of(Flavor.replaceInvalidCharacters(sharedLibrarySoName))).addFlavors(InternalFlavor.of(Flavor.replaceInvalidCharacters(targetCpuType.name()))).build();
Optional<BuildRule> previouslyCreated = ruleResolver.getRuleOptional(targetForStripRule);
StripLinkable stripLinkable;
if (previouslyCreated.isPresent()) {
stripLinkable = (StripLinkable) previouslyCreated.get();
} else {
BuildRuleParams paramsForStripLinkable = buildRuleParams.withBuildTarget(targetForStripRule).copyReplacingDeclaredAndExtraDeps(Suppliers.ofInstance(ImmutableSortedSet.<BuildRule>naturalOrder().addAll(ruleFinder.filterBuildRuleInputs(ImmutableList.of(sourcePath))).build()), Suppliers.ofInstance(ImmutableSortedSet.of()));
stripLinkable = new StripLinkable(paramsForStripLinkable, platform.getCxxPlatform().getStrip(), sourcePath, sharedLibrarySoName);
ruleResolver.addToIndex(stripLinkable);
}
result.put(stripLinkable, StrippedObjectDescription.builder().setSourcePath(stripLinkable.getSourcePathToOutput()).setStrippedObjectName(sharedLibrarySoName).setTargetCpuType(targetCpuType).build());
}
return result.build();
}
Aggregations