com.google.devtools.build.lib.collect.nestedset.NestedSet.toList() - java examples

Here are the examples of the java api com.google.devtools.build.lib.collect.nestedset.NestedSet.toList() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

62 Examples 7

19 View Complete Implementation : TargetCompleteEvent.java
Copyright Apache License 2.0
Author : bazelbuild
public Iterable<Artifact> getLegacyFilteredImportantArtifacts() {
    // TODO(ulfjack): This duplicates code in ArtifactsToBuild.
    NestedSetBuilder<Artifact> builder = new NestedSetBuilder<>(outputs.getOrder());
    for (ArtifactsInOutputGroup artifactsInOutputGroup : outputs.toList()) {
        if (artifactsInOutputGroup.areImportant()) {
            builder.addTransitive(artifactsInOutputGroup.getArtifacts());
        }
    }
    return Iterables.filter(builder.build().toList(), (artifact) -> !artifact.isSourceArtifact() && !artifact.isMiddlemanArtifact());
}

19 View Complete Implementation : SkylarkJavaLiteProtoLibraryTest.java
Copyright Apache License 2.0
Author : bazelbuild
@Test
public void testExperimentalProtoExtraActions() throws Exception {
    scratch.file("x/BUILD", "load('//tools/build_rules/java_lite_proto_library:java_lite_proto_library.bzl',", "      'java_lite_proto_library')", "java_lite_proto_library(name = 'lite_pb2', deps = [':foo'])", "proto_library(name = 'foo', srcs = ['foo.proto'])");
    scratch.file("xa/BUILD", "extra_action(", "    name = 'xa',", "    cmd = 'echo $(EXTRA_ACTION_FILE)')", "action_listener(", "    name = 'al',", "    mnemonics = ['Javac'],", "    extra_actions = [':xa'])");
    useConfiguration("--experimental_action_listener=//xa:al");
    ConfiguredTarget ct = getConfiguredTarget("//x:lite_pb2");
    NestedSet<DerivedArtifact> artifacts = ct.getProvider(ExtraActionArtifactsProvider.clreplaced).getTransitiveExtraActionArtifacts();
    Iterable<String> extraActionOwnerLabels = transform(artifacts.toList(), (artifact) -> artifact == null ? null : artifact.getOwnerLabel().toString());
    replacedertThat(extraActionOwnerLabels).contains("//x:foo");
}

19 View Complete Implementation : NativeLibs.java
Copyright Apache License 2.0
Author : bazelbuild
public ImmutableSet<Artifact> getAllNativeLibs() {
    ImmutableSet.Builder<Artifact> result = ImmutableSet.builder();
    for (NestedSet<Artifact> libs : nativeLibs.values()) {
        result.addAll(libs.toList());
    }
    return result.build();
}

19 View Complete Implementation : CcCompilationContext.java
Copyright Apache License 2.0
Author : bazelbuild
public ImmutableList<HeaderInfo> getTransitiveHeaderInfos() {
    return transitiveHeaderInfos.toList();
}

19 View Complete Implementation : TargetCompleteEvent.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public ReportedArtifacts reportedArtifacts() {
    ImmutableSet.Builder<NestedSet<Artifact>> builder = ImmutableSet.builder();
    for (ArtifactsInOutputGroup artifactsInGroup : outputs.toList()) {
        if (artifactsInGroup.areImportant()) {
            builder.add(artifactsInGroup.getArtifacts());
        }
    }
    if (baselineCoverageArtifacts != null) {
        builder.add(baselineCoverageArtifacts);
    }
    return new ReportedArtifacts(builder.build(), completionContext);
}

19 View Complete Implementation : Depset.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public void repr(Printer printer) {
    printer.append("depset(");
    printer.printList(set.toList(), "[", ", ", "]", null);
    Order order = getOrder();
    if (order != Order.STABLE_ORDER) {
        printer.append(", order = ");
        printer.repr(order.getSkylarkName());
    }
    printer.append(")");
}

19 View Complete Implementation : Runfiles.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Returns the unified map of path fragments to artifacts, taking into account artifacts,
 * symlinks, and pruning manifest candidates. The returned set is guaranteed to be a (not
 * necessarily strict) superset of the actual runfiles tree created at execution time.
 */
public NestedSet<Artifact> getAllArtifacts() {
    if (isEmpty()) {
        return NestedSetBuilder.emptySet(Order.STABLE_ORDER);
    }
    NestedSetBuilder<Artifact> allArtifacts = NestedSetBuilder.stableOrder();
    allArtifacts.addTransitive(unconditionalArtifacts).addAll(Iterables.transform(symlinks.toList(), TO_ARTIFACT)).addAll(Iterables.transform(rootSymlinks.toList(), TO_ARTIFACT));
    for (PruningManifest manifest : getPruningManifests().toList()) {
        allArtifacts.addTransitive(manifest.getCandidateRunfiles());
    }
    return allArtifacts.build();
}

19 View Complete Implementation : Depset.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Returns the contents of the set as a {@link Collection}.
 */
public Collection<?> toCollection() {
    return set.toList();
}

18 View Complete Implementation : CcLinkingContext.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public void debugPrint(Printer printer) {
    printer.append("<CcLinkingContext([");
    for (LinkerInput linkerInput : linkerInputs.toList()) {
        linkerInput.debugPrint(printer);
        printer.append(", ");
    }
    printer.append("])>");
}

18 View Complete Implementation : AspectCompleteEvent.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public ReportedArtifacts reportedArtifacts() {
    ImmutableSet.Builder<NestedSet<Artifact>> builder = ImmutableSet.builder();
    if (artifactOutputGroups != null) {
        for (ArtifactsInOutputGroup artifactsInGroup : artifactOutputGroups.toList()) {
            builder.add(artifactsInGroup.getArtifacts());
        }
    }
    return new ReportedArtifacts(builder.build(), completionContext);
}

18 View Complete Implementation : CcLinkingContext.java
Copyright Apache License 2.0
Author : bazelbuild
public NestedSet<Linkstamp> getLinkstamps() {
    NestedSetBuilder<Linkstamp> linkstamps = NestedSetBuilder.linkOrder();
    for (LinkerInput linkerInput : linkerInputs.toList()) {
        linkstamps.addAll(linkerInput.getLinkstamps());
    }
    return linkstamps.build();
}

18 View Complete Implementation : CcLinkingContext.java
Copyright Apache License 2.0
Author : bazelbuild
public NestedSet<LinkOptions> getUserLinkFlags() {
    NestedSetBuilder<LinkOptions> userLinkFlags = NestedSetBuilder.linkOrder();
    for (LinkerInput linkerInput : linkerInputs.toList()) {
        userLinkFlags.addAll(linkerInput.getUserLinkFlags());
    }
    return userLinkFlags.build();
}

18 View Complete Implementation : JavaGenJarsProvider.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public ImmutableList<String> getProcessorClreplacedNames() {
    return processorClreplacedNames.toList();
}

18 View Complete Implementation : CcLinkingContext.java
Copyright Apache License 2.0
Author : bazelbuild
public NestedSet<Artifact> getNonCodeInputs() {
    NestedSetBuilder<Artifact> nonCodeInputs = NestedSetBuilder.linkOrder();
    for (LinkerInput linkerInput : linkerInputs.toList()) {
        nonCodeInputs.addAll(linkerInput.getNonCodeInputs());
    }
    return nonCodeInputs.build();
}

18 View Complete Implementation : ObjcProvider.java
Copyright Apache License 2.0
Author : bazelbuild
@SuppressWarnings("unchecked")
private <T> void addTransitiveAndFilter(ObjcProvider.Builder objcProviderBuilder, Key<T> key, Predicate<T> filterPredicate) {
    NestedSet<T> propagableItems = (NestedSet<T>) items.get(key);
    NestedSet<T> nonPropagableItems = (NestedSet<T>) nonPropagatedItems.get(key);
    NestedSet<T> stricreplacedems = (NestedSet<T>) strictDependencyItems.get(key);
    if (propagableItems != null) {
        objcProviderBuilder.addAll(key, Iterables.filter(propagableItems.toList(), filterPredicate));
    }
    if (nonPropagableItems != null) {
        objcProviderBuilder.addAllNonPropagable(key, Iterables.filter(nonPropagableItems.toList(), filterPredicate));
    }
    if (stricreplacedems != null) {
        objcProviderBuilder.addAllForDirectDependents(key, Iterables.filter(stricreplacedems.toList(), filterPredicate));
    }
}

18 View Complete Implementation : TargetCompleteEvent.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public BuildEventStreamProtos.BuildEvent replacedtreamProto(BuildEventContext converters) {
    BuildEventStreamProtos.TargetComplete.Builder builder = BuildEventStreamProtos.TargetComplete.newBuilder();
    builder.setSuccess(!failed());
    builder.addAllTag(getTags());
    builder.addAllOutputGroup(getOutputFilesByGroup(converters.artifactGroupNamer()));
    if (isTest) {
        builder.setTestTimeoutSeconds(testTimeoutSeconds);
    }
    // TODO(aehlig): remove direct reporting of artifacts as soon as clients no longer
    // need it.
    if (converters.getOptions().legacyImportantOutputs) {
        addImportantOutputs(completionContext, builder, converters, getLegacyFilteredImportantArtifacts());
        if (baselineCoverageArtifacts != null) {
            addImportantOutputs(completionContext, builder, (artifact -> BASELINE_COVERAGE), converters, baselineCoverageArtifacts.toList());
        }
    }
    BuildEventStreamProtos.TargetComplete complete = builder.build();
    return GenericBuildEvent.protoChaining(this).setCompleted(complete).build();
}

18 View Complete Implementation : ObjcProvider.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Returns the list of .a files required for linking that arise from objc libraries.
 */
ImmutableList<Artifact> getObjcLibraries() {
    // JRE libraries must be ordered after all regular objc libraries.
    NestedSet<Artifact> jreLibs = get(JRE_LIBRARY);
    return ImmutableList.<Artifact>builder().addAll(Iterables.filter(get(LIBRARY).toList(), Predicates.not(Predicates.in(jreLibs.toSet())))).addAll(jreLibs.toList()).build();
}

18 View Complete Implementation : JavaCompilationInfoProvider.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public ImmutableList<Artifact> getBootClreplacedpath() {
    return bootClreplacedpath.toList();
}

18 View Complete Implementation : Runfiles.java
Copyright Apache License 2.0
Author : bazelbuild
public NestedSet<String> getEmptyFilenames() {
    Set<PathFragment> manifestKeys = Streams.concat(symlinks.toList().stream().map(SymlinkEntry::getPath), getArtifacts().toList().stream().map(Artifact::getRootRelativePath)).collect(ImmutableSet.toImmutableSet());
    Iterable<PathFragment> emptyKeys = emptyFilesSupplier.getExtraPaths(manifestKeys);
    return NestedSetBuilder.<String>stableOrder().addAll(Streams.stream(emptyKeys).map(PathFragment::toString).collect(ImmutableList.toImmutableList())).build();
}

18 View Complete Implementation : TargetCompleteEvent.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public Collection<LocalFile> referencedLocalFiles() {
    ImmutableList.Builder<LocalFile> builder = ImmutableList.builder();
    for (ArtifactsInOutputGroup group : outputs.toList()) {
        if (group.areImportant()) {
            completionContext.visitArtifacts(filterFilesets(group.getArtifacts().toList()), new ArtifactReceiver() {

                @Override
                public void accept(Artifact artifact) {
                    builder.add(new LocalFile(completionContext.pathResolver().toPath(artifact), LocalFileType.OUTPUT));
                }

                @Override
                public void acceptFilesetMapping(Artifact fileset, PathFragment name, Path targetFile) {
                    throw new IllegalStateException(fileset + " should have been filtered out");
                }
            });
        }
    }
    if (baselineCoverageArtifacts != null) {
        for (Artifact artifact : baselineCoverageArtifacts.toList()) {
            builder.add(new LocalFile(completionContext.pathResolver().toPath(artifact), LocalFileType.COVERAGE_OUTPUT));
        }
    }
    return builder.build();
}

18 View Complete Implementation : TopLevelArtifactHelperTest.java
Copyright Apache License 2.0
Author : bazelbuild
@Test
public void emptyGroupsShouldBeIgnored() {
    setup(asList(Pair.of("foo", 1), Pair.of("bar", 0)));
    ArtifactsToBuild allArtifacts = getAllArtifactsToBuild(groupProvider, null, ctx);
    replacedertThat(allArtifacts.getAllArtifacts().toList()).hreplacedize(1);
    replacedertThat(allArtifacts.getImportantArtifacts().toList()).hreplacedize(1);
    NestedSet<ArtifactsInOutputGroup> artifactsByGroup = allArtifacts.getAllArtifactsByOutputGroup();
    // The bar list should not appear here, as it contains no artifacts.
    replacedertThat(artifactsByGroup.toList()).hreplacedize(1);
    replacedertThat(artifactsByGroup.toList().get(0).getOutputGroup()).isEqualTo("foo");
}

18 View Complete Implementation : TopLevelArtifactHelperTest.java
Copyright Apache License 2.0
Author : bazelbuild
@Test
public void artifactsShouldBeSeparateByGroup() {
    setup(asList(Pair.of("foo", 3), Pair.of("bar", 2)));
    ArtifactsToBuild allArtifacts = getAllArtifactsToBuild(groupProvider, null, ctx);
    replacedertThat(allArtifacts.getAllArtifacts().toList()).hreplacedize(5);
    replacedertThat(allArtifacts.getImportantArtifacts().toList()).hreplacedize(5);
    NestedSet<ArtifactsInOutputGroup> artifactsByGroup = allArtifacts.getAllArtifactsByOutputGroup();
    // Two groups
    replacedertThat(artifactsByGroup.toList()).hreplacedize(2);
    for (ArtifactsInOutputGroup artifacts : artifactsByGroup.toList()) {
        String outputGroup = artifacts.getOutputGroup();
        if ("foo".equals(outputGroup)) {
            replacedertThat(artifacts.getArtifacts().toList()).hreplacedize(3);
        } else if ("bar".equals(outputGroup)) {
            replacedertThat(artifacts.getArtifacts().toList()).hreplacedize(2);
        }
    }
}

18 View Complete Implementation : AarImportTest.java
Copyright Apache License 2.0
Author : bazelbuild
@Test
public void testRClreplacedFromAarImportInCompileClreplacedpath() throws Exception {
    NestedSet<Artifact> compilationClreplacedpath = JavaInfo.getProvider(JavaCompilationInfoProvider.clreplaced, getConfiguredTarget("//a:library")).getCompilationClreplacedpath().getSet(Artifact.clreplaced);
    replacedertThat(compilationClreplacedpath.toList().stream().filter(artifact -> artifact.getFilename().equalsIgnoreCase("foo_resources.jar")).count()).isEqualTo(1);
}

18 View Complete Implementation : TargetCompleteEvent.java
Copyright Apache License 2.0
Author : bazelbuild
private Iterable<OutputGroup> getOutputFilesByGroup(ArtifactGroupNamer namer) {
    ImmutableList.Builder<OutputGroup> groups = ImmutableList.builder();
    for (ArtifactsInOutputGroup artifactsInOutputGroup : outputs.toList()) {
        if (!artifactsInOutputGroup.areImportant()) {
            continue;
        }
        OutputGroup.Builder groupBuilder = OutputGroup.newBuilder();
        groupBuilder.setName(artifactsInOutputGroup.getOutputGroup());
        groupBuilder.addFileSets(namer.apply((new NestedSetView<Artifact>(artifactsInOutputGroup.getArtifacts())).identifier()));
        groups.add(groupBuilder.build());
    }
    if (baselineCoverageArtifacts != null) {
        groups.add(OutputGroup.newBuilder().setName(BASELINE_COVERAGE).addFileSets(namer.apply((new NestedSetView<Artifact>(baselineCoverageArtifacts).identifier()))).build());
    }
    return groups.build();
}

18 View Complete Implementation : BaselineCoverageAction.java
Copyright Apache License 2.0
Author : bazelbuild
private Iterable<String> getInstrumentedFilePathStrings() {
    List<String> result = new ArrayList<>();
    for (Artifact instrumentedFile : instrumentedFiles.toList()) {
        result.add(instrumentedFile.getExecPathString());
    }
    return result;
}

18 View Complete Implementation : BuildResultPrinter.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Prints a flat list of all artifacts built by the preplaceded top-level targets.
 *
 * <p>This corresponds to the --experimental_show_artifacts flag.
 */
public void showArtifacts(BuildRequest request, Collection<ConfiguredTarget> configuredTargets, Collection<AspectValue> aspects) {
    TopLevelArtifactContext context = request.getTopLevelArtifactContext();
    Collection<ConfiguredTarget> targetsToPrint = filterTargetsToPrint(configuredTargets);
    Collection<AspectValue> aspectsToPrint = filterAspectsToPrint(aspects);
    NestedSetBuilder<Artifact> artifactsBuilder = NestedSetBuilder.stableOrder();
    for (ConfiguredTarget target : targetsToPrint) {
        artifactsBuilder.addTransitive(TopLevelArtifactHelper.getAllArtifactsToBuild(target, context).getImportantArtifacts());
    }
    for (AspectValue aspect : aspectsToPrint) {
        artifactsBuilder.addTransitive(TopLevelArtifactHelper.getAllArtifactsToBuild(aspect, context).getImportantArtifacts());
    }
    OutErr outErr = request.getOutErr();
    outErr.printErrLn("Build artifacts:");
    NestedSet<Artifact> artifacts = artifactsBuilder.build();
    for (Artifact artifact : artifacts.toList()) {
        if (!artifact.isSourceArtifact()) {
            outErr.printErrLn(">>>" + artifact.getPath());
        }
    }
}

17 View Complete Implementation : AnalysisFailureEvent.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Returns the label of a single root cause. Use {@link #getRootCauses} to report all root causes.
 */
@Nullable
public Label getLegacyFailureReason() {
    if (rootCauses.isEmpty()) {
        return null;
    }
    return rootCauses.toList().get(0).getLabel();
}

17 View Complete Implementation : Runfiles.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Returns the unified map of path fragments to artifacts, taking both artifacts and symlinks into
 * account.
 */
public Map<PathFragment, Artifact> asMapWithoutRootSymlinks() {
    Map<PathFragment, Artifact> result = entriesToMap(symlinks, null);
    // If multiple artifacts have the same root-relative path, the last one in the list will win.
    // That is because the runfiles tree cannot contain the same artifact for different
    // configurations, because it only uses root-relative paths.
    for (Artifact artifact : unconditionalArtifacts.toList()) {
        result.put(artifact.getRootRelativePath(), artifact);
    }
    return result;
}

17 View Complete Implementation : CcLinkingContext.java
Copyright Apache License 2.0
Author : bazelbuild
public NestedSet<LibraryToLink> getLibraries() {
    NestedSetBuilder<LibraryToLink> libraries = NestedSetBuilder.linkOrder();
    for (LinkerInput linkerInput : linkerInputs.toList()) {
        libraries.addAll(linkerInput.libraries);
    }
    return libraries.build();
}

17 View Complete Implementation : ObjcProvider.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Returns the set of generated header files.
 */
NestedSet<Artifact> getGeneratedHeaders() {
    if (generatedHeaders == null) {
        synchronized (this) {
            if (generatedHeaders == null) {
                NestedSet<Artifact> headers = header();
                NestedSetBuilder<Artifact> generatedHeadersBuilder = new NestedSetBuilder<>(headers.getOrder());
                for (Artifact header : headers.toList()) {
                    if (!header.isSourceArtifact()) {
                        generatedHeadersBuilder.add(header);
                    }
                }
                generatedHeaders = generatedHeadersBuilder.build();
            }
        }
    }
    return generatedHeaders;
}

17 View Complete Implementation : AspectTest.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Test that actions registered in an Aspect are reported as extra-actions on the attached rule.
 * AspectThatRegistersAction registers a NullAction, whose mnemonic is "Null". We have an
 * action_listener that targets that mnemonic, which makes sure the Aspect machinery will expose
 * an ExtraActionArtifactsProvider.
 * The rule //a:a doesn't have an aspect, so the only action we get is the one on //a:b
 * (which does have an aspect).
 */
@Test
public void extraActionsAreEmitted() throws Exception {
    setRulesAndAspectsAvailableInTests(ImmutableList.of(TestAspects.SIMPLE_ASPECT, ExtraActionsAreEmitted.AspectThatRegistersAction.INSTANCE), ImmutableList.of(TestAspects.BASE_RULE, ExtraActionsAreEmitted.TEST_RULE));
    useConfiguration("--experimental_action_listener=//extra_actions:listener");
    scratch.file("extra_actions/BUILD", "extra_action(name='xa', cmd='echo dont-care')", "action_listener(name='listener', mnemonics=['Null'], extra_actions=[':xa'])");
    pkg("a", "testrule(name='a', foo=[':b'])", "testrule(name='b')");
    update();
    ConfiguredTarget a = getConfiguredTarget("//a:a");
    NestedSet<Artifact.DerivedArtifact> extraActionArtifacts = a.getProvider(ExtraActionArtifactsProvider.clreplaced).getTransitiveExtraActionArtifacts();
    for (Artifact artifact : extraActionArtifacts.toList()) {
        replacedertThat(artifact.getOwnerLabel()).isEqualTo(Label.create("@//a", "b"));
    }
}

16 View Complete Implementation : LazyWriteNestedSetOfPairAction.java
Copyright Apache License 2.0
Author : bazelbuild
private String getContents() {
    if (fileContents == null) {
        StringBuilder stringBuilder = new StringBuilder();
        for (Pair<String, String> pair : pairsToWrite.toList()) {
            stringBuilder.append(pair.first).append(":").append(pair.second).append(System.lineSeparator());
        }
        fileContents = stringBuilder.toString();
    }
    return fileContents;
}

16 View Complete Implementation : LazyWritePathsFileAction.java
Copyright Apache License 2.0
Author : bazelbuild
private String getContents() {
    StringBuilder stringBuilder = new StringBuilder();
    for (Artifact file : files.toList()) {
        if (filesToIgnore.contains(file)) {
            continue;
        }
        if (file.isSourceArtifact() || includeDerivedArtifacts) {
            stringBuilder.append(file.getRootRelativePathString());
            stringBuilder.append("\n");
        }
    }
    return stringBuilder.toString();
}

16 View Complete Implementation : AnalysisFailureEvent.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public Collection<BuildEventId> getChildrenEvents() {
    return ImmutableList.copyOf(Iterables.transform(rootCauses.toList(), BuildEventId::fromCause));
}

16 View Complete Implementation : AspectCompleteEvent.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public BuildEventStreamProtos.BuildEvent replacedtreamProto(BuildEventContext converters) {
    ArtifactGroupNamer namer = converters.artifactGroupNamer();
    BuildEventStreamProtos.TargetComplete.Builder builder = BuildEventStreamProtos.TargetComplete.newBuilder();
    builder.setSuccess(!failed());
    if (artifactOutputGroups != null) {
        for (ArtifactsInOutputGroup artifactsInGroup : artifactOutputGroups.toList()) {
            OutputGroup.Builder groupBuilder = OutputGroup.newBuilder();
            groupBuilder.setName(artifactsInGroup.getOutputGroup());
            groupBuilder.addFileSets(namer.apply((new NestedSetView<Artifact>(artifactsInGroup.getArtifacts())).identifier()));
            builder.addOutputGroup(groupBuilder.build());
        }
    }
    return GenericBuildEvent.protoChaining(this).setCompleted(builder.build()).build();
}

16 View Complete Implementation : InstrumentedFileManifestAction.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
protected void computeKey(ActionKeyContext actionKeyContext, Fingerprint fp) {
    fp.addString(GUID);
    // Not sorting here is probably cheaper, though it might lead to unnecessary re-execution.
    fp.addStrings(Iterables.transform(files.toList(), TO_EXEC_PATH));
}

16 View Complete Implementation : BuildResultPrinter.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Shows the result of the build. Information includes the list of up-to-date
 * and failed targets and list of output artifacts for successful targets
 *
 * <p>This corresponds to the --show_result flag.
 */
public void showBuildResult(BuildRequest request, BuildResult result, Collection<ConfiguredTarget> configuredTargets, Collection<ConfiguredTarget> configuredTargetsToSkip, Collection<AspectValue> aspects) {
    // NOTE: be careful what you print!  We don't want to create a consistency
    // problem where the summary message and the exit code disagree.  The logic
    // here is already complex.
    BlazeRuntime runtime = env.getRuntime();
    String productName = runtime.getProductName();
    PathPrettyPrinter prettyPrinter = OutputDirectoryLinksUtils.getPathPrettyPrinter(runtime.getRuleClreplacedProvider().getSymlinkDefinitions(), request.getBuildOptions().getSymlinkPrefix(productName), productName, env.getWorkspace(), request.getBuildOptions().printWorkspaceInOutputPathsIfNeeded ? env.getWorkingDirectory() : env.getWorkspace());
    OutErr outErr = request.getOutErr();
    Collection<ConfiguredTarget> targetsToPrint = filterTargetsToPrint(configuredTargets);
    Collection<AspectValue> aspectsToPrint = filterAspectsToPrint(aspects);
    final boolean success;
    if (aspectsToPrint.isEmpty()) {
        // Suppress summary if --show_result value is exceeded:
        if (targetsToPrint.size() > request.getBuildOptions().maxResultTargets) {
            return;
        }
        // Filter the targets we care about into two buckets:
        Collection<ConfiguredTarget> succeeded = new ArrayList<>();
        Collection<ConfiguredTarget> failed = new ArrayList<>();
        Collection<ConfiguredTarget> successfulTargets = result.getSuccessfulTargets();
        for (ConfiguredTarget target : targetsToPrint) {
            (successfulTargets.contains(target) ? succeeded : failed).add(target);
        }
        // TODO(bazel-team): convert these to a new "SKIPPED" status when ready: b/62191890.
        failed.addAll(configuredTargetsToSkip);
        TopLevelArtifactContext context = request.getTopLevelArtifactContext();
        for (ConfiguredTarget target : succeeded) {
            Label label = target.getLabel();
            // For up-to-date targets report generated artifacts, but only
            // if they have replacedociated action and not middleman artifacts.
            boolean headerFlag = true;
            for (Artifact artifact : TopLevelArtifactHelper.getAllArtifactsToBuild(target, context).getImportantArtifacts().toList()) {
                if (shouldPrint(artifact)) {
                    if (headerFlag) {
                        outErr.printErr("Target " + label + " up-to-date:\n");
                        headerFlag = false;
                    }
                    outErr.printErrLn(formatArtifactForShowResults(prettyPrinter, artifact));
                }
            }
            if (headerFlag) {
                outErr.printErr("Target " + label + " up-to-date (nothing to build)\n");
            }
        }
        for (ConfiguredTarget target : failed) {
            outErr.printErr("Target " + target.getLabel() + " failed to build\n");
            // For failed compilation, it is still useful to examine temp artifacts,
            // (ie, preprocessed and replacedembler files).
            OutputGroupInfo topLevelProvider = OutputGroupInfo.get(target);
            if (topLevelProvider != null) {
                for (Artifact temp : topLevelProvider.getOutputGroup(OutputGroupInfo.TEMP_FILES).toList()) {
                    if (temp.getPath().exists()) {
                        outErr.printErrLn("  See temp at " + prettyPrinter.getPrettyPath(temp.getPath()));
                    }
                }
            }
        }
        success = failed.isEmpty();
    } else {
        // Suppress summary if --show_result value is exceeded:
        if (aspectsToPrint.size() > request.getBuildOptions().maxResultTargets) {
            return;
        }
        // Filter the targets we care about into two buckets:
        Collection<AspectValue> succeeded = new ArrayList<>();
        Collection<AspectValue> failed = new ArrayList<>();
        Collection<AspectValue> successfulAspects = result.getSuccessfulAspects();
        for (AspectValue aspect : aspectsToPrint) {
            (successfulAspects.contains(aspect) ? succeeded : failed).add(aspect);
        }
        TopLevelArtifactContext context = request.getTopLevelArtifactContext();
        for (AspectValue aspect : succeeded) {
            Label label = aspect.getLabel();
            String aspectName = aspect.getConfiguredAspect().getName();
            boolean headerFlag = true;
            NestedSet<Artifact> importantArtifacts = TopLevelArtifactHelper.getAllArtifactsToBuild(aspect, context).getImportantArtifacts();
            for (Artifact importantArtifact : importantArtifacts.toList()) {
                if (headerFlag) {
                    outErr.printErr("Aspect " + aspectName + " of " + label + " up-to-date:\n");
                    headerFlag = false;
                }
                if (shouldPrint(importantArtifact)) {
                    outErr.printErrLn(formatArtifactForShowResults(prettyPrinter, importantArtifact));
                }
            }
            if (headerFlag) {
                outErr.printErr("Aspect " + aspectName + " of " + label + " up-to-date (nothing to build)\n");
            }
        }
        for (AspectValue aspect : failed) {
            Label label = aspect.getLabel();
            String aspectName = aspect.getConfiguredAspect().getName();
            outErr.printErr("Aspect " + aspectName + " of " + label + " failed to build\n");
        }
        success = failed.isEmpty();
    }
    if (!success && !request.getOptions(ExecutionOptions.clreplaced).verboseFailures) {
        outErr.printErr("Use --verbose_failures to see the command lines of failed build steps.\n");
    }
}

16 View Complete Implementation : DexArchiveProvider.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Returns a flat map from Jars to dex archives transitively produced for the given dexopts.
 */
public Map<Artifact, Artifact> archivesForDexopts(ImmutableSet<String> dexopts) {
    // Can't use ImmutableMap because we can encounter the same key-value pair multiple times.
    // Use LinkedHashMap in case someone tries to iterate this map (not the case as of 2/2017).
    LinkedHashMap<Artifact, Artifact> result = new LinkedHashMap<>();
    for (ImmutableTable<ImmutableSet<String>, Artifact, Artifact> partialMapping : dexArchives.toList()) {
        result.putAll(partialMapping.row(dexopts));
    }
    return result;
}

16 View Complete Implementation : JavaCompilationArgsProvider.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Returns a {@link JavaCompilationArgsProvider} for the given {@link TransitiveInfoCollection}s.
 *
 * <p>If the given targets have a {@link JavaCompilationArgsProvider}, the information from that
 * provider will be returned. Otherwise, any jar files provided by the targets will be wrapped in
 * the returned provider.
 *
 * @deprecated The handling of raw jar files is present for legacy compatibility. All new
 *     Java-based rules should require their dependencies to provide {@link
 *     JavaCompilationArgsProvider}, and that precompiled jar files be wrapped in {@code
 *     java_import}. New rules should not use this method, and existing rules should be cleaned up
 *     to disallow jar files in their deps.
 */
// TODO(b/11285003): disallow jar files in deps, require java_import instead
@Deprecated
public static JavaCompilationArgsProvider legacyFromTargets(Iterable<? extends TransitiveInfoCollection> infos) {
    Builder argsBuilder = builder();
    for (TransitiveInfoCollection info : infos) {
        JavaCompilationArgsProvider provider = null;
        JavaStrictCompilationArgsProvider strictCompilationArgsProvider = JavaInfo.getProvider(JavaStrictCompilationArgsProvider.clreplaced, info);
        if (strictCompilationArgsProvider != null) {
            provider = strictCompilationArgsProvider.getJavaCompilationArgsProvider();
        }
        if (provider == null) {
            provider = JavaInfo.getProvider(JavaCompilationArgsProvider.clreplaced, info);
        }
        if (provider != null) {
            argsBuilder.addExports(provider);
        } else {
            NestedSet<Artifact> filesToBuild = info.getProvider(FileProvider.clreplaced).getFilesToBuild();
            for (Artifact jar : FileType.filter(filesToBuild.toList(), JavaSemantics.JAR)) {
                argsBuilder.addRuntimeJar(jar).addDirectCompileTimeJar(/* interfaceJar= */
                jar, /* fullJar= */
                jar);
            }
        }
    }
    return argsBuilder.build();
}

16 View Complete Implementation : PyProviderUtils.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Returns whether a target uses shared libraries.
 *
 * <p>If the target has a py provider, the value from that provider is used. Otherwise, we fall
 * back on checking whether the target's filesToBuild contains a shared library file type (e.g., a
 * .so file).
 *
 * @throws EvalException if the legacy struct provider is present but malformed
 */
public static boolean getUsesSharedLibraries(TransitiveInfoCollection target) throws EvalException {
    if (hasModernProvider(target)) {
        return getModernProvider(target).getUsesSharedLibraries();
    } else if (hasLegacyProvider(target)) {
        return PyStructUtils.getUsesSharedLibraries(getLegacyProvider(target));
    } else {
        NestedSet<Artifact> files = target.getProvider(FileProvider.clreplaced).getFilesToBuild();
        return FileType.contains(files.toList(), CppFileTypes.SHARED_LIBRARY);
    }
}

16 View Complete Implementation : PyProviderUtils.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Returns the transitive sources of a given target.
 *
 * <p>If the target has a py provider, the value from that provider is used. Otherwise, we fall
 * back on collecting .py source files from the target's filesToBuild.
 *
 * @throws EvalException if the legacy struct provider is present but malformed
 */
// TODO(bazel-team): Eliminate the fallback behavior by returning an appropriate py provider from
// the relevant rules.
public static NestedSet<Artifact> getTransitiveSources(TransitiveInfoCollection target) throws EvalException {
    if (hasModernProvider(target)) {
        return getModernProvider(target).getTransitiveSourcesSet();
    } else if (hasLegacyProvider(target)) {
        return PyStructUtils.getTransitiveSources(getLegacyProvider(target));
    } else {
        NestedSet<Artifact> files = target.getProvider(FileProvider.clreplaced).getFilesToBuild();
        return NestedSetBuilder.<Artifact>compileOrder().addAll(FileType.filter(files.toList(), PyRuleClreplacedes.PYTHON_SOURCE)).build();
    }
}

16 View Complete Implementation : TransitiveTargetFunction.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
void processDeps(TransitiveTargetValueBuilder builder, EventHandler eventHandler, TargetAndErrorIfAny targetAndErrorIfAny, Iterable<Map.Entry<SkyKey, ValueOrException2<NoSuchPackageException, NoSuchTargetException>>> depEntries) {
    boolean successfulTransitiveLoading = builder.isSuccessfulTransitiveLoading();
    Target target = targetAndErrorIfAny.getTarget();
    NestedSetBuilder<Label> transitiveRootCauses = builder.getTransitiveRootCauses();
    for (Map.Entry<SkyKey, ValueOrException2<NoSuchPackageException, NoSuchTargetException>> entry : depEntries) {
        Label depLabel = ((TransitiveTargetKey) entry.getKey()).getLabel();
        TransitiveTargetValue transitiveTargetValue;
        try {
            transitiveTargetValue = (TransitiveTargetValue) entry.getValue().get();
            if (transitiveTargetValue == null) {
                continue;
            }
        } catch (NoSuchPackageException | NoSuchTargetException e) {
            successfulTransitiveLoading = false;
            transitiveRootCauses.add(depLabel);
            maybeReportErrorAboutMissingEdge(target, depLabel, e, eventHandler);
            continue;
        }
        builder.getTransitiveTargets().addTransitive(transitiveTargetValue.getTransitiveTargets());
        NestedSet<Label> rootCauses = transitiveTargetValue.getTransitiveRootCauses();
        if (rootCauses != null) {
            successfulTransitiveLoading = false;
            transitiveRootCauses.addTransitive(rootCauses);
            if (transitiveTargetValue.getErrorLoadingTarget() != null) {
                maybeReportErrorAboutMissingEdge(target, depLabel, transitiveTargetValue.getErrorLoadingTarget(), eventHandler);
            }
        }
        NestedSet<Clreplaced<? extends Fragment>> depFragments = transitiveTargetValue.getTransitiveConfigFragments();
        ImmutableList<Clreplaced<? extends Fragment>> depFragmentsAsList = depFragments.toList();
        // The simplest collection technique would be to unconditionally add all deps' nested
        // sets to the current target's nested set. But when there's large overlap between their
        // fragment needs, this produces unnecessarily bloated nested sets and a lot of references
        // that don't contribute anything unique to the required fragment set. So we optimize here
        // by completely skipping sets that don't offer anything new. More fine-tuned optimization
        // is possible, but this offers a good balance between simplicity and practical efficiency.
        Set<Clreplaced<? extends Fragment>> addedConfigFragments = builder.getConfigFragmentsFromDeps();
        if (!addedConfigFragments.containsAll(depFragmentsAsList)) {
            builder.getTransitiveConfigFragments().addTransitive(depFragments);
            addedConfigFragments.addAll(depFragmentsAsList);
        }
    }
    builder.setSuccessfulTransitiveLoading(successfulTransitiveLoading);
}

16 View Complete Implementation : AarImportTest.java
Copyright Apache License 2.0
Author : bazelbuild
@Test
public void testNativeLibsProvided() throws Exception {
    ConfiguredTarget androidLibraryTarget = getConfiguredTarget("//java:lib");
    NestedSet<Artifact> nativeLibs = androidLibraryTarget.get(AndroidNativeLibsInfo.PROVIDER).getNativeLibs();
    replacedertThat(nativeLibs.toList()).containsExactly(ActionsTestUtil.getFirstArtifactEndingWith(nativeLibs, "foo/native_libs.zip"), ActionsTestUtil.getFirstArtifactEndingWith(nativeLibs, "bar/native_libs.zip"), ActionsTestUtil.getFirstArtifactEndingWith(nativeLibs, "baz/native_libs.zip"));
}

15 View Complete Implementation : DeployArchiveBuilder.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Builds the action as configured.
 */
public void build() throws InterruptedException {
    ImmutableList<Artifact> clreplacedpathResources = attributes.getClreplacedPathResources();
    Set<String> clreplacedPathResourceNames = new HashSet<>();
    for (Artifact artifact : clreplacedpathResources) {
        String name = artifact.getExecPath().getBaseName();
        if (!clreplacedPathResourceNames.add(name)) {
            ruleContext.attributeError("clreplacedpath_resources", "entries must have different file names (duplicate: " + name + ")");
            return;
        }
    }
    NestedSet<Artifact> runtimeJars = runtimeJarsBuilder.build();
    NestedSet<Artifact> runtimeClreplacedpathForArchive = attributes.getRuntimeClreplacedPathForArchive();
    // TODO(kmb): Consider not using getArchiveInputs, specifically because we don't want/need to
    // transform anything but the runtimeClreplacedpath and b/c we currently do it twice here and below
    NestedSetBuilder<Artifact> inputs = NestedSetBuilder.stableOrder();
    inputs.addTransitive(getArchiveInputs(attributes, runtimeClreplacedpathForArchive, derivedJars));
    if (derivedJars != null) {
        inputs.addAll(Iterables.transform(runtimeJars.toList(), derivedJars));
    } else {
        inputs.addTransitive(runtimeJars);
    }
    if (runfilesMiddleman != null) {
        inputs.add(runfilesMiddleman);
    }
    ImmutableList<Artifact> buildInfoArtifacts = ruleContext.getBuildInfo(JavaBuildInfoFactory.KEY);
    inputs.addAll(buildInfoArtifacts);
    NestedSetBuilder<Artifact> runtimeClreplacedpath = NestedSetBuilder.stableOrder();
    if (derivedJars != null) {
        runtimeClreplacedpath.addAll(Iterables.transform(runtimeJars.toList(), derivedJars));
        runtimeClreplacedpath.addAll(Iterables.transform(runtimeClreplacedpathForArchive.toList(), derivedJars));
    } else {
        runtimeClreplacedpath.addTransitive(runtimeJars);
        runtimeClreplacedpath.addTransitive(runtimeClreplacedpathForArchive);
    }
    if (launcher != null) {
        inputs.add(launcher);
    }
    if (oneVersionEnforcementLevel != OneVersionEnforcementLevel.OFF) {
        if (oneVersionWhitelistArtifact == null) {
            OneVersionCheckActionBuilder.addRuleErrorForMissingArtifacts(ruleContext, JavaToolchainProvider.from(ruleContext));
            return;
        }
        inputs.add(oneVersionWhitelistArtifact);
    }
    // If singlejar's name ends with .jar, it is Java application, otherwise it is native.
    // TODO(asmundak): once https://github.com/bazelbuild/bazel/issues/2241 is fixed (that is,
    // the native singlejar is used on windows) remove support for the Java implementation
    Artifact singlejar = JavaToolchainProvider.from(ruleContext).getSingleJar();
    boolean usingNativeSinglejar = !singlejar.getFilename().endsWith(".jar");
    CommandLine commandLine = semantics.buildSingleJarCommandLine(CppHelper.getToolchainUsingDefaultCcToolchainAttribute(ruleContext).getToolchainIdentifier(), outputJar, javaStartClreplaced, deployManifestLines, buildInfoArtifacts, clreplacedpathResources, runtimeClreplacedpath.build(), includeBuildData, compression, launcher, usingNativeSinglejar, oneVersionEnforcementLevel, oneVersionWhitelistArtifact);
    if (checkDesugarDeps) {
        commandLine = CommandLine.concat(commandLine, ImmutableList.of("--check_desugar_deps"));
    }
    List<String> jvmArgs = ImmutableList.of(SINGLEJAR_MAX_MEMORY);
    if (!usingNativeSinglejar) {
        ruleContext.registerAction(new SpawnAction.Builder().addTransitiveInputs(inputs.build()).addTransitiveInputs(JavaRuntimeInfo.forHost(ruleContext).javaBaseInputsMiddleman()).addOutput(outputJar).setResources(DEPLOY_ACTION_RESOURCE_SET).setJarExecutable(JavaCommon.getHostJavaExecutable(ruleContext), singlejar, jvmArgs).addCommandLine(commandLine, ParamFileInfo.builder(ParameterFileType.SHELL_QUOTED).setUseAlways(true).build()).setProgressMessage("Building deploy jar %s", outputJar.prettyPrint()).setMnemonic("JavaDeployJar").setExecutionInfo(ExecutionRequirements.WORKER_MODE_ENABLED).build(ruleContext));
    } else {
        ruleContext.registerAction(new SpawnAction.Builder().addTransitiveInputs(inputs.build()).addOutput(outputJar).setResources(DEPLOY_ACTION_RESOURCE_SET).setExecutable(singlejar).addCommandLine(commandLine, ParamFileInfo.builder(ParameterFileType.SHELL_QUOTED).setUseAlways(true).build()).setProgressMessage("Building deploy jar %s", outputJar.prettyPrint()).setMnemonic("JavaDeployJar").build(ruleContext));
    }
}

15 View Complete Implementation : PyCommon.java
Copyright Apache License 2.0
Author : bazelbuild
public void addCommonTransitiveInfoProviders(RuleConfiguredTargetBuilder builder, NestedSet<Artifact> filesToBuild) {
    // Add PyInfo and/or legacy "py" struct provider.
    boolean createLegacyPyProvider = !ruleContext.getFragment(PythonConfiguration.clreplaced).disallowLegacyPyProvider();
    PyProviderUtils.builder(createLegacyPyProvider).setTransitiveSources(transitivePythonSources).setUsesSharedLibraries(usesSharedLibraries).setImports(imports).setHasPy2OnlySources(hasPy2OnlySources).setHasPy3OnlySources(hasPy3OnlySources).buildAndAddToTarget(builder);
    // Add PyRuntimeInfo if this is an executable rule.
    if (runtimeFromToolchain != null) {
        builder.addNativeDeclaredProvider(runtimeFromToolchain);
    }
    builder.addNativeDeclaredProvider(InstrumentedFilesCollector.collect(ruleContext, semantics.getCoverageInstrumentationSpec(), METADATA_COLLECTOR, filesToBuild.toList(), /* reportedToActualSources= */
    NestedSetBuilder.create(Order.STABLE_ORDER))).addOutputGroup(OutputGroupInfo.FILES_TO_COMPILE, transitivePythonSources).addOutputGroup(OutputGroupInfo.COMPILATION_PREREQUISITES, transitivePythonSources);
}

15 View Complete Implementation : AarImportTest.java
Copyright Apache License 2.0
Author : bazelbuild
@Test
public void testResourcesProvided() throws Exception {
    ConfiguredTarget aarImportTarget = getConfiguredTarget("//a:foo");
    NestedSet<ValidatedAndroidResources> directResources = aarImportTarget.get(AndroidResourcesInfo.PROVIDER).getDirectAndroidResources();
    replacedertThat(directResources.toList()).hreplacedize(1);
    ValidatedAndroidResources resourceContainer = directResources.toList().get(0);
    replacedertThat(resourceContainer.getManifest()).isNotNull();
    Artifact resourceTreeArtifact = Iterables.getOnlyElement(resourceContainer.getResources());
    replacedertThat(resourceTreeArtifact.isTreeArtifact()).isTrue();
    replacedertThat(resourceTreeArtifact.getExecPathString()).endsWith("_aar/unzipped/resources/foo");
    NestedSet<ParsedAndroidreplacedets> directreplacedets = aarImportTarget.get(AndroidreplacedetsInfo.PROVIDER).getDirectParsedreplacedets();
    replacedertThat(directreplacedets.toList()).hreplacedize(1);
    ParsedAndroidreplacedets replacedets = directreplacedets.toList().get(0);
    replacedertThat(replacedets.getSymbols()).isNotNull();
    Artifact replacedetsTreeArtifact = Iterables.getOnlyElement(replacedets.getreplacedets());
    replacedertThat(replacedetsTreeArtifact.isTreeArtifact()).isTrue();
    replacedertThat(replacedetsTreeArtifact.getExecPathString()).endsWith("_aar/unzipped/replacedets/foo");
}

15 View Complete Implementation : AarImportTest.java
Copyright Apache License 2.0
Author : bazelbuild
@Test
public void testDepsCheckerActionDoesNotExistsForLevelOff() throws Exception {
    useConfiguration("--experimental_import_deps_checking=off");
    ConfiguredTarget aarImportTarget = getConfiguredTarget("//a:bar");
    OutputGroupInfo outputGroupInfo = aarImportTarget.get(OutputGroupInfo.SKYLARK_CONSTRUCTOR);
    NestedSet<Artifact> outputGroup = outputGroupInfo.getOutputGroup(OutputGroupInfo.HIDDEN_TOP_LEVEL);
    replacedertThat(outputGroup.toList()).hreplacedize(1);
    replacedertThat(ActionsTestUtil.getFirstArtifactEndingWith(outputGroup, "jdeps.proto")).isNull();
}

15 View Complete Implementation : AndroidLocalTestTest.java
Copyright Apache License 2.0
Author : bazelbuild
@Test
public void testResourcesClreplacedJarInRunfiles() throws Exception {
    scratch.file("java/test/BUILD", "load('//java/bar:foo.bzl', 'extra_deps')", "android_local_test(name = 'dummyTest',", "    srcs = ['test.java'],", "    deps = extra_deps)");
    ConfiguredTarget target = getConfiguredTarget("//java/test:dummyTest");
    NestedSet<Artifact> runfilesArtifacts = collectRunfiles(target);
    Artifact resourceClreplacedJar = getImplicitOutputArtifact(target, AndroidRuleClreplacedes.ANDROID_RESOURCES_CLreplaced_JAR);
    replacedertThat(runfilesArtifacts.toList()).contains(resourceClreplacedJar);
}

14 View Complete Implementation : SkylarkCommandLine.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public String joinPaths(String separator, Depset files) throws EvalException {
    NestedSet<Artifact> artifacts = files.getSetFromParam(Artifact.clreplaced, "files");
    // TODO(bazel-team): This method should be deprecated and strongly discouraged, as it
    // flattens a depset during replacedysis.
    return Artifact.joinExecPaths(separator, artifacts.toList());
}

14 View Complete Implementation : AndroidRuntimeJarProvider.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Returns function that maps Jars to desugaring results if available and returns the given Jar
 * otherwise.
 */
public Function<Artifact, Artifact> collapseToFunction() {
    final HashMap<Artifact, Artifact> collapsed = new HashMap<>();
    for (ImmutableMap<Artifact, Artifact> partialMapping : runtimeJars.toList()) {
        collapsed.putAll(partialMapping);
    }
    return jar -> {
        Artifact result = collapsed.get(jar);
        // return null iff input == null
        return result != null ? result : jar;
    };
}