Java Code Examples for com.google.common.collect.ImmutableSortedSet#naturalOrder()

The following examples show how to use com.google.common.collect.ImmutableSortedSet#naturalOrder() . 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: PlayerShareUtils.java    From Rails with GNU General Public License v2.0 6 votes vote down vote up
private static SortedSet<Integer> presidentSellStandard(PublicCompany company, Player president) {
    int presidentShares = president.getPortfolioModel().getShareNumber(company);
    int poolShares = poolAllowsShareNumbers(company);
    
    // check if there is a potential new president ...
    int presidentCertificateShares = company.getPresidentsShare().getShares();
    Player potential = company.findPlayerToDump();

    int maxShares;
    if (potential == null) {
        // ... if there is none, selling is only possible until the presidentCerificate or pool maximum
        maxShares = Math.min(presidentShares - presidentCertificateShares, poolShares);
    } else { 
        // otherwise until pool maximum only
        maxShares = Math.min(presidentShares, poolShares);
    }
     
    ImmutableSortedSet.Builder<Integer> sharesToSell = ImmutableSortedSet.naturalOrder();
    for (int s=1; s <= maxShares; s++) {
        sharesToSell.add(s);
    }
    return sharesToSell.build();
}
 
Example 2
Source File: UtilsResourceMount.java    From OpenPeripheral with MIT License 6 votes vote down vote up
public UtilsResourceMount() {
	ImmutableSortedSet.Builder<String> files = ImmutableSortedSet.naturalOrder();
	InputStream fileList = getClass().getResourceAsStream(RESOURCE_PATH + "files.lst");
	if (fileList != null) {
		Scanner sc = new Scanner(fileList);

		while (sc.hasNextLine()) {
			String fileName = sc.nextLine();
			files.add(fileName);
		}

		sc.close();
	}

	this.files = files.build();
}
 
Example 3
Source File: BoundingBox.java    From activitystreams with Apache License 2.0 6 votes vote down vote up
protected static BoundingBox calculateBoundingBoxLineStrings(Iterable<LineString> lineStrings) {
  ImmutableSortedSet.Builder<Float> xset = 
    ImmutableSortedSet.naturalOrder();
  ImmutableSortedSet.Builder<Float> yset = 
      ImmutableSortedSet.naturalOrder();
  ImmutableSortedSet.Builder<Float> zset = 
      ImmutableSortedSet.naturalOrder();
  for (LineString ls : lineStrings) {
    for (Position p : ls) {
      xset.add(p.northing());
      yset.add(p.easting());
      if (p.hasAltitude())
        zset.add(p.altitude());
    }
  }
  return buildBoundingBox(
    xset.build(), 
    yset.build(), 
    zset.build());
}
 
Example 4
Source File: MultiarchFileInfosTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void testOutputFormatStringDifferentOutputFileNameThinRules() {
  ProjectFilesystem filesystem = new FakeProjectFilesystem();
  SourcePathResolverAdapter pathResolver = newSourcePathResolver();

  ImmutableSortedSet.Builder<SourcePath> inputsBuilder = ImmutableSortedSet.naturalOrder();

  inputsBuilder.add(PathSourcePath.of(filesystem, Paths.get("libNiceLibrary.a")));
  inputsBuilder.add(PathSourcePath.of(filesystem, Paths.get("libBadLibrary.a")));

  ImmutableSortedSet<SourcePath> inputs = inputsBuilder.build();

  String outputFormatString =
      MultiarchFileInfos.getMultiarchOutputFormatString(pathResolver, inputs);

  assertThat(outputFormatString, equalTo("%s"));
}
 
Example 5
Source File: MapManager.java    From Rails with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Calculate the distances between a given tokenable city hex
 * and all other tokenable city hexes.
 * <p> Distances are cached.
 * @param initHex Start hex
 * @return Sorted integer list containing all occurring distances only once.
 */
public SortedSet<Integer> getCityDistances (MapHex initHex) {
    
    if (hexDistances == null) {
        hexDistances = HashBasedTable.create();
    }

    if (!hexDistances.containsRow(initHex)) {
        calculateHexDistances(initHex, initHex, 0);
    }
    
    ImmutableSortedSet.Builder<Integer> distances = 
            ImmutableSortedSet.naturalOrder();
    
    for (Entry<MapHex, Integer> otherHex:hexDistances.row(initHex).entrySet()) {
        if (otherHex.getKey().getCurrentTile().hasStations()) {
            distances.add(otherHex.getValue());
        }
    }
    return distances.build();
}
 
Example 6
Source File: RequiredConfigFragmentsTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method that returns a combined set of the common fragments all genrules require plus
 * instance-specific requirements passed here.
 */
private ImmutableSortedSet<String> genRuleFragments(String... targetSpecificRequirements)
    throws Exception {
  scratch.file(
      "base_genrule/BUILD",
      "genrule(",
      "    name = 'base_genrule',",
      "    srcs = [],",
      "    outs = ['base_genrule.out'],",
      "    cmd = 'echo hi > $@')");
  ImmutableSortedSet.Builder<String> builder = ImmutableSortedSet.naturalOrder();
  builder.add(targetSpecificRequirements);
  builder.addAll(
      getConfiguredTarget("//base_genrule")
          .getProvider(RequiredConfigFragmentsProvider.class)
          .getRequiredConfigFragments());
  return builder.build();
}
 
Example 7
Source File: AndroidBinaryGraphEnhancer.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * Provides {@see BuildRule} set of abi dependencies that have desugar enabled on them.
 *
 * <p>These are the deps that are required for full desugaring of default and static interface
 * methods
 */
private static ImmutableSortedSet<BuildRule> getDesugarDeps(
    JavaLibrary javaLibrary, Function<BuildTarget, BuildRule> targetToRule) {
  ImmutableSortedSet.Builder<BuildRule> resultBuilder = ImmutableSortedSet.naturalOrder();
  for (JavaLibrary library :
      JavaLibraryClasspathProvider.getTransitiveClasspathDeps(javaLibrary)) {
    if (javaLibrary != library && library.isDesugarEnabled()) {
      library
          .getAbiJar()
          .ifPresent(buildTarget -> resultBuilder.add(targetToRule.apply(buildTarget)));
    }
  }
  return resultBuilder.build();
}
 
Example 8
Source File: ElementCostOfDataStructures.java    From memory-measurer with Apache License 2.0 5 votes vote down vote up
public ImmutableSortedSet construct(int entries) {
  ImmutableSortedSet.Builder builder = ImmutableSortedSet.<Comparable>naturalOrder();
  for (int i = 0; i < entries; i++) {
    builder.add(newEntry());
  }
  return builder.build();
}
 
Example 9
Source File: AbstractTestState.java    From jesos with Apache License 2.0 5 votes vote down vote up
@Test
public void testNames()
    throws Exception
{
    final State state = getState();

    final byte[] value = "The quick brown fox jumps over the lazy dog.".getBytes(StandardCharsets.UTF_8);

    final ImmutableSortedSet.Builder<String> builder = ImmutableSortedSet.naturalOrder();

    for (int i = 0; i < 10; i++) {
        final String key = "name-" + UUID.randomUUID().toString();
        builder.add(key);

        final Variable var = state.fetch(key).get();
        assertTrue(var.value().length == 0);
        state.store(var.mutate(value)).get();
    }

    final SortedSet<String> keys = builder.build();

    final Iterator<String> it = state.names().get();

    final SortedSet<String> entries = ImmutableSortedSet.copyOf(it);

    assertEquals(keys, entries);
}
 
Example 10
Source File: MultiarchFileInfosTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testOutputFormatStringEmptyThinRules() {
  SourcePathResolverAdapter pathResolver = newSourcePathResolver();

  ImmutableSortedSet.Builder<SourcePath> inputsBuilder = ImmutableSortedSet.naturalOrder();
  ImmutableSortedSet<SourcePath> inputs = inputsBuilder.build();

  String outputFormatString =
      MultiarchFileInfos.getMultiarchOutputFormatString(pathResolver, inputs);

  assertThat(outputFormatString, equalTo("%s"));
}
 
Example 11
Source File: HaskellSources.java    From buck with Apache License 2.0 5 votes vote down vote up
public ImmutableSortedSet<String> getModuleNames() {
  ImmutableSortedSet.Builder<String> builder = ImmutableSortedSet.naturalOrder();
  for (HaskellSourceModule module : getModuleMap().keySet()) {
    if (module.getSourceType() == HaskellSourceModule.SourceType.HsSrcFile) {
      builder.add(module.getModuleName());
    }
  }
  return builder.build();
}
 
Example 12
Source File: SourceArtifactConverter.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * @param srcs the set of the sources of a rule attribute
 * @param deps the {@link ProviderInfoCollection} from the dependencies of a rule
 * @return the {@link Artifact}s representing the sources.
 */
public static ImmutableSortedSet<Artifact> getArtifactsFromSrcs(
    Iterable<SourcePath> srcs, ImmutableMap<BuildTarget, ProviderInfoCollection> deps) {
  ImmutableSortedSet.Builder<Artifact> artifacts = ImmutableSortedSet.naturalOrder();
  for (SourcePath src : srcs) {
    artifacts.add(SourceArtifactConverter.getArtifactsFromSrc(src, deps));
  }
  return artifacts.build();
}
 
Example 13
Source File: ImmutableSortedSetDeserializer.java    From jackson-datatypes-collections with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected Builder<Object> createBuilder() {
    /* Not quite sure what to do with sorting/ordering; may require better support either
     * via annotations, or via custom serialization (bean style that includes ordering
     * aspects)
     */
    @SuppressWarnings("rawtypes")
    ImmutableSortedSet.Builder<?> builderComp = ImmutableSortedSet.<Comparable> naturalOrder();
    ImmutableSortedSet.Builder<Object> builder = (ImmutableSortedSet.Builder<Object>) builderComp;
    return builder;
}
 
Example 14
Source File: DiscoveryGenerator.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
private List<String> computeParameterOrder(ApiMethodConfig methodConfig) {
  ImmutableSortedSet.Builder<String> queryParamBuilder = ImmutableSortedSet.naturalOrder();
  Collection<String> pathParameters = methodConfig.getPathParameters();
  for (ApiParameterConfig parameterConfig : methodConfig.getParameterConfigs()) {
    if (parameterConfig.getClassification() == Classification.API_PARAMETER
        && !pathParameters.contains(parameterConfig.getName())
        && !parameterConfig.getNullable()) {
      queryParamBuilder.add(parameterConfig.getName());
    }
  }
  List<String> order = new ArrayList<>(pathParameters);
  order.addAll(queryParamBuilder.build());
  return order;
}
 
Example 15
Source File: GwtBinaryDescription.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
public BuildRule createBuildRule(
    BuildRuleCreationContextWithTargetGraph context,
    BuildTarget buildTarget,
    BuildRuleParams params,
    GwtBinaryDescriptionArg args) {

  ActionGraphBuilder graphBuilder = context.getActionGraphBuilder();

  ImmutableSortedSet.Builder<BuildRule> extraDeps = ImmutableSortedSet.naturalOrder();

  // Find all of the reachable JavaLibrary rules and grab their associated GwtModules.
  ImmutableSortedSet.Builder<SourcePath> gwtModuleJarsBuilder = ImmutableSortedSet.naturalOrder();
  ImmutableSortedSet<BuildRule> moduleDependencies =
      graphBuilder.getAllRules(args.getModuleDeps());
  new AbstractBreadthFirstTraversal<BuildRule>(moduleDependencies) {
    @Override
    public Iterable<BuildRule> visit(BuildRule rule) {
      if (!(rule instanceof JavaLibrary)) {
        return ImmutableSet.of();
      }

      JavaLibrary javaLibrary = (JavaLibrary) rule;
      Iterable<BuildRule> ruleDeps = javaLibrary.getDepsForTransitiveClasspathEntries();

      // If the java library doesn't generate any output, it doesn't contribute a GwtModule
      if (javaLibrary.getSourcePathToOutput() == null) {
        return ruleDeps;
      }

      BuildRule gwtModule =
          graphBuilder.computeIfAbsent(
              javaLibrary
                  .getBuildTarget()
                  .assertUnflavored()
                  .withFlavors(JavaLibrary.GWT_MODULE_FLAVOR),
              gwtModuleTarget -> {
                ImmutableSortedSet<SourcePath> filesForGwtModule =
                    ImmutableSortedSet.<SourcePath>naturalOrder()
                        .addAll(javaLibrary.getSources())
                        .addAll(javaLibrary.getResources())
                        .build();
                ImmutableSortedSet<BuildRule> deps =
                    ImmutableSortedSet.copyOf(
                        graphBuilder.filterBuildRuleInputs(filesForGwtModule));

                return new GwtModule(
                    gwtModuleTarget,
                    context.getProjectFilesystem(),
                    params.withDeclaredDeps(deps).withoutExtraDeps(),
                    graphBuilder,
                    filesForGwtModule,
                    javaLibrary.getResourcesRoot());
              });

      extraDeps.add(gwtModule);
      gwtModuleJarsBuilder.add(Objects.requireNonNull(gwtModule.getSourcePathToOutput()));

      Optional<SourcePath> generatedCode = javaLibrary.getGeneratedAnnotationSourcePath();
      if (generatedCode.isPresent()) {
        extraDeps.add(javaLibrary);
        gwtModuleJarsBuilder.add(generatedCode.get());
      }

      // Traverse all of the deps of this rule.
      return ruleDeps;
    }
  }.start();

  return new GwtBinary(
      buildTarget,
      context.getProjectFilesystem(),
      params.withExtraDeps(extraDeps.build()),
      args.getModules(),
      javaOptions
          .apply(buildTarget.getTargetConfiguration())
          .getJavaRuntimeLauncher(graphBuilder, buildTarget.getTargetConfiguration()),
      args.getVmArgs(),
      args.getStyle().orElse(DEFAULT_STYLE),
      args.getDraftCompile().orElse(DEFAULT_DRAFT_COMPILE),
      args.getOptimize().orElse(DEFAULT_OPTIMIZE),
      args.getLocalWorkers().orElse(DEFAULT_NUM_LOCAL_WORKERS),
      args.getStrict().orElse(DEFAULT_STRICT),
      args.getExperimentalArgs(),
      gwtModuleJarsBuilder.build());
}
 
Example 16
Source File: CxxDescriptionEnhancer.java    From buck with Apache License 2.0 4 votes vote down vote up
public static CxxLinkAndCompileRules createBuildRulesForCxxBinaryDescriptionArg(
    TargetGraph targetGraph,
    BuildTarget target,
    ProjectFilesystem projectFilesystem,
    ActionGraphBuilder graphBuilder,
    CellPathResolver cellRoots,
    CxxBuckConfig cxxBuckConfig,
    CxxPlatform cxxPlatform,
    CommonArg args,
    ImmutableSet<BuildTarget> extraDeps,
    Optional<StripStyle> stripStyle,
    Optional<LinkerMapMode> flavoredLinkerMapMode) {

  ImmutableMap<String, CxxSource> srcs = parseCxxSources(target, graphBuilder, cxxPlatform, args);
  ImmutableMap<Path, SourcePath> headers =
      parseHeaders(target, graphBuilder, projectFilesystem, Optional.of(cxxPlatform), args);

  // Build the binary deps.
  ImmutableSortedSet.Builder<BuildRule> depsBuilder = ImmutableSortedSet.naturalOrder();
  // Add original declared and extra deps.
  args.getCxxDeps().get(graphBuilder, cxxPlatform).forEach(depsBuilder::add);
  // Add in deps found via deps query.
  ImmutableList<BuildRule> depQueryDeps =
      args.getDepsQuery().map(query -> Objects.requireNonNull(query.getResolvedQuery()))
          .orElse(ImmutableSortedSet.of()).stream()
          .map(graphBuilder::getRule)
          .collect(ImmutableList.toImmutableList());
  depsBuilder.addAll(depQueryDeps);
  // Add any extra deps passed in.
  extraDeps.stream().map(graphBuilder::getRule).forEach(depsBuilder::add);
  ImmutableSortedSet<BuildRule> deps = depsBuilder.build();

  CxxLinkOptions linkOptions =
      CxxLinkOptions.of(
          args.getThinLto(),
          args.getFatLto()
          );

  Optional<LinkableListFilter> linkableListFilter =
      LinkableListFilterFactory.from(cxxBuckConfig, args, targetGraph);

  return createBuildRulesForCxxBinary(
      target,
      projectFilesystem,
      graphBuilder,
      cellRoots,
      cxxBuckConfig,
      cxxPlatform,
      srcs,
      headers,
      deps,
      args.getLinkDepsQueryWhole()
          ? RichStream.from(depQueryDeps).map(BuildRule::getBuildTarget).toImmutableSet()
          : ImmutableSet.of(),
      stripStyle,
      flavoredLinkerMapMode,
      args.getLinkStyle().orElse(Linker.LinkableDepType.STATIC),
      linkableListFilter,
      linkOptions,
      args.getPreprocessorFlags(),
      args.getPlatformPreprocessorFlags(),
      args.getLangPreprocessorFlags(),
      args.getLangPlatformPreprocessorFlags(),
      args.getFrameworks(),
      args.getLibraries(),
      args.getCompilerFlags(),
      args.getLangCompilerFlags(),
      args.getPlatformCompilerFlags(),
      args.getLangPlatformCompilerFlags(),
      args.getPrefixHeader(),
      args.getPrecompiledHeader(),
      args.getLinkerFlags(),
      args.getLinkerExtraOutputs(),
      args.getPlatformLinkerFlags(),
      args.getCxxRuntimeType(),
      args.getRawHeaders(),
      args.getIncludeDirectories(),
      args.getExecutableName());
}
 
Example 17
Source File: FilterLineReachabilityAnswerer.java    From batfish with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
static BlockingProperties findBlockingPropsForLine(
    int blockedLineNum, List<PermitAndDenyBdds> bdds) {
  PermitAndDenyBdds blockedLine = bdds.get(blockedLineNum);

  ImmutableSortedSet.Builder<LineAndWeight> linesByWeight =
      ImmutableSortedSet.orderedBy(LineAndWeight.COMPARATOR);

  // First, we find all lines before blockedLine that actually terminate any packets
  // blockedLine intends to. These, collectively, are the (partially-)blocking lines.
  //
  // In this same loop, we also compute the overlap of each such line with the blocked line
  // and weight each blocking line by that overlap.
  //
  // Finally, we record whether any of these lines has a different action than the blocked line.
  PermitAndDenyBdds restOfLine = blockedLine;
  boolean diffAction = false; // true if some partially-blocking line has a different action.
  for (int prevLineNum = 0; prevLineNum < blockedLineNum && !restOfLine.isZero(); prevLineNum++) {
    PermitAndDenyBdds prevLine = bdds.get(prevLineNum);

    if (!prevLine.getMatchBdd().andSat(restOfLine.getMatchBdd())) {
      continue;
    }

    BDD blockedLineOverlap = prevLine.getMatchBdd().and(blockedLine.getMatchBdd());
    linesByWeight.add(new LineAndWeight(prevLineNum, blockedLineOverlap.satCount()));
    diffAction = diffAction || takeDifferentActions(prevLine, restOfLine);
    restOfLine = restOfLine.diff(prevLine.getMatchBdd());
  }

  // In this second loop, we compute the answer:
  // * include partially-blocking lines in weight order until the blocked line is fully blocked by
  //   this subset.
  // * also include the largest blocking line with a different action than the blocked line, if
  //   not already in the above subset.
  ImmutableSortedSet.Builder<Integer> answerLines = ImmutableSortedSet.naturalOrder();
  restOfLine = blockedLine;
  boolean needDiffAction = diffAction;
  for (LineAndWeight line : linesByWeight.build()) {
    int curLineNum = line.getLine();
    PermitAndDenyBdds curLine = bdds.get(curLineNum);
    boolean curDiff = takeDifferentActions(curLine, blockedLine);

    // The original line is still not blocked, or this is the first line with a different action.
    if (!restOfLine.isZero() || needDiffAction && curDiff) {
      restOfLine = restOfLine.diff(curLine.getMatchBdd());
      answerLines.add(curLineNum);
      needDiffAction = needDiffAction && !curDiff;
    }

    // The original line is blocked and we have a line with a different action (if such exists).
    if (restOfLine.isZero() && !needDiffAction) {
      break;
    }
  }

  return new BlockingProperties(answerLines.build(), diffAction);
}
 
Example 18
Source File: ImportOrderer.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Scans a sequence of import lines. The parsing uses this approximate grammar:
 * <p>
 * <pre>{@code
 * <imports> -> (<end-of-line> | <import>)*
 * <import> -> "import" <whitespace> ("static" <whitespace>)?
 *    <identifier> ("." <identifier>)* ("." "*")? <whitespace>? ";"
 *    <whitespace>? <line-comment>? <end-of-line>
 * }</pre>
 *
 * @param i the index to start parsing at.
 * @return the result of parsing the imports.
 * @throws FormatterException if imports could not parsed according to the grammar.
 */
private ImportsAndIndex scanImports(int i) throws FormatterException {
    int afterLastImport = i;
    ImmutableSortedSet.Builder<Import> imports = ImmutableSortedSet.naturalOrder();
    // JavaInput.buildToks appends a zero-width EOF token after all tokens. It won't match any
    // of our tests here and protects us from running off the end of the toks list. Since it is
    // zero-width it doesn't matter if we include it in our string concatenation at the end.
    while (i < toks.size() && tokenAt(i).equals("import")) {
        i++;
        if (isSpaceToken(i)) {
            i++;
        }
        boolean isStatic = tokenAt(i).equals("static");
        if (isStatic) {
            i++;
            if (isSpaceToken(i)) {
                i++;
            }
        }
        if (!isIdentifierToken(i)) {
            throw new FormatterException("Unexpected token after import: " + tokenAt(i));
        }
        StringAndIndex imported = scanImported(i);
        String importedName = imported.string;
        i = imported.index;
        if (isSpaceToken(i)) {
            i++;
        }
        if (!tokenAt(i).equals(";")) {
            throw new FormatterException("Expected ; after import");
        }
        while (tokenAt(i).equals(";")) {
            // Extra semicolons are not allowed by the JLS but are accepted by javac.
            i++;
        }
        StringBuilder trailing = new StringBuilder();
        if (isSpaceToken(i)) {
            trailing.append(tokenAt(i));
            i++;
        }
        if (isSlashSlashCommentToken(i)) {
            trailing.append(tokenAt(i));
            i++;
        }
        if (!isNewlineToken(i)) {
            throw new FormatterException("Extra tokens after import: " + tokenAt(i));
        }
        trailing.append(tokenAt(i));
        i++;
        imports.add(new Import(importedName, trailing.toString(), isStatic));
        // Remember the position just after the import we just saw, before skipping blank lines.
        // If the next thing after the blank lines is not another import then we don't want to
        // include those blank lines in the text to be replaced.
        afterLastImport = i;
        while (isNewlineToken(i) || isSpaceToken(i)) {
            i++;
        }
    }
    return new ImportsAndIndex(imports.build(), afterLastImport);
}
 
Example 19
Source File: CachingBuildEngineTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test
public void pendingWorkIsCancelledOnFailures() throws Exception {
  String description = "failing step";
  AtomicInteger failedSteps = new AtomicInteger(0);
  Step failingStep =
      new AbstractExecutionStep(description) {
        @Override
        public StepExecutionResult execute(ExecutionContext context) {
          System.out.println("Failing");
          failedSteps.incrementAndGet();
          return StepExecutionResults.ERROR;
        }
      };
  ImmutableSortedSet.Builder<BuildRule> depsBuilder = ImmutableSortedSet.naturalOrder();
  for (int i = 0; i < 20; i++) {
    BuildRule failingDep =
        createRule(
            filesystem,
            graphBuilder,
            /* deps */ ImmutableSortedSet.of(),
            /* buildSteps */ ImmutableList.of(failingStep),
            /* postBuildSteps */ ImmutableList.of(),
            /* pathToOutputFile */ null,
            ImmutableList.of(InternalFlavor.of("failing-" + i)));
    graphBuilder.addToIndex(failingDep);
    depsBuilder.add(failingDep);
  }

  FakeBuildRule withFailingDeps =
      new FakeBuildRule(
          BuildTargetFactory.newInstance("//:with_failing_deps"), depsBuilder.build());

  // Use a CommandThreadManager to closely match the real-world CachingBuildEngine experience.
  // Limit it to 1 thread so that we don't start multiple deps at the same time.
  try (CommandThreadManager threadManager =
      new CommandThreadManager(
          "cachingBuildEngingTest",
          new ConcurrencyLimit(
              1,
              ResourceAllocationFairness.FAIR,
              1,
              ResourceAmounts.of(100, 100, 100, 100),
              ResourceAmounts.of(0, 0, 0, 0)))) {
    CachingBuildEngine cachingBuildEngine =
        cachingBuildEngineFactory()
            .setExecutorService(threadManager.getWeightedListeningExecutorService())
            .build();
    BuildResult result =
        cachingBuildEngine
            .build(buildContext, TestExecutionContext.newInstance(), withFailingDeps)
            .getResult()
            .get();

    assertThat(result.getStatus(), equalTo(BuildRuleStatus.FAIL));
    assertThat(result.getFailure(), instanceOf(BuildRuleFailedException.class));
    Throwable cause = result.getFailure().getCause();
    assertThat(cause, instanceOf(StepFailedException.class));
    assertThat(failedSteps.get(), equalTo(1));
    assertThat(((StepFailedException) cause).getStep().getShortName(), equalTo(description));
  }
}
 
Example 20
Source File: AppleBundleDescriptionTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test
public void depsHaveStripAndDebugFlavorsPropagatedForPlatformDeps() {
  BuildTarget bundleTargetWithStripFlavor =
      BuildTargetFactory.newInstance("//bar:bundle#iphoneos-arm64,strip-all,dwarf-and-dsym");

  BuildTarget unflavoredDep = BuildTargetFactory.newInstance("//bar:dep1");
  BuildTarget unflavoredDepAfterPropagation =
      BuildTargetFactory.newInstance("//bar:dep1#iphoneos-arm64,strip-all,dwarf-and-dsym");

  BuildTarget flavoredDep =
      BuildTargetFactory.newInstance("//bar:dep2#iphoneos-armv7,strip-debug,dwarf");

  BuildTarget flavoredDepNotInDomain = BuildTargetFactory.newInstance("//bar:dep3#otherflavor");
  BuildTarget flavoredDepNotInDomainAfterPropagation =
      BuildTargetFactory.newInstance(
          "//bar:dep3#iphoneos-arm64,strip-all,dwarf-and-dsym,otherflavor");

  BuildTarget stripFlavorOnly = BuildTargetFactory.newInstance("//bar:dep4#strip-debug");
  BuildTarget stripFlavorOnlyAfterPropagation =
      BuildTargetFactory.newInstance("//bar:dep4#iphoneos-arm64,strip-debug,dwarf-and-dsym");

  BuildTarget debugFlavorOnly = BuildTargetFactory.newInstance("//bar:dep5#dwarf");
  BuildTarget debugFlavorOnlyAfterPropagation =
      BuildTargetFactory.newInstance("//bar:dep5#iphoneos-arm64,strip-all,dwarf");

  BuildTarget binary = BuildTargetFactory.newInstance("//bar:binary");

  AppleBundleDescription desc = FakeAppleRuleDescriptions.BUNDLE_DESCRIPTION;
  AppleBundleDescriptionArg constructorArg =
      AppleBundleDescriptionArg.builder()
          .setName("bundle")
          .setExtension(Either.ofLeft(AppleBundleExtension.BUNDLE))
          .setInfoPlist(FakeSourcePath.of("Info.plist"))
          .setPlatformBinary(
              PatternMatchedCollection.<BuildTarget>builder()
                  .add(Pattern.compile("iphoneos-arm64"), binary)
                  .build())
          .setDeps(
              ImmutableSortedSet.<BuildTarget>naturalOrder()
                  .add(binary)
                  .add(unflavoredDep)
                  .add(flavoredDep)
                  .add(flavoredDepNotInDomain)
                  .add(stripFlavorOnly)
                  .add(debugFlavorOnly)
                  .build())
          .build();

  // Now call the find deps methods and verify it returns the targets with flavors.
  ImmutableSortedSet.Builder<BuildTarget> implicitDeps = ImmutableSortedSet.naturalOrder();
  desc.findDepsForTargetFromConstructorArgs(
      bundleTargetWithStripFlavor,
      createCellRoots(filesystem).getCellNameResolver(),
      constructorArg,
      implicitDeps,
      ImmutableSortedSet.naturalOrder());

  assertEquals(
      ImmutableSortedSet.<BuildTarget>naturalOrder()
          .add(unflavoredDepAfterPropagation)
          .add(flavoredDep)
          .add(flavoredDepNotInDomainAfterPropagation)
          .add(stripFlavorOnlyAfterPropagation)
          .add(debugFlavorOnlyAfterPropagation)
          .build(),
      implicitDeps.build());
}