Search in sources :

Example 6 with TargetNode

use of com.facebook.buck.rules.TargetNode in project buck by facebook.

the class ResolveAliasHelper method validateBuildTargetForFullyQualifiedTarget.

/**
   * Verify that the given target is a valid full-qualified (non-alias) target.
   */
@Nullable
static String validateBuildTargetForFullyQualifiedTarget(CommandRunnerParams params, ListeningExecutorService executor, boolean enableProfiling, String target, Parser parser) {
    BuildTarget buildTarget = getBuildTargetForFullyQualifiedTarget(params.getBuckConfig(), target);
    Cell owningCell = params.getCell().getCell(buildTarget);
    Path buildFile;
    try {
        buildFile = owningCell.getAbsolutePathToBuildFile(buildTarget);
    } catch (Cell.MissingBuildFileException e) {
        throw new HumanReadableException(e);
    }
    // Get all valid targets in our target directory by reading the build file.
    ImmutableSet<TargetNode<?, ?>> targetNodes;
    try {
        targetNodes = parser.getAllTargetNodes(params.getBuckEventBus(), owningCell, enableProfiling, executor, buildFile);
    } catch (BuildFileParseException e) {
        throw new HumanReadableException(e);
    }
    // Check that the given target is a valid target.
    for (TargetNode<?, ?> candidate : targetNodes) {
        if (candidate.getBuildTarget().equals(buildTarget)) {
            return buildTarget.getFullyQualifiedName();
        }
    }
    return null;
}
Also used : Path(java.nio.file.Path) TargetNode(com.facebook.buck.rules.TargetNode) BuildTarget(com.facebook.buck.model.BuildTarget) HumanReadableException(com.facebook.buck.util.HumanReadableException) Cell(com.facebook.buck.rules.Cell) BuildFileParseException(com.facebook.buck.json.BuildFileParseException) Nullable(javax.annotation.Nullable)

Example 7 with TargetNode

use of com.facebook.buck.rules.TargetNode in project buck by facebook.

the class TargetsCommand method printJsonForTargets.

@VisibleForTesting
void printJsonForTargets(CommandRunnerParams params, ListeningExecutorService executor, Iterable<TargetNode<?, ?>> targetNodes, ImmutableMap<BuildTarget, ShowOptions> showRulesResult, ImmutableSet<String> outputAttributes) throws BuildFileParseException {
    PatternsMatcher attributesPatternsMatcher = new PatternsMatcher(outputAttributes);
    // Print the JSON representation of the build node for the specified target(s).
    params.getConsole().getStdOut().println("[");
    ObjectMapper mapper = params.getObjectMapper();
    Iterator<TargetNode<?, ?>> targetNodeIterator = targetNodes.iterator();
    while (targetNodeIterator.hasNext()) {
        TargetNode<?, ?> targetNode = targetNodeIterator.next();
        Map<String, Object> sortedTargetRule;
        sortedTargetRule = params.getParser().getRawTargetNode(params.getBuckEventBus(), params.getCell(), getEnableParserProfiling(), executor, targetNode);
        if (sortedTargetRule == null) {
            params.getConsole().printErrorText("unable to find rule for target " + targetNode.getBuildTarget().getFullyQualifiedName());
            continue;
        }
        sortedTargetRule = attributesPatternsMatcher.filterMatchingMapKeys(sortedTargetRule);
        ShowOptions showOptions = showRulesResult.get(targetNode.getBuildTarget());
        if (showOptions != null) {
            putIfValuePresentAndMatches(ShowOptionsName.RULE_KEY.getName(), showOptions.getRuleKey(), sortedTargetRule, attributesPatternsMatcher);
            putIfValuePresentAndMatches(ShowOptionsName.OUTPUT_PATH.getName(), showOptions.getOutputPath(), sortedTargetRule, attributesPatternsMatcher);
            putIfValuePresentAndMatches(ShowOptionsName.TARGET_HASH.getName(), showOptions.getTargetHash(), sortedTargetRule, attributesPatternsMatcher);
        }
        String fullyQualifiedNameAttribute = "fully_qualified_name";
        if (attributesPatternsMatcher.matches(fullyQualifiedNameAttribute)) {
            sortedTargetRule.put(fullyQualifiedNameAttribute, targetNode.getBuildTarget().getFullyQualifiedName());
        }
        String cellPathAttribute = "buck.cell_path";
        if (isShowCellPath() && attributesPatternsMatcher.matches(cellPathAttribute)) {
            sortedTargetRule.put(cellPathAttribute, targetNode.getBuildTarget().getCellPath());
        }
        // Print the build rule information as JSON.
        StringWriter stringWriter = new StringWriter();
        try {
            mapper.writerWithDefaultPrettyPrinter().writeValue(stringWriter, sortedTargetRule);
        } catch (IOException e) {
            // Shouldn't be possible while writing to a StringWriter...
            throw new RuntimeException(e);
        }
        String output = stringWriter.getBuffer().toString();
        if (targetNodeIterator.hasNext()) {
            output += ",";
        }
        params.getConsole().getStdOut().println(output);
    }
    params.getConsole().getStdOut().println("]");
}
Also used : PatternsMatcher(com.facebook.buck.util.PatternsMatcher) TargetNode(com.facebook.buck.rules.TargetNode) StringWriter(java.io.StringWriter) IOException(java.io.IOException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 8 with TargetNode

use of com.facebook.buck.rules.TargetNode in project buck by facebook.

the class TargetsCommand method getDependentNodes.

/**
   * @param graph A graph used to resolve dependencies between targets.
   * @param nodes A set of nodes.
   * @param detectTestChanges If true, tests are considered to be dependencies of the targets they
   *                          are testing.
   * @return A set of all nodes that transitively depend on {@code nodes}
   * (a superset of {@code nodes}).
   */
private static ImmutableSet<TargetNode<?, ?>> getDependentNodes(final TargetGraph graph, ImmutableSet<TargetNode<?, ?>> nodes, boolean detectTestChanges) {
    ImmutableMultimap.Builder<TargetNode<?, ?>, TargetNode<?, ?>> extraEdgesBuilder = ImmutableMultimap.builder();
    if (detectTestChanges) {
        for (TargetNode<?, ?> node : graph.getNodes()) {
            if (node.getConstructorArg() instanceof HasTests) {
                ImmutableSortedSet<BuildTarget> tests = ((HasTests) node.getConstructorArg()).getTests();
                for (BuildTarget testTarget : tests) {
                    Optional<TargetNode<?, ?>> testNode = graph.getOptional(testTarget);
                    if (!testNode.isPresent()) {
                        throw new HumanReadableException("'%s' (test of '%s') is not in the target graph.", testTarget, node);
                    }
                    extraEdgesBuilder.put(testNode.get(), node);
                }
            }
        }
    }
    final ImmutableMultimap<TargetNode<?, ?>, TargetNode<?, ?>> extraEdges = extraEdgesBuilder.build();
    final ImmutableSet.Builder<TargetNode<?, ?>> builder = ImmutableSet.builder();
    AbstractBreadthFirstTraversal<TargetNode<?, ?>> traversal = new AbstractBreadthFirstTraversal<TargetNode<?, ?>>(nodes) {

        @Override
        public ImmutableSet<TargetNode<?, ?>> visit(TargetNode<?, ?> targetNode) {
            builder.add(targetNode);
            return FluentIterable.from(graph.getIncomingNodesFor(targetNode)).append(extraEdges.get(targetNode)).toSet();
        }
    };
    traversal.start();
    return builder.build();
}
Also used : TargetNode(com.facebook.buck.rules.TargetNode) ImmutableSet(com.google.common.collect.ImmutableSet) BuildTarget(com.facebook.buck.model.BuildTarget) HumanReadableException(com.facebook.buck.util.HumanReadableException) HasTests(com.facebook.buck.model.HasTests) AbstractBreadthFirstTraversal(com.facebook.buck.graph.AbstractBreadthFirstTraversal) ImmutableMultimap(com.google.common.collect.ImmutableMultimap)

Example 9 with TargetNode

use of com.facebook.buck.rules.TargetNode in project buck by facebook.

the class AppleDescriptions method createBuildRulesForCoreDataDependencies.

public static Optional<CoreDataModel> createBuildRulesForCoreDataDependencies(TargetGraph targetGraph, BuildRuleParams params, String moduleName, AppleCxxPlatform appleCxxPlatform) {
    TargetNode<?, ?> targetNode = targetGraph.get(params.getBuildTarget());
    ImmutableSet<AppleWrapperResourceArg> coreDataModelArgs = AppleBuildRules.collectTransitiveBuildRules(targetGraph, Optional.empty(), AppleBuildRules.CORE_DATA_MODEL_DESCRIPTION_CLASSES, ImmutableList.of(targetNode));
    BuildRuleParams coreDataModelParams = params.withAppendedFlavor(CoreDataModel.FLAVOR).copyReplacingDeclaredAndExtraDeps(Suppliers.ofInstance(ImmutableSortedSet.of()), Suppliers.ofInstance(ImmutableSortedSet.of()));
    if (coreDataModelArgs.isEmpty()) {
        return Optional.empty();
    } else {
        return Optional.of(new CoreDataModel(coreDataModelParams, appleCxxPlatform, moduleName, coreDataModelArgs.stream().map(input -> new PathSourcePath(params.getProjectFilesystem(), input.path)).collect(MoreCollectors.toImmutableSet())));
    }
}
Also used : OptionalCompat(com.facebook.buck.util.OptionalCompat) ProvidesLinkedBinaryDeps(com.facebook.buck.cxx.ProvidesLinkedBinaryDeps) SourcePathRuleFinder(com.facebook.buck.rules.SourcePathRuleFinder) AbstractGenruleDescription(com.facebook.buck.shell.AbstractGenruleDescription) RichStream(com.facebook.buck.util.RichStream) InternalFlavor(com.facebook.buck.model.InternalFlavor) FlavorDomain(com.facebook.buck.model.FlavorDomain) CxxCompilationDatabase(com.facebook.buck.cxx.CxxCompilationDatabase) FluentIterable(com.google.common.collect.FluentIterable) SourcePathResolver(com.facebook.buck.rules.SourcePathResolver) SourceList(com.facebook.buck.rules.coercer.SourceList) StripStyle(com.facebook.buck.cxx.StripStyle) BuildRuleParams(com.facebook.buck.rules.BuildRuleParams) Path(java.nio.file.Path) CxxDescriptionEnhancer(com.facebook.buck.cxx.CxxDescriptionEnhancer) BuildRules(com.facebook.buck.rules.BuildRules) FrameworkDependencies(com.facebook.buck.cxx.FrameworkDependencies) Function(com.google.common.base.Function) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) TargetGraph(com.facebook.buck.rules.TargetGraph) Set(java.util.Set) BuildTarget(com.facebook.buck.model.BuildTarget) Sets(com.google.common.collect.Sets) LinkerMapMode(com.facebook.buck.cxx.LinkerMapMode) SourceWithFlags(com.facebook.buck.rules.SourceWithFlags) Predicate(com.google.common.base.Predicate) PathSourcePath(com.facebook.buck.rules.PathSourcePath) Optional(java.util.Optional) BuildRuleResolver(com.facebook.buck.rules.BuildRuleResolver) CxxBinaryDescription(com.facebook.buck.cxx.CxxBinaryDescription) Joiner(com.google.common.base.Joiner) CxxStrip(com.facebook.buck.cxx.CxxStrip) CxxLibraryDescription(com.facebook.buck.cxx.CxxLibraryDescription) SourcePath(com.facebook.buck.rules.SourcePath) Either(com.facebook.buck.model.Either) BuildRule(com.facebook.buck.rules.BuildRule) HashSet(java.util.HashSet) Tool(com.facebook.buck.rules.Tool) ImmutableList(com.google.common.collect.ImmutableList) NoSuchBuildTargetException(com.facebook.buck.parser.NoSuchBuildTargetException) BuildTargetSourcePath(com.facebook.buck.rules.BuildTargetSourcePath) Predicates(com.google.common.base.Predicates) Suppliers(com.google.common.base.Suppliers) ImmutableSortedMap(com.google.common.collect.ImmutableSortedMap) MoreCollectors(com.facebook.buck.util.MoreCollectors) ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) CxxConstructorArg(com.facebook.buck.cxx.CxxConstructorArg) TargetNode(com.facebook.buck.rules.TargetNode) CxxPlatform(com.facebook.buck.cxx.CxxPlatform) HumanReadableException(com.facebook.buck.util.HumanReadableException) MorePaths(com.facebook.buck.io.MorePaths) Ordering(com.google.common.collect.Ordering) BuildRuleWithBinary(com.facebook.buck.cxx.BuildRuleWithBinary) Paths(java.nio.file.Paths) SWIFT_EXTENSION(com.facebook.buck.swift.SwiftDescriptions.SWIFT_EXTENSION) Preconditions(com.google.common.base.Preconditions) Flavor(com.facebook.buck.model.Flavor) VisibleForTesting(com.google.common.annotations.VisibleForTesting) BuildRuleParams(com.facebook.buck.rules.BuildRuleParams) PathSourcePath(com.facebook.buck.rules.PathSourcePath)

Example 10 with TargetNode

use of com.facebook.buck.rules.TargetNode in project buck by facebook.

the class FineGrainedJavaDependencySuggester method createBuildRuleDefinition.

/**
   * Creates the build rule definition for the {@code namedComponent}.
   */
private String createBuildRuleDefinition(NamedStronglyConnectedComponent namedComponent, Map<String, PathSourcePath> providedSymbolToSrc, Multimap<String, String> providedSymbolToRequiredSymbols, Map<String, NamedStronglyConnectedComponent> namedComponentsIndex, JavaDepsFinder.DependencyInfo dependencyInfo, MutableDirectedGraph<String> symbolsDependencies, String visibilityArg) {
    final TargetNode<?, ?> suggestedNode = graph.get(suggestedTarget);
    SortedSet<String> deps = new TreeSet<>(LOCAL_DEPS_FIRST_COMPARATOR);
    SortedSet<PathSourcePath> srcs = new TreeSet<>();
    for (String providedSymbol : namedComponent.symbols) {
        PathSourcePath src = providedSymbolToSrc.get(providedSymbol);
        srcs.add(src);
        for (String requiredSymbol : providedSymbolToRequiredSymbols.get(providedSymbol)) {
            // First, check to see whether the requiredSymbol is in one of the newly created
            // strongly connected components. If so, add it to the deps so long as it is not the
            // strongly connected component that we are currently exploring.
            NamedStronglyConnectedComponent requiredComponent = namedComponentsIndex.get(requiredSymbol);
            if (requiredComponent != null) {
                if (!requiredComponent.equals(namedComponent)) {
                    deps.add(":" + requiredComponent.name);
                }
                continue;
            }
            Set<TargetNode<?, ?>> depProviders = dependencyInfo.symbolToProviders.get(requiredSymbol);
            if (depProviders == null || depProviders.size() == 0) {
                console.getStdErr().printf("# Suspicious: no provider for '%s'\n", requiredSymbol);
                continue;
            }
            depProviders = FluentIterable.from(depProviders).filter(provider -> provider.isVisibleTo(graph, suggestedNode)).toSet();
            TargetNode<?, ?> depProvider;
            if (depProviders.size() == 1) {
                depProvider = Iterables.getOnlyElement(depProviders);
            } else {
                console.getStdErr().printf("# Suspicious: no lone provider for '%s': [%s]\n", requiredSymbol, Joiner.on(", ").join(depProviders));
                continue;
            }
            if (!depProvider.equals(suggestedNode)) {
                deps.add(depProvider.toString());
            }
        }
        // Find deps within package.
        for (String requiredSymbol : symbolsDependencies.getOutgoingNodesFor(providedSymbol)) {
            NamedStronglyConnectedComponent componentDep = Preconditions.checkNotNull(namedComponentsIndex.get(requiredSymbol));
            if (!componentDep.equals(namedComponent)) {
                deps.add(":" + componentDep.name);
            }
        }
    }
    final Path basePathForSuggestedTarget = suggestedTarget.getBasePath();
    Iterable<String> relativeSrcs = FluentIterable.from(srcs).transform(input -> basePathForSuggestedTarget.relativize(input.getRelativePath()).toString());
    StringBuilder rule = new StringBuilder("\njava_library(\n" + "  name = '" + namedComponent.name + "',\n" + "  srcs = [\n");
    for (String src : relativeSrcs) {
        rule.append(String.format("    '%s',\n", src));
    }
    rule.append("  ],\n" + "  deps = [\n");
    for (String dep : deps) {
        rule.append(String.format("    '%s',\n", dep));
    }
    rule.append("  ],\n" + visibilityArg + ")\n");
    return rule.toString();
}
Also used : SourcePath(com.facebook.buck.rules.SourcePath) Path(java.nio.file.Path) PathSourcePath(com.facebook.buck.rules.PathSourcePath) TargetNode(com.facebook.buck.rules.TargetNode) TreeSet(java.util.TreeSet) PathSourcePath(com.facebook.buck.rules.PathSourcePath)

Aggregations

TargetNode (com.facebook.buck.rules.TargetNode)88 BuildTarget (com.facebook.buck.model.BuildTarget)73 TargetGraph (com.facebook.buck.rules.TargetGraph)43 Test (org.junit.Test)40 Path (java.nio.file.Path)36 ImmutableSet (com.google.common.collect.ImmutableSet)33 FakeSourcePath (com.facebook.buck.rules.FakeSourcePath)23 PathSourcePath (com.facebook.buck.rules.PathSourcePath)22 SourcePath (com.facebook.buck.rules.SourcePath)22 ImmutableMap (com.google.common.collect.ImmutableMap)22 Optional (java.util.Optional)20 Map (java.util.Map)18 HumanReadableException (com.facebook.buck.util.HumanReadableException)17 ImmutableList (com.google.common.collect.ImmutableList)17 ProjectFilesystem (com.facebook.buck.io.ProjectFilesystem)13 UnflavoredBuildTarget (com.facebook.buck.model.UnflavoredBuildTarget)13 BuildRuleResolver (com.facebook.buck.rules.BuildRuleResolver)13 Cell (com.facebook.buck.rules.Cell)13 IOException (java.io.IOException)13 DefaultBuildTargetSourcePath (com.facebook.buck.rules.DefaultBuildTargetSourcePath)12