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;
}
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("]");
}
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();
}
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())));
}
}
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();
}
Aggregations