Search in sources :

Example 76 with ImmutableList

use of org.apache.flink.shaded.guava30.com.google.common.collect.ImmutableList in project buck by facebook.

the class WriteStringTemplateRule method getBuildSteps.

@Override
public ImmutableList<Step> getBuildSteps(BuildContext context, BuildableContext buildableContext) {
    buildableContext.recordArtifact(output);
    ImmutableList.Builder<Step> steps = ImmutableList.builder();
    steps.add(new MkdirStep(getProjectFilesystem(), output.getParent()));
    steps.add(new StringTemplateStep(context.getSourcePathResolver().getAbsolutePath(template), getProjectFilesystem(), output, st -> {
        for (Map.Entry<String, String> ent : values.entrySet()) {
            st = st.add(ent.getKey(), ent.getValue());
        }
        return st;
    }));
    if (executable) {
        steps.add(new AbstractExecutionStep("chmod +x") {

            @Override
            public StepExecutionResult execute(ExecutionContext context) throws IOException {
                MoreFiles.makeExecutable(getProjectFilesystem().resolve(output));
                return StepExecutionResult.of(0, Optional.empty());
            }
        });
    }
    return steps.build();
}
Also used : ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) Step(com.facebook.buck.step.Step) ImmutableMap(com.google.common.collect.ImmutableMap) IOException(java.io.IOException) BuildTarget(com.facebook.buck.model.BuildTarget) MkdirStep(com.facebook.buck.step.fs.MkdirStep) StringTemplateStep(com.facebook.buck.step.fs.StringTemplateStep) AbstractExecutionStep(com.facebook.buck.step.AbstractExecutionStep) ExecutionContext(com.facebook.buck.step.ExecutionContext) ImmutableList(com.google.common.collect.ImmutableList) Map(java.util.Map) Suppliers(com.google.common.base.Suppliers) Optional(java.util.Optional) MoreFiles(com.facebook.buck.io.MoreFiles) StepExecutionResult(com.facebook.buck.step.StepExecutionResult) Path(java.nio.file.Path) ExecutionContext(com.facebook.buck.step.ExecutionContext) AbstractExecutionStep(com.facebook.buck.step.AbstractExecutionStep) StepExecutionResult(com.facebook.buck.step.StepExecutionResult) ImmutableList(com.google.common.collect.ImmutableList) MkdirStep(com.facebook.buck.step.fs.MkdirStep) Step(com.facebook.buck.step.Step) MkdirStep(com.facebook.buck.step.fs.MkdirStep) StringTemplateStep(com.facebook.buck.step.fs.StringTemplateStep) AbstractExecutionStep(com.facebook.buck.step.AbstractExecutionStep) IOException(java.io.IOException) StringTemplateStep(com.facebook.buck.step.fs.StringTemplateStep)

Example 77 with ImmutableList

use of org.apache.flink.shaded.guava30.com.google.common.collect.ImmutableList in project buck by facebook.

the class StringWithMacrosTypeCoercer method parse.

private StringWithMacros parse(CellPathResolver cellRoots, ProjectFilesystem filesystem, Path pathRelativeToProjectRoot, String blob) throws CoerceFailedException {
    ImmutableList.Builder<Either<String, Macro>> parts = ImmutableList.builder();
    // Iterate over all macros found in the string, expanding each found macro.
    int lastEnd = 0;
    MacroFinder.MacroFinderAutomaton matcher = new MacroFinder.MacroFinderAutomaton(blob);
    while (matcher.hasNext()) {
        MacroMatchResult matchResult = matcher.next();
        // Add everything from the original string since the last match to this one.
        if (lastEnd < matchResult.getStartIndex()) {
            parts.add(Either.ofLeft(blob.substring(lastEnd, matchResult.getStartIndex())));
        }
        // Look up the macro coercer that owns this macro name.
        String name = matchResult.getMacroType();
        Class<? extends Macro> clazz = macros.get(name);
        if (clazz == null) {
            throw new CoerceFailedException(String.format("expanding %s: no such macro \"%s\"", blob.substring(matchResult.getStartIndex(), matchResult.getEndIndex()), matchResult.getMacroType()));
        }
        MacroTypeCoercer<? extends Macro> coercer = Preconditions.checkNotNull(coercers.get(clazz));
        ImmutableList<String> args = matchResult.getMacroInput();
        // Delegate to the macro coercers to parse the macro..
        Macro macro;
        try {
            macro = coercer.coerce(cellRoots, filesystem, pathRelativeToProjectRoot, args);
        } catch (CoerceFailedException e) {
            throw new CoerceFailedException(String.format("macro \"%s\": %s", name, e.getMessage()), e);
        }
        parts.add(Either.ofRight(macro));
        lastEnd = matchResult.getEndIndex();
    }
    // Append the remaining part of the original string after the last match.
    if (lastEnd < blob.length()) {
        parts.add(Either.ofLeft(blob.substring(lastEnd, blob.length())));
    }
    return StringWithMacros.of(parts.build());
}
Also used : MacroMatchResult(com.facebook.buck.model.MacroMatchResult) ImmutableList(com.google.common.collect.ImmutableList) Macro(com.facebook.buck.rules.macros.Macro) MacroFinder(com.facebook.buck.model.MacroFinder) Either(com.facebook.buck.model.Either)

Example 78 with ImmutableList

use of org.apache.flink.shaded.guava30.com.google.common.collect.ImmutableList in project buck by facebook.

the class RmStep method getShellCommand.

public ImmutableList<String> getShellCommand() {
    ImmutableList.Builder<String> args = ImmutableList.builder();
    args.add("rm");
    args.add("-f");
    for (Mode mode : modes) {
        args.add(mode.toShellArgument());
    }
    Path absolutePath = filesystem.resolve(toDelete);
    args.add(absolutePath.toString());
    return args.build();
}
Also used : Path(java.nio.file.Path) ImmutableList(com.google.common.collect.ImmutableList)

Example 79 with ImmutableList

use of org.apache.flink.shaded.guava30.com.google.common.collect.ImmutableList in project buck by facebook.

the class AppleBundle method getBuildSteps.

@Override
public ImmutableList<Step> getBuildSteps(BuildContext context, BuildableContext buildableContext) {
    ImmutableList.Builder<Step> stepsBuilder = ImmutableList.builder();
    stepsBuilder.add(new MakeCleanDirectoryStep(getProjectFilesystem(), bundleRoot));
    Path resourcesDestinationPath = bundleRoot.resolve(this.destinations.getResourcesPath());
    if (assetCatalog.isPresent()) {
        stepsBuilder.add(new MkdirStep(getProjectFilesystem(), resourcesDestinationPath));
        Path bundleDir = assetCatalog.get().getOutputDir();
        stepsBuilder.add(CopyStep.forDirectory(getProjectFilesystem(), bundleDir, resourcesDestinationPath, CopyStep.DirectoryMode.CONTENTS_ONLY));
    }
    if (coreDataModel.isPresent()) {
        stepsBuilder.add(new MkdirStep(getProjectFilesystem(), resourcesDestinationPath));
        stepsBuilder.add(CopyStep.forDirectory(getProjectFilesystem(), context.getSourcePathResolver().getRelativePath(coreDataModel.get().getSourcePathToOutput()), resourcesDestinationPath, CopyStep.DirectoryMode.CONTENTS_ONLY));
    }
    if (sceneKitAssets.isPresent()) {
        stepsBuilder.add(new MkdirStep(getProjectFilesystem(), resourcesDestinationPath));
        stepsBuilder.add(CopyStep.forDirectory(getProjectFilesystem(), context.getSourcePathResolver().getRelativePath(sceneKitAssets.get().getSourcePathToOutput()), resourcesDestinationPath, CopyStep.DirectoryMode.CONTENTS_ONLY));
    }
    Path metadataPath = getMetadataPath();
    Path infoPlistInputPath = context.getSourcePathResolver().getAbsolutePath(infoPlist);
    Path infoPlistSubstitutionTempPath = BuildTargets.getScratchPath(getProjectFilesystem(), getBuildTarget(), "%s.plist");
    Path infoPlistOutputPath = metadataPath.resolve("Info.plist");
    stepsBuilder.add(new MkdirStep(getProjectFilesystem(), metadataPath), // TODO(bhamiltoncx): This is only appropriate for .app bundles.
    new WriteFileStep(getProjectFilesystem(), "APPLWRUN", metadataPath.resolve("PkgInfo"), /* executable */
    false), new MkdirStep(getProjectFilesystem(), infoPlistSubstitutionTempPath.getParent()), new FindAndReplaceStep(getProjectFilesystem(), infoPlistInputPath, infoPlistSubstitutionTempPath, InfoPlistSubstitution.createVariableExpansionFunction(withDefaults(infoPlistSubstitutions, ImmutableMap.of("EXECUTABLE_NAME", binaryName, "PRODUCT_NAME", binaryName)))), new PlistProcessStep(getProjectFilesystem(), infoPlistSubstitutionTempPath, assetCatalog.isPresent() ? Optional.of(assetCatalog.get().getOutputPlist()) : Optional.empty(), infoPlistOutputPath, getInfoPlistAdditionalKeys(), getInfoPlistOverrideKeys(), PlistProcessStep.OutputFormat.BINARY));
    if (hasBinary) {
        appendCopyBinarySteps(stepsBuilder, context.getSourcePathResolver());
        appendCopyDsymStep(stepsBuilder, buildableContext, context.getSourcePathResolver());
    }
    if (!Iterables.isEmpty(Iterables.concat(resources.getResourceDirs(), resources.getDirsContainingResourceDirs(), resources.getResourceFiles()))) {
        stepsBuilder.add(new MkdirStep(getProjectFilesystem(), resourcesDestinationPath));
        for (SourcePath dir : resources.getResourceDirs()) {
            stepsBuilder.add(CopyStep.forDirectory(getProjectFilesystem(), context.getSourcePathResolver().getAbsolutePath(dir), resourcesDestinationPath, CopyStep.DirectoryMode.DIRECTORY_AND_CONTENTS));
        }
        for (SourcePath dir : resources.getDirsContainingResourceDirs()) {
            stepsBuilder.add(CopyStep.forDirectory(getProjectFilesystem(), context.getSourcePathResolver().getAbsolutePath(dir), resourcesDestinationPath, CopyStep.DirectoryMode.CONTENTS_ONLY));
        }
        for (SourcePath file : resources.getResourceFiles()) {
            // TODO(shs96c): Check that this work cross-cell
            Path resolvedFilePath = context.getSourcePathResolver().getRelativePath(file);
            Path destinationPath = resourcesDestinationPath.resolve(resolvedFilePath.getFileName());
            addResourceProcessingSteps(context.getSourcePathResolver(), resolvedFilePath, destinationPath, stepsBuilder);
        }
    }
    ImmutableList.Builder<Path> codeSignOnCopyPathsBuilder = ImmutableList.builder();
    addStepsToCopyExtensionBundlesDependencies(context.getSourcePathResolver(), stepsBuilder, codeSignOnCopyPathsBuilder);
    for (SourcePath variantSourcePath : resources.getResourceVariantFiles()) {
        // TODO(shs96c): Ensure this works cross-cell, as relative path begins with "buck-out"
        Path variantFilePath = context.getSourcePathResolver().getRelativePath(variantSourcePath);
        Path variantDirectory = variantFilePath.getParent();
        if (variantDirectory == null || !variantDirectory.toString().endsWith(".lproj")) {
            throw new HumanReadableException("Variant files have to be in a directory with name ending in '.lproj', " + "but '%s' is not.", variantFilePath);
        }
        Path bundleVariantDestinationPath = resourcesDestinationPath.resolve(variantDirectory.getFileName());
        stepsBuilder.add(new MkdirStep(getProjectFilesystem(), bundleVariantDestinationPath));
        Path destinationPath = bundleVariantDestinationPath.resolve(variantFilePath.getFileName());
        addResourceProcessingSteps(context.getSourcePathResolver(), variantFilePath, destinationPath, stepsBuilder);
    }
    if (!frameworks.isEmpty()) {
        Path frameworksDestinationPath = bundleRoot.resolve(this.destinations.getFrameworksPath());
        stepsBuilder.add(new MkdirStep(getProjectFilesystem(), frameworksDestinationPath));
        for (SourcePath framework : frameworks) {
            Path srcPath = context.getSourcePathResolver().getAbsolutePath(framework);
            stepsBuilder.add(CopyStep.forDirectory(getProjectFilesystem(), srcPath, frameworksDestinationPath, CopyStep.DirectoryMode.DIRECTORY_AND_CONTENTS));
            codeSignOnCopyPathsBuilder.add(frameworksDestinationPath.resolve(srcPath.getFileName()));
        }
    }
    if (needCodeSign()) {
        Optional<Path> signingEntitlementsTempPath;
        Supplier<CodeSignIdentity> codeSignIdentitySupplier;
        if (adHocCodeSignIsSufficient()) {
            signingEntitlementsTempPath = Optional.empty();
            codeSignIdentitySupplier = () -> CodeSignIdentity.AD_HOC;
        } else {
            // Copy the .mobileprovision file if the platform requires it, and sign the executable.
            Optional<Path> entitlementsPlist = Optional.empty();
            final Path srcRoot = getProjectFilesystem().getRootPath().resolve(getBuildTarget().getBasePath());
            Optional<String> entitlementsPlistString = InfoPlistSubstitution.getVariableExpansionForPlatform(CODE_SIGN_ENTITLEMENTS, platform.getName(), withDefaults(infoPlistSubstitutions, ImmutableMap.of("SOURCE_ROOT", srcRoot.toString(), "SRCROOT", srcRoot.toString())));
            if (entitlementsPlistString.isPresent()) {
                entitlementsPlist = Optional.of(srcRoot.resolve(Paths.get(entitlementsPlistString.get())));
            }
            signingEntitlementsTempPath = Optional.of(BuildTargets.getScratchPath(getProjectFilesystem(), getBuildTarget(), "%s.xcent"));
            final Path dryRunResultPath = bundleRoot.resolve(PP_DRY_RUN_RESULT_FILE);
            final ProvisioningProfileCopyStep provisioningProfileCopyStep = new ProvisioningProfileCopyStep(getProjectFilesystem(), infoPlistOutputPath, platform, // Provisioning profile UUID -- find automatically.
            Optional.empty(), entitlementsPlist, provisioningProfileStore, resourcesDestinationPath.resolve("embedded.mobileprovision"), dryRunCodeSigning ? bundleRoot.resolve(CODE_SIGN_DRY_RUN_ENTITLEMENTS_FILE) : signingEntitlementsTempPath.get(), codeSignIdentityStore, dryRunCodeSigning ? Optional.of(dryRunResultPath) : Optional.empty());
            stepsBuilder.add(provisioningProfileCopyStep);
            codeSignIdentitySupplier = () -> {
                // Using getUnchecked here because the previous step should already throw if exception
                // occurred, and this supplier would never be evaluated.
                Optional<ProvisioningProfileMetadata> selectedProfile = Futures.getUnchecked(provisioningProfileCopyStep.getSelectedProvisioningProfileFuture());
                if (!selectedProfile.isPresent()) {
                    // This should only happen in dry-run codesign mode (since otherwise an exception
                    // would have been thrown already.)  Still, we need to return *something*.
                    Preconditions.checkState(dryRunCodeSigning);
                    return CodeSignIdentity.AD_HOC;
                }
                ImmutableSet<HashCode> fingerprints = selectedProfile.get().getDeveloperCertificateFingerprints();
                if (fingerprints.isEmpty()) {
                    // If no identities are available, use an ad-hoc identity.
                    return Iterables.getFirst(codeSignIdentityStore.getIdentities(), CodeSignIdentity.AD_HOC);
                }
                for (CodeSignIdentity identity : codeSignIdentityStore.getIdentities()) {
                    if (identity.getFingerprint().isPresent() && fingerprints.contains(identity.getFingerprint().get())) {
                        return identity;
                    }
                }
                throw new HumanReadableException("No code sign identity available for provisioning profile: %s\n" + "Profile requires an identity with one of the following SHA1 fingerprints " + "available in your keychain: \n  %s", selectedProfile.get().getProfilePath(), Joiner.on("\n  ").join(fingerprints));
            };
        }
        addSwiftStdlibStepIfNeeded(context.getSourcePathResolver(), bundleRoot.resolve(Paths.get("Frameworks")), dryRunCodeSigning ? Optional.<Supplier<CodeSignIdentity>>empty() : Optional.of(codeSignIdentitySupplier), stepsBuilder, false);
        for (Path codeSignOnCopyPath : codeSignOnCopyPathsBuilder.build()) {
            stepsBuilder.add(new CodeSignStep(getProjectFilesystem(), context.getSourcePathResolver(), codeSignOnCopyPath, Optional.empty(), codeSignIdentitySupplier, codesign, codesignAllocatePath, dryRunCodeSigning ? Optional.of(codeSignOnCopyPath.resolve(CODE_SIGN_DRY_RUN_ARGS_FILE)) : Optional.empty()));
        }
        stepsBuilder.add(new CodeSignStep(getProjectFilesystem(), context.getSourcePathResolver(), bundleRoot, signingEntitlementsTempPath, codeSignIdentitySupplier, codesign, codesignAllocatePath, dryRunCodeSigning ? Optional.of(bundleRoot.resolve(CODE_SIGN_DRY_RUN_ARGS_FILE)) : Optional.empty()));
    } else {
        addSwiftStdlibStepIfNeeded(context.getSourcePathResolver(), bundleRoot.resolve(Paths.get("Frameworks")), Optional.<Supplier<CodeSignIdentity>>empty(), stepsBuilder, false);
    }
    // Ensure the bundle directory is archived so we can fetch it later.
    buildableContext.recordArtifact(context.getSourcePathResolver().getRelativePath(getSourcePathToOutput()));
    return stepsBuilder.build();
}
Also used : Path(java.nio.file.Path) PathSourcePath(com.facebook.buck.rules.PathSourcePath) SourcePath(com.facebook.buck.rules.SourcePath) ExplicitBuildTargetSourcePath(com.facebook.buck.rules.ExplicitBuildTargetSourcePath) FindAndReplaceStep(com.facebook.buck.step.fs.FindAndReplaceStep) ImmutableList(com.google.common.collect.ImmutableList) MkdirStep(com.facebook.buck.step.fs.MkdirStep) RmStep(com.facebook.buck.step.fs.RmStep) CopyStep(com.facebook.buck.step.fs.CopyStep) MkdirStep(com.facebook.buck.step.fs.MkdirStep) WriteFileStep(com.facebook.buck.step.fs.WriteFileStep) Step(com.facebook.buck.step.Step) MakeCleanDirectoryStep(com.facebook.buck.step.fs.MakeCleanDirectoryStep) MoveStep(com.facebook.buck.step.fs.MoveStep) FindAndReplaceStep(com.facebook.buck.step.fs.FindAndReplaceStep) NSString(com.dd.plist.NSString) PathSourcePath(com.facebook.buck.rules.PathSourcePath) SourcePath(com.facebook.buck.rules.SourcePath) ExplicitBuildTargetSourcePath(com.facebook.buck.rules.ExplicitBuildTargetSourcePath) HashCode(com.google.common.hash.HashCode) HumanReadableException(com.facebook.buck.util.HumanReadableException) MakeCleanDirectoryStep(com.facebook.buck.step.fs.MakeCleanDirectoryStep) Supplier(com.google.common.base.Supplier) WriteFileStep(com.facebook.buck.step.fs.WriteFileStep)

Example 80 with ImmutableList

use of org.apache.flink.shaded.guava30.com.google.common.collect.ImmutableList in project buck by facebook.

the class AppleCxxPlatforms method buildWithExecutableChecker.

@VisibleForTesting
static AppleCxxPlatform buildWithExecutableChecker(ProjectFilesystem filesystem, AppleSdk targetSdk, String minVersion, String targetArchitecture, final AppleSdkPaths sdkPaths, BuckConfig buckConfig, AppleConfig appleConfig, ExecutableFinder executableFinder, Optional<ProcessExecutor> processExecutor, Optional<AppleToolchain> swiftToolChain) {
    AppleCxxPlatform.Builder platformBuilder = AppleCxxPlatform.builder();
    ImmutableList.Builder<Path> toolSearchPathsBuilder = ImmutableList.builder();
    // Search for tools from most specific to least specific.
    toolSearchPathsBuilder.add(sdkPaths.getSdkPath().resolve(USR_BIN)).add(sdkPaths.getSdkPath().resolve("Developer").resolve(USR_BIN)).add(sdkPaths.getPlatformPath().resolve("Developer").resolve(USR_BIN));
    for (Path toolchainPath : sdkPaths.getToolchainPaths()) {
        toolSearchPathsBuilder.add(toolchainPath.resolve(USR_BIN));
    }
    if (sdkPaths.getDeveloperPath().isPresent()) {
        toolSearchPathsBuilder.add(sdkPaths.getDeveloperPath().get().resolve(USR_BIN));
        toolSearchPathsBuilder.add(sdkPaths.getDeveloperPath().get().resolve("Tools"));
    }
    // TODO(bhamiltoncx): Add more and better cflags.
    ImmutableList.Builder<String> cflagsBuilder = ImmutableList.builder();
    cflagsBuilder.add("-isysroot", sdkPaths.getSdkPath().toString());
    cflagsBuilder.add("-iquote", filesystem.getRootPath().toString());
    cflagsBuilder.add("-arch", targetArchitecture);
    cflagsBuilder.add(targetSdk.getApplePlatform().getMinVersionFlagPrefix() + minVersion);
    if (targetSdk.getApplePlatform().equals(ApplePlatform.WATCHOS)) {
        cflagsBuilder.add("-fembed-bitcode");
    }
    ImmutableList.Builder<String> ldflagsBuilder = ImmutableList.builder();
    ldflagsBuilder.addAll(Linkers.iXlinker("-sdk_version", targetSdk.getVersion(), "-ObjC"));
    if (targetSdk.getApplePlatform().equals(ApplePlatform.WATCHOS)) {
        ldflagsBuilder.addAll(Linkers.iXlinker("-bitcode_verify", "-bitcode_hide_symbols", "-bitcode_symbol_map"));
    }
    // Populate Xcode version keys from Xcode's own Info.plist if available.
    Optional<String> xcodeBuildVersion = Optional.empty();
    Optional<Path> developerPath = sdkPaths.getDeveloperPath();
    if (developerPath.isPresent()) {
        Path xcodeBundlePath = developerPath.get().getParent();
        if (xcodeBundlePath != null) {
            File xcodeInfoPlistPath = xcodeBundlePath.resolve("Info.plist").toFile();
            try {
                NSDictionary parsedXcodeInfoPlist = (NSDictionary) PropertyListParser.parse(xcodeInfoPlistPath);
                NSObject xcodeVersionObject = parsedXcodeInfoPlist.objectForKey("DTXcode");
                if (xcodeVersionObject != null) {
                    Optional<String> xcodeVersion = Optional.of(xcodeVersionObject.toString());
                    platformBuilder.setXcodeVersion(xcodeVersion);
                }
            } catch (IOException e) {
                LOG.warn("Error reading Xcode's info plist %s; ignoring Xcode versions", xcodeInfoPlistPath);
            } catch (PropertyListFormatException | ParseException | ParserConfigurationException | SAXException e) {
                LOG.warn("Error in parsing %s; ignoring Xcode versions", xcodeInfoPlistPath);
            }
        }
        // different than the build number in the Info.plist, sigh.
        if (processExecutor.isPresent()) {
            xcodeBuildVersion = appleConfig.getXcodeBuildVersionSupplier(developerPath.get(), processExecutor.get()).get();
            platformBuilder.setXcodeBuildVersion(xcodeBuildVersion);
            LOG.debug("Xcode build version is: " + xcodeBuildVersion.orElse("<absent>"));
        }
    }
    ImmutableList.Builder<String> versions = ImmutableList.builder();
    versions.add(targetSdk.getVersion());
    ImmutableList<String> toolchainVersions = targetSdk.getToolchains().stream().map(AppleToolchain::getVersion).flatMap(Optionals::toStream).collect(MoreCollectors.toImmutableList());
    if (toolchainVersions.isEmpty()) {
        if (!xcodeBuildVersion.isPresent()) {
            throw new HumanReadableException("Failed to read toolchain versions and Xcode version.");
        }
        versions.add(xcodeBuildVersion.get());
    } else {
        versions.addAll(toolchainVersions);
    }
    String version = Joiner.on(':').join(versions.build());
    ImmutableList<Path> toolSearchPaths = toolSearchPathsBuilder.build();
    Tool clangPath = VersionedTool.of(getToolPath("clang", toolSearchPaths, executableFinder), "apple-clang", version);
    Tool clangXxPath = VersionedTool.of(getToolPath("clang++", toolSearchPaths, executableFinder), "apple-clang++", version);
    Tool ar = VersionedTool.of(getToolPath("ar", toolSearchPaths, executableFinder), "apple-ar", version);
    Tool ranlib = VersionedTool.builder().setPath(getToolPath("ranlib", toolSearchPaths, executableFinder)).setName("apple-ranlib").setVersion(version).build();
    Tool strip = VersionedTool.of(getToolPath("strip", toolSearchPaths, executableFinder), "apple-strip", version);
    Tool nm = VersionedTool.of(getToolPath("nm", toolSearchPaths, executableFinder), "apple-nm", version);
    Tool actool = VersionedTool.of(getToolPath("actool", toolSearchPaths, executableFinder), "apple-actool", version);
    Tool ibtool = VersionedTool.of(getToolPath("ibtool", toolSearchPaths, executableFinder), "apple-ibtool", version);
    Tool momc = VersionedTool.of(getToolPath("momc", toolSearchPaths, executableFinder), "apple-momc", version);
    Tool xctest = VersionedTool.of(getToolPath("xctest", toolSearchPaths, executableFinder), "apple-xctest", version);
    Tool dsymutil = VersionedTool.of(getToolPath("dsymutil", toolSearchPaths, executableFinder), "apple-dsymutil", version);
    Tool lipo = VersionedTool.of(getToolPath("lipo", toolSearchPaths, executableFinder), "apple-lipo", version);
    Tool lldb = VersionedTool.of(getToolPath("lldb", toolSearchPaths, executableFinder), "lldb", version);
    Optional<Path> stubBinaryPath = targetSdk.getApplePlatform().getStubBinaryPath().map(input -> sdkPaths.getSdkPath().resolve(input));
    CxxBuckConfig config = new CxxBuckConfig(buckConfig);
    UserFlavor targetFlavor = UserFlavor.of(Flavor.replaceInvalidCharacters(targetSdk.getName() + "-" + targetArchitecture), String.format("SDK: %s, architecture: %s", targetSdk.getName(), targetArchitecture));
    ImmutableBiMap.Builder<Path, Path> sanitizerPaths = ImmutableBiMap.builder();
    sanitizerPaths.put(sdkPaths.getSdkPath(), Paths.get("APPLE_SDKROOT"));
    sanitizerPaths.put(sdkPaths.getPlatformPath(), Paths.get("APPLE_PLATFORM_DIR"));
    if (sdkPaths.getDeveloperPath().isPresent()) {
        sanitizerPaths.put(sdkPaths.getDeveloperPath().get(), Paths.get("APPLE_DEVELOPER_DIR"));
    }
    DebugPathSanitizer compilerDebugPathSanitizer = new PrefixMapDebugPathSanitizer(config.getDebugPathSanitizerLimit(), File.separatorChar, Paths.get("."), sanitizerPaths.build(), filesystem.getRootPath().toAbsolutePath(), CxxToolProvider.Type.CLANG, filesystem);
    DebugPathSanitizer assemblerDebugPathSanitizer = new MungingDebugPathSanitizer(config.getDebugPathSanitizerLimit(), File.separatorChar, Paths.get("."), sanitizerPaths.build());
    ImmutableList<String> cflags = cflagsBuilder.build();
    ImmutableMap.Builder<String, String> macrosBuilder = ImmutableMap.builder();
    macrosBuilder.put("SDKROOT", sdkPaths.getSdkPath().toString());
    macrosBuilder.put("PLATFORM_DIR", sdkPaths.getPlatformPath().toString());
    macrosBuilder.put("CURRENT_ARCH", targetArchitecture);
    if (sdkPaths.getDeveloperPath().isPresent()) {
        macrosBuilder.put("DEVELOPER_DIR", sdkPaths.getDeveloperPath().get().toString());
    }
    ImmutableMap<String, String> macros = macrosBuilder.build();
    Optional<String> buildVersion = Optional.empty();
    Path platformVersionPlistPath = sdkPaths.getPlatformPath().resolve("version.plist");
    try (InputStream versionPlist = Files.newInputStream(platformVersionPlistPath)) {
        NSDictionary versionInfo = (NSDictionary) PropertyListParser.parse(versionPlist);
        if (versionInfo != null) {
            NSObject productBuildVersion = versionInfo.objectForKey("ProductBuildVersion");
            if (productBuildVersion != null) {
                buildVersion = Optional.of(productBuildVersion.toString());
            } else {
                LOG.warn("In %s, missing ProductBuildVersion. Build version will be unset for this platform.", platformVersionPlistPath);
            }
        } else {
            LOG.warn("Empty version plist in %s. Build version will be unset for this platform.", platformVersionPlistPath);
        }
    } catch (NoSuchFileException e) {
        LOG.warn("%s does not exist. Build version will be unset for this platform.", platformVersionPlistPath);
    } catch (PropertyListFormatException | SAXException | ParserConfigurationException | ParseException | IOException e) {
        // Some other error occurred, print the exception since it may contain error details.
        LOG.warn(e, "Failed to parse %s. Build version will be unset for this platform.", platformVersionPlistPath);
    }
    PreprocessorProvider aspp = new PreprocessorProvider(new ConstantToolProvider(clangPath), CxxToolProvider.Type.CLANG);
    CompilerProvider as = new CompilerProvider(new ConstantToolProvider(clangPath), CxxToolProvider.Type.CLANG);
    PreprocessorProvider cpp = new PreprocessorProvider(new ConstantToolProvider(clangPath), CxxToolProvider.Type.CLANG);
    CompilerProvider cc = new CompilerProvider(new ConstantToolProvider(clangPath), CxxToolProvider.Type.CLANG);
    PreprocessorProvider cxxpp = new PreprocessorProvider(new ConstantToolProvider(clangXxPath), CxxToolProvider.Type.CLANG);
    CompilerProvider cxx = new CompilerProvider(new ConstantToolProvider(clangXxPath), CxxToolProvider.Type.CLANG);
    ImmutableList.Builder<String> whitelistBuilder = ImmutableList.builder();
    whitelistBuilder.add("^" + Pattern.quote(sdkPaths.getSdkPath().toString()) + "\\/.*");
    whitelistBuilder.add("^" + Pattern.quote(sdkPaths.getPlatformPath().toString() + "/Developer/Library/Frameworks") + "\\/.*");
    for (Path toolchainPath : sdkPaths.getToolchainPaths()) {
        LOG.debug("Apple toolchain path: %s", toolchainPath);
        try {
            whitelistBuilder.add("^" + Pattern.quote(toolchainPath.toRealPath().toString()) + "\\/.*");
        } catch (IOException e) {
            LOG.warn(e, "Apple toolchain path could not be resolved: %s", toolchainPath);
        }
    }
    HeaderVerification headerVerification = config.getHeaderVerification().withPlatformWhitelist(whitelistBuilder.build());
    LOG.debug("Headers verification platform whitelist: %s", headerVerification.getPlatformWhitelist());
    CxxPlatform cxxPlatform = CxxPlatforms.build(targetFlavor, Platform.MACOS, config, as, aspp, cc, cxx, cpp, cxxpp, new DefaultLinkerProvider(LinkerProvider.Type.DARWIN, new ConstantToolProvider(clangXxPath)), ImmutableList.<String>builder().addAll(cflags).addAll(ldflagsBuilder.build()).build(), strip, new BsdArchiver(ar), ranlib, new PosixNmSymbolNameTool(nm), cflagsBuilder.build(), ImmutableList.of(), cflags, ImmutableList.of(), "dylib", "%s.dylib", "a", "o", compilerDebugPathSanitizer, assemblerDebugPathSanitizer, macros, Optional.empty(), headerVerification);
    ApplePlatform applePlatform = targetSdk.getApplePlatform();
    ImmutableList.Builder<Path> swiftOverrideSearchPathBuilder = ImmutableList.builder();
    AppleSdkPaths.Builder swiftSdkPathsBuilder = AppleSdkPaths.builder().from(sdkPaths);
    if (swiftToolChain.isPresent()) {
        swiftOverrideSearchPathBuilder.add(swiftToolChain.get().getPath().resolve(USR_BIN));
        swiftSdkPathsBuilder.setToolchainPaths(ImmutableList.of(swiftToolChain.get().getPath()));
    }
    Optional<SwiftPlatform> swiftPlatform = getSwiftPlatform(applePlatform.getName(), targetArchitecture + "-apple-" + applePlatform.getSwiftName().orElse(applePlatform.getName()) + minVersion, version, swiftSdkPathsBuilder.build(), swiftOverrideSearchPathBuilder.addAll(toolSearchPaths).build(), executableFinder);
    platformBuilder.setCxxPlatform(cxxPlatform).setSwiftPlatform(swiftPlatform).setAppleSdk(targetSdk).setAppleSdkPaths(sdkPaths).setMinVersion(minVersion).setBuildVersion(buildVersion).setActool(actool).setIbtool(ibtool).setMomc(momc).setCopySceneKitAssets(getOptionalTool("copySceneKitAssets", toolSearchPaths, executableFinder, version)).setXctest(xctest).setDsymutil(dsymutil).setLipo(lipo).setStubBinary(stubBinaryPath).setLldb(lldb).setCodesignAllocate(getOptionalTool("codesign_allocate", toolSearchPaths, executableFinder, version)).setCodesignProvider(appleConfig.getCodesignProvider());
    return platformBuilder.build();
}
Also used : NSDictionary(com.dd.plist.NSDictionary) NoSuchFileException(java.nio.file.NoSuchFileException) CompilerProvider(com.facebook.buck.cxx.CompilerProvider) SAXException(org.xml.sax.SAXException) DefaultLinkerProvider(com.facebook.buck.cxx.DefaultLinkerProvider) MungingDebugPathSanitizer(com.facebook.buck.cxx.MungingDebugPathSanitizer) DebugPathSanitizer(com.facebook.buck.cxx.DebugPathSanitizer) PrefixMapDebugPathSanitizer(com.facebook.buck.cxx.PrefixMapDebugPathSanitizer) VersionedTool(com.facebook.buck.rules.VersionedTool) PosixNmSymbolNameTool(com.facebook.buck.cxx.PosixNmSymbolNameTool) Tool(com.facebook.buck.rules.Tool) BsdArchiver(com.facebook.buck.cxx.BsdArchiver) MungingDebugPathSanitizer(com.facebook.buck.cxx.MungingDebugPathSanitizer) ImmutableMap(com.google.common.collect.ImmutableMap) PropertyListFormatException(com.dd.plist.PropertyListFormatException) ImmutableBiMap(com.google.common.collect.ImmutableBiMap) PreprocessorProvider(com.facebook.buck.cxx.PreprocessorProvider) File(java.io.File) PosixNmSymbolNameTool(com.facebook.buck.cxx.PosixNmSymbolNameTool) SwiftPlatform(com.facebook.buck.swift.SwiftPlatform) NSObject(com.dd.plist.NSObject) ConstantToolProvider(com.facebook.buck.rules.ConstantToolProvider) ImmutableList(com.google.common.collect.ImmutableList) HeaderVerification(com.facebook.buck.cxx.HeaderVerification) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Path(java.nio.file.Path) PrefixMapDebugPathSanitizer(com.facebook.buck.cxx.PrefixMapDebugPathSanitizer) CxxPlatform(com.facebook.buck.cxx.CxxPlatform) InputStream(java.io.InputStream) IOException(java.io.IOException) CxxBuckConfig(com.facebook.buck.cxx.CxxBuckConfig) HumanReadableException(com.facebook.buck.util.HumanReadableException) UserFlavor(com.facebook.buck.model.UserFlavor) ParseException(java.text.ParseException) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Aggregations

ImmutableList (com.google.common.collect.ImmutableList)1042 List (java.util.List)287 ArrayList (java.util.ArrayList)160 Test (org.junit.Test)155 Path (java.nio.file.Path)149 Map (java.util.Map)142 ImmutableMap (com.google.common.collect.ImmutableMap)122 IOException (java.io.IOException)110 Set (java.util.Set)97 ImmutableSet (com.google.common.collect.ImmutableSet)96 SourcePath (com.facebook.buck.rules.SourcePath)91 Optional (java.util.Optional)87 HashMap (java.util.HashMap)80 Step (com.facebook.buck.step.Step)76 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)66 Collectors (java.util.stream.Collectors)60 File (java.io.File)57 HashSet (java.util.HashSet)55 ExplicitBuildTargetSourcePath (com.facebook.buck.rules.ExplicitBuildTargetSourcePath)52 MakeCleanDirectoryStep (com.facebook.buck.step.fs.MakeCleanDirectoryStep)52