in src/com/facebook/buck/cli/TargetsCommand.java [187:263]
private void printJsonForTargetsInternal(
SortedMap<String, BuildRule> buildIndex,
ImmutableList<String> defaultIncludes) throws BuildFileParseException, IOException {
// Print the JSON representation of the build rule for the specified target(s).
getStdOut().println("[");
ObjectMapper mapper = new ObjectMapper();
Iterator<String> keySetIterator = buildIndex.keySet().iterator();
while (keySetIterator.hasNext()) {
String key = keySetIterator.next();
BuildRule buildRule = buildIndex.get(key);
BuildTarget buildTarget = buildRule.getBuildTarget();
List<Map<String, Object>> rules;
try {
File buildFile = buildTarget.getBuildFile(getProjectFilesystem());
rules = getParser().parseBuildFile(buildFile, defaultIncludes);
} catch (BuildTargetException e) {
console.printErrorText(
"unable to find rule for target " + buildTarget.getFullyQualifiedName());
continue;
}
// Find the build rule information that corresponds to this build buildTarget.
Map<String, Object> targetRule = null;
for (Map<String, Object> rule : rules) {
String name = (String)rule.get("name");
if (name.equals(buildTarget.getShortName())) {
targetRule = rule;
break;
}
}
if (targetRule == null) {
console.printErrorText(
"unable to find rule for target " + buildTarget.getFullyQualifiedName());
continue;
}
String outputPath;
Buildable buildable = buildRule.getBuildable();
if (buildable != null) {
outputPath = buildable.getPathToOutputFile();
} else if (BuildRuleType.PROJECT_CONFIG.equals(buildRule.getType())) {
// We know that project_config() rules are special.
outputPath = null;
} else {
throw new RuntimeException("No Buildable for " + buildRule.getFullyQualifiedName());
}
if (outputPath != null) {
targetRule.put("buck.output_file", outputPath);
}
// Sort the rule items, both so we have a stable order for unit tests and
// to improve readability of the output.
SortedMap<String, Object> sortedTargetRule = Maps.newTreeMap();
sortedTargetRule.putAll(targetRule);
// 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 Throwables.propagate(e);
}
String output = stringWriter.getBuffer().toString();
if (keySetIterator.hasNext()) {
output += ",";
}
getStdOut().println(output);
}
getStdOut().println("]");
}