Java Code Examples for com.google.common.collect.ImmutableSortedMap#entrySet()

The following examples show how to use com.google.common.collect.ImmutableSortedMap#entrySet() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SummarizeCorpusScores2016.java    From tac-kbp-eal with MIT License 6 votes vote down vote up
private void plotScores(final ImmutableSortedMap<File, CorpusScores> sortedScores,
    final File outputFile, final String axisTitle, final double upperRange,
    final Function<CorpusScores, double[]> extractScores) throws IOException {
  final BoxPlot.Builder corpusFScoresBoxPlot = BoxPlot.builder();
  corpusFScoresBoxPlot.setTitle("2016 Corpus Query " + axisTitle)
      .setYAxis(Axis.yAxis().setLabel(axisTitle).setRange(Range.closed(0.0, upperRange))
          .build())
      .setXAxis(Axis.xAxis().setLabel("System").rotateLabels().build())
      .hideKey()
      .setWhiskers(
          BoxPlot.Whiskers.builder().setExtentMode(BoxPlot.Whiskers.Fraction.of(0.95)).build());

  // make bootstrapped charts
  for (final Map.Entry<File, CorpusScores> e : sortedScores.entrySet()) {
    if (e.getValue().linearQueryScore() > 0) {
      corpusFScoresBoxPlot.addDataset(BoxPlot.Dataset.createCopyingData(e.getKey().getName(),
          checkNotNull(extractScores.apply(checkNotNull(e.getValue())))));
    }
  }
  plotRenderer.renderTo(corpusFScoresBoxPlot.build(), outputFile);
}
 
Example 2
Source File: NinjaBuild.java    From bazel with Apache License 2.0 6 votes vote down vote up
private static void symlinkDepsMappings(
    RuleContext ruleContext,
    NinjaGraphArtifactsHelper artifactsHelper,
    ImmutableSortedMap<PathFragment, Artifact> depsMap)
    throws GenericParsingException {
  for (Map.Entry<PathFragment, Artifact> entry : depsMap.entrySet()) {
    PathFragment depPath = entry.getKey();
    Artifact destinationArtifact = entry.getValue();
    Artifact outputArtifact = artifactsHelper.createOutputArtifact(depPath);

    SymlinkAction symlinkAction =
        SymlinkAction.toArtifact(
            ruleContext.getActionOwner(),
            destinationArtifact,
            outputArtifact,
            String.format(
                "Symlinking deps_mapping entry '%s' to '%s'",
                destinationArtifact.getExecPath(), outputArtifact.getExecPath()));
    ruleContext.registerAction(symlinkAction);
  }
}
 
Example 3
Source File: Config.java    From buck with Apache License 2.0 6 votes vote down vote up
private HashCode computeOrderIndependentHashCode() {
  ImmutableMap<String, ImmutableMap<String, String>> rawValues = rawConfig.getValues();
  ImmutableSortedMap.Builder<String, ImmutableSortedMap<String, String>> expanded =
      ImmutableSortedMap.naturalOrder();
  for (String section : rawValues.keySet()) {
    expanded.put(section, ImmutableSortedMap.copyOf(get(section)));
  }

  ImmutableSortedMap<String, ImmutableSortedMap<String, String>> sortedConfigMap =
      expanded.build();

  Hasher hasher = Hashing.sha256().newHasher();
  for (Entry<String, ImmutableSortedMap<String, String>> entry : sortedConfigMap.entrySet()) {
    hasher.putString(entry.getKey(), StandardCharsets.UTF_8);
    for (Entry<String, String> nestedEntry : entry.getValue().entrySet()) {
      hasher.putString(nestedEntry.getKey(), StandardCharsets.UTF_8);
      hasher.putString(nestedEntry.getValue(), StandardCharsets.UTF_8);
    }
  }

  return hasher.hash();
}
 
Example 4
Source File: BuildConfiguration.java    From buck with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static void writeBuildConfiguration(
    ProjectFilesystem projectFilesystem,
    Path xcconfigPath,
    ImmutableSortedMap<String, String> config,
    boolean readOnly)
    throws IOException {
  StringBuilder stringBuilder = new StringBuilder();
  for (Map.Entry<String, String> entry : config.entrySet()) {
    stringBuilder.append(entry.getKey());
    stringBuilder.append(" = ");
    stringBuilder.append(entry.getValue());
    stringBuilder.append('\n');
  }
  String xcconfigContents = stringBuilder.toString();

  projectFilesystem.mkdirs(Objects.requireNonNull(xcconfigPath).getParent());
  if (MoreProjectFilesystems.fileContentsDiffer(
      new ByteArrayInputStream(xcconfigContents.getBytes(Charsets.UTF_8)),
      xcconfigPath,
      projectFilesystem)) {
    if (readOnly) {
      projectFilesystem.writeContentsToPath(
          xcconfigContents, xcconfigPath, MorePosixFilePermissions.READ_ONLY_FILE_ATTRIBUTE);
    } else {
      projectFilesystem.writeContentsToPath(xcconfigContents, xcconfigPath);
    }
  }
}
 
Example 5
Source File: SortedMapTypeCoercer.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public void traverse(
    CellNameResolver cellRoots, ImmutableSortedMap<K, V> object, Traversal traversal) {
  traversal.traverse(object);
  for (Map.Entry<K, V> element : object.entrySet()) {
    keyTypeCoercer.traverse(cellRoots, element.getKey(), traversal);
    valueTypeCoercer.traverse(cellRoots, element.getValue(), traversal);
  }
}
 
Example 6
Source File: PluginBasedCommandHelpPrinter.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * Prints the text with usage information for the given command to the provided stream.
 *
 * <p>This method divides command options into multiple categories: global options (common to all
 * commands), common options for this command and options for every plugin-based subcommand.
 */
public void printUsage(PluginBasedCommand command, PrintStream stream) {
  printShortDescription(command, stream);
  CmdLineParserWithPrintInformation parser = new CmdLineParserWithPrintInformation(command);
  ImmutableSortedMap<PluginBasedSubCommand, CmdLineParserWithPrintInformation> subCommands =
      command.getSubCommands().stream()
          .collect(
              ImmutableSortedMap.toImmutableSortedMap(
                  Comparator.comparing(PluginBasedSubCommand::getOptionValue),
                  Functions.identity(),
                  CmdLineParserWithPrintInformation::new));

  int len = calculateTotalMaxLen(parser, subCommands.values());

  OutputStreamWriter writer = new OutputStreamWriter(stream);

  printGlobalOptionsUsage(stream, writer, parser, len);
  printCommonOptionsUsage(stream, writer, parser, len);

  for (Map.Entry<PluginBasedSubCommand, CmdLineParserWithPrintInformation> subCommand :
      subCommands.entrySet()) {
    printSubCommandUsage(
        stream,
        writer,
        subCommand.getKey(),
        subCommand.getValue(),
        command.getTypeOptionName(),
        len);
  }

  stream.println();
}
 
Example 7
Source File: TargetNodeTranslator.java    From buck with Apache License 2.0 5 votes vote down vote up
private <A extends Comparable<?>, B> Optional<ImmutableSortedMap<A, B>> translateSortedMap(
    CellNameResolver cellNameResolver, BaseName targetBaseName, ImmutableSortedMap<A, B> val) {
  boolean modified = false;
  ImmutableSortedMap.Builder<A, B> builder = ImmutableSortedMap.naturalOrder();
  for (Map.Entry<A, B> ent : val.entrySet()) {
    Optional<A> key = translate(cellNameResolver, targetBaseName, ent.getKey());
    Optional<B> value = translate(cellNameResolver, targetBaseName, ent.getValue());
    modified = modified || key.isPresent() || value.isPresent();
    builder.put(key.orElse(ent.getKey()), value.orElse(ent.getValue()));
  }
  return modified ? Optional.of(builder.build()) : Optional.empty();
}
 
Example 8
Source File: HaskellGhciRule.java    From buck with Apache License 2.0 5 votes vote down vote up
private void symlinkLibs(
    SourcePathResolverAdapter resolver,
    Path symlinkDir,
    ImmutableList.Builder<Step> steps,
    ImmutableSortedMap<String, NonHashableSourcePathContainer> libs) {
  for (Map.Entry<String, NonHashableSourcePathContainer> ent : libs.entrySet()) {
    steps.add(
        new ResolveAndSymlinkStep(
            resolver, symlinkDir, ent.getKey(), ent.getValue().getSourcePath()));
  }
}
 
Example 9
Source File: HeaderSearchPaths.java    From buck with Apache License 2.0 5 votes vote down vote up
private boolean shouldUpdateSymlinkTree(
    Path headerSymlinkTreeRoot,
    ImmutableSortedMap<Path, Path> resolvedContents,
    boolean shouldCreateHeadersSymlinks,
    ImmutableList.Builder<Path> headerSymlinkTreesBuilder)
    throws IOException {
  Path hashCodeFilePath = headerSymlinkTreeRoot.resolve(".contents-hash");
  Optional<String> currentHashCode = projectFilesystem.readFileIfItExists(hashCodeFilePath);
  String newHashCode = getHeaderSymlinkTreeHashCode(resolvedContents, true, false).toString();

  headerSymlinkTreesBuilder.add(headerSymlinkTreeRoot);
  if (Optional.of(newHashCode).equals(currentHashCode)) {
    LOG.debug(
        "Symlink tree at %s is up to date, not regenerating (key %s).",
        headerSymlinkTreeRoot, newHashCode);
    return false;
  }
  LOG.debug(
      "Updating symlink tree at %s (old key %s, new key %s).",
      headerSymlinkTreeRoot, currentHashCode, newHashCode);
  projectFilesystem.deleteRecursivelyIfExists(headerSymlinkTreeRoot);
  projectFilesystem.mkdirs(headerSymlinkTreeRoot);
  if (shouldCreateHeadersSymlinks) {
    for (Map.Entry<Path, Path> entry : resolvedContents.entrySet()) {
      Path link = entry.getKey();
      Path existing = entry.getValue();
      projectFilesystem.createParentDirs(link);
      projectFilesystem.createSymLink(link, existing, /* force */ false);
    }
  }

  projectFilesystem.writeContentsToPath(newHashCode, hashCodeFilePath);

  return true;
}
 
Example 10
Source File: SortedMapTypeCoercer.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public ImmutableSortedMap<K, V> coerce(
    CellNameResolver cellRoots,
    ProjectFilesystem filesystem,
    ForwardRelativePath pathRelativeToProjectRoot,
    TargetConfiguration targetConfiguration,
    TargetConfiguration hostConfiguration,
    ImmutableSortedMap<KU, VU> object)
    throws CoerceFailedException {
  ImmutableSortedMap.Builder<K, V> builder = ImmutableSortedMap.naturalOrder();

  for (Map.Entry<KU, VU> entry : object.entrySet()) {
    K key =
        keyTypeCoercer.coerce(
            cellRoots,
            filesystem,
            pathRelativeToProjectRoot,
            targetConfiguration,
            hostConfiguration,
            entry.getKey());
    V value =
        valueTypeCoercer.coerce(
            cellRoots,
            filesystem,
            pathRelativeToProjectRoot,
            targetConfiguration,
            hostConfiguration,
            entry.getValue());
    builder.put(key, value);
  }

  return builder.build();
}
 
Example 11
Source File: WorkspaceAndProjectGenerator.java    From buck with Apache License 2.0 5 votes vote down vote up
private static void addExtraWorkspaceSchemes(
    XCodeDescriptions xcodeDescriptions,
    TargetGraph projectGraph,
    AppleDependenciesCache dependenciesCache,
    ImmutableSortedMap<String, BuildTarget> extraSchemes,
    ImmutableMap.Builder<String, XcodeWorkspaceConfigDescriptionArg> schemeConfigsBuilder,
    ImmutableSetMultimap.Builder<String, Optional<TargetNode<?>>>
        schemeNameToSrcTargetNodeBuilder,
    ImmutableSetMultimap.Builder<String, TargetNode<AppleTestDescriptionArg>>
        extraTestNodesBuilder) {
  for (Map.Entry<String, BuildTarget> extraSchemeEntry : extraSchemes.entrySet()) {
    BuildTarget extraSchemeTarget = extraSchemeEntry.getValue();
    Optional<TargetNode<?>> extraSchemeNode = projectGraph.getOptional(extraSchemeTarget);
    if (!extraSchemeNode.isPresent()
        || !(extraSchemeNode.get().getDescription() instanceof XcodeWorkspaceConfigDescription)) {
      throw new HumanReadableException(
          "Extra scheme target '%s' should be of type 'xcode_workspace_config'",
          extraSchemeTarget);
    }
    XcodeWorkspaceConfigDescriptionArg extraSchemeArg =
        (XcodeWorkspaceConfigDescriptionArg) extraSchemeNode.get().getConstructorArg();
    String schemeName = extraSchemeEntry.getKey();
    addWorkspaceScheme(
        xcodeDescriptions,
        projectGraph,
        dependenciesCache,
        schemeName,
        extraSchemeArg,
        schemeConfigsBuilder,
        schemeNameToSrcTargetNodeBuilder,
        extraTestNodesBuilder);
  }
}
 
Example 12
Source File: WorkspaceAndProjectGenerator.java    From buck with Apache License 2.0 5 votes vote down vote up
private static void addExtraWorkspaceSchemes(
    XCodeDescriptions xcodeDescriptions,
    TargetGraph projectGraph,
    AppleDependenciesCache dependenciesCache,
    ImmutableSortedMap<String, BuildTarget> extraSchemes,
    ImmutableMap.Builder<String, XcodeWorkspaceConfigDescriptionArg> schemeConfigsBuilder,
    ImmutableSetMultimap.Builder<String, Optional<TargetNode<?>>>
        schemeNameToSrcTargetNodeBuilder,
    ImmutableSetMultimap.Builder<String, TargetNode<AppleTestDescriptionArg>>
        extraTestNodesBuilder) {
  for (Map.Entry<String, BuildTarget> extraSchemeEntry : extraSchemes.entrySet()) {
    BuildTarget extraSchemeTarget = extraSchemeEntry.getValue();
    Optional<TargetNode<?>> extraSchemeNode = projectGraph.getOptional(extraSchemeTarget);
    if (!extraSchemeNode.isPresent()
        || !(extraSchemeNode.get().getDescription() instanceof XcodeWorkspaceConfigDescription)) {
      throw new HumanReadableException(
          "Extra scheme target '%s' should be of type 'xcode_workspace_config'",
          extraSchemeTarget);
    }
    XcodeWorkspaceConfigDescriptionArg extraSchemeArg =
        (XcodeWorkspaceConfigDescriptionArg) extraSchemeNode.get().getConstructorArg();
    String schemeName = extraSchemeEntry.getKey();
    addWorkspaceScheme(
        xcodeDescriptions,
        projectGraph,
        dependenciesCache,
        schemeName,
        extraSchemeArg,
        schemeConfigsBuilder,
        schemeNameToSrcTargetNodeBuilder,
        extraTestNodesBuilder);
  }
}
 
Example 13
Source File: LuaBinaryDescription.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * @return the native library map with additional entries for library names with the version
 *     suffix stripped (e.g. libfoo.so.1.0 -> libfoo.so) to appease LuaJIT, which wants to load
 *     libraries using the build-time name.
 */
private ImmutableSortedMap<String, SourcePath> addVersionLessLibraries(
    CxxPlatform cxxPlatform, ImmutableSortedMap<String, SourcePath> libraries) {
  Pattern versionedExtension =
      Pattern.compile(
          Joiner.on("[.\\d]*")
              .join(
                  Iterables.transform(
                      Splitter.on("%s")
                          .split(cxxPlatform.getSharedLibraryVersionedExtensionFormat()),
                      input -> input.isEmpty() ? input : Pattern.quote(input))));
  Map<String, SourcePath> librariesPaths = new HashMap<>();
  for (Map.Entry<String, SourcePath> ent : libraries.entrySet()) {
    String name = ent.getKey();

    if (librariesPaths.containsKey(name) && librariesPaths.get(name) != ent.getValue()) {
      throw new HumanReadableException(
          "Library %s has multiple possible paths: %s and %s",
          name, ent.getValue(), librariesPaths.get(name));
    }

    librariesPaths.put(name, ent.getValue());
    Matcher matcher = versionedExtension.matcher(name);
    String versionLessName = matcher.replaceAll(cxxPlatform.getSharedLibraryExtension());
    if (!versionLessName.equals(ent.getKey()) && !libraries.containsKey(versionLessName)) {
      librariesPaths.put(versionLessName, ent.getValue());
    }
  }
  return ImmutableSortedMap.copyOf(librariesPaths);
}
 
Example 14
Source File: CxxDescriptionEnhancer.java    From buck with Apache License 2.0 5 votes vote down vote up
private static MappedSymlinkTree createBinaryWithSharedLibrariesSymlinkTree(
    BuildTarget baseBuildTarget,
    ProjectFilesystem filesystem,
    ActionGraphBuilder graphBuilder,
    CxxPlatform cxxPlatform,
    Iterable<? extends BuildRule> deps,
    Path binaryName,
    SourcePath binarySource) {

  BuildTarget symlinkTreeTarget =
      createBinaryWithSharedLibrariesSymlinkTreeTarget(baseBuildTarget, cxxPlatform.getFlavor());
  Path symlinkTreeRoot =
      getBinaryWithSharedLibrariesSymlinkTreePath(
          filesystem, baseBuildTarget, cxxPlatform.getFlavor());

  ImmutableMap<BuildTarget, NativeLinkableGroup> roots =
      NativeLinkableGroups.getNativeLinkableRoots(deps, n -> Optional.empty());
  ImmutableSortedMap<String, SourcePath> libraries =
      NativeLinkables.getTransitiveSharedLibraries(
          graphBuilder,
          Iterables.transform(
              roots.values(), g -> g.getNativeLinkable(cxxPlatform, graphBuilder)),
          false);

  ImmutableMap.Builder<Path, SourcePath> links = ImmutableMap.builder();
  for (Map.Entry<String, SourcePath> ent : libraries.entrySet()) {
    links.put(Paths.get(ent.getKey()), ent.getValue());
  }
  links.put(binaryName, binarySource);
  return new MappedSymlinkTree(
      "cxx_binary", symlinkTreeTarget, filesystem, symlinkTreeRoot, links.build());
}
 
Example 15
Source File: CxxDescriptionEnhancer.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * Build a {@link HeaderSymlinkTree} of all the shared libraries found via the top-level rule's
 * transitive dependencies.
 */
public static MappedSymlinkTree createSharedLibrarySymlinkTree(
    BuildTarget baseBuildTarget,
    ProjectFilesystem filesystem,
    ActionGraphBuilder graphBuilder,
    CxxPlatform cxxPlatform,
    Iterable<? extends BuildRule> deps,
    Function<? super BuildRule, Optional<Iterable<? extends BuildRule>>> passthrough) {

  BuildTarget symlinkTreeTarget =
      createSharedLibrarySymlinkTreeTarget(baseBuildTarget, cxxPlatform.getFlavor());
  Path symlinkTreeRoot =
      getSharedLibrarySymlinkTreePath(filesystem, baseBuildTarget, cxxPlatform.getFlavor());

  ImmutableMap<BuildTarget, NativeLinkableGroup> roots =
      NativeLinkableGroups.getNativeLinkableRoots(deps, passthrough);
  ImmutableSortedMap<String, SourcePath> libraries =
      NativeLinkables.getTransitiveSharedLibraries(
          graphBuilder,
          Iterables.transform(
              roots.values(), g -> g.getNativeLinkable(cxxPlatform, graphBuilder)),
          false);

  ImmutableMap.Builder<Path, SourcePath> links = ImmutableMap.builder();
  for (Map.Entry<String, SourcePath> ent : libraries.entrySet()) {
    links.put(Paths.get(ent.getKey()), ent.getValue());
  }
  return new MappedSymlinkTree(
      "cxx_binary", symlinkTreeTarget, filesystem, symlinkTreeRoot, links.build());
}
 
Example 16
Source File: TargetsCommand.java    From buck with Apache License 2.0 5 votes vote down vote up
private void printShowRules(
    ImmutableSortedMap<BuildTargetWithOutputs, TargetResult> showRulesResult,
    CommandRunnerParams params) {
  for (Entry<BuildTargetWithOutputs, TargetResult> entry : showRulesResult.entrySet()) {
    ImmutableList.Builder<String> builder = ImmutableList.builder();
    builder.add(entry.getKey().toString());
    TargetResult targetResult = entry.getValue();
    targetResult.getRuleKey().ifPresent(builder::add);
    if (isShowCellPath) {
      Path cellPath =
          params
              .getCells()
              .getRootCell()
              .getNewCellPathResolver()
              .getCellPath(entry.getKey().getBuildTarget().getCell());
      builder.add(cellPath.toString());
    }
    @Nullable
    ImmutableSet<String> outputPathForLabel =
        targetResult.getOutputPathsByLabels().get(entry.getKey().getOutputLabel());
    if (outputPathForLabel != null && !outputPathForLabel.isEmpty()) {
      // TODO(irenewchen): Should loop through the set of strings and construct one line per
      // String
      builder.add(Iterables.getOnlyElement(outputPathForLabel));
    }
    targetResult.getGeneratedSourcePath().ifPresent(builder::add);
    targetResult.getTargetHash().ifPresent(builder::add);
    params.getConsole().getStdOut().println(Joiner.on(' ').join(builder.build()));
  }
}
 
Example 17
Source File: SummarizeCorpusScores2016.java    From tac-kbp-eal with MIT License 5 votes vote down vote up
private void writePerSubmissionSummaries(final Map<File, CorpusScores> scoresMap)
    throws IOException {
  final ImmutableSortedMap<File, CorpusScores> sortedScores =
      ImmutableSortedMap.copyOf(scoresMap);
  final ImmutableSortedMap<File, CorpusScores> sortedScoresNoLDC = ImmutableSortedMap.copyOf(
      Maps.filterKeys(scoresMap,
          not(compose(containsPredicate("LDC"), FileUtils.toNameFunction()))));

  // write CSV summary
  final File outputCSVFile = new File(outputDir, "perSubmission.csv");
  log.info("Writing CSV to {}", outputCSVFile);
  try (Writer out = Files.asCharSink(outputCSVFile, UTF_8).openBufferedStream()) {
    // write header
    out.write("System Name, ");
    out.write(CorpusScores.queryCSVHeader(""));
    out.write("\n");

    for (final Map.Entry<File, CorpusScores> e : sortedScores.entrySet()) {
      out.write(e.getKey().getName());
      out.write(", ");
      out.write(e.getValue().queryFAsCSVLine());
      out.write("\n");
    }
  }

  // plot with & without the LDC
  plotScores(sortedScores, new File(outputDir, "perSystemCorpusFScore.png"), "FScores",
      fScoreLDCMax, ExtractFScores.INSTANCE);
  plotScores(sortedScoresNoLDC, new File(outputDir, "perSystemCorpusFScoreNoLDC.png"), "FScores",
      fScoreNoLDCMax, ExtractFScores.INSTANCE);
  plotScores(sortedScores, new File(outputDir, "perSystemCorpusLinearScore.png"), "Linear Scores",
      linearScoreLDCMax, ExtractLinearScores.INSTANCE);
  plotScores(sortedScoresNoLDC, new File(outputDir, "perSystemCorpusLinearScoreNoLDC.png"),
      "Linear Scores", linearScoreNoLDCMax, ExtractLinearScores.INSTANCE);
}
 
Example 18
Source File: GeneratedResourceWarnings.java    From intellij with Apache License 2.0 4 votes vote down vote up
public static void submit(
    Consumer<IssueOutput> context,
    Project project,
    ProjectViewSet projectViewSet,
    ArtifactLocationDecoder artifactLocationDecoder,
    Set<ArtifactLocation> generatedResourceLocations,
    Set<String> whitelistedLocations) {
  if (generatedResourceLocations.isEmpty()) {
    return;
  }
  Set<ArtifactLocation> nonWhitelistedLocations = new HashSet<>();
  Set<String> unusedWhitelistEntries = new HashSet<>();
  filterWhitelistedEntries(
      generatedResourceLocations,
      whitelistedLocations,
      nonWhitelistedLocations,
      unusedWhitelistEntries);
  // Tag any warnings with the project view file.
  File projectViewFile = projectViewSet.getTopLevelProjectViewFile().projectViewFile;
  if (!nonWhitelistedLocations.isEmpty()) {
    GeneratedResourceClassifier classifier =
        new GeneratedResourceClassifier(
            project,
            nonWhitelistedLocations,
            artifactLocationDecoder,
            BlazeExecutor.getInstance().getExecutor());
    ImmutableSortedMap<ArtifactLocation, Integer> interestingDirectories =
        classifier.getInterestingDirectories();
    if (!interestingDirectories.isEmpty()) {
      context.accept(IssueOutput.warn(
              String.format(
                  "Dropping %d generated resource directories.\n"
                      + "R classes will not contain resources from these directories.\n"
                      + "Double-click to add to project view if needed to resolve references.",
                  interestingDirectories.size()))
          .inFile(projectViewFile)
          .onLine(1)
          .inColumn(1)
          .build());
      for (Map.Entry<ArtifactLocation, Integer> entry : interestingDirectories.entrySet()) {
        context.accept(IssueOutput.warn(
                String.format(
                    "Dropping generated resource directory '%s' w/ %d subdirs",
                    entry.getKey(), entry.getValue()))
            .inFile(projectViewFile)
            .navigatable(
                new AddGeneratedResourceDirectoryNavigatable(
                    project, projectViewFile, entry.getKey()))
            .build());
      }
    }
  }
  // Warn about unused parts of the whitelist.
  if (!unusedWhitelistEntries.isEmpty()) {
    context.accept(IssueOutput.warn(
            String.format(
                "%d unused entries in project view section \"%s\":\n%s",
                unusedWhitelistEntries.size(),
                GeneratedAndroidResourcesSection.KEY.getName(),
                String.join("\n  ", unusedWhitelistEntries)))
        .inFile(projectViewFile)
        .build());
  }
}
 
Example 19
Source File: HeaderSearchPaths.java    From buck with Apache License 2.0 4 votes vote down vote up
private void createPrivateHeaderSymlinkTree(
    TargetNode<? extends CxxLibraryDescription.CommonArg> targetNode,
    ImmutableSortedMap<Path, SourcePath> contents,
    ImmutableList.Builder<SourcePath> sourcePathsToBuildBuilder,
    boolean shouldCreateHeadersSymlinks,
    ImmutableList.Builder<Path> headerSymlinkTreesBuilder)
    throws IOException {

  contents.values().forEach(sourcePath -> sourcePathsToBuildBuilder.add(sourcePath));

  Path headerSymlinkTreeRoot = getPathToHeaderSymlinkTree(targetNode, HeaderVisibility.PRIVATE);

  LOG.verbose(
      "Building header symlink tree at %s with contents %s", headerSymlinkTreeRoot, contents);

  ImmutableSortedMap<Path, Path> resolvedContents =
      resolveHeaderContent(
          contents, ImmutableMap.of(), headerSymlinkTreeRoot, sourcePathsToBuildBuilder);

  if (!shouldUpdateSymlinkTree(
      headerSymlinkTreeRoot,
      resolvedContents,
      shouldCreateHeadersSymlinks,
      headerSymlinkTreesBuilder)) {
    return;
  }

  HeaderMap.Builder headerMapBuilder = new HeaderMap.Builder();
  for (Map.Entry<Path, SourcePath> entry : contents.entrySet()) {
    if (shouldCreateHeadersSymlinks) {
      headerMapBuilder.add(
          entry.getKey().toString(),
          getHeaderMapRelativeSymlinkPathForEntry(entry, headerSymlinkTreeRoot));
    } else {
      headerMapBuilder.add(
          entry.getKey().toString(),
          projectFilesystem.resolve(
              projectSourcePathResolver.resolveSourcePath(entry.getValue())));
    }
  }

  Path headerMapLocation = getHeaderMapLocationFromSymlinkTreeRoot(headerSymlinkTreeRoot);
  projectFilesystem.writeBytesToPath(headerMapBuilder.build().getBytes(), headerMapLocation);
}
 
Example 20
Source File: ConfigCommand.java    From bazel with Apache License 2.0 4 votes vote down vote up
/** Constructs a {@link ConfigurationForOutput} from the given input daata. */
private static ConfigurationForOutput getConfigurationForOutput(
    BuildConfigurationValue.Key skyKey,
    String configHash,
    BuildConfiguration config,
    ImmutableSortedMap<
            Class<? extends Fragment>, ImmutableSortedSet<Class<? extends FragmentOptions>>>
        fragmentDefs) {

  ImmutableSortedSet.Builder<FragmentForOutput> fragments =
      ImmutableSortedSet.orderedBy(comparing(e -> e.name));
  for (Map.Entry<Class<? extends Fragment>, ImmutableSortedSet<Class<? extends FragmentOptions>>>
      entry : fragmentDefs.entrySet()) {
    fragments.add(
        new FragmentForOutput(
            entry.getKey().getName(),
            entry.getValue().stream().map(clazz -> clazz.getName()).collect(toList())));
  }
  fragmentDefs.entrySet().stream()
      .filter(entry -> config.hasFragment(entry.getKey()))
      .forEach(
          entry ->
              fragments.add(
                  new FragmentForOutput(
                      entry.getKey().getName(),
                      entry.getValue().stream()
                          .map(clazz -> clazz.getName())
                          .collect(toList()))));

  ImmutableSortedSet.Builder<FragmentOptionsForOutput> fragmentOptions =
      ImmutableSortedSet.orderedBy(comparing(e -> e.name));
  config.getOptions().getFragmentClasses().stream()
      .map(optionsClass -> config.getOptions().get(optionsClass))
      .forEach(
          fragmentOptionsInstance -> {
            fragmentOptions.add(
                new FragmentOptionsForOutput(
                    fragmentOptionsInstance.getClass().getName(),
                    getOrderedNativeOptions(fragmentOptionsInstance)));
          });
  fragmentOptions.add(
      new FragmentOptionsForOutput(
          UserDefinedFragment.DESCRIPTIVE_NAME, getOrderedUserDefinedOptions(config)));

  return new ConfigurationForOutput(
      skyKey.toString(),
      configHash,
      fragments.build().asList(),
      fragmentOptions.build().asList());
}