com.google.devtools.common.options.OptionsParser Java Examples

The following examples show how to use com.google.devtools.common.options.OptionsParser. 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: AarGeneratorActionTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test public void testCheckFlags() throws IOException, OptionsParsingException {
  Path manifest = tempDir.resolve("AndroidManifest.xml");
  Files.createFile(manifest);
  Path rtxt = tempDir.resolve("R.txt");
  Files.createFile(rtxt);
  Path classes = tempDir.resolve("classes.jar");
  Files.createFile(classes);

  String[] args = new String[] {"--manifest", manifest.toString(), "--rtxt", rtxt.toString(),
      "--classes", classes.toString()};
  OptionsParser optionsParser =
      OptionsParser.builder().optionsClasses(AarGeneratorOptions.class).build();
  optionsParser.parse(args);
  AarGeneratorOptions options = optionsParser.getOptions(AarGeneratorOptions.class);
  AarGeneratorAction.checkFlags(options);
}
 
Example #2
Source File: AndroidResourceParsingAction.java    From bazel with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  OptionsParser optionsParser =
      OptionsParser.builder()
          .optionsClasses(Options.class, ResourceProcessorCommonOptions.class)
          .argsPreProcessor(new ShellQuotedParamsFilePreProcessor(FileSystems.getDefault()))
          .build();
  optionsParser.parseAndExitUponError(args);
  Options options = optionsParser.getOptions(Options.class);

  Preconditions.checkNotNull(options.primaryData);
  Preconditions.checkNotNull(options.output);

  final Stopwatch timer = Stopwatch.createStarted();
  ParsedAndroidData parsedPrimary = ParsedAndroidData.from(options.primaryData);
  logger.fine(String.format("Walked XML tree at %dms", timer.elapsed(TimeUnit.MILLISECONDS)));
  UnwrittenMergedAndroidData unwrittenData =
      UnwrittenMergedAndroidData.of(
          null, parsedPrimary, ParsedAndroidData.from(ImmutableList.<DependencyAndroidData>of()));
  AndroidDataSerializer serializer = AndroidDataSerializer.create();
  unwrittenData.serializeTo(serializer);
  serializer.flushTo(options.output);
  logger.fine(
      String.format("Finished parse + serialize in %dms", timer.elapsed(TimeUnit.MILLISECONDS)));
}
 
Example #3
Source File: DexBuilder.java    From bazel with Apache License 2.0 6 votes vote down vote up
private static void processRequest(
    ExecutorService executor,
    Cache<DexingKey, byte[]> dexCache,
    DxContext context,
    List<String> args)
    throws OptionsParsingException, IOException, InterruptedException, ExecutionException {
  OptionsParser optionsParser =
      OptionsParser.builder()
          .optionsClasses(Options.class, DexingOptions.class)
          .allowResidue(false)
          .build();
  optionsParser.parse(args);
  Options options = optionsParser.getOptions(Options.class);
  try (ZipFile in = new ZipFile(options.inputJar.toFile());
      ZipOutputStream out = createZipOutputStream(options.outputZip)) {
    produceDexArchive(
        in,
        out,
        executor,
        /*convertOnReaderThread*/ false,
        new Dexing(context, optionsParser.getOptions(DexingOptions.class)),
        dexCache);
  }
}
 
Example #4
Source File: BuildOptionsTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void parsingResultTransform() throws Exception {
  BuildOptions original = BuildOptions.of(BUILD_CONFIG_OPTIONS, "--cpu=foo", "--stamp");

  OptionsParser parser = OptionsParser.builder().optionsClasses(BUILD_CONFIG_OPTIONS).build();
  parser.parse("--cpu=bar", "--nostamp");
  parser.setStarlarkOptions(ImmutableMap.of("//custom:flag", "hello"));

  BuildOptions modified = original.applyParsingResult(parser);

  assertThat(original.get(CoreOptions.class).cpu)
      .isNotEqualTo(modified.get(CoreOptions.class).cpu);
  assertThat(modified.get(CoreOptions.class).cpu).isEqualTo("bar");
  assertThat(modified.get(CoreOptions.class).stampBinaries).isFalse();
  assertThat(modified.getStarlarkOptions().get(Label.parseAbsoluteUnchecked("//custom:flag")))
      .isEqualTo("hello");
}
 
Example #5
Source File: BlazeRuntime.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Parses the command line arguments into a {@link OptionsParser} object.
 *
 * <p>This function needs to parse the --option_sources option manually so that the real option
 * parser can set the source for every option correctly. If that cannot be parsed or is missing,
 * we just report an unknown source for every startup option.
 */
private static OptionsParsingResult parseStartupOptions(
    Iterable<BlazeModule> modules, List<String> args) throws OptionsParsingException {
  ImmutableList<Class<? extends OptionsBase>> optionClasses =
      BlazeCommandUtils.getStartupOptions(modules);

  // First parse the command line so that we get the option_sources argument
  OptionsParser parser =
      OptionsParser.builder().optionsClasses(optionClasses).allowResidue(false).build();
  parser.parse(PriorityCategory.COMMAND_LINE, null, args);
  Map<String, String> optionSources =
      parser.getOptions(BlazeServerStartupOptions.class).optionSources;
  Function<OptionDefinition, String> sourceFunction =
      option ->
          !optionSources.containsKey(option.getOptionName())
              ? "default"
              : optionSources.get(option.getOptionName()).isEmpty()
                  ? "command line"
                  : optionSources.get(option.getOptionName());

  // Then parse the command line again, this time with the correct option sources
  parser = OptionsParser.builder().optionsClasses(optionClasses).allowResidue(false).build();
  parser.parseWithSourceFunction(PriorityCategory.COMMAND_LINE, sourceFunction, args);
  return parser;
}
 
Example #6
Source File: ConfigurationTestCase.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Variation of {@link #createCollection(String...)} that also supports Starlark-defined options.
 *
 * @param starlarkOptions map of Starlark-defined options where the keys are option names (in the
 *     form of label-like strings) and the values are option values
 * @param args native option name/pair descriptions in command line form (e.g. "--cpu=k8")
 */
protected BuildConfigurationCollection createCollection(
    ImmutableMap<String, Object> starlarkOptions, String... args) throws Exception {
  OptionsParser parser =
      OptionsParser.builder()
          .optionsClasses(
              ImmutableList.<Class<? extends OptionsBase>>builder()
                  .addAll(buildOptionClasses)
                  .add(TestOptions.class)
                  .build())
          .build();
  parser.setStarlarkOptions(starlarkOptions);
  parser.parse(TestConstants.PRODUCT_SPECIFIC_FLAGS);
  parser.parse(args);

  ImmutableSortedSet<String> multiCpu = ImmutableSortedSet.copyOf(
      parser.getOptions(TestOptions.class).multiCpus);

  skyframeExecutor.handleDiffsForTesting(reporter);
  BuildConfigurationCollection collection = skyframeExecutor.createConfigurations(
      reporter, BuildOptions.of(buildOptionClasses, parser), multiCpu, false);
  return collection;
}
 
Example #7
Source File: ConfigCommand.java    From bazel with Apache License 2.0 6 votes vote down vote up
private static Map<String, Pair<Object, Object>> diffOptions(
    Class<? extends FragmentOptions> fragment,
    @Nullable FragmentOptions options1,
    @Nullable FragmentOptions options2) {
  Map<String, Pair<Object, Object>> diffs = new HashMap<>();

  for (OptionDefinition option : OptionsParser.getOptionDefinitions(fragment)) {
    Object value1 = options1 == null ? null : options1.getValueFromDefinition(option);
    Object value2 = options2 == null ? null : options2.getValueFromDefinition(option);

    if (!Objects.equals(value1, value2)) {
      diffs.put(option.getOptionName(), Pair.of(value1, value2));
    }
  }

  return diffs;
}
 
Example #8
Source File: ExampleWorkerMultiplexer.java    From bazel with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  if (ImmutableSet.copyOf(args).contains("--persistent_worker")) {
    OptionsParser parser =
        OptionsParser.builder()
            .optionsClasses(ExampleWorkerMultiplexerOptions.class)
            .allowResidue(false)
            .build();
    parser.parse(args);
    ExampleWorkerMultiplexerOptions workerOptions =
        parser.getOptions(ExampleWorkerMultiplexerOptions.class);
    Preconditions.checkState(workerOptions.persistentWorker);

    runPersistentWorker(workerOptions);
  } else {
    // This is a single invocation of the example that exits after it processed the request.
    processRequest(parserHelper(ImmutableList.copyOf(args)));
  }
}
 
Example #9
Source File: ExampleWorker.java    From bazel with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  if (ImmutableSet.copyOf(args).contains("--persistent_worker")) {
    OptionsParser parser =
        OptionsParser.builder()
            .optionsClasses(ExampleWorkerOptions.class)
            .allowResidue(false)
            .build();
    parser.parse(args);
    ExampleWorkerOptions workerOptions = parser.getOptions(ExampleWorkerOptions.class);
    Preconditions.checkState(workerOptions.persistentWorker);

    runPersistentWorker(workerOptions);
  } else {
    // This is a single invocation of the example that exits after it processed the request.
    processRequest(ImmutableList.copyOf(args));
  }
}
 
Example #10
Source File: AarGeneratorActionTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test public void testCheckFlags_MissingClasses() throws IOException, OptionsParsingException {
  Path manifest = tempDir.resolve("AndroidManifest.xml");
  Files.createFile(manifest);
  Path rtxt = tempDir.resolve("R.txt");
  Files.createFile(rtxt);

  String[] args = new String[] {"--manifest", manifest.toString(), "--rtxt", rtxt.toString()};
  OptionsParser optionsParser =
      OptionsParser.builder().optionsClasses(AarGeneratorOptions.class).build();
  optionsParser.parse(args);
  AarGeneratorOptions options = optionsParser.getOptions(AarGeneratorOptions.class);
  thrown.expect(IllegalArgumentException.class);
  thrown.expectMessage("classes must be specified. Building an .aar without"
        + " classes is unsupported.");
  AarGeneratorAction.checkFlags(options);
}
 
Example #11
Source File: BlazeCommandUtils.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * The help page for this command.
 *
 * @param verbosity a tri-state verbosity option selecting between just names, names and syntax,
 *     and full description.
 */
public static String getUsage(
    Class<? extends BlazeCommand> commandClass,
    OptionsParser.HelpVerbosity verbosity,
    Iterable<BlazeModule> blazeModules,
    ConfiguredRuleClassProvider ruleClassProvider,
    String productName) {
  Command commandAnnotation = commandClass.getAnnotation(Command.class);
  return BlazeCommandUtils.expandHelpTopic(
      commandAnnotation.name(),
      commandAnnotation.help(),
      commandClass,
      BlazeCommandUtils.getOptions(commandClass, blazeModules, ruleClassProvider),
      verbosity,
      productName);
}
 
Example #12
Source File: StarlarkOptionsParser.java    From bazel with Apache License 2.0 6 votes vote down vote up
private Target loadBuildSetting(
    String targetToBuild, OptionsParser optionsParser, ExtendedEventHandler eventHandler)
    throws OptionsParsingException {
  Target buildSetting;
  try {
    TargetPatternPhaseValue result =
        skyframeExecutor.loadTargetPatternsWithoutFilters(
            reporter,
            Collections.singletonList(targetToBuild),
            relativeWorkingDirectory,
            SkyframeExecutor.DEFAULT_THREAD_COUNT,
            optionsParser.getOptions(KeepGoingOption.class).keepGoing);
    buildSetting =
        Iterables.getOnlyElement(
            result.getTargets(eventHandler, skyframeExecutor.getPackageManager()));
  } catch (InterruptedException | TargetParsingException e) {
    Thread.currentThread().interrupt();
    throw new OptionsParsingException(
        "Error loading option " + targetToBuild + ": " + e.getMessage(), targetToBuild, e);
  }
  Rule associatedRule = buildSetting.getAssociatedRule();
  if (associatedRule == null || associatedRule.getRuleClassObject().getBuildSetting() == null) {
    throw new OptionsParsingException("Unrecognized option: " + targetToBuild, targetToBuild);
  }
  return buildSetting;
}
 
Example #13
Source File: StarlarkOptionCommandLineEventTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void testStarlarkOptions_canonical_defaultValue() throws Exception {
  OptionsParser fakeStartupOptions =
      OptionsParser.builder()
          .optionsClasses(BlazeServerStartupOptions.class, Options.class)
          .build();

  writeBasicIntFlag();

  parseStarlarkOptions("--//test:my_int_setting=42");

  CommandLine line =
      new CanonicalCommandLineEvent(
              "testblaze", fakeStartupOptions, "someCommandName", optionsParser)
          .asStreamProto(null)
          .getStructuredCommandLine();
  assertThat(line.getCommandLineLabel()).isEqualTo("canonical");

  // Command options should appear in section 3. See
  // CommandLineEventTest#testOptionsAtVariousPriorities_OriginalCommandLine.
  // Verify that the starlark flag was processed as expected.
  assertThat(line.getSections(3).getOptionList().getOptionCount()).isEqualTo(0);
}
 
Example #14
Source File: CommandLineEventTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void testLabelessParsingOfCompiledToolCommandLine() throws OptionsParsingException {
  OptionsParser parser =
      OptionsParser.builder().optionsClasses(CommonCommandOptions.class).build();
  CommandLine original =
      CommandLine.newBuilder().addSections(CommandLineSection.getDefaultInstance()).build();
  parser.parse(
      "--experimental_tool_command_line=" + BaseEncoding.base64().encode(original.toByteArray()));

  ToolCommandLineEvent event = parser.getOptions(CommonCommandOptions.class).toolCommandLine;
  StructuredCommandLineId id = event.getEventId().getStructuredCommandLine();
  CommandLine line = event.asStreamProto(null).getStructuredCommandLine();

  assertThat(id.getCommandLineLabel()).isEqualTo("tool");
  assertThat(line.getSectionsCount()).isEqualTo(1);
}
 
Example #15
Source File: OptionsUtilsTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void asStringOfExplicitOptionsWithBooleans() throws Exception {
  OptionsParser parser = OptionsParser.builder().optionsClasses(BooleanOpts.class).build();
  parser.parse(PriorityCategory.COMMAND_LINE, null, Arrays.asList("--b_one", "--nob_two"));
  assertThat(OptionsUtils.asShellEscapedString(parser)).isEqualTo("--b_one --nob_two");
  assertThat(OptionsUtils.asArgumentList(parser))
      .containsExactly("--b_one", "--nob_two")
      .inOrder();

  parser = OptionsParser.builder().optionsClasses(BooleanOpts.class).build();
  parser.parse(PriorityCategory.COMMAND_LINE, null, Arrays.asList("--b_one=true", "--b_two=0"));
  assertThat(parser.getOptions(BooleanOpts.class).bOne).isTrue();
  assertThat(parser.getOptions(BooleanOpts.class).bTwo).isFalse();
  assertThat(OptionsUtils.asShellEscapedString(parser)).isEqualTo("--b_one --nob_two");
  assertThat(OptionsUtils.asArgumentList(parser))
      .containsExactly("--b_one", "--nob_two")
      .inOrder();
}
 
Example #16
Source File: CommandLineEventTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void testMostlyEmpty_CanonicalCommandLine() {
  OptionsParser fakeStartupOptions =
      OptionsParser.builder().optionsClasses(BlazeServerStartupOptions.class).build();
  OptionsParser fakeCommandOptions =
      OptionsParser.builder().optionsClasses(TestOptions.class).build();

  CommandLine line =
      new CanonicalCommandLineEvent(
              "testblaze", fakeStartupOptions, "someCommandName", fakeCommandOptions)
          .asStreamProto(null)
          .getStructuredCommandLine();

  assertThat(line).isNotNull();
  assertThat(line.getCommandLineLabel()).isEqualTo("canonical");
  checkCommandLineSectionLabels(line);

  assertThat(line.getSections(0).getChunkList().getChunk(0)).isEqualTo("testblaze");
  assertThat(line.getSections(1).getOptionList().getOptionCount()).isEqualTo(1);
  assertThat(line.getSections(1).getOptionList().getOption(0).getCombinedForm())
      .isEqualTo("--ignore_all_rc_files");
  assertThat(line.getSections(2).getChunkList().getChunk(0)).isEqualTo("someCommandName");
  assertThat(line.getSections(3).getOptionList().getOptionCount()).isEqualTo(0);
  assertThat(line.getSections(4).getChunkList().getChunkCount()).isEqualTo(0);
}
 
Example #17
Source File: HttpProxy.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  // Only log severe log messages from Netty. Otherwise it logs warnings that look like this:
  //
  // 170714 08:16:28.552:WT 18 [io.grpc.netty.NettyServerHandler.onStreamError] Stream Error
  // io.netty.handler.codec.http2.Http2Exception$StreamException: Received DATA frame for an
  // unknown stream 11369
  nettyLogger.setLevel(Level.SEVERE);

  OptionsParser parser =
      OptionsParser.newOptionsParser(HttpProxyOptions.class, AuthAndTLSOptions.class);
  parser.parseAndExitUponError(args);
  List<String> residue = parser.getResidue();
  if (!residue.isEmpty()) {
    printUsage(parser);
    throw new IllegalArgumentException("Unrecognized arguments: " + residue);
  }
  HttpProxyOptions options = parser.getOptions(HttpProxyOptions.class);
  if (options.port < 0) {
    printUsage(parser);
    throw new IllegalArgumentException("invalid port: " + options.port);
  }
  AuthAndTLSOptions authAndTlsOptions = parser.getOptions(AuthAndTLSOptions.class);
  HttpProxy server = new HttpProxy(options, GoogleAuthUtils.newCredentials(authAndTlsOptions));
  server.start();
  server.blockUntilShutdown();
}
 
Example #18
Source File: BuildOptionsTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void parsingResultTransformNativeIgnored() throws Exception {
  ImmutableList.Builder<Class<? extends FragmentOptions>> fragmentClassesBuilder =
      ImmutableList.<Class<? extends FragmentOptions>>builder().add(CoreOptions.class);

  BuildOptions original = BuildOptions.of(fragmentClassesBuilder.build());

  fragmentClassesBuilder.add(CppOptions.class);

  OptionsParser parser =
      OptionsParser.builder().optionsClasses(fragmentClassesBuilder.build()).build();
  parser.parse("--cxxopt=bar");

  BuildOptions modified = original.applyParsingResult(parser);

  assertThat(modified.contains(CppOptions.class)).isFalse();
}
 
Example #19
Source File: BlazeCommandDispatcher.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an option parser using the common options classes and the command-specific options
 * classes.
 *
 * <p>An overriding method should first call this method and can then override default values
 * directly or by calling {@link BlazeOptionHandler#parseOptions} for command-specific options.
 */
private OptionsParser createOptionsParser(BlazeCommand command)
    throws OptionsParser.ConstructionException {
  OpaqueOptionsData optionsData;
  try {
    optionsData = optionsDataCache.getUnchecked(command);
  } catch (UncheckedExecutionException e) {
    Throwables.throwIfInstanceOf(e.getCause(), OptionsParser.ConstructionException.class);
    throw new IllegalStateException(e);
  }
  Command annotation = command.getClass().getAnnotation(Command.class);
  OptionsParser parser =
      OptionsParser.builder()
          .optionsData(optionsData)
          .skipStarlarkOptionPrefixes()
          .allowResidue(annotation.allowResidue())
          .build();
  return parser;
}
 
Example #20
Source File: PackageMetricsModuleTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static CommandEnvironment commandEnv(String... options) throws Exception {
  OptionsParser parser =
      OptionsParser.builder().optionsClasses(PackageMetricsModule.Options.class).build();
  parser.parse(options);

  CommandEnvironment mockEnv = mock(CommandEnvironment.class);
  when(mockEnv.getOptions()).thenReturn(parser);
  return mockEnv;
}
 
Example #21
Source File: StarlarkSemanticsConsistencyTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static StarlarkSemanticsOptions parseOptions(String... args) throws Exception {
  OptionsParser parser =
      OptionsParser.builder()
          .optionsClasses(StarlarkSemanticsOptions.class)
          .allowResidue(false)
          .build();
  parser.parse(Arrays.asList(args));
  return parser.getOptions(StarlarkSemanticsOptions.class);
}
 
Example #22
Source File: BuildOptionsTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void parsingResultTransformMultiValueOption() throws Exception {
  BuildOptions original = BuildOptions.of(BUILD_CONFIG_OPTIONS);

  OptionsParser parser = OptionsParser.builder().optionsClasses(BUILD_CONFIG_OPTIONS).build();
  parser.parse("--features=foo");

  BuildOptions modified = original.applyParsingResult(parser);

  assertThat(modified.get(CoreOptions.class).defaultFeatures).containsExactly("foo");
}
 
Example #23
Source File: CommandLineEventTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testExpansionOption_OriginalCommandLine() throws OptionsParsingException {
  OptionsParser fakeStartupOptions =
      OptionsParser.builder().optionsClasses(BlazeServerStartupOptions.class).build();
  OptionsParser fakeCommandOptions =
      OptionsParser.builder().optionsClasses(TestOptions.class).build();
  fakeCommandOptions.parse(
      PriorityCategory.COMMAND_LINE, "command line", ImmutableList.of("--test_expansion"));

  CommandLine line =
      new OriginalCommandLineEvent(
              "testblaze",
              fakeStartupOptions,
              "someCommandName",
              fakeCommandOptions,
              Optional.of(ImmutableList.of()))
          .asStreamProto(null)
          .getStructuredCommandLine();

  assertThat(line).isNotNull();
  assertThat(line.getCommandLineLabel()).isEqualTo("original");
  checkCommandLineSectionLabels(line);

  assertThat(line.getSections(0).getChunkList().getChunk(0)).isEqualTo("testblaze");
  assertThat(line.getSections(1).getOptionList().getOptionCount()).isEqualTo(0);
  assertThat(line.getSections(2).getChunkList().getChunk(0)).isEqualTo("someCommandName");
  // Expect the rc file option to not be listed with the explicit command line options.
  assertThat(line.getSections(3).getOptionList().getOptionCount()).isEqualTo(1);
  assertThat(line.getSections(3).getOptionList().getOption(0).getCombinedForm())
      .isEqualTo("--test_expansion");
  assertThat(line.getSections(4).getChunkList().getChunkCount()).isEqualTo(0);
}
 
Example #24
Source File: AllIncompatibleChangesExpansionTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void incompatibleChangeTagDoesNotTriggerAllIncompatibleChangesCheck() {
  try {
    OptionsParser.builder()
        .optionsClasses(ExampleOptions.class, IncompatibleChangeTagOption.class)
        .build();
  } catch (OptionsParser.ConstructionException e) {
    fail(
        "some_option_with_a_tag should not trigger the expansion, so there should be no checks "
            + "on it having the right prefix and metadata tags. Instead, the following exception "
            + "was thrown: "
            + e.getMessage());
  }
}
 
Example #25
Source File: DexBuilder.java    From bazel with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  if (args.length == 1 && args[0].startsWith("@")) {
    args = Files.readAllLines(Paths.get(args[0].substring(1)), ISO_8859_1).toArray(new String[0]);
  }

  OptionsParser optionsParser =
      OptionsParser.builder().optionsClasses(Options.class, DexingOptions.class).build();
  optionsParser.parseAndExitUponError(args);
  Options options = optionsParser.getOptions(Options.class);
  if (options.persistentWorker) {
    runPersistentWorker();
  } else {
    buildDexArchive(options, new Dexing(optionsParser.getOptions(DexingOptions.class)));
  }
}
 
Example #26
Source File: CommandLineEventTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testBazelrcs_CanonicalCommandLine() throws OptionsParsingException {
  OptionsParser fakeStartupOptions =
      OptionsParser.builder()
          .optionsClasses(BlazeServerStartupOptions.class, Options.class)
          .build();
  fakeStartupOptions.parse(
      "--bazelrc=/some/path", "--master_bazelrc", "--bazelrc", "/some/other/path");
  OptionsParser fakeCommandOptions =
      OptionsParser.builder().optionsClasses(TestOptions.class).build();

  CommandLine line =
      new CanonicalCommandLineEvent(
              "testblaze", fakeStartupOptions, "someCommandName", fakeCommandOptions)
          .asStreamProto(null)
          .getStructuredCommandLine();

  assertThat(line).isNotNull();
  assertThat(line.getCommandLineLabel()).isEqualTo("canonical");
  checkCommandLineSectionLabels(line);

  // Expect the provided rc-related startup options are removed and replaced with the
  // rc-prevention options.
  assertThat(line.getSections(0).getChunkList().getChunk(0)).isEqualTo("testblaze");
  assertThat(line.getSections(1).getOptionList().getOptionCount()).isEqualTo(1);
  assertThat(line.getSections(1).getOptionList().getOption(0).getCombinedForm())
      .isEqualTo("--ignore_all_rc_files");
  assertThat(line.getSections(2).getChunkList().getChunk(0)).isEqualTo("someCommandName");
  assertThat(line.getSections(3).getOptionList().getOptionCount()).isEqualTo(0);
  assertThat(line.getSections(4).getChunkList().getChunkCount()).isEqualTo(0);
}
 
Example #27
Source File: CommandLineEventTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testOptionWithImplicitRequirement_OriginalCommandLine()
    throws OptionsParsingException {
  OptionsParser fakeStartupOptions =
      OptionsParser.builder().optionsClasses(BlazeServerStartupOptions.class).build();
  OptionsParser fakeCommandOptions =
      OptionsParser.builder().optionsClasses(TestOptions.class).build();
  fakeCommandOptions.parse(
      PriorityCategory.COMMAND_LINE,
      "command line",
      ImmutableList.of("--test_implicit_requirement=foo"));

  CommandLine line =
      new OriginalCommandLineEvent(
              "testblaze",
              fakeStartupOptions,
              "someCommandName",
              fakeCommandOptions,
              Optional.of(ImmutableList.of()))
          .asStreamProto(null)
          .getStructuredCommandLine();

  assertThat(line).isNotNull();
  assertThat(line.getCommandLineLabel()).isEqualTo("original");
  checkCommandLineSectionLabels(line);

  assertThat(line.getSections(0).getChunkList().getChunk(0)).isEqualTo("testblaze");
  assertThat(line.getSections(1).getOptionList().getOptionCount()).isEqualTo(0);
  assertThat(line.getSections(2).getChunkList().getChunk(0)).isEqualTo("someCommandName");
  assertThat(line.getSections(3).getOptionList().getOptionCount()).isEqualTo(1);
  assertThat(line.getSections(3).getOptionList().getOption(0).getCombinedForm())
      .isEqualTo("--test_implicit_requirement=foo");
  assertThat(line.getSections(4).getChunkList().getChunkCount()).isEqualTo(0);
}
 
Example #28
Source File: MobileInstallCommand.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
public void editOptions(OptionsParser optionsParser) {
  Options options = optionsParser.getOptions(Options.class);
  try {
    if (options.mode == Mode.CLASSIC || options.mode == Mode.CLASSIC_INTERNAL_TEST_DO_NOT_USE) {
      String outputGroup =
          options.splitApks
              ? "mobile_install_split" + INTERNAL_SUFFIX
              : options.incremental
                  ? "mobile_install_incremental" + INTERNAL_SUFFIX
                  : "mobile_install_full" + INTERNAL_SUFFIX;
      optionsParser.parse(
          PriorityCategory.COMMAND_LINE,
          "Options required by the mobile-install command",
          ImmutableList.of("--output_groups=" + outputGroup));
    } else {
      optionsParser.parse(
          PriorityCategory.COMMAND_LINE,
          "Options required by the Starlark implementation of mobile-install command",
          ImmutableList.of(
              "--aspects=" + options.mobileInstallAspect + "%MIASPECT",
              "--output_groups=mobile_install" + INTERNAL_SUFFIX,
              "--output_groups=mobile_install_launcher" + INTERNAL_SUFFIX));
    }
  } catch (OptionsParsingException e) {
    throw new IllegalStateException(e);
  }
}
 
Example #29
Source File: StarlarkOptionsParser.java    From bazel with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public static StarlarkOptionsParser newStarlarkOptionsParserForTesting(
    SkyframeExecutor skyframeExecutor,
    Reporter reporter,
    PathFragment relativeWorkingDirectory,
    OptionsParser nativeOptionsParser) {
  return new StarlarkOptionsParser(
      skyframeExecutor, relativeWorkingDirectory, reporter, nativeOptionsParser);
}
 
Example #30
Source File: TransitiveOptionDetailsTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
/** Instantiates the given options classes, parsing the given options as well. */
public Iterable<FragmentOptions> parseOptions(
    Iterable<? extends Class<? extends FragmentOptions>> optionsClasses, String... options)
    throws Exception {
  OptionsParser optionsParser =
      OptionsParser.builder().optionsClasses(optionsClasses).allowResidue(false).build();
  optionsParser.parse(options);
  ImmutableList.Builder<FragmentOptions> output = new ImmutableList.Builder<>();
  for (Class<? extends FragmentOptions> optionsClass : optionsClasses) {
    output.add(optionsParser.getOptions(optionsClass));
  }
  return output.build();
}