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

The following examples show how to use com.google.devtools.common.options.OptionsParser#parseAndExitUponError() . 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: 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 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: LazyZoneRulesCompiler.java    From lazythreetenbp with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    OptionsParser parser = OptionsParser.newOptionsParser(CompilerOptions.class);
    parser.parseAndExitUponError(args);
    CompilerOptions options = parser.getOptions(CompilerOptions.class);
    if (options != null && options.validate()) {
        new LazyZoneRulesCompiler(options).run();
    }
}
 
Example 4
Source File: Aapt2OptimizeAction.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static List<String> buildCommand(String... args) {
  OptionsParser optionsParser =
      OptionsParser.builder()
          .optionsClasses(Aapt2ConfigOptions.class, ResourceProcessorCommonOptions.class)
          .argsPreProcessor(new ShellQuotedParamsFilePreProcessor(FileSystems.getDefault()))
          .allowResidue(true)
          .build();
  optionsParser.parseAndExitUponError(args);

  return ImmutableList.<String>builder()
      .add(optionsParser.getOptions(Aapt2ConfigOptions.class).aapt2.toString())
      .add("optimize")
      .addAll(optionsParser.getResidue())
      .build();
}
 
Example 5
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 6
Source File: KeepScanner.java    From bazel with Apache License 2.0 5 votes vote down vote up
public static void main(String... args) throws Exception {
  OptionsParser parser =
      OptionsParser.builder()
          .optionsClasses(KeepScannerOptions.class)
          .allowResidue(false)
          .argsPreProcessor(new ShellQuotedParamsFilePreProcessor(FileSystems.getDefault()))
          .build();
  parser.parseAndExitUponError(args);
  KeepScannerOptions options = parser.getOptions(KeepScannerOptions.class);

  Map<String, ImmutableSet<KeepReference>> seeds;
  try (Closer closer = Closer.create()) {
    // TODO(kmb): Try to share more of this code with Desugar binary
    IndexedInputs classpath =
        new IndexedInputs(toRegisteredInputFileProvider(closer, options.classpath));
    IndexedInputs bootclasspath =
        new IndexedInputs(toRegisteredInputFileProvider(closer, options.bootclasspath));

    // Construct classloader from classpath.  Since we're assuming the prefix we're looking for
    // isn't part of the input itself we shouldn't need to include the input in the classloader.
    CoreLibraryRewriter noopRewriter = new CoreLibraryRewriter("");
    ClassLoader classloader =
        new HeaderClassLoader(
            classpath,
            noopRewriter,
            new HeaderClassLoader(bootclasspath, noopRewriter, new ThrowingClassLoader()));
    seeds = scan(checkNotNull(options.inputJars), options.prefix, classloader);
  }

  try (PrintStream out =
      new PrintStream(
          Files.newOutputStream(options.keepDest, CREATE), /*autoFlush=*/ false, "UTF-8")) {
    writeKeepDirectives(out, seeds);
  }
}
 
Example 7
Source File: DexFileMerger.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static Options parseArguments(String[] args) throws IOException {
  OptionsParser optionsParser =
      OptionsParser.builder()
          .optionsClasses(Options.class)
          .argsPreProcessor(new ShellQuotedParamsFilePreProcessor(FileSystems.getDefault()))
          .build();
  optionsParser.parseAndExitUponError(args);

  return optionsParser.getOptions(Options.class);
}
 
Example 8
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 9
Source File: DexFileMerger.java    From bazel with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  OptionsParser optionsParser =
      OptionsParser.builder()
          .optionsClasses(Options.class)
          .argsPreProcessor(new ShellQuotedParamsFilePreProcessor(FileSystems.getDefault()))
          .build();
  optionsParser.parseAndExitUponError(args);

  buildMergedDexFiles(optionsParser.getOptions(Options.class));
}
 
Example 10
Source File: DexFileSplitter.java    From bazel with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  OptionsParser optionsParser =
      OptionsParser.builder()
          .optionsClasses(Options.class)
          .allowResidue(false)
          .argsPreProcessor(new ShellQuotedParamsFilePreProcessor(FileSystems.getDefault()))
          .build();
  optionsParser.parseAndExitUponError(args);

  splitIntoShards(optionsParser.getOptions(Options.class));
}
 
Example 11
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 12
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 13
Source File: Worker.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
public static void startWorker(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(SEVERE);

  OptionsParser parser = OptionsParser.newOptionsParser(WorkerOptions.class);
  parser.parseAndExitUponError(args);
  List<String> residue = parser.getResidue();
  if (residue.isEmpty()) {
    printUsage(parser);
    throw new IllegalArgumentException("Missing CONFIG_PATH");
  }
  Path configPath = Paths.get(residue.get(0));
  String session = UUID.randomUUID().toString();
  Worker worker;
  try (InputStream configInputStream = Files.newInputStream(configPath)) {
    worker =
        new Worker(
            session,
            toShardWorkerConfig(
                new InputStreamReader(configInputStream),
                parser.getOptions(WorkerOptions.class)));
  }
  worker.start();
  worker.blockUntilShutdown();
  System.exit(0); // bullet to the head in case anything is stuck
}
 
Example 14
Source File: CompatDx.java    From bazel with Apache License 2.0 4 votes vote down vote up
public static DxCompatOptions parse(String[] args) {
  OptionsParser optionsParser = OptionsParser.builder().optionsClasses(Options.class).build();
  optionsParser.parseAndExitUponError(args);
  Options options = optionsParser.getOptions(Options.class);
  return new DxCompatOptions(options, optionsParser.getResidue());
}
 
Example 15
Source File: AndroidDataBindingProcessingAction.java    From bazel with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws IOException {

    OptionsParser optionsParser =
        OptionsParser.builder()
            .allowResidue(true)
            .optionsClasses(
                Options.class, AaptConfigOptions.class, ResourceProcessorCommonOptions.class)
            .argsPreProcessor(new ShellQuotedParamsFilePreProcessor(FileSystems.getDefault()))
            .build();
    optionsParser.parseAndExitUponError(args);
    Options options = optionsParser.getOptions(Options.class);

    if (options.dataBindingInfoOut == null) {
      throw new IllegalArgumentException("--dataBindingInfoOut is required");
    }

    if (options.appId == null) {
      throw new IllegalArgumentException("--appId is required");
    }

    if (options.outputResourceDirectory == null) {
      throw new IllegalArgumentException("--output_resource_directory is required");
    }

    List<Path> resourceRoots = options.resourceRoots == null
        ? Collections.emptyList()
        : options.resourceRoots;

    try (ScopedTemporaryDirectory dataBindingInfoOutDir =
        new ScopedTemporaryDirectory("android_data_binding_layout_info_tmp")) {

      // 1. Process databinding resources for each source root.
      for (Path resourceRoot : resourceRoots) {

        AndroidResourceProcessor.processDataBindings(
            options.outputResourceDirectory,
            resourceRoot,
            dataBindingInfoOutDir.getPath(),
            options.appId,
            /* shouldZipDataBindingInfo= */ false);
      }

      // 2. Zip all the layout info files into one zip file.
      try (ZipOutputStream layoutInfoZip =
            new ZipOutputStream(Files.newOutputStream(options.dataBindingInfoOut));
          Stream<Path> layoutInfos = Files.list(dataBindingInfoOutDir.getPath())) {

        for (Path layoutInfo : (Iterable<Path>) layoutInfos::iterator) {
          ZipEntry zipEntry = new ZipEntry(layoutInfo.getFileName().toString());
          layoutInfoZip.putNextEntry(zipEntry);
          Files.copy(layoutInfo, layoutInfoZip);
          layoutInfoZip.closeEntry();
        }
      }
    }
  }
 
Example 16
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 17
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 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: ResourceShrinkerAction.java    From bazel with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
  final Stopwatch timer = Stopwatch.createStarted();
  // Parse arguments.
  OptionsParser optionsParser =
      OptionsParser.builder()
          .optionsClasses(Options.class, AaptConfigOptions.class)
          .argsPreProcessor(new ShellQuotedParamsFilePreProcessor(FileSystems.getDefault()))
          .build();
  optionsParser.parseAndExitUponError(args);
  aaptConfigOptions = optionsParser.getOptions(AaptConfigOptions.class);
  options = optionsParser.getOptions(Options.class);

  AndroidResourceProcessor resourceProcessor = new AndroidResourceProcessor(stdLogger);
  // Setup temporary working directories.
  try (ScopedTemporaryDirectory scopedTmp =
      new ScopedTemporaryDirectory("resource_shrinker_tmp")) {
    Path working = scopedTmp.getPath();
    final Path resourceFiles = working.resolve("resource_files");

    final Path shrunkResources = working.resolve("shrunk_resources");

    // Gather package list from manifests.
    Set<String> resourcePackages =
        getManifestPackages(options.primaryManifest, options.dependencyManifests);
    resourcePackages.addAll(options.resourcePackages);

    // Expand resource files zip into working directory.
    try (ZipInputStream zin =
        new ZipInputStream(new FileInputStream(options.resourcesZip.toFile()))) {
      ZipEntry entry;
      while ((entry = zin.getNextEntry()) != null) {
        if (!entry.isDirectory()) {
          Path output = resourceFiles.resolve(entry.getName());
          Files.createDirectories(output.getParent());
          try (FileOutputStream fos = new FileOutputStream(output.toFile())) {
            ByteStreams.copy(zin, fos);
          }
        }
      }
    }

    // Shrink resources.
    ResourceUsageAnalyzer resourceShrinker =
        new ResourceUsageAnalyzer(
            resourcePackages,
            options.rTxt,
            options.shrunkJar,
            options.primaryManifest,
            options.proguardMapping,
            resourceFiles.resolve("res"),
            options.log);

    resourceShrinker.shrink(shrunkResources);
    logger.fine(
        String.format(
            "Shrinking resources finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

    Path generatedSources = null;
    if (options.rTxtOutput != null) {
      generatedSources = working.resolve("generated_resources");
    }

    // Build ap_ with shrunk resources.
    resourceProcessor.processResources(
        working,
        aaptConfigOptions.aapt,
        aaptConfigOptions.androidJar,
        aaptConfigOptions.buildToolsVersion,
        VariantType.DEFAULT,
        aaptConfigOptions.debug,
        null /* packageForR */,
        new FlagAaptOptions(aaptConfigOptions),
        aaptConfigOptions.resourceConfigs,
        new MergedAndroidData(
            shrunkResources, resourceFiles.resolve("assets"), options.primaryManifest),
        ImmutableList.<DependencyAndroidData>of() /* libraries */,
        generatedSources,
        options.shrunkApk,
        null /* proguardOutput */,
        null /* mainDexProguardOutput */,
        /* publicResourcesOut= */ null,
        /* dataBindingInfoOut= */ null);
    if (options.shrunkResources != null) {
      ResourcesZip.from(shrunkResources, resourceFiles.resolve("assets"))
          .writeTo(options.shrunkResources, /* compress= */ false);
    }
    if (options.rTxtOutput != null) {
      AndroidResourceOutputs.copyRToOutput(
          generatedSources, options.rTxtOutput, options.packageType == VariantType.LIBRARY);
    }
    logger.fine(
        String.format(
            "Packing resources finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
  } catch (Exception e) {
    logger.log(Level.SEVERE, "Error shrinking resources", e);
    throw e;
  } finally {
    resourceProcessor.shutdown();
  }
}
 
Example 20
Source File: Aapt2ResourceShrinkingAction.java    From bazel with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
  final Profiler profiler = LoggingProfiler.createAndStart("shrink").startTask("flags");
  // Parse arguments.
  OptionsParser optionsParser =
      OptionsParser.builder()
          .optionsClasses(
              Options.class, Aapt2ConfigOptions.class, ResourceProcessorCommonOptions.class)
          .argsPreProcessor(new ShellQuotedParamsFilePreProcessor(FileSystems.getDefault()))
          .build();
  optionsParser.parseAndExitUponError(args);
  Aapt2ConfigOptions aapt2ConfigOptions = optionsParser.getOptions(Aapt2ConfigOptions.class);
  Options options = optionsParser.getOptions(Options.class);
  profiler.recordEndOf("flags").startTask("setup");

  try (ScopedTemporaryDirectory scopedTmp =
          new ScopedTemporaryDirectory("android_resources_tmp");
      ExecutorServiceCloser executorService = ExecutorServiceCloser.createWithFixedPoolOf(15)) {

    final ResourcesZip resourcesZip =
        ResourcesZip.createFrom(
            options.resourcesZip, scopedTmp.subDirectoryOf("merged-resources"));
    final ResourceLinker linker =
        ResourceLinker.create(
                aapt2ConfigOptions.aapt2, executorService, scopedTmp.subDirectoryOf("linking"))
            .profileUsing(profiler)
            .dependencies(ImmutableList.of(StaticLibrary.from(aapt2ConfigOptions.androidJar)));

    final Set<String> packages = new LinkedHashSet<>(resourcesZip.asPackages());

    profiler.recordEndOf("setup").startTask("resourceShrinker");

    try (final ShrunkProtoApk shrunk =
        resourcesZip.shrinkUsingProto(
            packages,
            options.shrunkJar,
            options.rTxt,
            options.proguardMapping,
            options.log,
            scopedTmp.subDirectoryOf("shrunk-resources"))) {
      shrunk
          .writeBinaryTo(linker, options.shrunkApk, aapt2ConfigOptions.resourceTableAsProto)
          .writeReportTo(options.log)
          .writeResourcesToZip(options.shrunkResources);
      if (options.resourcesConfigOutput != null) {
        shrunk.writeResourcesConfigTo(options.resourcesConfigOutput);
      }
      if (options.rTxtOutput != null) {
        // Fulfill the contract -- however, we do not generate an R.txt from the shrunk
        // resources.
        Files.copy(options.rTxt, options.rTxtOutput);
      }
    }
    profiler.recordEndOf("resourceShrinker").recordEndOf("shrink");
  }
}