Java Code Examples for com.google.devtools.common.options.OptionsParser#getOptions()

The following examples show how to use com.google.devtools.common.options.OptionsParser#getOptions() . 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_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 2
Source File: Main.java    From bazel with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static Options parseCommandLineOptions(String[] args) throws IOException {
  OptionsParser optionsParser =
      OptionsParser.builder()
          .optionsClasses(Options.class)
          .allowResidue(false)
          .argsPreProcessor(new ShellQuotedParamsFilePreProcessor(FileSystems.getDefault()))
          .build();
  optionsParser.parseAndExitUponError(args);
  Options options = optionsParser.getOptions(Options.class);

  checkArgument(!options.inputJars.isEmpty(), "--input is required");
  checkArgument(!options.bootclasspath.isEmpty(), "--bootclasspath_entry is required");
  // TODO(cushon): make --jdeps_output mandatory
  // checkArgument(
  //     options.jdepsOutput != null, "Invalid value of --jdeps_output: '%s'",
  //     options.jdepsOutput);

  return options;
}
 
Example 3
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 4
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 5
Source File: CommandLineEventTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleStringToolCommandLine() throws OptionsParsingException {
  OptionsParser parser =
      OptionsParser.builder().optionsClasses(CommonCommandOptions.class).build();
  parser.parse("--experimental_tool_command_line=The quick brown fox jumps over the lazy dog");

  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.getCommandLineLabel()).isEqualTo("tool");
  assertThat(line.getSectionsCount()).isEqualTo(1);
  assertThat(line.getSections(0).getSectionTypeCase()).isEqualTo(SectionTypeCase.CHUNK_LIST);
  assertThat(line.getSections(0).getChunkList().getChunk(0))
      .isEqualTo("The quick brown fox jumps over the lazy dog");
}
 
Example 6
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 7
Source File: AllIncompatibleChangesExpansionTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void invocationPolicy() throws OptionsParsingException {
  // Check that all-expansion behaves just like any other expansion flag and can be filtered
  // by invocation policy.
  InvocationPolicy.Builder invocationPolicyBuilder = InvocationPolicy.newBuilder();
  invocationPolicyBuilder.addFlagPoliciesBuilder()
      .setFlagName("incompatible_A")
      .setUseDefault(UseDefault.getDefaultInstance())
      .build();
  InvocationPolicy policy = invocationPolicyBuilder.build();
  InvocationPolicyEnforcer enforcer = new InvocationPolicyEnforcer(policy);

  OptionsParser parser = OptionsParser.builder().optionsClasses(ExampleOptions.class).build();
  parser.parse("--all");
  enforcer.enforce(parser);

  ExampleOptions opts = parser.getOptions(ExampleOptions.class);
  assertThat(opts.x).isFalse();
  assertThat(opts.y).isTrue();
  assertThat(opts.incompatibleA).isFalse(); // A should have been removed from the expansion.
  assertThat(opts.incompatibleB).isTrue(); // B, without a policy, should have been left alone.
}
 
Example 8
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 9
Source File: AllIncompatibleChangesExpansionTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void allChangesSelected() throws OptionsParsingException {
  OptionsParser parser = OptionsParser.builder().optionsClasses(ExampleOptions.class).build();
  parser.parse("--all");
  ExampleOptions opts = parser.getOptions(ExampleOptions.class);
  assertThat(opts.x).isFalse();
  assertThat(opts.y).isTrue();
  assertThat(opts.incompatibleA).isTrue();
  assertThat(opts.incompatibleB).isTrue();
  assertThat(opts.incompatibleC).isTrue();
}
 
Example 10
Source File: CommandLineEventTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testParsingOfCompiledToolCommandLine() throws OptionsParsingException {
  OptionsParser parser =
      OptionsParser.builder().optionsClasses(CommonCommandOptions.class).build();
  CommandLine original =
      CommandLine.newBuilder()
          .setCommandLineLabel("something meaningful")
          .addSections(
              CommandLineSection.newBuilder()
                  .setSectionLabel("command")
                  .setChunkList(ChunkList.newBuilder().addChunk("aCommand")))
          .addSections(
              CommandLineSection.newBuilder()
                  .setSectionLabel("someArguments")
                  .setChunkList(ChunkList.newBuilder().addChunk("arg1").addChunk("arg2")))
          .addSections(
              CommandLineSection.newBuilder()
                  .setSectionLabel("someOptions")
                  .setOptionList(OptionList.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.getCommandLineLabel()).isEqualTo("something meaningful");
  assertThat(line.getSectionsCount()).isEqualTo(3);
  assertThat(line.getSections(0).getSectionTypeCase()).isEqualTo(SectionTypeCase.CHUNK_LIST);
  assertThat(line.getSections(0).getChunkList().getChunkCount()).isEqualTo(1);
  assertThat(line.getSections(0).getChunkList().getChunk(0)).isEqualTo("aCommand");
  assertThat(line.getSections(1).getSectionTypeCase()).isEqualTo(SectionTypeCase.CHUNK_LIST);
  assertThat(line.getSections(1).getChunkList().getChunkCount()).isEqualTo(2);
  assertThat(line.getSections(1).getChunkList().getChunk(0)).isEqualTo("arg1");
  assertThat(line.getSections(1).getChunkList().getChunk(1)).isEqualTo("arg2");
  assertThat(line.getSections(2).getSectionTypeCase()).isEqualTo(SectionTypeCase.OPTION_LIST);
  assertThat(line.getSections(2).getOptionList().getOptionCount()).isEqualTo(0);
}
 
Example 11
Source File: AarGeneratorActionTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test public void testCheckFlags_MissingMultiple() throws IOException, OptionsParsingException {
  Path manifest = tempDir.resolve("AndroidManifest.xml");
  Files.createFile(manifest);
  String[] args = new String[] {"--manifest", manifest.toString()};
  OptionsParser optionsParser =
      OptionsParser.builder().optionsClasses(AarGeneratorOptions.class).build();
  optionsParser.parse(args);
  AarGeneratorOptions options = optionsParser.getOptions(AarGeneratorOptions.class);
  thrown.expect(IllegalArgumentException.class);
  thrown.expectMessage("rtxt, classes must be specified. Building an .aar without"
        + " rtxt, classes is unsupported.");
  AarGeneratorAction.checkFlags(options);
}
 
Example 12
Source File: DesugarOptions.java    From bazel with Apache License 2.0 5 votes vote down vote up
public static DesugarOptions parseCommandLineOptions(String[] args) {
  OptionsParser parser =
      OptionsParser.builder()
          .optionsClasses(DesugarOptions.class)
          .allowResidue(false)
          .argsPreProcessor(new ShellQuotedParamsFilePreProcessor(FileSystems.getDefault()))
          .build();
  parser.parseAndExitUponError(args);
  DesugarOptions options = parser.getOptions(DesugarOptions.class);

  return options;
}
 
Example 13
Source File: ApiExporter.java    From bazel with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
  OptionsParser parser =
      OptionsParser.builder().optionsClasses(BuildEncyclopediaOptions.class).build();
  parser.parseAndExitUponError(args);
  BuildEncyclopediaOptions options = parser.getOptions(BuildEncyclopediaOptions.class);

  if (options.help) {
    printUsage(parser);
    Runtime.getRuntime().exit(0);
  }

  if (options.productName.isEmpty()
      || options.inputDirs.isEmpty()
      || options.provider.isEmpty()
      || options.outputFile.isEmpty()) {
    printUsage(parser);
    Runtime.getRuntime().exit(1);
  }

  try {
    SymbolFamilies symbols =
        new SymbolFamilies(
            options.productName, options.provider, options.inputDirs, options.blacklist);
    Builtins.Builder builtins = Builtins.newBuilder();

    appendTypes(builtins, symbols.getTypes(), symbols.getNativeRules());
    appendGlobals(builtins, symbols.getGlobals());
    appendBzlGlobals(builtins, symbols.getBzlGlobals());
    appendNativeRules(builtins, symbols.getNativeRules());
    writeBuiltins(options.outputFile, builtins);

  } catch (Throwable e) {
    System.err.println("ERROR: " + e.getMessage());
    e.printStackTrace();
  }
}
 
Example 14
Source File: Desugar.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static DesugarOptions parseCommandLineOptions(String[] args) {
  OptionsParser parser =
      OptionsParser.builder()
          .optionsClasses(DesugarOptions.class)
          .allowResidue(false)
          .argsPreProcessor(new ShellQuotedParamsFilePreProcessor(FileSystems.getDefault()))
          .build();
  parser.parseAndExitUponError(args);
  DesugarOptions options = parser.getOptions(DesugarOptions.class);

  return options;
}
 
Example 15
Source File: AllIncompatibleChangesExpansionTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void expansionOptions() throws OptionsParsingException {
  // Check that all-expansion behaves just like any other expansion flag:
  // the rightmost setting of any individual option wins.
  OptionsParser parser =
      OptionsParser.builder()
          .optionsClasses(ExampleOptions.class, ExampleExpansionOptions.class)
          .build();
  parser.parse("--all");
  ExampleOptions opts = parser.getOptions(ExampleOptions.class);
  assertThat(opts.x).isTrue();
  assertThat(opts.y).isFalse();
  assertThat(opts.incompatibleA).isTrue();
  assertThat(opts.incompatibleB).isTrue();
}
 
Example 16
Source File: CompileLibraryResourcesAction.java    From bazel with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
  OptionsParser optionsParser =
      OptionsParser.builder()
          .optionsClasses(
              Options.class, Aapt2ConfigOptions.class, ResourceProcessorCommonOptions.class)
          .argsPreProcessor(new ShellQuotedParamsFilePreProcessor(FileSystems.getDefault()))
          .build();
  optionsParser.parseAndExitUponError(args);

  Options options = optionsParser.getOptions(Options.class);
  Aapt2ConfigOptions aapt2Options = optionsParser.getOptions(Aapt2ConfigOptions.class);

  Preconditions.checkNotNull(options.resources);
  Preconditions.checkNotNull(options.output);
  Preconditions.checkNotNull(aapt2Options.aapt2);

  try (ExecutorServiceCloser executorService = ExecutorServiceCloser.createWithFixedPoolOf(15);
      ScopedTemporaryDirectory scopedTmp =
          new ScopedTemporaryDirectory("android_resources_tmp")) {
    final Path tmp = scopedTmp.getPath();
    final Path databindingResourcesRoot =
        Files.createDirectories(tmp.resolve("android_data_binding_resources"));
    final Path compiledResources = Files.createDirectories(tmp.resolve("compiled"));

    final ResourceCompiler compiler =
        ResourceCompiler.create(
            executorService,
            compiledResources,
            aapt2Options.aapt2,
            aapt2Options.buildToolsVersion,
            aapt2Options.generatePseudoLocale);
    options
        .resources
        .toData(options.manifest)
        .processDataBindings(
            options.dataBindingInfoOut, options.packagePath, databindingResourcesRoot)
        .compile(compiler, compiledResources)
        .copyResourcesZipTo(options.output);
  } catch (IOException | ExecutionException | InterruptedException e) {
    logger.log(java.util.logging.Level.SEVERE, "Unexpected", e);
    throw e;
  }
}
 
Example 17
Source File: Tool.java    From smartcheck with GNU General Public License v3.0 4 votes vote down vote up
/**
 * @param args args
 * @throws Exception exception
 */
public static void main(final String[] args) throws Exception {
    OptionsParser parser = OptionsParser.newOptionsParser(CliOptions.class);
    parser.parseAndExitUponError(args);

    CliOptions options = parser.getOptions(CliOptions.class);

    if (options.help) {
        printUsage(parser);
        System.exit(0);
}

    if (options.version) {
        System.out.println("SmartCheck, version 2.1");
        System.exit(0);
    }

    Path src = Paths.get(options.path);
    if (!Files.exists(src)) {
        System.err.println("Path not exists");
        printUsage(parser);
        System.exit(1);
    }

    Function<SourceLanguage, RulesXml.Source> defaultRules =
            sourceLanguage -> () -> {
        String rulesFileName = sourceLanguage.rulesFileName();
        URI uri = RulesXml
                .class
                .getResource(rulesFileName)
                .toURI();
        try {
            // initialize a new ZipFilesystem
            HashMap<String, String> env = new HashMap<>();
            env.put("create", "true");
            FileSystems.newFileSystem(uri, env);
        } catch (FileSystemAlreadyExistsException ex) {
            // great!
            // appease PMD
            int p = 0;
        }

        return Paths.get(uri);
    };

    Function<SourceLanguage, RulesXml.Source> rules =
            options.rules.stream()
            .map(Paths::get)
            .filter(Files::isRegularFile)
            .<Function<SourceLanguage, RulesXml.Source>>
                    map(path -> language -> () -> path)
            .findAny().orElse(defaultRules);

    new Tool(src, rules).run();
}
 
Example 18
Source File: DexMapper.java    From bazel with Apache License 2.0 4 votes vote down vote up
/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

  OptionsParser parser =
      OptionsParser.builder()
          .optionsClasses(DexMapperOptions.class)
          .allowResidue(true)
          .argsPreProcessor(new ShellQuotedParamsFilePreProcessor(FileSystems.getDefault()))
          .build();
  parser.parseAndExitUponError(args);
  DexMapperOptions options = parser.getOptions(DexMapperOptions.class);

  List<String> inputs = options.inputJars;
  List<String> outputs = options.outputJars;
  String filterFile = options.mainDexFilter;
  String resourceFile = options.outputResources;

  try {
    // Always drop desugaring metadata, which we check elsewhere and don't want in final APKs
    // (see b/65645388).
    Predicate<String> inputFilter = Predicates.not(Predicates.equalTo("META-INF/desugar_deps"));
    if (options.inclusionFilterJar != null) {
      inputFilter =
          Predicates.and(inputFilter, SplitZipFilters.entriesIn(options.inclusionFilterJar));
    }
    new SplitZip()
        .setVerbose(false)
        .useDefaultEntryDate()
        .setSplitDexedClasses(options.splitDexedClasses)
        .addInputs(inputs)
        .addOutputs(outputs)
        .setInputFilter(inputFilter)
        .setMainClassListFile(filterFile)
        .setResourceFile(resourceFile)
        .run()
        .close();
  } catch (Exception ex) {
      System.err.println("Caught exception" + ex.getMessage());
      ex.printStackTrace(System.out);
      System.exit(1);
  }
}
 
Example 19
Source File: BuildViewTestCase.java    From bazel with Apache License 2.0 4 votes vote down vote up
private static PackageOptions parsePackageOptions(String... options) throws Exception {
  OptionsParser parser = OptionsParser.builder().optionsClasses(PackageOptions.class).build();
  parser.parse("--default_visibility=public");
  parser.parse(options);
  return parser.getOptions(PackageOptions.class);
}
 
Example 20
Source File: ExampleWorkerMultiplexer.java    From bazel with Apache License 2.0 4 votes vote down vote up
private static void runPersistentWorker(ExampleWorkerMultiplexerOptions workerOptions)
    throws IOException, ExecutionException, InterruptedException {
  PrintStream originalStdOut = System.out;
  PrintStream originalStdErr = System.err;

  ExecutorService executorService = Executors.newFixedThreadPool(CONCURRENT_THREAD_NUMBER);
  List<Future<?>> results = new ArrayList<>();

  while (true) {
    try {
      WorkRequest request = WorkRequest.parseDelimitedFrom(System.in);
      int requestId = request.getRequestId();
      if (request == null) {
        break;
      }

      inputs.clear();
      for (Input input : request.getInputsList()) {
        inputs.put(input.getPath(), input.getDigest().toStringUtf8());
      }

      // If true, returns corrupt responses instead of correct protobufs.
      boolean poisoned = false;
      if (workerOptions.poisonAfter > 0 && workUnitCounter > workerOptions.poisonAfter) {
        poisoned = true;
      }

      if (poisoned && workerOptions.hardPoison) {
        System.err.println("I'm a very poisoned worker and will just crash.");
        System.exit(1);
      } else {
        int exitCode = 0;
        try {
          OptionsParser parser = parserHelper(request.getArgumentsList());
          ExampleWorkMultiplexerOptions options =
              parser.getOptions(ExampleWorkMultiplexerOptions.class);
          if (options.writeCounter) {
            counterOutput = workUnitCounter++;
          }
          results.add(
              executorService.submit(
                  createTask(originalStdOut, originalStdErr, requestId, parser, poisoned)));
        } catch (Exception e) {
          e.printStackTrace();
          exitCode = 1;
          WorkResponse.newBuilder()
              .setRequestId(requestId)
              .setOutput(new ByteArrayOutputStream().toString())
              .setExitCode(exitCode)
              .build()
              .writeDelimitedTo(System.out);
        }
      }

      if (workerOptions.exitAfter > 0 && workUnitCounter > workerOptions.exitAfter) {
        System.in.close();
      }
    } finally {
      // Be a good worker process and consume less memory when idle.
      System.gc();
    }
  }

  for (Future<?> result : results) {
    result.get();
  }
}