Search in sources :

Example 11 with BuildTargetException

use of com.facebook.buck.model.BuildTargetException in project buck by facebook.

the class TestCommand method runWithoutHelp.

@Override
public int runWithoutHelp(CommandRunnerParams params) throws IOException, InterruptedException {
    LOG.debug("Running with arguments %s", getArguments());
    try (CommandThreadManager pool = new CommandThreadManager("Test", getConcurrencyLimit(params.getBuckConfig()))) {
        // Post the build started event, setting it to the Parser recorded start time if appropriate.
        BuildEvent.Started started = BuildEvent.started(getArguments());
        if (params.getParser().getParseStartTime().isPresent()) {
            params.getBuckEventBus().post(started, params.getParser().getParseStartTime().get());
        } else {
            params.getBuckEventBus().post(started);
        }
        // The first step is to parse all of the build files. This will populate the parser and find
        // all of the test rules.
        TargetGraphAndBuildTargets targetGraphAndBuildTargets;
        ParserConfig parserConfig = params.getBuckConfig().getView(ParserConfig.class);
        try {
            // If the user asked to run all of the tests, parse all of the build files looking for any
            // test rules.
            boolean ignoreBuckAutodepsFiles = false;
            if (isRunAllTests()) {
                targetGraphAndBuildTargets = params.getParser().buildTargetGraphForTargetNodeSpecs(params.getBuckEventBus(), params.getCell(), getEnableParserProfiling(), pool.getExecutor(), ImmutableList.of(TargetNodePredicateSpec.of(input -> Description.getBuildRuleType(input.getDescription()).isTestRule(), BuildFileSpec.fromRecursivePath(Paths.get(""), params.getCell().getRoot()))), ignoreBuckAutodepsFiles, parserConfig.getDefaultFlavorsMode());
                targetGraphAndBuildTargets = targetGraphAndBuildTargets.withBuildTargets(ImmutableSet.of());
            // Otherwise, the user specified specific test targets to build and run, so build a graph
            // around these.
            } else {
                LOG.debug("Parsing graph for arguments %s", getArguments());
                targetGraphAndBuildTargets = params.getParser().buildTargetGraphForTargetNodeSpecs(params.getBuckEventBus(), params.getCell(), getEnableParserProfiling(), pool.getExecutor(), parseArgumentsAsTargetNodeSpecs(params.getBuckConfig(), getArguments()), ignoreBuckAutodepsFiles, parserConfig.getDefaultFlavorsMode());
                LOG.debug("Got explicit build targets %s", targetGraphAndBuildTargets.getBuildTargets());
                ImmutableSet.Builder<BuildTarget> testTargetsBuilder = ImmutableSet.builder();
                for (TargetNode<?, ?> node : targetGraphAndBuildTargets.getTargetGraph().getAll(targetGraphAndBuildTargets.getBuildTargets())) {
                    ImmutableSortedSet<BuildTarget> nodeTests = TargetNodes.getTestTargetsForNode(node);
                    if (!nodeTests.isEmpty()) {
                        LOG.debug("Got tests for target %s: %s", node.getBuildTarget(), nodeTests);
                        testTargetsBuilder.addAll(nodeTests);
                    }
                }
                ImmutableSet<BuildTarget> testTargets = testTargetsBuilder.build();
                if (!testTargets.isEmpty()) {
                    LOG.debug("Got related test targets %s, building new target graph...", testTargets);
                    TargetGraph targetGraph = params.getParser().buildTargetGraph(params.getBuckEventBus(), params.getCell(), getEnableParserProfiling(), pool.getExecutor(), Iterables.concat(targetGraphAndBuildTargets.getBuildTargets(), testTargets));
                    LOG.debug("Finished building new target graph with tests.");
                    targetGraphAndBuildTargets = targetGraphAndBuildTargets.withTargetGraph(targetGraph);
                }
            }
            if (params.getBuckConfig().getBuildVersions()) {
                targetGraphAndBuildTargets = toVersionedTargetGraph(params, targetGraphAndBuildTargets);
            }
        } catch (BuildTargetException | BuildFileParseException | VersionException e) {
            params.getBuckEventBus().post(ConsoleEvent.severe(MoreExceptions.getHumanReadableOrLocalizedMessage(e)));
            return 1;
        }
        ActionGraphAndResolver actionGraphAndResolver = Preconditions.checkNotNull(params.getActionGraphCache().getActionGraph(params.getBuckEventBus(), params.getBuckConfig().isActionGraphCheckingEnabled(), params.getBuckConfig().isSkipActionGraphCache(), targetGraphAndBuildTargets.getTargetGraph(), params.getBuckConfig().getKeySeed()));
        // Look up all of the test rules in the action graph.
        Iterable<TestRule> testRules = Iterables.filter(actionGraphAndResolver.getActionGraph().getNodes(), TestRule.class);
        // the build.
        if (!isBuildFiltered(params.getBuckConfig())) {
            testRules = filterTestRules(params.getBuckConfig(), targetGraphAndBuildTargets.getBuildTargets(), testRules);
        }
        CachingBuildEngineBuckConfig cachingBuildEngineBuckConfig = params.getBuckConfig().getView(CachingBuildEngineBuckConfig.class);
        try (CommandThreadManager artifactFetchService = getArtifactFetchService(params.getBuckConfig(), pool.getExecutor());
            RuleKeyCacheScope<RuleKey> ruleKeyCacheScope = getDefaultRuleKeyCacheScope(params, new RuleKeyCacheRecycler.SettingsAffectingCache(params.getBuckConfig().getKeySeed(), actionGraphAndResolver.getActionGraph()))) {
            LocalCachingBuildEngineDelegate localCachingBuildEngineDelegate = new LocalCachingBuildEngineDelegate(params.getFileHashCache());
            CachingBuildEngine cachingBuildEngine = new CachingBuildEngine(new LocalCachingBuildEngineDelegate(params.getFileHashCache()), pool.getExecutor(), artifactFetchService == null ? pool.getExecutor() : artifactFetchService.getExecutor(), new DefaultStepRunner(), getBuildEngineMode().orElse(cachingBuildEngineBuckConfig.getBuildEngineMode()), cachingBuildEngineBuckConfig.getBuildDepFiles(), cachingBuildEngineBuckConfig.getBuildMaxDepFileCacheEntries(), cachingBuildEngineBuckConfig.getBuildArtifactCacheSizeLimit(), params.getObjectMapper(), actionGraphAndResolver.getResolver(), cachingBuildEngineBuckConfig.getResourceAwareSchedulingInfo(), new RuleKeyFactoryManager(params.getBuckConfig().getKeySeed(), fs -> localCachingBuildEngineDelegate.getFileHashCache(), actionGraphAndResolver.getResolver(), cachingBuildEngineBuckConfig.getBuildInputRuleKeyFileSizeLimit(), ruleKeyCacheScope.getCache()));
            try (Build build = createBuild(params.getBuckConfig(), actionGraphAndResolver.getActionGraph(), actionGraphAndResolver.getResolver(), params.getCell(), params.getAndroidPlatformTargetSupplier(), cachingBuildEngine, params.getArtifactCacheFactory().newInstance(), params.getConsole(), params.getBuckEventBus(), getTargetDeviceOptional(), params.getPersistentWorkerPools(), params.getPlatform(), params.getEnvironment(), params.getObjectMapper(), params.getClock(), Optional.of(getAdbOptions(params.getBuckConfig())), Optional.of(getTargetDeviceOptions()), params.getExecutors())) {
                // Build all of the test rules.
                int exitCode = build.executeAndPrintFailuresToEventBus(RichStream.from(testRules).map(TestRule::getBuildTarget).collect(MoreCollectors.toImmutableList()), isKeepGoing(), params.getBuckEventBus(), params.getConsole(), getPathToBuildReport(params.getBuckConfig()));
                params.getBuckEventBus().post(BuildEvent.finished(started, exitCode));
                if (exitCode != 0) {
                    return exitCode;
                }
                // the filtering here, after we've done the build but before we run the tests.
                if (isBuildFiltered(params.getBuckConfig())) {
                    testRules = filterTestRules(params.getBuckConfig(), targetGraphAndBuildTargets.getBuildTargets(), testRules);
                }
                // Once all of the rules are built, then run the tests.
                Optional<ImmutableList<String>> externalTestRunner = params.getBuckConfig().getExternalTestRunner();
                if (externalTestRunner.isPresent()) {
                    SourcePathResolver pathResolver = new SourcePathResolver(new SourcePathRuleFinder(actionGraphAndResolver.getResolver()));
                    return runTestsExternal(params, build, externalTestRunner.get(), testRules, pathResolver);
                }
                return runTestsInternal(params, cachingBuildEngine, build, testRules);
            }
        }
    }
}
Also used : TargetNodePredicateSpec(com.facebook.buck.parser.TargetNodePredicateSpec) SourcePathRuleFinder(com.facebook.buck.rules.SourcePathRuleFinder) RichStream(com.facebook.buck.util.RichStream) AdbOptions(com.facebook.buck.step.AdbOptions) TestRunningOptions(com.facebook.buck.test.TestRunningOptions) RuleKey(com.facebook.buck.rules.RuleKey) SourcePathResolver(com.facebook.buck.rules.SourcePathResolver) DefaultStepRunner(com.facebook.buck.step.DefaultStepRunner) Map(java.util.Map) ConcurrencyLimit(com.facebook.buck.util.concurrent.ConcurrencyLimit) TestRule(com.facebook.buck.rules.TestRule) Path(java.nio.file.Path) ImmutableSet(com.google.common.collect.ImmutableSet) TargetGraph(com.facebook.buck.rules.TargetGraph) BuildTargetException(com.facebook.buck.model.BuildTargetException) Set(java.util.Set) ProcessExecutorParams(com.facebook.buck.util.ProcessExecutorParams) Option(org.kohsuke.args4j.Option) BuildTarget(com.facebook.buck.model.BuildTarget) SuppressFieldNotInitialized(com.facebook.infer.annotation.SuppressFieldNotInitialized) Collectors(java.util.stream.Collectors) ActionGraphAndResolver(com.facebook.buck.rules.ActionGraphAndResolver) CachingBuildEngine(com.facebook.buck.rules.CachingBuildEngine) List(java.util.List) ForwardingProcessListener(com.facebook.buck.util.ForwardingProcessListener) ExternalTestRunnerTestSpec(com.facebook.buck.rules.ExternalTestRunnerTestSpec) Optional(java.util.Optional) Description(com.facebook.buck.rules.Description) RuleKeyFactoryManager(com.facebook.buck.rules.keys.RuleKeyFactoryManager) ExternalTestRunnerRule(com.facebook.buck.rules.ExternalTestRunnerRule) Iterables(com.google.common.collect.Iterables) TargetGraphAndBuildTargets(com.facebook.buck.rules.TargetGraphAndBuildTargets) Build(com.facebook.buck.command.Build) VersionException(com.facebook.buck.versions.VersionException) RuleKeyCacheRecycler(com.facebook.buck.rules.keys.RuleKeyCacheRecycler) MoreExceptions(com.facebook.buck.util.MoreExceptions) HashMap(java.util.HashMap) ConsoleEvent(com.facebook.buck.event.ConsoleEvent) Lists(com.google.common.collect.Lists) ParserConfig(com.facebook.buck.parser.ParserConfig) Label(com.facebook.buck.rules.Label) ImmutableList(com.google.common.collect.ImmutableList) LocalCachingBuildEngineDelegate(com.facebook.buck.rules.LocalCachingBuildEngineDelegate) CachingBuildEngineBuckConfig(com.facebook.buck.rules.CachingBuildEngineBuckConfig) BuildFileParseException(com.facebook.buck.json.BuildFileParseException) Nullable(javax.annotation.Nullable) MoreCollectors(com.facebook.buck.util.MoreCollectors) ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) PrintStream(java.io.PrintStream) Logger(com.facebook.buck.log.Logger) RuleKeyCacheScope(com.facebook.buck.rules.keys.RuleKeyCacheScope) BuildFileSpec(com.facebook.buck.parser.BuildFileSpec) Files(java.nio.file.Files) TargetNode(com.facebook.buck.rules.TargetNode) Channels(java.nio.channels.Channels) TargetDeviceOptions(com.facebook.buck.step.TargetDeviceOptions) IOException(java.io.IOException) TargetDevice(com.facebook.buck.step.TargetDevice) ExecutionException(java.util.concurrent.ExecutionException) BuildEvent(com.facebook.buck.rules.BuildEvent) CoverageReportFormat(com.facebook.buck.test.CoverageReportFormat) Paths(java.nio.file.Paths) BuildEngine(com.facebook.buck.rules.BuildEngine) Preconditions(com.google.common.base.Preconditions) TargetNodes(com.facebook.buck.rules.TargetNodes) VisibleForTesting(com.google.common.annotations.VisibleForTesting) ListeningProcessExecutor(com.facebook.buck.util.ListeningProcessExecutor) Comparator(java.util.Comparator) ImmutableList(com.google.common.collect.ImmutableList) TargetGraph(com.facebook.buck.rules.TargetGraph) RuleKeyFactoryManager(com.facebook.buck.rules.keys.RuleKeyFactoryManager) BuildFileParseException(com.facebook.buck.json.BuildFileParseException) ImmutableSet(com.google.common.collect.ImmutableSet) BuildTarget(com.facebook.buck.model.BuildTarget) Build(com.facebook.buck.command.Build) DefaultStepRunner(com.facebook.buck.step.DefaultStepRunner) ActionGraphAndResolver(com.facebook.buck.rules.ActionGraphAndResolver) BuildTargetException(com.facebook.buck.model.BuildTargetException) LocalCachingBuildEngineDelegate(com.facebook.buck.rules.LocalCachingBuildEngineDelegate) RuleKey(com.facebook.buck.rules.RuleKey) CachingBuildEngine(com.facebook.buck.rules.CachingBuildEngine) SourcePathResolver(com.facebook.buck.rules.SourcePathResolver) SourcePathRuleFinder(com.facebook.buck.rules.SourcePathRuleFinder) TestRule(com.facebook.buck.rules.TestRule) BuildEvent(com.facebook.buck.rules.BuildEvent) RuleKeyCacheRecycler(com.facebook.buck.rules.keys.RuleKeyCacheRecycler) TargetGraphAndBuildTargets(com.facebook.buck.rules.TargetGraphAndBuildTargets) ParserConfig(com.facebook.buck.parser.ParserConfig) VersionException(com.facebook.buck.versions.VersionException) CachingBuildEngineBuckConfig(com.facebook.buck.rules.CachingBuildEngineBuckConfig)

Example 12 with BuildTargetException

use of com.facebook.buck.model.BuildTargetException in project buck by facebook.

the class UninstallCommand method runWithoutHelp.

@Override
public int runWithoutHelp(CommandRunnerParams params) throws IOException, InterruptedException {
    // Parse all of the build targets specified by the user.
    BuildRuleResolver resolver;
    ImmutableSet<BuildTarget> buildTargets;
    try (CommandThreadManager pool = new CommandThreadManager("Uninstall", getConcurrencyLimit(params.getBuckConfig()))) {
        TargetGraphAndBuildTargets result = params.getParser().buildTargetGraphForTargetNodeSpecs(params.getBuckEventBus(), params.getCell(), getEnableParserProfiling(), pool.getExecutor(), parseArgumentsAsTargetNodeSpecs(params.getBuckConfig(), getArguments()), /* ignoreBuckAutodepsFiles */
        false);
        buildTargets = result.getBuildTargets();
        resolver = Preconditions.checkNotNull(params.getActionGraphCache().getActionGraph(params.getBuckEventBus(), params.getBuckConfig().isActionGraphCheckingEnabled(), params.getBuckConfig().isSkipActionGraphCache(), result.getTargetGraph(), params.getBuckConfig().getKeySeed())).getResolver();
    } catch (BuildTargetException | BuildFileParseException e) {
        params.getBuckEventBus().post(ConsoleEvent.severe(MoreExceptions.getHumanReadableOrLocalizedMessage(e)));
        return 1;
    }
    // Make sure that only one build target is specified.
    if (buildTargets.size() != 1) {
        params.getBuckEventBus().post(ConsoleEvent.severe("Must specify exactly one android_binary() rule."));
        return 1;
    }
    BuildTarget buildTarget = Iterables.get(buildTargets, 0);
    // Find the android_binary() rule from the parse.
    BuildRule buildRule;
    try {
        buildRule = resolver.requireRule(buildTarget);
    } catch (NoSuchBuildTargetException e) {
        throw new HumanReadableException(e.getHumanReadableErrorMessage());
    }
    if (!(buildRule instanceof HasInstallableApk)) {
        params.getBuckEventBus().post(ConsoleEvent.severe(String.format("Specified rule %s must be of type android_binary() or apk_genrule() but was %s().\n", buildRule.getFullyQualifiedName(), buildRule.getType())));
        return 1;
    }
    HasInstallableApk hasInstallableApk = (HasInstallableApk) buildRule;
    // We need this in case adb isn't already running.
    try (ExecutionContext context = createExecutionContext(params)) {
        final AdbHelper adbHelper = new AdbHelper(adbOptions(params.getBuckConfig()), targetDeviceOptions(), context, params.getConsole(), params.getBuckEventBus(), params.getBuckConfig().getRestartAdbOnFailure());
        // Find application package name from manifest and uninstall from matching devices.
        SourcePathResolver pathResolver = new SourcePathResolver(new SourcePathRuleFinder(resolver));
        String appId = AdbHelper.tryToExtractPackageNameFromManifest(pathResolver, hasInstallableApk.getApkInfo());
        return adbHelper.uninstallApp(appId, uninstallOptions().shouldKeepUserData()) ? 0 : 1;
    }
}
Also used : NoSuchBuildTargetException(com.facebook.buck.parser.NoSuchBuildTargetException) BuildTargetException(com.facebook.buck.model.BuildTargetException) BuildFileParseException(com.facebook.buck.json.BuildFileParseException) SourcePathResolver(com.facebook.buck.rules.SourcePathResolver) SourcePathRuleFinder(com.facebook.buck.rules.SourcePathRuleFinder) BuildRuleResolver(com.facebook.buck.rules.BuildRuleResolver) ExecutionContext(com.facebook.buck.step.ExecutionContext) BuildTarget(com.facebook.buck.model.BuildTarget) HumanReadableException(com.facebook.buck.util.HumanReadableException) NoSuchBuildTargetException(com.facebook.buck.parser.NoSuchBuildTargetException) BuildRule(com.facebook.buck.rules.BuildRule) AdbHelper(com.facebook.buck.android.AdbHelper) TargetGraphAndBuildTargets(com.facebook.buck.rules.TargetGraphAndBuildTargets) HasInstallableApk(com.facebook.buck.android.HasInstallableApk)

Example 13 with BuildTargetException

use of com.facebook.buck.model.BuildTargetException in project buck by facebook.

the class Parser method resolveTargetSpecs.

private ImmutableList<ImmutableSet<BuildTarget>> resolveTargetSpecs(PerBuildState state, BuckEventBus eventBus, Cell rootCell, Iterable<? extends TargetNodeSpec> specs, final ParserConfig.ApplyDefaultFlavorsMode applyDefaultFlavorsMode) throws BuildFileParseException, BuildTargetException, InterruptedException, IOException {
    ParserConfig parserConfig = rootCell.getBuckConfig().getView(ParserConfig.class);
    ParserConfig.BuildFileSearchMethod buildFileSearchMethod;
    if (parserConfig.getBuildFileSearchMethod().isPresent()) {
        buildFileSearchMethod = parserConfig.getBuildFileSearchMethod().get();
    } else if (parserConfig.getAllowSymlinks() == ParserConfig.AllowSymlinks.FORBID) {
        // If unspecified, only use Watchman in repositories which enforce a "no symlinks" rule
        // (Watchman doesn't follow symlinks).
        buildFileSearchMethod = ParserConfig.BuildFileSearchMethod.WATCHMAN;
    } else {
        buildFileSearchMethod = ParserConfig.BuildFileSearchMethod.FILESYSTEM_CRAWL;
    }
    // Convert the input spec iterable into a list so we have a fixed ordering, which we'll rely on
    // when returning results.
    final ImmutableList<TargetNodeSpec> orderedSpecs = ImmutableList.copyOf(specs);
    // Resolve all the build files from all the target specs.  We store these into a multi-map which
    // maps the path to the build file to the index of it's spec file in the ordered spec list.
    Multimap<Path, Integer> perBuildFileSpecs = LinkedHashMultimap.create();
    for (int index = 0; index < orderedSpecs.size(); index++) {
        TargetNodeSpec spec = orderedSpecs.get(index);
        Cell cell = rootCell.getCell(spec.getBuildFileSpec().getCellPath());
        ImmutableSet<Path> buildFiles;
        try (SimplePerfEvent.Scope perfEventScope = SimplePerfEvent.scope(eventBus, PerfEventId.of("FindBuildFiles"), "targetNodeSpec", spec)) {
            // Iterate over the build files the given target node spec returns.
            buildFiles = spec.getBuildFileSpec().findBuildFiles(cell, buildFileSearchMethod);
        }
        for (Path buildFile : buildFiles) {
            perBuildFileSpecs.put(buildFile, index);
        }
    }
    // Kick off parse futures for each build file.
    ArrayList<ListenableFuture<ImmutableList<Map.Entry<Integer, ImmutableSet<BuildTarget>>>>> targetFutures = new ArrayList<>();
    for (Path buildFile : perBuildFileSpecs.keySet()) {
        final Collection<Integer> buildFileSpecs = perBuildFileSpecs.get(buildFile);
        TargetNodeSpec firstSpec = orderedSpecs.get(Iterables.get(buildFileSpecs, 0));
        Cell cell = rootCell.getCell(firstSpec.getBuildFileSpec().getCellPath());
        // Format a proper error message for non-existent build files.
        if (!cell.getFilesystem().isFile(buildFile)) {
            throw new MissingBuildFileException(firstSpec, cell.getFilesystem().getRootPath().relativize(buildFile));
        }
        // Build up a list of all target nodes from the build file.
        targetFutures.add(Futures.transform(state.getAllTargetNodesJob(cell, buildFile), new Function<ImmutableSet<TargetNode<?, ?>>, ImmutableList<Map.Entry<Integer, ImmutableSet<BuildTarget>>>>() {

            @Override
            public ImmutableList<Map.Entry<Integer, ImmutableSet<BuildTarget>>> apply(ImmutableSet<TargetNode<?, ?>> nodes) {
                ImmutableList.Builder<Map.Entry<Integer, ImmutableSet<BuildTarget>>> targets = ImmutableList.builder();
                for (int index : buildFileSpecs) {
                    // Call back into the target node spec to filter the relevant build targets.
                    // We return a pair of spec index and build target set, so that we can build a
                    // final result list that maintains the input spec ordering.
                    targets.add(new AbstractMap.SimpleEntry<>(index, applySpecFilter(orderedSpecs.get(index), nodes, applyDefaultFlavorsMode)));
                }
                return targets.build();
            }
        }));
    }
    // Now walk through and resolve all the futures, and place their results in a multimap that
    // is indexed by the integer representing the input target spec order.
    LinkedHashMultimap<Integer, BuildTarget> targetsMap = LinkedHashMultimap.create();
    try {
        for (ListenableFuture<ImmutableList<Map.Entry<Integer, ImmutableSet<BuildTarget>>>> targetFuture : targetFutures) {
            ImmutableList<Map.Entry<Integer, ImmutableSet<BuildTarget>>> results = targetFuture.get();
            for (Map.Entry<Integer, ImmutableSet<BuildTarget>> ent : results) {
                targetsMap.putAll(ent.getKey(), ent.getValue());
            }
        }
    } catch (ExecutionException e) {
        Throwables.throwIfInstanceOf(e.getCause(), BuildFileParseException.class);
        Throwables.throwIfInstanceOf(e.getCause(), BuildTargetException.class);
        Throwables.throwIfInstanceOf(e.getCause(), IOException.class);
        Throwables.throwIfUnchecked(e.getCause());
        throw new RuntimeException(e.getCause());
    }
    // Finally, pull out the final build target results in input target spec order, and place them
    // into a list of sets that exactly matches the ihput order.
    ImmutableList.Builder<ImmutableSet<BuildTarget>> targets = ImmutableList.builder();
    for (int index = 0; index < orderedSpecs.size(); index++) {
        targets.add(ImmutableSet.copyOf(targetsMap.get(index)));
    }
    return targets.build();
}
Also used : TargetNode(com.facebook.buck.rules.TargetNode) ImmutableList(com.google.common.collect.ImmutableList) ArrayList(java.util.ArrayList) BuildFileParseException(com.facebook.buck.json.BuildFileParseException) AbstractMap(java.util.AbstractMap) Function(com.google.common.base.Function) ImmutableSet(com.google.common.collect.ImmutableSet) BuildTarget(com.facebook.buck.model.BuildTarget) SimplePerfEvent(com.facebook.buck.event.SimplePerfEvent) ExecutionException(java.util.concurrent.ExecutionException) Cell(com.facebook.buck.rules.Cell) Path(java.nio.file.Path) BuildTargetException(com.facebook.buck.model.BuildTargetException) IOException(java.io.IOException) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) SortedMap(java.util.SortedMap) HashMap(java.util.HashMap) AbstractMap(java.util.AbstractMap) TreeMap(java.util.TreeMap)

Example 14 with BuildTargetException

use of com.facebook.buck.model.BuildTargetException in project buck by facebook.

the class Parser method buildTargetGraph.

@SuppressWarnings("PMD.PrematureDeclaration")
protected TargetGraph buildTargetGraph(final PerBuildState state, final BuckEventBus eventBus, final Iterable<BuildTarget> toExplore, final boolean ignoreBuckAutodepsFiles) throws IOException, InterruptedException, BuildFileParseException, BuildTargetException {
    if (Iterables.isEmpty(toExplore)) {
        return TargetGraph.EMPTY;
    }
    final Map<BuildTarget, TargetGroup> groups = Maps.newHashMap();
    for (TargetGroup group : state.getAllGroups()) {
        groups.put(group.getBuildTarget(), group);
    }
    final MutableDirectedGraph<TargetNode<?, ?>> graph = new MutableDirectedGraph<>();
    final Map<BuildTarget, TargetNode<?, ?>> index = new HashMap<>();
    ParseEvent.Started parseStart = ParseEvent.started(toExplore);
    eventBus.post(parseStart);
    GraphTraversable<BuildTarget> traversable = target -> {
        TargetNode<?, ?> node;
        try {
            node = state.getTargetNode(target);
        } catch (BuildFileParseException | BuildTargetException e) {
            throw new RuntimeException(e);
        }
        if (ignoreBuckAutodepsFiles) {
            return Collections.emptyIterator();
        }
        for (BuildTarget dep : node.getDeps()) {
            try {
                state.getTargetNode(dep);
            } catch (BuildFileParseException | BuildTargetException | HumanReadableException e) {
                throw new HumanReadableException(e, "Couldn't get dependency '%s' of target '%s':\n%s", dep, target, e.getMessage());
            }
        }
        return node.getDeps().iterator();
    };
    GraphTraversable<BuildTarget> groupExpander = target -> {
        TargetGroup group = Preconditions.checkNotNull(groups.get(target), "SANITY FAILURE: Tried to expand group %s but it doesn't exist.", target);
        return Iterators.filter(group.iterator(), groups::containsKey);
    };
    AcyclicDepthFirstPostOrderTraversal<BuildTarget> targetGroupExpansion = new AcyclicDepthFirstPostOrderTraversal<>(groupExpander);
    AcyclicDepthFirstPostOrderTraversal<BuildTarget> targetNodeTraversal = new AcyclicDepthFirstPostOrderTraversal<>(traversable);
    TargetGraph targetGraph = null;
    try {
        for (BuildTarget target : targetNodeTraversal.traverse(toExplore)) {
            TargetNode<?, ?> targetNode = state.getTargetNode(target);
            Preconditions.checkNotNull(targetNode, "No target node found for %s", target);
            graph.addNode(targetNode);
            MoreMaps.putCheckEquals(index, target, targetNode);
            if (target.isFlavored()) {
                BuildTarget unflavoredTarget = BuildTarget.of(target.getUnflavoredBuildTarget());
                MoreMaps.putCheckEquals(index, unflavoredTarget, state.getTargetNode(unflavoredTarget));
            }
            for (BuildTarget dep : targetNode.getDeps()) {
                graph.addEdge(targetNode, state.getTargetNode(dep));
            }
        }
        for (BuildTarget groupTarget : targetGroupExpansion.traverse(groups.keySet())) {
            ImmutableMap<BuildTarget, Iterable<BuildTarget>> replacements = Maps.toMap(groupExpander.findChildren(groupTarget), target -> {
                TargetGroup group = groups.get(target);
                return Preconditions.checkNotNull(group, "SANITY FAILURE: Tried to expand group %s but it doesn't exist.", target);
            });
            if (!replacements.isEmpty()) {
                // TODO(tophyr): Stop duplicating target lists
                groups.put(groupTarget, Preconditions.checkNotNull(groups.get(groupTarget)).withReplacedTargets(replacements));
            }
        }
        targetGraph = new TargetGraph(graph, ImmutableMap.copyOf(index), ImmutableSet.copyOf(groups.values()));
        state.ensureConcreteFilesExist(eventBus);
        return targetGraph;
    } catch (AcyclicDepthFirstPostOrderTraversal.CycleException e) {
        throw new HumanReadableException(e.getMessage());
    } catch (RuntimeException e) {
        throw propagateRuntimeCause(e);
    } finally {
        eventBus.post(ParseEvent.finished(parseStart, Optional.ofNullable(targetGraph)));
    }
}
Also used : BroadcastEventListener(com.facebook.buck.event.listener.BroadcastEventListener) PerfEventId(com.facebook.buck.event.PerfEventId) BuckEvent(com.facebook.buck.event.BuckEvent) MoreMaps(com.facebook.buck.util.MoreMaps) TypeCoercerFactory(com.facebook.buck.rules.coercer.TypeCoercerFactory) Map(java.util.Map) AcyclicDepthFirstPostOrderTraversal(com.facebook.buck.graph.AcyclicDepthFirstPostOrderTraversal) Cell(com.facebook.buck.rules.Cell) Path(java.nio.file.Path) LinkedHashMultimap(com.google.common.collect.LinkedHashMultimap) Function(com.google.common.base.Function) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) TargetGraph(com.facebook.buck.rules.TargetGraph) Collection(java.util.Collection) BuildTargetException(com.facebook.buck.model.BuildTargetException) WatchEvents(com.facebook.buck.io.WatchEvents) BuildTarget(com.facebook.buck.model.BuildTarget) HasDefaultFlavors(com.facebook.buck.model.HasDefaultFlavors) ConstructorArgMarshaller(com.facebook.buck.rules.ConstructorArgMarshaller) Optional(java.util.Optional) SortedMap(java.util.SortedMap) ImplicitFlavorsInferringDescription(com.facebook.buck.rules.ImplicitFlavorsInferringDescription) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) BuckEventBus(com.facebook.buck.event.BuckEventBus) Iterables(com.google.common.collect.Iterables) TargetGraphAndBuildTargets(com.facebook.buck.rules.TargetGraphAndBuildTargets) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) SimplePerfEvent(com.facebook.buck.event.SimplePerfEvent) MutableDirectedGraph(com.facebook.buck.graph.MutableDirectedGraph) HashMap(java.util.HashMap) Multimap(com.google.common.collect.Multimap) GraphTraversable(com.facebook.buck.graph.GraphTraversable) Iterators(com.google.common.collect.Iterators) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) TargetGroup(com.facebook.buck.rules.TargetGroup) Subscribe(com.google.common.eventbus.Subscribe) BuildFileParseException(com.facebook.buck.json.BuildFileParseException) Nullable(javax.annotation.Nullable) MoreCollectors(com.facebook.buck.util.MoreCollectors) ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) Logger(com.facebook.buck.log.Logger) Counter(com.facebook.buck.counters.Counter) TargetNode(com.facebook.buck.rules.TargetNode) WatchEvent(java.nio.file.WatchEvent) Throwables(com.google.common.base.Throwables) IOException(java.io.IOException) HumanReadableException(com.facebook.buck.util.HumanReadableException) Maps(com.google.common.collect.Maps) ExecutionException(java.util.concurrent.ExecutionException) Futures(com.google.common.util.concurrent.Futures) AbstractMap(java.util.AbstractMap) TreeMap(java.util.TreeMap) Preconditions(com.google.common.base.Preconditions) Flavor(com.facebook.buck.model.Flavor) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Collections(java.util.Collections) TargetNode(com.facebook.buck.rules.TargetNode) HashMap(java.util.HashMap) TargetGraph(com.facebook.buck.rules.TargetGraph) BuildTarget(com.facebook.buck.model.BuildTarget) HumanReadableException(com.facebook.buck.util.HumanReadableException) TargetGroup(com.facebook.buck.rules.TargetGroup) AcyclicDepthFirstPostOrderTraversal(com.facebook.buck.graph.AcyclicDepthFirstPostOrderTraversal) MutableDirectedGraph(com.facebook.buck.graph.MutableDirectedGraph)

Aggregations

BuildTargetException (com.facebook.buck.model.BuildTargetException)14 BuildFileParseException (com.facebook.buck.json.BuildFileParseException)13 BuildTarget (com.facebook.buck.model.BuildTarget)12 ImmutableSet (com.google.common.collect.ImmutableSet)10 TargetNode (com.facebook.buck.rules.TargetNode)8 HumanReadableException (com.facebook.buck.util.HumanReadableException)8 ImmutableList (com.google.common.collect.ImmutableList)8 IOException (java.io.IOException)8 Path (java.nio.file.Path)8 ConsoleEvent (com.facebook.buck.event.ConsoleEvent)6 TargetGraph (com.facebook.buck.rules.TargetGraph)6 MoreExceptions (com.facebook.buck.util.MoreExceptions)6 Logger (com.facebook.buck.log.Logger)5 ParserConfig (com.facebook.buck.parser.ParserConfig)5 Cell (com.facebook.buck.rules.Cell)5 MoreCollectors (com.facebook.buck.util.MoreCollectors)5 Lists (com.google.common.collect.Lists)5 List (java.util.List)5 Optional (java.util.Optional)5 Option (org.kohsuke.args4j.Option)5