Example usage for com.google.common.base Optional asSet

List of usage examples for com.google.common.base Optional asSet

Introduction

In this page you can find the example usage for com.google.common.base Optional asSet.

Prototype

public abstract Set<T> asSet();

Source Link

Document

Returns an immutable singleton Set whose only element is the contained instance if it is present; an empty immutable Set otherwise.

Usage

From source file:com.google.devtools.build.lib.rules.objc.ObjcActionsBuilder.java

private void registerCompileAction(Artifact sourceFile, Artifact objFile, Optional<Artifact> pchFile,
        ObjcProvider objcProvider, Iterable<String> otherFlags, OptionsProvider optionsProvider,
        boolean isCodeCoverageEnabled) {
    ImmutableList.Builder<String> coverageFlags = new ImmutableList.Builder<>();
    ImmutableList.Builder<Artifact> gcnoFiles = new ImmutableList.Builder<>();
    if (isCodeCoverageEnabled) {
        coverageFlags.addAll(CLANG_COVERAGE_FLAGS);
        gcnoFiles.add(intermediateArtifacts.gcnoFile(sourceFile));
    }/*  w  ww  .j  av  a 2  s  .com*/
    CustomCommandLine.Builder commandLine = new CustomCommandLine.Builder();
    if (ObjcRuleClasses.CPP_SOURCES.matches(sourceFile.getExecPath())) {
        commandLine.add("-stdlib=libc++");
    }
    commandLine.add(IosSdkCommands.compileFlagsForClang(objcConfiguration))
            .add(IosSdkCommands.commonLinkAndCompileFlagsForClang(objcProvider, objcConfiguration))
            .add(objcConfiguration.getCoptsForCompilationMode())
            .addBeforeEachPath("-iquote", ObjcCommon.userHeaderSearchPaths(buildConfiguration))
            .addBeforeEachExecPath("-include", pchFile.asSet())
            .addBeforeEachPath("-I", objcProvider.get(INCLUDE)).add(otherFlags)
            .addFormatEach("-D%s", objcProvider.get(DEFINE)).add(coverageFlags.build())
            .add(objcConfiguration.getCopts()).add(optionsProvider.getCopts()).addExecPath("-c", sourceFile)
            .addExecPath("-o", objFile);

    register(spawnOnDarwinActionBuilder().setMnemonic("ObjcCompile").setExecutable(CLANG)
            .setCommandLine(commandLine.build()).addInput(sourceFile).addOutput(objFile)
            .addOutputs(gcnoFiles.build()).addTransitiveInputs(objcProvider.get(HEADER))
            .addTransitiveInputs(objcProvider.get(FRAMEWORK_FILE)).addInputs(pchFile.asSet()).build(context));
}

From source file:com.google.devtools.build.lib.rules.objc.LegacyCompilationSupport.java

private void registerLinkAction(ObjcProvider objcProvider, ExtraLinkArgs extraLinkArgs,
        Iterable<Artifact> extraLinkInputs, Optional<Artifact> dsymBundleZip,
        Iterable<Artifact> prunedJ2ObjcArchives, Optional<Artifact> linkmap) {
    Artifact binaryToLink = getBinaryToLink();

    ImmutableList<Artifact> objcLibraries = objcProvider.getObjcLibraries();
    ImmutableList<Artifact> ccLibraries = objcProvider.getCcLibraries();
    ImmutableList<Artifact> bazelBuiltLibraries = Iterables.isEmpty(prunedJ2ObjcArchives) ? objcLibraries
            : substituteJ2ObjcPrunedLibraries(objcProvider);
    CommandLine commandLine = linkCommandLine(extraLinkArgs, objcProvider, binaryToLink, dsymBundleZip,
            ccLibraries, bazelBuiltLibraries, linkmap);
    ruleContext.registerAction(ObjcRuleClasses
            .spawnAppleEnvActionBuilder(appleConfiguration, appleConfiguration.getSingleArchPlatform())
            .setMnemonic("ObjcLink").setShellCommand(ImmutableList.of("/bin/bash", "-c"))
            .setCommandLine(new SingleArgCommandLine(commandLine)).addOutput(binaryToLink)
            .addOutputs(dsymBundleZip.asSet()).addOutputs(linkmap.asSet()).addInputs(bazelBuiltLibraries)
            .addTransitiveInputs(objcProvider.get(IMPORTED_LIBRARY))
            .addTransitiveInputs(objcProvider.get(STATIC_FRAMEWORK_FILE))
            .addTransitiveInputs(objcProvider.get(DYNAMIC_FRAMEWORK_FILE))
            .addTransitiveInputs(objcProvider.get(LINK_INPUTS)).addInputs(ccLibraries)
            .addInputs(extraLinkInputs).addInputs(prunedJ2ObjcArchives)
            .addInput(intermediateArtifacts.linkerObjList()).addInput(xcrunwrapper(ruleContext).getExecutable())
            .build(ruleContext));//www. j  a v a 2 s.  c o m

    if (objcConfiguration.shouldStripBinary()) {
        final Iterable<String> stripArgs;
        if (TargetUtils.isTestRule(ruleContext.getRule())) {
            // For test targets, only debug symbols are stripped off, since /usr/bin/strip is not able
            // to strip off all symbols in XCTest bundle.
            stripArgs = ImmutableList.of("-S");
        } else if (isDynamicLib(commandLine)) {
            // For dynamic libs must pass "-x" to strip only local symbols.
            stripArgs = ImmutableList.of("-x");
        } else {
            stripArgs = ImmutableList.<String>of();
        }

        Artifact strippedBinary = intermediateArtifacts.strippedSingleArchitectureBinary();

        ruleContext.registerAction(ObjcRuleClasses
                .spawnAppleEnvActionBuilder(appleConfiguration, appleConfiguration.getSingleArchPlatform())
                .setMnemonic("ObjcBinarySymbolStrip").setExecutable(xcrunwrapper(ruleContext))
                .setCommandLine(symbolStripCommandLine(stripArgs, binaryToLink, strippedBinary))
                .addOutput(strippedBinary).addInput(binaryToLink).build(ruleContext));
    }
}

From source file:com.spotify.helios.testing.TemporaryJobs.java

void after(final Optional<TemporaryJobReports.ReportWriter> writer) {
    final Optional<TemporaryJobReports.Step> undeploy = writer
            .transform(new Function<TemporaryJobReports.ReportWriter, TemporaryJobReports.Step>() {
                @Override//from w  w w . j a va  2s.c o m
                public TemporaryJobReports.Step apply(final TemporaryJobReports.ReportWriter writer) {
                    return writer.step("undeploy");
                }
            });
    final List<JobId> jobIds = Lists.newArrayListWithCapacity(jobs.size());

    // Stop the test runner thread
    executor.shutdownNow();
    try {
        final boolean terminated = executor.awaitTermination(30, SECONDS);
        if (!terminated) {
            log.warn("Failed to stop test runner thread");
        }
    } catch (InterruptedException ignore) {
    }

    final List<AssertionError> errors = newArrayList();

    for (final TemporaryJob job : jobs) {
        jobIds.add(job.job().getId());
        job.undeploy(errors);
    }

    for (final TemporaryJobReports.Step step : undeploy.asSet()) {
        step.tag("jobs", jobIds);
    }

    for (final AssertionError error : errors) {
        log.error(error.getMessage());
    }

    // Don't delete the prefix file if any errors occurred during undeployment, so that we'll
    // try to undeploy them the next time TemporaryJobs is run.
    if (errors.isEmpty()) {
        jobPrefixFile.delete();
        for (final TemporaryJobReports.Step step : undeploy.asSet()) {
            step.markSuccess();
        }
    }

    for (final TemporaryJobReports.Step step : undeploy.asSet()) {
        step.finish();
    }
}

From source file:com.google.devtools.build.lib.rules.objc.LegacyCompilationSupport.java

private CustomCommandLine compileActionCommandLine(Artifact sourceFile, Artifact objFile,
        ObjcProvider objcProvider, Iterable<PathFragment> priorityHeaders, Optional<CppModuleMap> moduleMap,
        Optional<Artifact> pchFile, Optional<Artifact> dotdFile, Iterable<String> otherFlags,
        boolean collectCodeCoverage, boolean isCPlusPlusSource) {
    CustomCommandLine.Builder commandLine = new CustomCommandLine.Builder().add(CLANG);

    if (isCPlusPlusSource) {
        commandLine.add("-stdlib=libc++");
        commandLine.add("-std=gnu++11");
    }/* ww  w .jav a 2 s .  c o m*/

    // The linker needs full debug symbol information to perform binary dead-code stripping.
    if (objcConfiguration.shouldStripBinary()) {
        commandLine.add("-g");
    }

    List<String> coverageFlags = ImmutableList.of();
    if (collectCodeCoverage) {
        if (buildConfiguration.isLLVMCoverageMapFormatEnabled()) {
            coverageFlags = CLANG_LLVM_COVERAGE_FLAGS;
        } else {
            coverageFlags = CLANG_GCOV_COVERAGE_FLAGS;
        }
    }

    commandLine.add(compileFlagsForClang(appleConfiguration))
            .add(commonLinkAndCompileFlagsForClang(objcProvider, objcConfiguration, appleConfiguration))
            .add(objcConfiguration.getCoptsForCompilationMode())
            .addBeforeEachPath("-iquote", ObjcCommon.userHeaderSearchPaths(buildConfiguration))
            .addBeforeEachExecPath("-include", pchFile.asSet()).addBeforeEachPath("-I", priorityHeaders)
            .addBeforeEachPath("-I", objcProvider.get(INCLUDE))
            .addBeforeEachPath("-isystem", objcProvider.get(INCLUDE_SYSTEM)).add(otherFlags)
            .addFormatEach("-D%s", objcProvider.get(DEFINE)).add(coverageFlags).add(getCompileRuleCopts());

    // Add input source file arguments
    commandLine.add("-c");
    if (!sourceFile.getExecPath().isAbsolute() && objcConfiguration.getUseAbsolutePathsForActions()) {
        String workspaceRoot = objcConfiguration.getXcodeWorkspaceRoot();

        // If the source file is a tree artifact, it means the file is basically a directory that may
        // contain multiple concrete source files at execution time. When constructing the command
        // line, we insert the source tree artifact as a placeholder, which will be replaced with
        // one of its contained source files of type {@link Artifact.TreeFileArtifact} at execution
        // time.
        //
        // We also do something similar for the object file arguments below.
        if (sourceFile.isTreeArtifact()) {
            commandLine.addPlaceholderTreeArtifactFormattedExecPath(workspaceRoot + "/%s", sourceFile);
        } else {
            commandLine.addPaths(workspaceRoot + "/%s", sourceFile.getExecPath());
        }
    } else {
        if (sourceFile.isTreeArtifact()) {
            commandLine.addPlaceholderTreeArtifactExecPath(sourceFile);
        } else {
            commandLine.addPath(sourceFile.getExecPath());
        }
    }

    // Add output object file arguments.
    commandLine.add("-o");
    if (objFile.isTreeArtifact()) {
        commandLine.addPlaceholderTreeArtifactExecPath(objFile);
    } else {
        commandLine.addPath(objFile.getExecPath());
    }

    // Add Dotd file arguments.
    if (dotdFile.isPresent()) {
        commandLine.add("-MD").addExecPath("-MF", dotdFile.get());
    }

    // Add module map arguments.
    if (moduleMap.isPresent()) {
        // If modules are enabled for the rule, -fmodules is added to the copts already. (This implies
        // module map usage). Otherwise, we need to pass -fmodule-maps.
        if (!attributes.enableModules()) {
            commandLine.add("-fmodule-maps");
        }
        // -fmodule-map-file only loads the module in Xcode 7, so we add the module maps's directory
        // to the include path instead.
        // TODO(bazel-team): Use -fmodule-map-file when Xcode 6 support is dropped.
        commandLine.add("-iquote")
                .add(moduleMap.get().getArtifact().getExecPath().getParentDirectory().toString())
                .add("-fmodule-name=" + moduleMap.get().getName());
    }

    return commandLine.build();
}

From source file:com.google.devtools.build.lib.rules.objc.LegacyCompilationSupport.java

private void registerCompileAction(Artifact sourceFile, Artifact objFile, ObjcProvider objcProvider,
        Iterable<PathFragment> priorityHeaders, Optional<CppModuleMap> moduleMap,
        CompilationArtifacts compilationArtifacts, Iterable<String> otherFlags) {
    boolean isCPlusPlusSource = ObjcRuleClasses.CPP_SOURCES.matches(sourceFile.getExecPath());
    boolean runCodeCoverage = buildConfiguration.isCodeCoverageEnabled()
            && ObjcRuleClasses.isInstrumentable(sourceFile);
    DotdFile dotdFile = intermediateArtifacts.dotdFile(sourceFile);

    CustomCommandLine commandLine = compileActionCommandLine(sourceFile, objFile, objcProvider, priorityHeaders,
            moduleMap, compilationArtifacts.getPchFile(), Optional.of(dotdFile.artifact()), otherFlags,
            runCodeCoverage, isCPlusPlusSource);

    Optional<Artifact> gcnoFile = Optional.absent();
    if (runCodeCoverage && !buildConfiguration.isLLVMCoverageMapFormatEnabled()) {
        gcnoFile = Optional.of(intermediateArtifacts.gcnoFile(sourceFile));
    }//from www. j ava  2s . c o  m

    NestedSet<Artifact> moduleMapInputs = NestedSetBuilder.emptySet(Order.STABLE_ORDER);
    if (objcConfiguration.moduleMapsEnabled()) {
        moduleMapInputs = objcProvider.get(MODULE_MAP);
    }

    // TODO(bazel-team): Remove private headers from inputs once they're added to the provider.
    ruleContext.registerAction(ObjcCompileAction.Builder
            .createObjcCompileActionBuilderWithAppleEnv(appleConfiguration,
                    appleConfiguration.getSingleArchPlatform())
            .setDotdPruningPlan(objcConfiguration.getDotdPruningPlan()).setSourceFile(sourceFile)
            .addTransitiveHeaders(objcProvider.get(HEADER)).addHeaders(compilationArtifacts.getPrivateHdrs())
            .addTransitiveMandatoryInputs(moduleMapInputs)
            .addTransitiveMandatoryInputs(objcProvider.get(STATIC_FRAMEWORK_FILE))
            .addTransitiveMandatoryInputs(objcProvider.get(DYNAMIC_FRAMEWORK_FILE)).setDotdFile(dotdFile)
            .addInputs(compilationArtifacts.getPchFile().asSet()).setMnemonic("ObjcCompile")
            .setExecutable(xcrunwrapper(ruleContext)).setCommandLine(commandLine).addOutput(objFile)
            .addOutputs(gcnoFile.asSet()).addOutput(dotdFile.artifact()).build(ruleContext));
}

From source file:com.google.devtools.build.lib.rules.android.JackCompilationHelper.java

/**
 * Builds one or more dex files from the jack libraries in the transitive closure of this rule.
 *
 * <p>This method should only be called once, as it will generate the same artifact each time.
 * It will fail if called a second time.
 *
 * @param multidexMode The multidex flag to send to Jack.
 * @param manualMainDexList Iff multidexMode is MANUAL_MAIN_DEX, an artifact representing the file
 *     with the list of class filenames which should go in the main dex. Else, absent.
 * @param proguardSpecs A collection of Proguard configuration files to be used to process the
 *     Jack libraries before building a dex out of them.
 * @returns A zip file containing the dex file(s) and Java resource(s) generated by Jack.
 *//*from   w ww .  j  a v a2  s. c  om*/
// TODO(bazel-team): this method (compile to jack library, compile all transitive jacks to dex)
// may be too much overhead for manydex (dex per library) mode.
// Instead, consider running jack --output-dex right on the source files, bypassing the
// intermediate jack library format.
public Artifact compileAsDex(MultidexMode multidexMode, Optional<Artifact> manualMainDexList,
        Collection<Artifact> proguardSpecs) {
    Preconditions.checkNotNull(multidexMode);
    Preconditions.checkNotNull(manualMainDexList);
    Preconditions.checkNotNull(proguardSpecs);
    Preconditions.checkArgument(multidexMode.isSupportedByJack(), "Multidex mode '%s' is not supported by Jack",
            multidexMode);
    Preconditions.checkArgument(manualMainDexList.isPresent() == (multidexMode == MultidexMode.MANUAL_MAIN_DEX),
            "The main dex list must be supplied if and only if the multidex mode is 'manual_main_dex'");
    Preconditions.checkState(!wasDexBuilt, "A dex file has already been built.");

    Artifact outputZip = AndroidBinary.getDxArtifact(ruleContext, ZIP_OUTPUT_FILENAME);

    NestedSet<Artifact> transitiveJackLibraries = compileAsLibrary().getTransitiveJackLibrariesToLink();
    CustomCommandLine.Builder builder = CustomCommandLine.builder()
            // Have jack double-check its behavior and crash rather than producing invalid output
            .add(SANITY_CHECKS).add(useSanityChecks ? SANITY_CHECKS_ON : SANITY_CHECKS_OFF)
            // Have jack take the first match in the event of a class or resource name collision.
            .add(JACK_PROPERTY).add(PROPERTY_KEEP_FIRST_RESOURCE).add(JACK_PROPERTY)
            .add(PROPERTY_KEEP_FIRST_TYPE);

    for (Artifact jackLibrary : transitiveJackLibraries) {
        builder.addExecPath(IMPORT_JACK_LIBRARY, jackLibrary);
    }
    for (Artifact proguardSpec : proguardSpecs) {
        builder.addExecPath(CONFIG_PROGUARD, proguardSpec);
    }
    builder.add(MULTI_DEX).add(multidexMode.getJackFlagValue());
    if (manualMainDexList.isPresent()) {
        builder.addExecPath(MAIN_DEX_LIST, manualMainDexList.get());
    }
    builder.addExecPath(OUTPUT_DEX_ZIP, outputZip);
    ruleContext.registerAction(new SpawnAction.Builder().setExecutable(jackBinary)
            .addTransitiveInputs(transitiveJackLibraries).addInputs(proguardSpecs)
            .addInputs(manualMainDexList.asSet()).addOutput(outputZip).setCommandLine(builder.build())
            .setProgressMessage("Dexing " + ruleContext.getLabel() + " with Jack").setMnemonic("AndroidJackDex")
            .build(ruleContext));
    return outputZip;
}

From source file:dagger2.internal.codegen.ComponentGenerator.java

private void writeField(ClassWriter componentWriter, Set<JavaWriter> proxyWriters,
        Map<BindingKey, MemberSelect> memberSelectSnippetsBuilder,
        Map<ContributionBinding, Snippet> parentMultibindingContributionSnippetsBuilder,
        Map<ContributionBinding, Snippet> multibindingContributionSnippetsBuilder,
        ImmutableSet.Builder<BindingKey> enumBindingKeysBuilder, Map<String, ProxyClassAndField> packageProxies,
        ResolvedBindings resolvedBindings) {
    BindingKey bindingKey = resolvedBindings.bindingKey();

    if (bindingKey.kind().equals(BindingKey.Kind.CONTRIBUTION)
            && resolvedBindings.ownedContributionBindings().isEmpty()
            && !ContributionBinding.bindingTypeFor(resolvedBindings.contributionBindings()).isMultibinding()) {
        return;//w w  w  . jav a 2 s . c o m
    }

    if (resolvedBindings.bindings().size() == 1) {
        if (bindingKey.kind().equals(BindingKey.Kind.CONTRIBUTION)) {
            ContributionBinding contributionBinding = Iterables
                    .getOnlyElement(resolvedBindings.contributionBindings());
            if (!contributionBinding.bindingType().isMultibinding()
                    && (contributionBinding instanceof ProvisionBinding)) {
                ProvisionBinding provisionBinding = (ProvisionBinding) contributionBinding;
                if (provisionBinding.factoryCreationStrategy().equals(ENUM_INSTANCE)
                        && !provisionBinding.scope().isPresent()) {
                    enumBindingKeysBuilder.add(bindingKey);
                    // skip keys whose factories are enum instances and aren't scoped
                    memberSelectSnippetsBuilder.put(bindingKey, MemberSelect.staticSelect(
                            factoryNameForProvisionBinding(provisionBinding), Snippet.format("create()")));
                    return;
                }
            }
        } else if (bindingKey.kind().equals(BindingKey.Kind.MEMBERS_INJECTION)) {
            MembersInjectionBinding membersInjectionBinding = Iterables
                    .getOnlyElement(resolvedBindings.membersInjectionBindings());
            if (membersInjectionBinding.injectionStrategy().equals(NO_OP)) {
                // TODO(gak): refactor to use enumBindingKeys throughout the generator
                enumBindingKeysBuilder.add(bindingKey);
                // TODO(gak): suppress the warnings in a reasonable place
                memberSelectSnippetsBuilder.put(bindingKey,
                        MemberSelect.staticMethodInvocationWithCast(ClassName.fromClass(MembersInjectors.class),
                                Snippet.format("noOp()"), ClassName.fromClass(MembersInjector.class)));
                return;
            }
        }
    }

    String bindingPackage = bindingPackageFor(resolvedBindings.bindings())
            .or(componentWriter.name().packageName());

    final Optional<String> proxySelector;
    final TypeWriter classWithFields;
    final Set<Modifier> fieldModifiers;

    if (bindingPackage.equals(componentWriter.name().packageName())) {
        // no proxy
        proxySelector = Optional.absent();
        // component gets the fields
        classWithFields = componentWriter;
        // private fields
        fieldModifiers = EnumSet.of(PRIVATE);
    } else {
        // get or create the proxy
        ProxyClassAndField proxyClassAndField = packageProxies.get(bindingPackage);
        if (proxyClassAndField == null) {
            JavaWriter proxyJavaWriter = JavaWriter.inPackage(bindingPackage);
            proxyWriters.add(proxyJavaWriter);
            ClassWriter proxyWriter = proxyJavaWriter
                    .addClass(componentWriter.name().simpleName() + "_PackageProxy");
            proxyWriter.annotate(Generated.class).setValue(ComponentProcessor.class.getCanonicalName());
            proxyWriter.addModifiers(PUBLIC, FINAL);
            // create the field for the proxy in the component
            FieldWriter proxyFieldWriter = componentWriter.addField(proxyWriter.name(),
                    bindingPackage.replace('.', '_') + "_Proxy");
            proxyFieldWriter.addModifiers(PRIVATE, FINAL);
            proxyFieldWriter.setInitializer("new %s()", proxyWriter.name());
            proxyClassAndField = ProxyClassAndField.create(proxyWriter, proxyFieldWriter);
            packageProxies.put(bindingPackage, proxyClassAndField);
        }
        // add the field for the member select
        proxySelector = Optional.of(proxyClassAndField.proxyFieldWriter().name());
        // proxy gets the fields
        classWithFields = proxyClassAndField.proxyWriter();
        // public fields in the proxy
        fieldModifiers = EnumSet.of(PUBLIC);
    }

    if (bindingKey.kind().equals(BindingKey.Kind.CONTRIBUTION)) {
        ImmutableSet<? extends ContributionBinding> contributionBindings = resolvedBindings
                .contributionBindings();
        if (ContributionBinding.bindingTypeFor(contributionBindings).isMultibinding()) {
            // note that here we rely on the order of the resolved bindings being from parent to child
            // otherwise, the numbering wouldn't work
            int contributionNumber = 0;
            for (ContributionBinding contributionBinding : contributionBindings) {
                if (!contributionBinding.isSyntheticBinding()) {
                    contributionNumber++;
                    if (!parentMultibindingContributionSnippetsBuilder.containsKey(contributionBinding)) {
                        FrameworkField contributionBindingField = frameworkFieldForSyntheticContributionBinding(
                                bindingKey, contributionNumber, contributionBinding);
                        FieldWriter contributionField = classWithFields.addField(
                                contributionBindingField.frameworkType(), contributionBindingField.name());
                        contributionField.addModifiers(fieldModifiers);

                        ImmutableList<String> contributionSelectTokens = new ImmutableList.Builder<String>()
                                .addAll(proxySelector.asSet()).add(contributionField.name()).build();
                        multibindingContributionSnippetsBuilder.put(contributionBinding,
                                Snippet.memberSelectSnippet(contributionSelectTokens));
                    }
                }
            }
        }
    }

    FrameworkField bindingField = frameworkFieldForResolvedBindings(resolvedBindings);
    FieldWriter frameworkField = classWithFields.addField(bindingField.frameworkType(), bindingField.name());
    frameworkField.addModifiers(fieldModifiers);

    ImmutableList<String> memberSelectTokens = new ImmutableList.Builder<String>().addAll(proxySelector.asSet())
            .add(frameworkField.name()).build();
    memberSelectSnippetsBuilder.put(bindingKey, MemberSelect.instanceSelect(componentWriter.name(),
            Snippet.memberSelectSnippet(memberSelectTokens)));
}