Java Code Examples for com.google.common.collect.ImmutableList#isEmpty()

The following examples show how to use com.google.common.collect.ImmutableList#isEmpty() . 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: BuildBundleCommand.java    From bundletool with Apache License 2.0 6 votes vote down vote up
private static Optional<Assets> generateAssetsTargeting(BundleModule module) {
  ImmutableList<ZipPath> assetDirectories =
      module
          .findEntriesUnderPath(BundleModule.ASSETS_DIRECTORY)
          .map(ModuleEntry::getPath)
          .filter(path -> path.getNameCount() > 1)
          .map(ZipPath::getParent)
          .distinct()
          .collect(toImmutableList());

  if (assetDirectories.isEmpty()) {
    return Optional.empty();
  }

  return Optional.of(new TargetingGenerator().generateTargetingForAssets(assetDirectories));
}
 
Example 2
Source File: ProtoCommon.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the direct sources and import paths of a proto library. If protoSourcesImportPaths is not
 * empty, the value is just protoSourcesImportPaths. Otherwise, it's the combined sources of all
 * direct dependencies of the given RuleContext.
 *
 * @param protoDeps the proto dependencies.
 * @param sourceImportPathPairs List of proto sources to import paths.
 * @return the direct sources and import paths of a proto library.
 */
private static NestedSet<Pair<Artifact, String>>
    computeStrictImportableProtosImportPathsForDependents(
        ImmutableList<ProtoInfo> protoDeps,
        ImmutableList<Pair<Artifact, String>> sourceImportPathPairs) {

  if (sourceImportPathPairs.isEmpty()) {
    /* a proxy/alias library, return the sources of the direct deps */
    NestedSetBuilder<Pair<Artifact, String>> builder = NestedSetBuilder.stableOrder();
    for (ProtoInfo provider : protoDeps) {
      builder.addTransitive(provider.getStrictImportableProtoSourcesImportPathsForDependents());
    }
    return builder.build();
  } else {
    return NestedSetBuilder.wrap(STABLE_ORDER, sourceImportPathPairs);
  }
}
 
Example 3
Source File: DeleteTypeAction.java    From binnavi with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(ActionEvent event) {
  final ImmutableList<BaseType> types = typeEditor.getSelectedTypes();
  if (types.isEmpty() ||
      CMessageBox.showYesNoQuestion(owner, "Do you really want to delete these type(s)?")
      != JOptionPane.YES_OPTION) {
    return;
  }

  try {
    for (final BaseType baseType : types) {
      typeManager.deleteType(baseType);
    }
  } catch (final CouldntDeleteException exception) {
    CUtilityFunctions.logException(exception);
  }
}
 
Example 4
Source File: AdbRunner.java    From bundletool with Apache License 2.0 6 votes vote down vote up
private void run(Consumer<Device> deviceAction, Predicate<Device> deviceFilter) {
  try {
    ImmutableList<Device> matchedDevices =
        adbServer.getDevices().stream().filter(deviceFilter).collect(toImmutableList());
    if (matchedDevices.isEmpty()) {
      throw new DeviceNotFoundException("Unable to find a device matching the criteria.");
    } else if (matchedDevices.size() > 1) {
      throw new TooManyDevicesMatchedException(matchedDevices.size());
    }

    deviceAction.accept(matchedDevices.get(0));

  } catch (TimeoutException e) {
    throw CommandExecutionException.builder()
        .withCause(e)
        .withInternalMessage("Timed out while waiting for ADB.")
        .build();
  }
}
 
Example 5
Source File: ServiceManager.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Constructs a new instance for managing the given services.
 *
 * @param services The services to manage
 *
 * @throws IllegalArgumentException if not all services are {@linkplain State#NEW new} or if there
 *     are any duplicate services.
 */
public ServiceManager(Iterable<? extends Service> services) {
  ImmutableList<Service> copy = ImmutableList.copyOf(services);
  if (copy.isEmpty()) {
    // Having no services causes the manager to behave strangely. Notably, listeners are never
    // fired. To avoid this we substitute a placeholder service.
    logger.log(
        Level.WARNING,
        "ServiceManager configured with no services.  Is your application configured properly?",
        new EmptyServiceManagerWarning());
    copy = ImmutableList.<Service>of(new NoOpService());
  }
  this.state = new ServiceManagerState(copy);
  this.services = copy;
  WeakReference<ServiceManagerState> stateReference =
      new WeakReference<ServiceManagerState>(state);
  for (Service service : copy) {
    service.addListener(new ServiceListener(service, stateReference), directExecutor());
    // We check the state after adding the listener as a way to ensure that our listener was added
    // to a NEW service.
    checkArgument(service.state() == NEW, "Can only manage NEW services, %s", service);
  }
  // We have installed all of our listeners and after this point any state transition should be
  // correct.
  this.state.markReady();
}
 
Example 6
Source File: ExtractApksCommand.java    From bundletool with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
ImmutableList<Path> execute(PrintStream output) {
  validateInput();

  BuildApksResult toc = ResultUtils.readTableOfContents(getApksArchivePath());
  Optional<ImmutableSet<String>> requestedModuleNames =
      getModules().map(modules -> resolveRequestedModules(modules, toc));

  ApkMatcher apkMatcher = new ApkMatcher(getDeviceSpec(), requestedModuleNames, getInstant());
  ImmutableList<ZipPath> matchedApks = apkMatcher.getMatchingApks(toc);

  if (matchedApks.isEmpty()) {
    throw IncompatibleDeviceException.builder()
        .withUserMessage("No compatible APKs found for the device.")
        .build();
  }


  if (Files.isDirectory(getApksArchivePath())) {
    return matchedApks.stream()
        .map(matchedApk -> getApksArchivePath().resolve(matchedApk.toString()))
        .collect(toImmutableList());
  } else {
    return extractMatchedApksFromApksArchive(matchedApks);
  }
}
 
Example 7
Source File: ExpressionConverter.java    From beam with Apache License 2.0 5 votes vote down vote up
private static int indexOfResolvedColumnInExprList(
    ImmutableList<ResolvedComputedColumn> exprList, ResolvedColumn column) {
  if (exprList == null || exprList.isEmpty()) {
    return -1;
  }

  for (int i = 0; i < exprList.size(); i++) {
    ResolvedComputedColumn computedColumn = exprList.get(i);
    if (computedColumn.getColumn().equals(column)) {
      return i;
    }
  }

  return -1;
}
 
Example 8
Source File: ChannelResponse.java    From synapse with Apache License 2.0 5 votes vote down vote up
private ChannelResponse(final String channelName,
                        final ImmutableList<ShardResponse> shardResponses) {
    if (shardResponses.isEmpty()) {
        throw new IllegalArgumentException("Unable to create ChannelResponse without KinesisShardResponses");
    }
    this.channelName = channelName;
    this.shardResponses = shardResponses;
}
 
Example 9
Source File: TurbineTypes.java    From turbine with Apache License 2.0 5 votes vote down vote up
private boolean isClassSubtype(ClassTy a, Type other, boolean strict) {
  if (other.tyKind() != TyKind.CLASS_TY) {
    return false;
  }
  ClassTy b = (ClassTy) other;
  if (!a.sym().equals(b.sym())) {
    // find a path from a to b in the type hierarchy
    ImmutableList<ClassTy> path = factory.cha().search(a, b.sym());
    if (path.isEmpty()) {
      return false;
    }
    // perform repeated type substitution to get an instance of B with the type arguments
    // provided by A
    a = path.get(0);
    for (ClassTy ty : path) {
      ImmutableMap<TyVarSymbol, Type> mapping = getMapping(ty);
      if (mapping == null) {
        // if we encounter a raw type on the path from A to B the result is erased
        a = (ClassTy) erasure(a);
        break;
      }
      a = substClassTy(a, mapping);
    }
  }
  Iterator<SimpleClassTy> ax = a.classes().reverse().iterator();
  Iterator<SimpleClassTy> bx = b.classes().reverse().iterator();
  while (ax.hasNext() && bx.hasNext()) {
    if (!tyArgsContains(ax.next(), bx.next(), strict)) {
      return false;
    }
  }
  return !hasTyArgs(ax) && !hasTyArgs(bx);
}
 
Example 10
Source File: BuildPackagePathToUnconfiguredTargetNodePackageComputation.java    From buck with Apache License 2.0 5 votes vote down vote up
private ImmutableList<ParsingError> getParsingErrors(
    ImmutableList<ParsingError> translateErrors, ImmutableList<ParsingError> errors) {
  if (translateErrors.isEmpty() || errors.isEmpty()) {
    return translateErrors.isEmpty() ? errors : translateErrors;
  }
  return ImmutableList.<ParsingError>builderWithExpectedSize(
          translateErrors.size() + errors.size())
      .addAll(errors)
      .addAll(translateErrors)
      .build();
}
 
Example 11
Source File: ZeroArgMacroTypeCoercer.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public M coerce(
    CellNameResolver cellNameResolver,
    ProjectFilesystem filesystem,
    ForwardRelativePath pathRelativeToProjectRoot,
    TargetConfiguration targetConfiguration,
    TargetConfiguration hostConfiguration,
    ImmutableList<String> args)
    throws CoerceFailedException {
  if (!args.isEmpty()) {
    throw new CoerceFailedException(
        String.format("expected zero arguments (found %d)", args.size()));
  }
  return val;
}
 
Example 12
Source File: RdapJsonFormatter.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a JSON object for a {@link RegistrarContact}.
 *
 * <p>Returns empty if this contact shouldn't be visible (doesn't have a role).
 *
 * <p>NOTE that registrar locations in the response require different roles and different VCard
 * members according to the spec. Currently, this function returns all the rolls and all the
 * members for every location, but we might consider refactoring it to allow the minimal required
 * roles and members.
 *
 * <p>Specifically:
 * <li>Registrar inside a Domain only requires the ABUSE role, and only the TEL and EMAIL members
 *     (RDAP Response Profile 2.4.5)
 * <li>Registrar responses to direct query don't require any contact, but *should* have the TECH
 *     and ADMIN roles, but require the FN, TEL and EMAIL members
 * <li>Registrar inside a Nameserver isn't required at all, and if given doesn't require any
 *     contacts
 *
 * @param registrarContact the registrar contact for which the JSON object should be created
 */
static Optional<RdapContactEntity> makeRdapJsonForRegistrarContact(
    RegistrarContact registrarContact) {
  ImmutableList<RdapEntity.Role> roles = makeRdapRoleList(registrarContact);
  if (roles.isEmpty()) {
    return Optional.empty();
  }
  RdapContactEntity.Builder builder = RdapContactEntity.builder();
  builder.statusBuilder().addAll(STATUS_LIST_ACTIVE);
  builder.rolesBuilder().addAll(roles);
  // Create the vCard.
  VcardArray.Builder vcardBuilder = VcardArray.builder();
  // MUST include FN member: RDAP Response Profile 3.2
  String name = registrarContact.getName();
  if (name != null) {
    vcardBuilder.add(Vcard.create("fn", "text", name));
  }
  // MUST include TEL and EMAIL members: RDAP Response Profile 2.4.5, 3.2
  String voicePhoneNumber = registrarContact.getPhoneNumber();
  if (voicePhoneNumber != null) {
    vcardBuilder.add(makePhoneEntry(PHONE_TYPE_VOICE, "tel:" + voicePhoneNumber));
  }
  String faxPhoneNumber = registrarContact.getFaxNumber();
  if (faxPhoneNumber != null) {
    vcardBuilder.add(makePhoneEntry(PHONE_TYPE_FAX, "tel:" + faxPhoneNumber));
  }
  String emailAddress = registrarContact.getEmailAddress();
  if (emailAddress != null) {
    vcardBuilder.add(Vcard.create("email", "text", emailAddress));
  }
  builder.setVcardArray(vcardBuilder.build());
  return Optional.of(builder.build());
}
 
Example 13
Source File: CommandLine.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a {@link CommandLine} that is constructed by prepending the {@code executableArgs} to
 * {@code commandLine}.
 */
public static CommandLine concat(
    final ImmutableList<String> executableArgs, final CommandLine commandLine) {
  if (executableArgs.isEmpty()) {
    return commandLine;
  }
  if (commandLine == EMPTY) {
    return CommandLine.of(executableArgs);
  }
  return new PrefixedCommandLine(executableArgs, commandLine);
}
 
Example 14
Source File: BigQueryClient.java    From spark-bigquery-connector with Apache License 2.0 5 votes vote down vote up
String createSql(TableId table, ImmutableList<String> requiredColumns, String[] filters) {
    String columns = requiredColumns.isEmpty() ? "*" :
            requiredColumns.stream().map(column -> format("`%s`", column)).collect(joining(","));

    String whereClause = createWhereClause(filters)
            .map(clause -> "WHERE " + clause)
            .orElse("");

    return createSql(table, columns, filters);
}
 
Example 15
Source File: JavacToJarStepFactory.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
public void createCompileToJarStepImpl(
    ProjectFilesystem projectFilesystem,
    BuildContext context,
    BuildTarget invokingRule,
    CompilerParameters compilerParameters,
    ImmutableList<String> postprocessClassesCommands,
    @Nullable JarParameters abiJarParameters,
    @Nullable JarParameters libraryJarParameters,
    /* output params */
    Builder<Step> steps,
    BuildableContext buildableContext) {
  Preconditions.checkArgument(
      libraryJarParameters == null
          || libraryJarParameters
              .getEntriesToJar()
              .contains(compilerParameters.getOutputPaths().getClassesDir()));

  String spoolMode = javacOptions.getSpoolMode().name();
  // In order to use direct spooling to the Jar:
  // (1) It must be enabled through a .buckconfig.
  // (2) The target must have 0 postprocessing steps.
  // (3) Tha compile API must be JSR 199.
  boolean isSpoolingToJarEnabled =
      compilerParameters.getAbiGenerationMode().isSourceAbi()
          || (postprocessClassesCommands.isEmpty()
              && javacOptions.getSpoolMode() == JavacOptions.SpoolMode.DIRECT_TO_JAR
              && javac instanceof Jsr199Javac);

  LOG.info(
      "Target: %s SpoolMode: %s Expected SpoolMode: %s Postprocessing steps: %s",
      invokingRule.getBaseName(),
      (isSpoolingToJarEnabled) ? (SpoolMode.DIRECT_TO_JAR) : (SpoolMode.INTERMEDIATE_TO_DISK),
      spoolMode,
      postprocessClassesCommands.toString());

  if (isSpoolingToJarEnabled) {
    JavacOptions buildTimeOptions =
        javacOptions.withBootclasspathFromContext(extraClasspathProvider);

    steps.add(
        new JavacStep(
            javac,
            buildTimeOptions,
            invokingRule,
            context.getSourcePathResolver(),
            projectFilesystem,
            new ClasspathChecker(),
            compilerParameters,
            abiJarParameters,
            libraryJarParameters));
  } else {
    super.createCompileToJarStepImpl(
        projectFilesystem,
        context,
        invokingRule,
        compilerParameters,
        postprocessClassesCommands,
        null,
        libraryJarParameters,
        steps,
        buildableContext);
  }
}
 
Example 16
Source File: BlazeCommandRunConfiguration.java    From intellij with Apache License 2.0 4 votes vote down vote up
@Override
public void checkConfiguration() throws RuntimeConfigurationException {
  // Our handler check is not valid when we don't have BlazeProjectData.
  if (BlazeProjectDataManager.getInstance(getProject()).getBlazeProjectData() == null) {
    throw new RuntimeConfigurationError(
        "Configuration cannot be run until project has been synced.");
  }
  boolean hasBlazeBeforeRunTask =
      RunManagerEx.getInstanceEx(getProject()).getBeforeRunTasks(this).stream()
          .anyMatch(
              task ->
                  task.getProviderId().equals(BlazeBeforeRunTaskProvider.ID) && task.isEnabled());
  if (!hasBlazeBeforeRunTask) {
    throw new RuntimeConfigurationError(
        String.format(
            "Invalid run configuration: the %s before run task is missing. Please re-run sync "
                + "to add it back",
            Blaze.buildSystemName(getProject())));
  }
  handler.checkConfiguration();
  PendingRunConfigurationContext pendingContext = this.pendingContext;
  if (pendingContext != null && !pendingContext.isDone()) {
    return;
  }
  ImmutableList<String> targetPatterns = this.targetPatterns;
  if (targetPatterns.isEmpty()) {
    throw new RuntimeConfigurationError(
        String.format(
            "You must specify a %s target expression.", Blaze.buildSystemName(getProject())));
  }
  for (String pattern : targetPatterns) {
    if (Strings.isNullOrEmpty(pattern)) {
      throw new RuntimeConfigurationError(
          String.format(
              "You must specify a %s target expression.", Blaze.buildSystemName(getProject())));
    }
    if (!pattern.startsWith("//") && !pattern.startsWith("@")) {
      throw new RuntimeConfigurationError(
          "You must specify the full target expression, starting with // or @");
    }

    String error = TargetExpression.validate(pattern);
    if (error != null) {
      throw new RuntimeConfigurationError(error);
    }
  }
}
 
Example 17
Source File: PatchingOptions.java    From copybara with Apache License 2.0 4 votes vote down vote up
private boolean shouldUsePatch(@Nullable Path gitDir, ImmutableList<String> excludedPaths)
    throws ValidationException {
  // We are going to patch a git checkout dir. We should use git apply three way.
  if (gitDir != null) {
    return false;
  }
  if (skipVersionCheck) {
    ValidationException.checkCondition(excludedPaths.isEmpty(),
        "%s is incompatible with patch transformations that uses excluded paths: %s",
        SKIP_VERSION_CHECK_FLAG, excludedPaths);
    return true;
  }
  // GNU Patch doesn't have a way to exclude paths
  if (useGitApply || !excludedPaths.isEmpty()) {
    return false;
  }

  try {
    Version version = getPatchVersion(patchBin);
    if (!version.isTooOld()) {
      return true;
    }

    if (isMac()) {
      generalOptions.console()
          .warnFmt("GNU Patch version is too old (%s) to be used by Copybara. "
              + "Defaulting to 'git apply'. Use %s if patch is available in a different"
              + " location", version, PATCH_BIN_FLAG);
      return false;
    }

    throw new ValidationException(String.format(
        "Too old version of GNU Patch (%s). Copybara required at least 2.7 version."
            + " Path used: %s. Use %s to use a different path",
        version, patchBin, PATCH_BIN_FLAG));

  } catch (CommandException e) {
    // While this might be an environment error, normally it is attributable to the user
    // (not having patch available).
    throw new ValidationException(
        String.format("Error using GNU Patch. Path used: %s. Use %s to use a different path",
            patchBin, PATCH_BIN_FLAG),
        e);
  }
}
 
Example 18
Source File: ConfigurationFactory.java    From monasca-common with Apache License 2.0 4 votes vote down vote up
private void validate(String file, T config) throws ConfigurationException {
  final ImmutableList<String> errors = new Validator().validate(config);
  if (!errors.isEmpty()) {
    throw new ConfigurationException(file, errors);
  }
}
 
Example 19
Source File: XdsNameResolver.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
static ImmutableMap<String, ?> convertToRawRoute(RouteMatch routeMatch, String actionName) {
  ImmutableMap.Builder<String, Object> configRouteBuilder = new ImmutableMap.Builder<>();

  PathMatcher pathMatcher = routeMatch.getPathMatch();
  String path = pathMatcher.getPath();
  String prefix = pathMatcher.getPrefix();
  Pattern regex = pathMatcher.getRegEx();
  if (path != null) {
    configRouteBuilder.put("path", path);
  }
  if (prefix != null) {
    configRouteBuilder.put("prefix", prefix);
  }
  if (regex != null) {
    configRouteBuilder.put("regex", regex.pattern());
  }

  ImmutableList.Builder<Object> rawHeaderMatcherListBuilder = new ImmutableList.Builder<>();
  List<HeaderMatcher> headerMatchers = routeMatch.getHeaderMatchers();
  for (HeaderMatcher headerMatcher : headerMatchers) {
    ImmutableMap.Builder<String, Object> rawHeaderMatcherBuilder = new ImmutableMap.Builder<>();
    rawHeaderMatcherBuilder.put("name", headerMatcher.getName());
    String exactMatch = headerMatcher.getExactMatch();
    Pattern regexMatch = headerMatcher.getRegExMatch();
    HeaderMatcher.Range rangeMatch = headerMatcher.getRangeMatch();
    Boolean presentMatch = headerMatcher.getPresentMatch();
    String prefixMatch = headerMatcher.getPrefixMatch();
    String suffixMatch = headerMatcher.getSuffixMatch();
    if (exactMatch != null) {
      rawHeaderMatcherBuilder.put("exactMatch", exactMatch);
    }
    if (regexMatch != null) {
      rawHeaderMatcherBuilder.put("regexMatch", regexMatch.pattern());
    }
    if (rangeMatch != null) {
      rawHeaderMatcherBuilder
          .put(
              "rangeMatch",
              ImmutableMap.of("start", rangeMatch.getStart(), "end", rangeMatch.getEnd()));
    }
    if (presentMatch != null) {
      rawHeaderMatcherBuilder.put("presentMatch", presentMatch);
    }
    if (prefixMatch != null) {
      rawHeaderMatcherBuilder.put("prefixMatch", prefixMatch);
    }
    if (suffixMatch != null) {
      rawHeaderMatcherBuilder.put("suffixMatch", suffixMatch);
    }
    rawHeaderMatcherBuilder.put("invertMatch", headerMatcher.isInvertedMatch());
    rawHeaderMatcherListBuilder.add(rawHeaderMatcherBuilder.build());
  }
  ImmutableList<?> rawHeaderMatchers = rawHeaderMatcherListBuilder.build();
  if (!rawHeaderMatchers.isEmpty()) {
    configRouteBuilder.put("headers", rawHeaderMatchers);
  }

  FractionMatcher matchFraction = routeMatch.getFractionMatch();
  if (matchFraction != null) {
    configRouteBuilder
        .put(
            "matchFraction",
            ImmutableMap.of(
                "numerator", matchFraction.getNumerator(),
                "denominator", matchFraction.getDenominator()));
  }

  configRouteBuilder.put("action", actionName);
  return configRouteBuilder.build();
}
 
Example 20
Source File: VanillaJavaBuilder.java    From bazel with Apache License 2.0 4 votes vote down vote up
public VanillaJavaBuilderResult run(List<String> args) throws IOException {
  OptionsParser optionsParser;
  try {
    optionsParser = new OptionsParser(args);
  } catch (InvalidCommandLineException e) {
    return new VanillaJavaBuilderResult(false, e.getMessage());
  }
  DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
  StringWriter output = new StringWriter();
  JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
  Path tempDir = Paths.get(firstNonNull(optionsParser.getTempDir(), "_tmp"));
  Path nativeHeaderDir = tempDir.resolve("native_headers");
  Files.createDirectories(nativeHeaderDir);
  boolean ok;
  try (StandardJavaFileManager fileManager =
      javaCompiler.getStandardFileManager(diagnosticCollector, ENGLISH, UTF_8)) {
    setLocations(optionsParser, fileManager, nativeHeaderDir);
    ImmutableList<JavaFileObject> sources = getSources(optionsParser, fileManager);
    if (sources.isEmpty()) {
      ok = true;
    } else {
      CompilationTask task =
          javaCompiler.getTask(
              new PrintWriter(output, true),
              fileManager,
              diagnosticCollector,
              JavacOptions.removeBazelSpecificFlags(optionsParser.getJavacOpts()),
              ImmutableList.<String>of() /*classes*/,
              sources);
      setProcessors(optionsParser, fileManager, task);
      ok = task.call();
    }
  }
  if (ok) {
    writeOutput(optionsParser);
    writeNativeHeaderOutput(optionsParser, nativeHeaderDir);
  }
  writeGeneratedSourceOutput(optionsParser);
  // the jdeps output doesn't include any information about dependencies, but Bazel still expects
  // the file to be created
  if (optionsParser.getOutputDepsProtoFile() != null) {
    try (OutputStream os =
        Files.newOutputStream(Paths.get(optionsParser.getOutputDepsProtoFile()))) {
      Deps.Dependencies.newBuilder()
          .setRuleLabel(optionsParser.getTargetLabel())
          .setSuccess(ok)
          .build()
          .writeTo(os);
    }
  }
  // TODO(cushon): support manifest protos & genjar
  if (optionsParser.getManifestProtoPath() != null) {
    try (OutputStream os =
        Files.newOutputStream(Paths.get(optionsParser.getManifestProtoPath()))) {
      Manifest.getDefaultInstance().writeTo(os);
    }
  }

  for (Diagnostic<? extends JavaFileObject> diagnostic : diagnosticCollector.getDiagnostics()) {
    String code = diagnostic.getCode();
    if (code.startsWith("compiler.note.deprecated")
        || code.startsWith("compiler.note.unchecked")
        || code.equals("compiler.warn.sun.proprietary")) {
      continue;
    }
    StringBuilder message = new StringBuilder();
    if (diagnostic.getSource() != null) {
      message.append(diagnostic.getSource().getName());
      if (diagnostic.getLineNumber() != -1) {
        message.append(':').append(diagnostic.getLineNumber());
      }
      message.append(": ");
    }
    message.append(diagnostic.getKind().toString().toLowerCase(ENGLISH));
    message.append(": ").append(diagnostic.getMessage(ENGLISH)).append(System.lineSeparator());
    output.write(message.toString());
  }
  return new VanillaJavaBuilderResult(ok, output.toString());
}