com.google.devtools.build.lib.events.EventHandler - java examples

Here are the examples of the java api com.google.devtools.build.lib.events.EventHandler taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

106 Examples 7

19 View Complete Implementation : Rule.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Collects the output files (both implicit and explicit). All the implicit output files are added
 * first, followed by any explicit files. Additionally both implicit and explicit output files
 * will retain the relative order in which they were declared.
 */
void populateOutputFiles(EventHandler eventHandler, Package.Builder pkgBuilder) throws LabelSyntaxException, InterruptedException {
    populateOutputFilesInternal(eventHandler, pkgBuilder, /*performChecks=*/
    true);
}

19 View Complete Implementation : Rule.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Implicit output files come from rule-specific patterns, and are a function of the rule's
 * "name", "srcs", and other attributes.
 */
private void populateImplicitOutputFiles(EventHandler eventHandler, Package.Builder pkgBuilder, ImmutableList.Builder<OutputFile> outputFilesBuilder, boolean performChecks) throws InterruptedException {
    try {
        RawAttributeMapper attributeMap = RawAttributeMapper.of(this);
        for (String out : implicitOutputsFunction.getImplicitOutputs(eventHandler, attributeMap)) {
            Label label;
            if (performChecks) {
                try {
                    label = pkgBuilder.createLabel(out);
                } catch (LabelSyntaxException e) {
                    reportError("illegal output file name '" + out + "' in rule " + getLabel() + " due to: " + e.getMessage(), eventHandler);
                    continue;
                }
            } else {
                label = Label.createUnvalidated(pkgBuilder.getPackageIdentifier(), out);
            }
            addOutputFile(label, eventHandler, outputFilesBuilder);
        }
    } catch (EvalException e) {
        reportError(String.format("In rule %s: %s", getLabel(), e.print()), eventHandler);
    }
}

19 View Complete Implementation : ActionExecutionStatusReporter.java
Copyright Apache License 2.0
Author : bazelbuild
public static ActionExecutionStatusReporter create(EventHandler eventHandler, @Nullable EventBus eventBus) {
    return create(eventHandler, eventBus, null);
}

19 View Complete Implementation : Rule.java
Copyright Apache License 2.0
Author : bazelbuild
void populateOutputFilesUnchecked(EventHandler eventHandler, Package.Builder pkgBuilder) throws InterruptedException {
    try {
        populateOutputFilesInternal(eventHandler, pkgBuilder, /*performChecks=*/
        false);
    } catch (LabelSyntaxException e) {
        throw new IllegalStateException(e);
    }
}

19 View Complete Implementation : PathPackageLocator.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * A factory of PathPackageLocators from a list of path elements. Elements may contain
 * "%workspace%", indicating the workspace.
 *
 * <p>If any of the paths given do not exist, an exception will be thrown.
 *
 * @param outputBase the output base. Can be null if remote repositories are not in use.
 * @param pathElements Each element must be an absolute path, relative path, or some string
 *     "%workspace%" + relative, where relative is itself a relative path. The special symbol
 *     "%workspace%" means to interpret the path relative to the nearest enclosing workspace.
 *     Relative paths are interpreted relative to the client's working directory, which may be
 *     below the workspace.
 * @param eventHandler The eventHandler.
 * @param workspace The nearest enclosing package root directory.
 * @param clientWorkingDirectory The client's working directory.
 * @param buildFilesByPriority The ordered collection of {@link BuildFileName}s to check in each
 *     potential package directory.
 * @return a {@link PathPackageLocator} that uses the {@code outputBase} and {@code pathElements}
 *     provided.
 */
public static PathPackageLocator create(Path outputBase, List<String> pathElements, EventHandler eventHandler, Path workspace, Path clientWorkingDirectory, List<BuildFileName> buildFilesByPriority) {
    return createInternal(outputBase, pathElements, eventHandler, workspace, clientWorkingDirectory, buildFilesByPriority, true);
}

19 View Complete Implementation : ActionCacheChecker.java
Copyright Apache License 2.0
Author : bazelbuild
private static void reportNewAction(@Nullable EventHandler handler, Action action) {
    reportRebuild(handler, action, "no entry in the cache (action is new)");
}

19 View Complete Implementation : Rule.java
Copyright Apache License 2.0
Author : bazelbuild
private void addLabelOutput(Attribute attribute, Label label, EventHandler eventHandler, ImmutableList.Builder<OutputFile> outputFilesBuilder, ImmutableListMultimap.Builder<String, OutputFile> outputFileMapBuilder, boolean performChecks) throws LabelSyntaxException {
    if (performChecks) {
        if (!label.getPackageIdentifier().equals(pkg.getPackageIdentifier())) {
            throw new IllegalStateException("Label for attribute " + attribute + " should refer to '" + pkg.getName() + "' but instead refers to '" + label.getPackageFragment() + "' (label '" + label.getName() + "')");
        }
        if (label.getName().equals(".")) {
            throw new LabelSyntaxException("output file name can't be equal '.'");
        }
    }
    OutputFile outputFile = addOutputFile(label, eventHandler, outputFilesBuilder);
    outputFileMapBuilder.put(attribute.getName(), outputFile);
}

19 View Complete Implementation : ActionCacheChecker.java
Copyright Apache License 2.0
Author : bazelbuild
// Called by IncrementalDependencyChecker.
protected static void reportUnconditionalExecution(@Nullable EventHandler handler, Action action) {
    reportRebuild(handler, action, "unconditional execution is requested");
}

19 View Complete Implementation : Rule.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Check if this rule is valid according to the validityPredicate of its RuleClreplaced.
 */
void checkValidityPredicate(EventHandler eventHandler) {
    PredicateWithMessage<Rule> predicate = getRuleClreplacedObject().getValidityPredicate();
    if (!predicate.apply(this)) {
        reportError(predicate.getErrorReason(this), eventHandler);
    }
}

19 View Complete Implementation : ActionExecutionStatusReporter.java
Copyright Apache License 2.0
Author : bazelbuild
@VisibleForTesting
static ActionExecutionStatusReporter create(EventHandler eventHandler, @Nullable Clock clock) {
    return create(eventHandler, null, clock);
}

19 View Complete Implementation : EventCollectionApparatus.java
Copyright Apache License 2.0
Author : bazelbuild
public void addHandler(EventHandler eventHandler) {
    reporter.addHandler(eventHandler);
    handlers.add(eventHandler);
}

19 View Complete Implementation : RemoteOutputService.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public ModifiedFileSet startBuild(EventHandler eventHandler, UUID buildId, boolean finalizeActions) {
    return ModifiedFileSet.EVERYTHING_MODIFIED;
}

19 View Complete Implementation : ActionCacheChecker.java
Copyright Apache License 2.0
Author : bazelbuild
private void reportClientEnv(EventHandler handler, Action action, Map<String, String> used) {
    if (handler != null) {
        if (cacheConfig.verboseExplanations()) {
            StringBuilder message = new StringBuilder();
            message.append("Effective client environment has changed. Now using\n");
            for (Map.Entry<String, String> entry : used.entrySet()) {
                message.append("  ").append(entry.getKey()).append("=").append(entry.getValue()).append("\n");
            }
            reportRebuild(handler, action, message.toString());
        } else {
            reportRebuild(handler, action, "Effective client environment has changed (try --verbose_explanations for more info)");
        }
    }
}

19 View Complete Implementation : Rule.java
Copyright Apache License 2.0
Author : bazelbuild
private void reportWarning(String message, EventHandler eventHandler) {
    eventHandler.handle(Event.warn(location, message));
}

19 View Complete Implementation : ActionCacheChecker.java
Copyright Apache License 2.0
Author : bazelbuild
private static void reportCorruptedCacheEntry(@Nullable EventHandler handler, Action action) {
    reportRebuild(handler, action, "cache entry is corrupted");
}

19 View Complete Implementation : Rule.java
Copyright Apache License 2.0
Author : bazelbuild
// Explicit output files are user-specified attributes of type OUTPUT.
private void populateExplicitOutputFiles(EventHandler eventHandler, ImmutableList.Builder<OutputFile> outputFilesBuilder, ImmutableListMultimap.Builder<String, OutputFile> outputFileMapBuilder, boolean performChecks) throws LabelSyntaxException {
    NonconfigurableAttributeMapper nonConfigurableAttributes = NonconfigurableAttributeMapper.of(this);
    for (Attribute attribute : ruleClreplaced.getAttributes()) {
        String name = attribute.getName();
        Type<?> type = attribute.getType();
        if (type == BuildType.OUTPUT) {
            Label outputLabel = nonConfigurableAttributes.get(name, BuildType.OUTPUT);
            if (outputLabel != null) {
                addLabelOutput(attribute, outputLabel, eventHandler, outputFilesBuilder, outputFileMapBuilder, performChecks);
            }
        } else if (type == BuildType.OUTPUT_LIST) {
            for (Label label : nonConfigurableAttributes.get(name, BuildType.OUTPUT_LIST)) {
                addLabelOutput(attribute, label, eventHandler, outputFilesBuilder, outputFileMapBuilder, performChecks);
            }
        }
    }
}

19 View Complete Implementation : ActionCacheChecker.java
Copyright Apache License 2.0
Author : bazelbuild
private static void reportChangedDeps(@Nullable EventHandler handler, Action action) {
    reportRebuild(handler, action, "the set of files on which this action depends has changed");
}

19 View Complete Implementation : Rule.java
Copyright Apache License 2.0
Author : bazelbuild
void reportError(String message, EventHandler eventHandler) {
    eventHandler.handle(Event.error(location, message));
    this.containsErrors = true;
}

19 View Complete Implementation : ActionCacheChecker.java
Copyright Apache License 2.0
Author : bazelbuild
private void reportCommand(EventHandler handler, Action action) {
    if (handler != null) {
        if (cacheConfig.verboseExplanations()) {
            String keyDescription = action.describeKey();
            reportRebuild(handler, action, keyDescription == null ? "action command has changed" : "action command has changed.\nNew action: " + keyDescription);
        } else {
            reportRebuild(handler, action, "action command has changed (try --verbose_explanations for more info)");
        }
    }
}

19 View Complete Implementation : Rule.java
Copyright Apache License 2.0
Author : bazelbuild
private void populateOutputFilesInternal(EventHandler eventHandler, Package.Builder pkgBuilder, boolean performChecks) throws LabelSyntaxException, InterruptedException {
    Preconditions.checkState(outputFiles == null);
    // Order is important here: implicit before explicit
    ImmutableList.Builder<OutputFile> outputFilesBuilder = ImmutableList.builder();
    ImmutableListMultimap.Builder<String, OutputFile> outputFileMapBuilder = ImmutableListMultimap.builder();
    populateImplicitOutputFiles(eventHandler, pkgBuilder, outputFilesBuilder, performChecks);
    populateExplicitOutputFiles(eventHandler, outputFilesBuilder, outputFileMapBuilder, performChecks);
    outputFiles = outputFilesBuilder.build();
    outputFileMap = outputFileMapBuilder.build();
}

19 View Complete Implementation : ActionExecutionStatusReporter.java
Copyright Apache License 2.0
Author : bazelbuild
private static ActionExecutionStatusReporter create(EventHandler eventHandler, @Nullable EventBus eventBus, @Nullable Clock clock) {
    ActionExecutionStatusReporter result = new ActionExecutionStatusReporter(eventHandler, eventBus, clock == null ? BlazeClock.instance() : clock);
    if (eventBus != null) {
        eventBus.register(result);
    }
    return result;
}

19 View Complete Implementation : Rule.java
Copyright Apache License 2.0
Author : bazelbuild
private OutputFile addOutputFile(Label label, EventHandler eventHandler, ImmutableList.Builder<OutputFile> outputFilesBuilder) {
    if (label.getName().equals(getName())) {
        // TODO(bazel-team): for now (23 Apr 2008) this is just a warning.  After
        // June 1st we should make it an error.
        reportWarning("target '" + getName() + "' is both a rule and a file; please choose " + "another name for the rule", eventHandler);
    }
    OutputFile outputFile = new OutputFile(pkg, label, ruleClreplaced.getOutputFileKind(), this);
    outputFilesBuilder.add(outputFile);
    return outputFile;
}

19 View Complete Implementation : AbstractAction.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * If the action might read directories as inputs in a way that is unsound wrt dependency
 * checking, this method must be called.
 */
protected void checkInputsForDirectories(EventHandler eventHandler, MetadataProvider metadataProvider) throws IOException {
    // Report "directory dependency checking" warning only for non-generated directories (generated
    // ones will be reported earlier).
    for (Artifact input : getMandatoryInputs().toList()) {
        // replacedume that if the file did not exist, we would not have gotten here.
        if (input.isSourceArtifact() && metadataProvider.getMetadata(input).getType().isDirectory()) {
            // TODO(ulfjack): What about dependency checking of special files?
            eventHandler.handle(Event.warn(getOwner().getLocation(), String.format("input '%s' to %s is a directory; " + "dependency checking of directories is unsound", input.prettyPrint(), getOwner().getLabel())));
        }
    }
}

19 View Complete Implementation : PathPackageLocator.java
Copyright Apache License 2.0
Author : bazelbuild
private static PathPackageLocator createInternal(Path outputBase, List<String> pathElements, EventHandler eventHandler, Path workspace, Path clientWorkingDirectory, List<BuildFileName> buildFilesByPriority, boolean checkExistence) {
    List<Root> resolvedPaths = new ArrayList<>();
    for (String pathElement : pathElements) {
        // Replace "%workspace%" with the path of the enclosing workspace directory.
        pathElement = maybeReplaceWorkspaceInString(pathElement, workspace);
        PathFragment pathElementFragment = PathFragment.create(pathElement);
        // If the path string started with "%workspace%" or "/", it is already absolute,
        // so the following line is a no-op.
        Path rootPath = clientWorkingDirectory.getRelative(pathElementFragment);
        if (!pathElementFragment.isAbsolute() && !clientWorkingDirectory.equals(workspace)) {
            eventHandler.handle(Event.warn("The package path element '" + pathElementFragment + "' will be taken relative to your working directory. You may have intended to" + " have the path taken relative to your workspace directory. If so, please use" + "the '" + WORKSPACE_WILDCARD + "' wildcard."));
        }
        if (!checkExistence || rootPath.exists()) {
            resolvedPaths.add(Root.fromPath(rootPath));
        }
    }
    return new PathPackageLocator(outputBase, resolvedPaths, buildFilesByPriority);
}

19 View Complete Implementation : ActionExecutionStatusReporter.java
Copyright Apache License 2.0
Author : bazelbuild
public static ActionExecutionStatusReporter create(EventHandler eventHandler) {
    return create(eventHandler, null, null);
}

19 View Complete Implementation : SkylarkDebugServer.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Manages the network socket and debugging state for threads running Skylark code.
 */
public final clreplaced SkylarkDebugServer implements Debugger {

    /**
     * Initializes debugging support, setting up any debugging-specific overrides, then opens the
     * debug server socket and blocks waiting for an incoming connection.
     *
     * @param port the port on which the server should listen for connections
     * @param verboseLogging if true, debug-level events will be logged
     * @throws IOException if an I/O error occurs while opening the socket or waiting for a connection
     */
    public static SkylarkDebugServer createAndWaitForConnection(EventHandler eventHandler, int port, boolean verboseLogging) throws IOException {
        ServerSocket serverSocket = new ServerSocket(port, /* backlog */
        1);
        return createAndWaitForConnection(eventHandler, serverSocket, verboseLogging);
    }

    /**
     * Initializes debugging support, setting up any debugging-specific overrides, then opens the
     * debug server socket and blocks waiting for an incoming connection.
     *
     * @param verboseLogging if true, debug-level events will be logged
     * @throws IOException if an I/O error occurs while waiting for a connection
     */
    @VisibleForTesting
    static SkylarkDebugServer createAndWaitForConnection(EventHandler eventHandler, ServerSocket serverSocket, boolean verboseLogging) throws IOException {
        DebugServerTransport transport = DebugServerTransport.createAndWaitForClient(eventHandler, serverSocket, verboseLogging);
        return new SkylarkDebugServer(eventHandler, transport, verboseLogging);
    }

    private final EventHandler eventHandler;

    /**
     * Handles all thread-related state.
     */
    private final ThreadHandler threadHandler;

    /**
     * The server socket for the debug server.
     */
    private final DebugServerTransport transport;

    private final boolean verboseLogging;

    private SkylarkDebugServer(EventHandler eventHandler, DebugServerTransport transport, boolean verboseLogging) {
        this.eventHandler = eventHandler;
        this.threadHandler = new ThreadHandler();
        this.transport = transport;
        this.verboseLogging = verboseLogging;
        listenForClientRequests();
    }

    /**
     * Starts a worker thread to listen for and handle incoming client requests, returning any
     * relevant responses.
     */
    private void listenForClientRequests() {
        Thread clientThread = new Thread(() -> {
            try {
                while (true) {
                    SkylarkDebuggingProtos.DebugRequest request = transport.readClientRequest();
                    if (request == null) {
                        return;
                    }
                    SkylarkDebuggingProtos.DebugEvent response = handleClientRequest(request);
                    if (response != null) {
                        transport.postEvent(response);
                    }
                }
            } catch (Throwable e) {
                if (!transport.isClosed()) {
                    eventHandler.handle(Event.error("Debug server listener thread died: " + Throwables.getStackTracereplacedtring(e)));
                }
            } finally {
                eventHandler.handle(Event.info("Debug server listener thread closed; shutting down debug server and " + "resuming all threads"));
                close();
            }
        });
        clientThread.setDaemon(true);
        clientThread.start();
    }

    @Override
    public void close() {
        try {
            if (verboseLogging) {
                eventHandler.handle(Event.debug("Closing debug server"));
            }
            transport.close();
        } catch (IOException e) {
            eventHandler.handle(Event.error("Error shutting down the debug server: " + Throwables.getStackTracereplacedtring(e)));
        } finally {
            // ensure no threads are left paused, otherwise the build command will never complete
            threadHandler.resumeAllThreads();
        }
    }

    /**
     * Called by the interpreter before execution of the code at the specified location. Pauses the
     * execution of the current thread if there are conditions that should cause it to be paused, such
     * as a breakpoint being reached.
     *
     * @param location the location of the statement or expression currently being executed
     */
    @Override
    public void before(StarlarkThread thread, Location location) {
        if (!transport.isClosed()) {
            threadHandler.pauseIfNecessary(thread, location, transport);
        }
    }

    /**
     * Handles a request from the client, and returns the response, where relevant.
     */
    @Nullable
    private SkylarkDebuggingProtos.DebugEvent handleClientRequest(SkylarkDebuggingProtos.DebugRequest request) {
        long sequenceNumber = request.getSequenceNumber();
        try {
            switch(request.getPayloadCase()) {
                case START_DEBUGGING:
                    threadHandler.resumeAllThreads();
                    return DebugEventHelper.startDebuggingResponse(sequenceNumber);
                case LIST_FRAMES:
                    return listFrames(sequenceNumber, request.getListFrames());
                case SET_BREAKPOINTS:
                    return setBreakpoints(sequenceNumber, request.getSetBreakpoints());
                case CONTINUE_EXECUTION:
                    return continueExecution(sequenceNumber, request.getContinueExecution());
                case PAUSE_THREAD:
                    return pauseThread(sequenceNumber, request.getPauseThread());
                case EVALUATE:
                    return evaluate(sequenceNumber, request.getEvaluate());
                case GET_CHILDREN:
                    return getChildren(sequenceNumber, request.getGetChildren());
                case PAYLOAD_NOT_SET:
                    DebugEventHelper.error(sequenceNumber, "No request payload found");
            }
            return DebugEventHelper.error(sequenceNumber, "Unhandled request type: " + request.getPayloadCase());
        } catch (DebugRequestException e) {
            return DebugEventHelper.error(sequenceNumber, e.getMessage());
        }
    }

    /**
     * Handles a {@code ListFramesRequest} and returns its response.
     */
    private SkylarkDebuggingProtos.DebugEvent listFrames(long sequenceNumber, SkylarkDebuggingProtos.ListFramesRequest request) throws DebugRequestException {
        List<SkylarkDebuggingProtos.Frame> frames = threadHandler.listFrames(request.getThreadId());
        return DebugEventHelper.listFramesResponse(sequenceNumber, frames);
    }

    /**
     * Handles a {@code SetBreakpointsRequest} and returns its response.
     */
    private SkylarkDebuggingProtos.DebugEvent setBreakpoints(long sequenceNumber, SkylarkDebuggingProtos.SetBreakpointsRequest request) {
        threadHandler.setBreakpoints(request.getBreakpointList());
        return DebugEventHelper.setBreakpointsResponse(sequenceNumber);
    }

    /**
     * Handles a {@code EvaluateRequest} and returns its response.
     */
    private SkylarkDebuggingProtos.DebugEvent evaluate(long sequenceNumber, SkylarkDebuggingProtos.EvaluateRequest request) throws DebugRequestException {
        return DebugEventHelper.evaluateResponse(sequenceNumber, threadHandler.evaluate(request.getThreadId(), request.getStatement()));
    }

    /**
     * Handles a {@code GetChildrenRequest} and returns its response.
     */
    private SkylarkDebuggingProtos.DebugEvent getChildren(long sequenceNumber, SkylarkDebuggingProtos.GetChildrenRequest request) throws DebugRequestException {
        return DebugEventHelper.getChildrenResponse(sequenceNumber, threadHandler.getChildrenForValue(request.getThreadId(), request.getValueId()));
    }

    /**
     * Handles a {@code ContinueExecutionRequest} and returns its response.
     */
    private SkylarkDebuggingProtos.DebugEvent continueExecution(long sequenceNumber, SkylarkDebuggingProtos.ContinueExecutionRequest request) throws DebugRequestException {
        long threadId = request.getThreadId();
        if (threadId == 0) {
            threadHandler.resumeAllThreads();
            return DebugEventHelper.continueExecutionResponse(sequenceNumber);
        }
        threadHandler.resumeThread(threadId, request.getStepping());
        return DebugEventHelper.continueExecutionResponse(sequenceNumber);
    }

    private SkylarkDebuggingProtos.DebugEvent pauseThread(long sequenceNumber, SkylarkDebuggingProtos.PauseThreadRequest request) throws DebugRequestException {
        long threadId = request.getThreadId();
        if (threadId == 0) {
            threadHandler.pauseAllThreads();
        } else {
            threadHandler.pauseThread(threadId);
        }
        return DebugEventHelper.pauseThreadResponse(sequenceNumber);
    }
}

19 View Complete Implementation : SingleToolchainResolutionFunction.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Helper method to print a debugging message, if the given {@link EventHandler} is not {@code
 * null}.
 */
@FormatMethod
private static void debugMessage(@Nullable EventHandler eventHandler, @FormatString String template, Object... args) {
    if (eventHandler == null) {
        return;
    }
    eventHandler.handle(Event.info("ToolchainResolution: " + String.format(template, args)));
}

19 View Complete Implementation : ImplicitOutputsFunction.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Given a newly-constructed Rule instance (with attributes populated), returns the list of output
 * files that this rule produces implicitly.
 */
public abstract Iterable<String> getImplicitOutputs(EventHandler eventHandler, AttributeMap rule) throws EvalException, InterruptedException;

19 View Complete Implementation : PackageContext.java
Copyright Apache License 2.0
Author : facebook
public static PackageContext of(Globber globber, Map<String, ? extends ImmutableMap<String, String>> rawConfig, PackageIdentifier packageIdentifier, EventHandler eventHandler, Map<String, ? extends Object> implicitlyLoadedSymbols) {
    return ImmutablePackageContext.of(globber, rawConfig, packageIdentifier, eventHandler, implicitlyLoadedSymbols);
}

19 View Complete Implementation : ActionCacheChecker.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Checks whether {@code action} needs to be executed and returns a non-null Token if so.
 *
 * <p>The method checks if any of the action's inputs or outputs have changed. Returns a non-null
 * {@link Token} if the action needs to be executed, and null otherwise.
 *
 * <p>If this method returns non-null, indicating that the action will be executed, the
 * metadataHandler's {@link MetadataHandler#discardOutputMetadata} method must be called, so that
 * it does not serve stale metadata for the action's outputs after the action is executed.
 */
// Note: the handler should only be used for DEPCHECKER events; there's no
// guarantee it will be available for other events.
public Token getTokenIfNeedToExecute(Action action, List<Artifact> resolvedCacheArtifacts, Map<String, String> clientEnv, EventHandler handler, MetadataHandler metadataHandler, Map<String, String> remoteDefaultPlatformProperties) {
    // TODO(bazel-team): (2010) For RunfilesAction/SymlinkAction and similar actions that
    // produce only symlinks we should not check whether inputs are valid at all - all that matters
    // that inputs and outputs are still exist (and new inputs have not appeared). All other checks
    // are unnecessary. In other words, the only metadata we should check for them is file existence
    // itself.
    MiddlemanType middlemanType = action.getActionType();
    if (middlemanType.isMiddleman()) {
        // Some types of middlemen are not checked because they should not
        // propagate invalidation of their inputs.
        if (middlemanType != MiddlemanType.SCHEDULING_DEPENDENCY_MIDDLEMAN) {
            checkMiddlemanAction(action, handler, metadataHandler);
        }
        return null;
    }
    if (!cacheConfig.enabled()) {
        return new Token(getKeyString(action));
    }
    NestedSet<Artifact> actionInputs = action.getInputs();
    // Resolve action inputs from cache, if necessary.
    boolean inputsDiscovered = action.inputsDiscovered();
    if (!inputsDiscovered && resolvedCacheArtifacts != null) {
        // The action doesn't know its inputs, but the caller has a good idea of what they are.
        Preconditions.checkState(action.discoversInputs(), "Actions that don't know their inputs must discover them: %s", action);
        actionInputs = NestedSetBuilder.wrap(Order.STABLE_ORDER, resolvedCacheArtifacts);
    }
    ActionCache.Entry entry = getCacheEntry(action);
    if (mustExecute(action, entry, handler, metadataHandler, actionInputs, clientEnv, remoteDefaultPlatformProperties)) {
        if (entry != null) {
            removeCacheEntry(action);
        }
        return new Token(getKeyString(action));
    }
    if (!inputsDiscovered) {
        action.updateInputs(actionInputs);
    }
    return null;
}

19 View Complete Implementation : ActionCacheChecker.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * In most cases, this method should not be called directly - reportXXX() methods
 * should be used instead. This is done to avoid cost replacedociated with building
 * the message.
 */
private static void reportRebuild(@Nullable EventHandler handler, Action action, String message) {
    // For MiddlemanAction, do not report rebuild.
    if (handler != null && !action.getActionType().isMiddleman()) {
        handler.handle(Event.of(EventKind.DEPCHECKER, null, "Executing " + action.prettyPrint() + ": " + message + "."));
    }
}

19 View Complete Implementation : ActionCacheChecker.java
Copyright Apache License 2.0
Author : bazelbuild
private static void reportChanged(@Nullable EventHandler handler, Action action) {
    reportRebuild(handler, action, "One of the files has changed");
}

19 View Complete Implementation : SpawnActionContextMaps.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Returns a list of appropriate {@link ActionContext}s to execute the given {@link Spawn} with.
 *
 * <p>If the reason for selecting the context is worth mentioning to the user, logs a message
 * using the given {@link Reporter}.
 */
List<SpawnStrategy> getSpawnActionContexts(Spawn spawn, EventHandler reporter) {
    Preconditions.checkNotNull(spawn);
    if (!spawnStrategyRegexList.isEmpty() && spawn.getResourceOwner() != null && // Don't override test strategies by --strategy_regexp for backwards compatibility.
    !"TestRunner".equals(spawn.getMnemonic())) {
        String description = spawn.getResourceOwner().getProgressMessage();
        if (description != null) {
            for (RegexFilterSpawnStrategy entry : spawnStrategyRegexList) {
                if (entry.regexFilter().isIncluded(description) && entry.strategies() != null) {
                    reporter.handle(Event.progress(description + " with context " + entry.strategies().toString()));
                    return entry.strategies();
                }
            }
        }
    }
    List<SpawnStrategy> strategies = mnemonicToSpawnStrategiesMap.get(spawn.getMnemonic());
    if (strategies != null) {
        return strategies;
    }
    return Preconditions.checkNotNull(mnemonicToSpawnStrategiesMap.get(""));
}

19 View Complete Implementation : TransitiveBaseTraversalFunction.java
Copyright Apache License 2.0
Author : bazelbuild
abstract void processDeps(ProcessedTargetsT processedTargets, EventHandler eventHandler, TargetAndErrorIfAny targetAndErrorIfAny, Iterable<Map.Entry<SkyKey, ValueOrException2<NoSuchPackageException, NoSuchTargetException>>> depEntries);

18 View Complete Implementation : SourceManifestAction.java
Copyright Apache License 2.0
Author : bazelbuild
@VisibleForTesting
public void writeOutputFile(OutputStream out, EventHandler eventHandler) throws IOException {
    writeFile(out, runfiles.getRunfilesInputs(eventHandler, getOwner().getLocation(), ArtifactPathResolver.IDENreplacedY));
}

18 View Complete Implementation : NdkMajorRevisionR10.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public ApiLevel apiLevel(EventHandler eventHandler, String name, String apiLevel) {
    return new ApiLevelR10e(eventHandler, name, apiLevel);
}

18 View Complete Implementation : NdkMajorRevisionR11.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public ApiLevel apiLevel(EventHandler eventHandler, String name, String apiLevel) {
    return new ApiLevelR11(eventHandler, name, apiLevel);
}

18 View Complete Implementation : NdkMajorRevisionR12.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public ApiLevel apiLevel(EventHandler eventHandler, String name, String apiLevel) {
    return new ApiLevelR12(eventHandler, name, apiLevel);
}

18 View Complete Implementation : NdkMajorRevisionR13.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public ApiLevel apiLevel(EventHandler eventHandler, String name, String apiLevel) {
    return new ApiLevelR13(eventHandler, name, apiLevel);
}

18 View Complete Implementation : NdkMajorRevisionR15.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public ApiLevel apiLevel(EventHandler eventHandler, String name, String apiLevel) {
    return new ApiLevelR15(eventHandler, name, apiLevel);
}

18 View Complete Implementation : NdkMajorRevisionR17.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public ApiLevel apiLevel(EventHandler eventHandler, String name, String apiLevel) {
    return new ApiLevelR17(eventHandler, name, apiLevel);
}

18 View Complete Implementation : NdkMajorRevisionR18.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public ApiLevel apiLevel(EventHandler eventHandler, String name, String apiLevel) {
    return new ApiLevelR18(eventHandler, name, apiLevel);
}

18 View Complete Implementation : NdkMajorRevisionR19.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public ApiLevel apiLevel(EventHandler eventHandler, String name, String apiLevel) {
    return new ApiLevelR19(eventHandler, name, apiLevel);
}

18 View Complete Implementation : BuildEventServiceModule.java
Copyright Apache License 2.0
Author : bazelbuild
protected void reportCommandLineError(EventHandler commandLineReporter, Exception exception) {
    // Don't hide unchecked exceptions as part of the error reporting.
    Throwables.throwIfUnchecked(exception);
    commandLineReporter.handle(Event.error(exception.getMessage()));
}

18 View Complete Implementation : OutputDirectoryLinksUtils.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Attempts to remove the convenience symlinks in the workspace directory.
 *
 * <p>Issues a warning if it fails, e.g. because workspaceDirectory is readonly. Also cleans up
 * any child directories created by a custom prefix.
 *
 * @param symlinkDefinitions extra symlink types added by the {@link ConfiguredRuleClreplacedProvider}
 * @param workspace the runtime's workspace
 * @param eventHandler the error eventHandler
 * @param symlinkPrefix the symlink prefix which should be removed
 * @param productName the product name
 */
public static void removeOutputDirectoryLinks(Iterable<SymlinkDefinition> symlinkDefinitions, String workspaceName, Path workspace, EventHandler eventHandler, String symlinkPrefix, String productName) {
    if (NO_CREATE_SYMLINKS_PREFIX.equals(symlinkPrefix)) {
        return;
    }
    List<String> failures = new ArrayList<>();
    String workspaceBaseName = workspace.getBaseName();
    for (SymlinkDefinition link : getAllLinkDefinitions(symlinkDefinitions)) {
        removeLink(workspace, link.getLinkName(symlinkPrefix, productName, workspaceBaseName), failures, ImmutableList.builder(), false);
    }
    FileSystemUtils.removeDirectoryAndParents(workspace, PathFragment.create(symlinkPrefix));
    if (!failures.isEmpty()) {
        eventHandler.handle(Event.warn(String.format("failed to remove one or more convenience symlinks for prefix '%s':\n  %s", symlinkPrefix, Joiner.on("\n  ").join(failures))));
    }
}

18 View Complete Implementation : OutputDirectoryLinksUtils.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Attempts to create or delete convenience symlinks in the workspace to the various output
 * directories, and generates replacedociated log events.
 *
 * <p>If {@code --symlink_prefix} is {@link NO_CREATE_SYMLINKS_PREFIX}, or {@code
 * --experimental_convenience_symlinks} is {@link ConvenienceSymlinksMode.IGNORE}, this method is
 * a no-op.
 *
 * <p>Otherwise, for each symlink type, we decide whether the symlink should exist or not. If it
 * should exist, it is created with the appropriate destination path; if not, it is deleted if
 * already present on the file system. In either case, the decision of whether to create or delete
 * the symlink is logged. (Note that deleting pre-existing symlinks helps ensure the user's
 * workspace is in a consistent state after the build. However, if the {@code --symlink_prefix}
 * has changed, we have no way to cleanup old symlink names leftover from a previous invocation.)
 *
 * <p>If {@code --experimental_convenience_symlinks} is set to {@link
 * ConvenienceSymlinksMode.CLEAN}, all symlinks are set to be deleted. If it's set to {@link
 * ConvenienceSymlinksMode.NORMAL}, each symlink type decides whether it should be created or
 * deleted. (A symlink may decide to be deleted if e.g. it is disabled by a flag, or would want to
 * point to more than one destination.) If it's set to {@link ConvenienceSymlinksMode.LOG_ONLY},
 * the same logic is run as in the {@code NORMAL} case, but the result is only emitting log
 * messages, with no actual filesystem mutations.
 *
 * <p>A warning is emitted if a symlink would resolve to multiple destinations, or if a filesystem
 * mutation operation fails.
 *
 * @return a list of {@link ConvenienceSymlink} messages describing what was created and
 *     destroyed.
 */
static ImmutableList<ConvenienceSymlink> createOutputDirectoryLinks(Iterable<SymlinkDefinition> symlinkDefinitions, BuildRequestOptions buildRequestOptions, String workspaceName, Path workspace, BlazeDirectories directories, EventHandler eventHandler, Set<BuildConfiguration> targetConfigs, Function<BuildOptions, BuildConfiguration> configGetter, String productName) {
    Path execRoot = directories.getExecRoot(workspaceName);
    Path outputPath = directories.getOutputPath(workspaceName);
    Path outputBase = directories.getOutputBase();
    String symlinkPrefix = buildRequestOptions.getSymlinkPrefix(productName);
    ConvenienceSymlinksMode mode = buildRequestOptions.experimentalConvenienceSymlinks;
    if (NO_CREATE_SYMLINKS_PREFIX.equals(symlinkPrefix)) {
        return ImmutableList.of();
    }
    ImmutableList.Builder<ConvenienceSymlink> convenienceSymlinksBuilder = ImmutableList.builder();
    List<String> failures = new ArrayList<>();
    List<String> ambiguousLinks = new ArrayList<>();
    Set<String> createdLinks = new LinkedHashSet<>();
    String workspaceBaseName = workspace.getBaseName();
    RepositoryName repositoryName = RepositoryName.createFromValidStrippedName(workspaceName);
    boolean logOnly = mode == ConvenienceSymlinksMode.LOG_ONLY;
    for (SymlinkDefinition symlink : getAllLinkDefinitions(symlinkDefinitions)) {
        String linkName = symlink.getLinkName(symlinkPrefix, productName, workspaceBaseName);
        if (!createdLinks.add(linkName)) {
            // already created a link by this name
            continue;
        }
        if (mode == ConvenienceSymlinksMode.CLEAN) {
            removeLink(workspace, linkName, failures, convenienceSymlinksBuilder, logOnly);
        } else {
            Set<Path> candidatePaths = symlink.getLinkPaths(buildRequestOptions, targetConfigs, configGetter, repositoryName, outputPath, execRoot);
            if (candidatePaths.size() == 1) {
                createLink(workspace, linkName, outputBase, Iterables.getOnlyElement(candidatePaths), failures, convenienceSymlinksBuilder, logOnly);
            } else {
                removeLink(workspace, linkName, failures, convenienceSymlinksBuilder, logOnly);
                // candidatePaths can be empty if the symlink decided not to be created. This can happen
                // if the symlink is disabled by a flag, or it intercepts an error while computing its
                // target path. In that case, don't trigger a warning about an ambiguous link.
                if (candidatePaths.size() > 1) {
                    ambiguousLinks.add(linkName);
                }
            }
        }
    }
    if (!failures.isEmpty()) {
        eventHandler.handle(Event.warn(String.format("failed to create one or more convenience symlinks for prefix '%s':\n  %s", symlinkPrefix, Joiner.on("\n  ").join(failures))));
    }
    if (!ambiguousLinks.isEmpty()) {
        eventHandler.handle(Event.warn(String.format("cleared convenience symlink(s) %s because their destinations would be ambiguous", Joiner.on(", ").join(ambiguousLinks))));
    }
    return convenienceSymlinksBuilder.build();
}

18 View Complete Implementation : RuleFactory.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Creates a {@link Rule} instance, adds it to the {@link Package.Builder} and returns it.
 *
 * @param pkgBuilder the under-construction {@link Package.Builder} to which the rule belongs
 * @param ruleClreplaced the {@link RuleClreplaced} of the rule
 * @param attributeValues a {@link BuildLangTypedAttributeValuesMap} mapping attribute names to
 *     attribute values of build-language type. Each attribute must be defined for this clreplaced of
 *     rule, and have a build-language-typed value which can be converted to the appropriate
 *     native type of the attribute (i.e. via {@link BuildType#selectableConvert}). There must be
 *     a map entry for each non-optional attribute of this clreplaced of rule.
 * @param eventHandler a eventHandler on which errors and warnings are reported during rule
 *     creation
 * @param location the location at which this rule was declared
 * @param thread the lexical environment of the function call which declared this rule (optional)
 * @param attributeContainer the {@link AttributeContainer} the rule will contain
 * @throws InvalidRuleException if the rule could not be constructed for any reason (e.g. no
 *     {@code name} attribute is defined)
 * @throws NameConflictException if the rule's name or output files conflict with others in this
 *     package
 * @throws InterruptedException if interrupted
 */
static Rule createAndAddRule(Package.Builder pkgBuilder, RuleClreplaced ruleClreplaced, BuildLangTypedAttributeValuesMap attributeValues, EventHandler eventHandler, Location location, @Nullable StarlarkThread thread, AttributeContainer attributeContainer) throws InvalidRuleException, NameConflictException, InterruptedException {
    Rule rule = createRule(pkgBuilder, ruleClreplaced, attributeValues, eventHandler, location, thread, attributeContainer);
    pkgBuilder.addRule(rule);
    return rule;
}

18 View Complete Implementation : ErrorPrintingTargetEdgeErrorObserver.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Record errors, such as missing package/target or rules containing errors, encountered during
 * visitation. Emit an error message upon encountering missing edges
 *
 * <p>The accessor {@link #hasErrors}) may not be called until the concurrent phase is over, i.e.
 * all external calls to visit() methods have completed.
 */
// condition: only call hasErrors
@ThreadSafety.ConditionallyThreadSafe
clreplaced ErrorPrintingTargetEdgeErrorObserver extends TargetEdgeErrorObserver {

    private final EventHandler eventHandler;

    /**
     * @param eventHandler eventHandler to route exceptions to as errors.
     */
    public ErrorPrintingTargetEdgeErrorObserver(EventHandler eventHandler) {
        this.eventHandler = eventHandler;
    }

    @ThreadSafety.ThreadSafe
    @Override
    public void missingEdge(Target target, Label label, NoSuchThingException e) {
        eventHandler.handle(Event.error(TargetUtils.getLocationMaybe(target), TargetUtils.formatMissingEdge(target, label, e)));
        super.missingEdge(target, label, e);
    }
}

18 View Complete Implementation : BlazeOptionHandler.java
Copyright Apache License 2.0
Author : bazelbuild
private List<String> getExpansion(EventHandler eventHandler, ListMultimap<String, RcChunkOfArgs> commandToRcArgs, String configToExpand) throws OptionsParsingException {
    LinkedHashSet<String> configAncestorSet = new LinkedHashSet<>();
    configAncestorSet.add(configToExpand);
    List<String> longestChain = new ArrayList<>();
    List<String> finalExpansion = getExpansion(eventHandler, commandToRcArgs, configAncestorSet, configToExpand, longestChain);
    // In order to prevent warning about a long chain of 13 configs at the 10, 11, 12, and 13
    // point, we identify the longest chain for this 'high-level' --config found and only warn
    // about it once. This may mean we missed a fork where each branch was independently long
    // enough to warn, but the single warning should convey the message reasonably.
    if (longestChain.size() >= 10) {
        eventHandler.handle(Event.warn(String.format("There is a recursive chain of configs %s configs long: %s. This seems " + "excessive, and might be hiding errors.", longestChain.size(), longestChain)));
    }
    return finalExpansion;
}

18 View Complete Implementation : DiffAwarenessManager.java
Copyright Apache License 2.0
Author : bazelbuild
private void handleBrokenDiffAwareness(EventHandler eventHandler, Root pathEntry, BrokenDiffAwarenessException e) {
    currentDiffAwarenessStates.remove(pathEntry);
    logger.info("Broken diff awareness for " + pathEntry + ": " + e);
    eventHandler.handle(Event.warn(e.getMessage() + "... temporarily falling back to manually " + "checking files for changes"));
}