Make the position of 'n files selected' label synced with the width of navigation...
[chromium-blink-merge.git] / tools / gn / command_desc.cc
blob5c2e2d4bbb954d78550a7cf886c23bb02759bd6a
1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include <algorithm>
6 #include <set>
7 #include <sstream>
9 #include "base/command_line.h"
10 #include "tools/gn/commands.h"
11 #include "tools/gn/config.h"
12 #include "tools/gn/config_values_extractors.h"
13 #include "tools/gn/deps_iterator.h"
14 #include "tools/gn/filesystem_utils.h"
15 #include "tools/gn/item.h"
16 #include "tools/gn/label.h"
17 #include "tools/gn/setup.h"
18 #include "tools/gn/standard_out.h"
19 #include "tools/gn/substitution_writer.h"
20 #include "tools/gn/target.h"
21 #include "tools/gn/variables.h"
23 namespace commands {
25 namespace {
27 // Prints the given directory in a nice way for the user to view.
28 std::string FormatSourceDir(const SourceDir& dir) {
29 #if defined(OS_WIN)
30 // On Windows we fix up system absolute paths to look like native ones.
31 // Internally, they'll look like "/C:\foo\bar/"
32 if (dir.is_system_absolute()) {
33 std::string buf = dir.value();
34 if (buf.size() > 3 && buf[2] == ':') {
35 buf.erase(buf.begin()); // Erase beginning slash.
36 return buf;
39 #endif
40 return dir.value();
43 void RecursiveCollectChildDeps(const Target* target, std::set<Label>* result);
45 void RecursiveCollectDeps(const Target* target, std::set<Label>* result) {
46 if (result->find(target->label()) != result->end())
47 return; // Already did this target.
48 result->insert(target->label());
50 RecursiveCollectChildDeps(target, result);
53 void RecursiveCollectChildDeps(const Target* target, std::set<Label>* result) {
54 for (const auto& pair : target->GetDeps(Target::DEPS_ALL))
55 RecursiveCollectDeps(pair.ptr, result);
58 // Prints dependencies of the given target (not the target itself). If the
59 // set is non-null, new targets encountered will be added to the set, and if
60 // a dependency is in the set already, it will not be recused into. When the
61 // set is null, all dependencies will be printed.
62 void RecursivePrintDeps(const Target* target,
63 const Label& default_toolchain,
64 std::set<const Target*>* seen_targets,
65 int indent_level) {
66 // Combine all deps into one sorted list.
67 std::vector<LabelTargetPair> sorted_deps;
68 for (const auto& pair : target->GetDeps(Target::DEPS_ALL))
69 sorted_deps.push_back(pair);
70 std::sort(sorted_deps.begin(), sorted_deps.end(),
71 LabelPtrLabelLess<Target>());
73 std::string indent(indent_level * 2, ' ');
74 for (const auto& pair : sorted_deps) {
75 const Target* cur_dep = pair.ptr;
77 OutputString(indent +
78 cur_dep->label().GetUserVisibleName(default_toolchain));
79 bool print_children = true;
80 if (seen_targets) {
81 if (seen_targets->find(cur_dep) == seen_targets->end()) {
82 // New target, mark it visited.
83 seen_targets->insert(cur_dep);
84 } else {
85 // Already seen.
86 print_children = false;
87 // Only print "..." if something is actually elided, which means that
88 // the current target has children.
89 if (!cur_dep->public_deps().empty() ||
90 !cur_dep->private_deps().empty() ||
91 !cur_dep->data_deps().empty())
92 OutputString("...");
96 OutputString("\n");
97 if (print_children) {
98 RecursivePrintDeps(cur_dep, default_toolchain, seen_targets,
99 indent_level + 1);
104 void PrintDeps(const Target* target, bool display_header) {
105 const base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess();
106 Label toolchain_label = target->label().GetToolchainLabel();
108 // Tree mode is separate.
109 if (cmdline->HasSwitch("tree")) {
110 if (display_header)
111 OutputString("\nDependency tree:\n");
113 if (cmdline->HasSwitch("all")) {
114 // Show all tree deps with no eliding.
115 RecursivePrintDeps(target, toolchain_label, nullptr, 1);
116 } else {
117 // Don't recurse into duplicates.
118 std::set<const Target*> seen_targets;
119 RecursivePrintDeps(target, toolchain_label, &seen_targets, 1);
121 return;
124 // Collect the deps to display.
125 std::vector<Label> deps;
126 if (cmdline->HasSwitch("all")) {
127 // Show all dependencies.
128 if (display_header)
129 OutputString("\nAll recursive dependencies:\n");
131 std::set<Label> all_deps;
132 RecursiveCollectChildDeps(target, &all_deps);
133 for (const auto& dep : all_deps)
134 deps.push_back(dep);
135 } else {
136 // Show direct dependencies only.
137 if (display_header) {
138 OutputString(
139 "\nDirect dependencies "
140 "(try also \"--all\", \"--tree\", or even \"--all --tree\"):\n");
142 for (const auto& pair : target->GetDeps(Target::DEPS_ALL))
143 deps.push_back(pair.label);
146 std::sort(deps.begin(), deps.end());
147 for (const auto& dep : deps)
148 OutputString(" " + dep.GetUserVisibleName(toolchain_label) + "\n");
151 void PrintForwardDependentConfigsFrom(const Target* target,
152 bool display_header) {
153 if (target->forward_dependent_configs().empty())
154 return;
156 if (display_header)
157 OutputString("\nforward_dependent_configs_from:\n");
159 // Collect the sorted list of deps.
160 std::vector<Label> forward;
161 for (const auto& pair : target->forward_dependent_configs())
162 forward.push_back(pair.label);
163 std::sort(forward.begin(), forward.end());
165 Label toolchain_label = target->label().GetToolchainLabel();
166 for (const auto& fwd : forward)
167 OutputString(" " + fwd.GetUserVisibleName(toolchain_label) + "\n");
170 // libs and lib_dirs are special in that they're inherited. We don't currently
171 // implement a blame feature for this since the bottom-up inheritance makes
172 // this difficult.
173 void PrintLibDirs(const Target* target, bool display_header) {
174 const OrderedSet<SourceDir>& lib_dirs = target->all_lib_dirs();
175 if (lib_dirs.empty())
176 return;
178 if (display_header)
179 OutputString("\nlib_dirs\n");
181 for (size_t i = 0; i < lib_dirs.size(); i++)
182 OutputString(" " + FormatSourceDir(lib_dirs[i]) + "\n");
185 void PrintLibs(const Target* target, bool display_header) {
186 const OrderedSet<std::string>& libs = target->all_libs();
187 if (libs.empty())
188 return;
190 if (display_header)
191 OutputString("\nlibs\n");
193 for (size_t i = 0; i < libs.size(); i++)
194 OutputString(" " + libs[i] + "\n");
197 void PrintPublic(const Target* target, bool display_header) {
198 if (display_header)
199 OutputString("\npublic:\n");
201 if (target->all_headers_public()) {
202 OutputString(" [All headers listed in the sources are public.]\n");
203 return;
206 Target::FileList public_headers = target->public_headers();
207 std::sort(public_headers.begin(), public_headers.end());
208 for (const auto& hdr : public_headers)
209 OutputString(" " + hdr.value() + "\n");
212 void PrintCheckIncludes(const Target* target, bool display_header) {
213 if (display_header)
214 OutputString("\ncheck_includes:\n");
216 if (target->check_includes())
217 OutputString(" true\n");
218 else
219 OutputString(" false\n");
222 void PrintAllowCircularIncludesFrom(const Target* target, bool display_header) {
223 if (display_header)
224 OutputString("\nallow_circular_includes_from:\n");
226 Label toolchain_label = target->label().GetToolchainLabel();
227 for (const auto& cur : target->allow_circular_includes_from())
228 OutputString(" " + cur.GetUserVisibleName(toolchain_label) + "\n");
231 void PrintVisibility(const Target* target, bool display_header) {
232 if (display_header)
233 OutputString("\nvisibility:\n");
235 OutputString(target->visibility().Describe(2, false));
238 void PrintTestonly(const Target* target, bool display_header) {
239 if (display_header)
240 OutputString("\ntestonly:\n");
242 if (target->testonly())
243 OutputString(" true\n");
244 else
245 OutputString(" false\n");
248 void PrintConfigsVector(const Target* target,
249 const LabelConfigVector& configs,
250 const std::string& heading,
251 bool display_header) {
252 if (configs.empty())
253 return;
255 // Don't sort since the order determines how things are processed.
256 if (display_header)
257 OutputString("\n" + heading + " (in order applying):\n");
259 Label toolchain_label = target->label().GetToolchainLabel();
260 for (size_t i = 0; i < configs.size(); i++) {
261 OutputString(" " +
262 configs[i].label.GetUserVisibleName(toolchain_label) + "\n");
266 void PrintConfigsVector(const Target* target,
267 const UniqueVector<LabelConfigPair>& configs,
268 const std::string& heading,
269 bool display_header) {
270 if (configs.empty())
271 return;
273 // Don't sort since the order determines how things are processed.
274 if (display_header)
275 OutputString("\n" + heading + " (in order applying):\n");
277 Label toolchain_label = target->label().GetToolchainLabel();
278 for (size_t i = 0; i < configs.size(); i++) {
279 OutputString(" " +
280 configs[i].label.GetUserVisibleName(toolchain_label) + "\n");
284 void PrintConfigs(const Target* target, bool display_header) {
285 PrintConfigsVector(target, target->configs().vector(), "configs",
286 display_header);
289 void PrintPublicConfigs(const Target* target, bool display_header) {
290 PrintConfigsVector(target, target->public_configs(),
291 "public_configs", display_header);
294 void PrintAllDependentConfigs(const Target* target, bool display_header) {
295 PrintConfigsVector(target, target->all_dependent_configs(),
296 "all_dependent_configs", display_header);
299 void PrintFileList(const Target::FileList& files,
300 const std::string& header,
301 bool indent_extra,
302 bool display_header) {
303 if (files.empty())
304 return;
306 if (display_header)
307 OutputString("\n" + header + ":\n");
309 std::string indent = indent_extra ? " " : " ";
311 Target::FileList sorted = files;
312 std::sort(sorted.begin(), sorted.end());
313 for (size_t i = 0; i < sorted.size(); i++)
314 OutputString(indent + sorted[i].value() + "\n");
317 void PrintSources(const Target* target, bool display_header) {
318 PrintFileList(target->sources(), "sources", false, display_header);
321 void PrintInputs(const Target* target, bool display_header) {
322 PrintFileList(target->inputs(), "inputs", false, display_header);
325 void PrintOutputs(const Target* target, bool display_header) {
326 if (display_header)
327 OutputString("\noutputs:\n");
329 if (target->output_type() == Target::ACTION) {
330 // Action, print out outputs, don't apply sources to it.
331 for (size_t i = 0; i < target->action_values().outputs().list().size();
332 i++) {
333 OutputString(" " +
334 target->action_values().outputs().list()[i].AsString() +
335 "\n");
337 } else {
338 const SubstitutionList& outputs = target->action_values().outputs();
339 if (!outputs.required_types().empty()) {
340 // Display the pattern and resolved pattern separately, since there are
341 // subtitutions used.
342 OutputString(" Output pattern:\n");
343 for (size_t i = 0; i < outputs.list().size(); i++)
344 OutputString(" " + outputs.list()[i].AsString() + "\n");
346 // Now display what that resolves to given the sources.
347 OutputString("\n Resolved output file list:\n");
350 // Resolved output list.
351 std::vector<SourceFile> output_files;
352 SubstitutionWriter::ApplyListToSources(target->settings(), outputs,
353 target->sources(), &output_files);
354 PrintFileList(output_files, "", true, false);
358 void PrintScript(const Target* target, bool display_header) {
359 if (display_header)
360 OutputString("\nscript:\n");
361 OutputString(" " + target->action_values().script().value() + "\n");
364 void PrintArgs(const Target* target, bool display_header) {
365 if (display_header)
366 OutputString("\nargs:\n");
367 for (size_t i = 0; i < target->action_values().args().list().size(); i++) {
368 OutputString(" " +
369 target->action_values().args().list()[i].AsString() + "\n");
373 void PrintDepfile(const Target* target, bool display_header) {
374 if (target->action_values().depfile().empty())
375 return;
376 if (display_header)
377 OutputString("\ndepfile:\n");
378 OutputString(" " + target->action_values().depfile().AsString() + "\n");
381 // Attribute the origin for attributing from where a target came from. Does
382 // nothing if the input is null or it does not have a location.
383 void OutputSourceOfDep(const ParseNode* origin, std::ostream& out) {
384 if (!origin)
385 return;
386 Location location = origin->GetRange().begin();
387 out << " (Added by " + location.file()->name().value() << ":"
388 << location.line_number() << ")\n";
391 // Templatized writer for writing out different config value types.
392 template<typename T> struct DescValueWriter {};
393 template<> struct DescValueWriter<std::string> {
394 void operator()(const std::string& str, std::ostream& out) const {
395 out << " " << str << "\n";
398 template<> struct DescValueWriter<SourceDir> {
399 void operator()(const SourceDir& dir, std::ostream& out) const {
400 out << " " << FormatSourceDir(dir) << "\n";
404 // Writes a given config value type to the string, optionally with attribution.
405 // This should match RecursiveTargetConfigToStream in the order it traverses.
406 template<typename T> void OutputRecursiveTargetConfig(
407 const Target* target,
408 const char* header_name,
409 const std::vector<T>& (ConfigValues::* getter)() const) {
410 bool display_blame =
411 base::CommandLine::ForCurrentProcess()->HasSwitch("blame");
413 DescValueWriter<T> writer;
414 std::ostringstream out;
416 for (ConfigValuesIterator iter(target); !iter.done(); iter.Next()) {
417 if ((iter.cur().*getter)().empty())
418 continue;
420 // Optional blame sub-head.
421 if (display_blame) {
422 const Config* config = iter.GetCurrentConfig();
423 if (config) {
424 // Source of this value is a config.
425 out << " From " << config->label().GetUserVisibleName(false) << "\n";
426 OutputSourceOfDep(iter.origin(), out);
427 } else {
428 // Source of this value is the target itself.
429 out << " From " << target->label().GetUserVisibleName(false) << "\n";
433 // Actual values.
434 ConfigValuesToStream(iter.cur(), getter, writer, out);
437 std::string out_str = out.str();
438 if (!out_str.empty()) {
439 OutputString("\n" + std::string(header_name) + "\n");
440 OutputString(out_str);
444 } // namespace
446 // desc ------------------------------------------------------------------------
448 const char kDesc[] = "desc";
449 const char kDesc_HelpShort[] =
450 "desc: Show lots of insightful information about a target.";
451 const char kDesc_Help[] =
452 "gn desc <out_dir> <target label> [<what to show>]\n"
453 " [--blame] [--all | --tree]\n"
454 "\n"
455 " Displays information about a given labeled target for the given build.\n"
456 " The build parameters will be taken for the build in the given\n"
457 " <out_dir>.\n"
458 "\n"
459 "Possibilities for <what to show>:\n"
460 " (If unspecified an overall summary will be displayed.)\n"
461 "\n"
462 " sources\n"
463 " Source files.\n"
464 "\n"
465 " inputs\n"
466 " Additional input dependencies.\n"
467 "\n"
468 " public\n"
469 " Public header files.\n"
470 "\n"
471 " check_includes\n"
472 " Whether \"gn check\" checks this target for include usage.\n"
473 "\n"
474 " allow_circular_includes_from\n"
475 " Permit includes from these targets.\n"
476 "\n"
477 " visibility\n"
478 " Prints which targets can depend on this one.\n"
479 "\n"
480 " testonly\n"
481 " Whether this target may only be used in tests.\n"
482 "\n"
483 " configs\n"
484 " Shows configs applied to the given target, sorted in the order\n"
485 " they're specified. This includes both configs specified in the\n"
486 " \"configs\" variable, as well as configs pushed onto this target\n"
487 " via dependencies specifying \"all\" or \"direct\" dependent\n"
488 " configs.\n"
489 "\n"
490 " deps [--all | --tree]\n"
491 " Show immediate (or, when \"--all\" or \"--tree\" is specified,\n"
492 " recursive) dependencies of the given target. \"--tree\" shows them\n"
493 " in a tree format with duplicates elided (noted by \"...\").\n"
494 " \"--all\" shows them sorted alphabetically. Using both flags will\n"
495 " print a tree with no omissions. The \"deps\", \"public_deps\", and\n"
496 " \"data_deps\" will all be included.\n"
497 "\n"
498 " public_configs\n"
499 " all_dependent_configs\n"
500 " Shows the labels of configs applied to targets that depend on this\n"
501 " one (either directly or all of them).\n"
502 "\n"
503 " forward_dependent_configs_from\n"
504 " Shows the labels of dependencies for which dependent configs will\n"
505 " be pushed to targets depending on the current one.\n"
506 "\n"
507 " script\n"
508 " args\n"
509 " depfile\n"
510 " Actions only. The script and related values.\n"
511 "\n"
512 " outputs\n"
513 " Outputs for script and copy target types.\n"
514 "\n"
515 " defines [--blame]\n"
516 " include_dirs [--blame]\n"
517 " cflags [--blame]\n"
518 " cflags_cc [--blame]\n"
519 " cflags_cxx [--blame]\n"
520 " ldflags [--blame]\n"
521 " lib_dirs\n"
522 " libs\n"
523 " Shows the given values taken from the target and all configs\n"
524 " applying. See \"--blame\" below.\n"
525 "\n"
526 " --blame\n"
527 " Used with any value specified by a config, this will name\n"
528 " the config that specified the value. This doesn't currently work\n"
529 " for libs and lib_dirs because those are inherited and are more\n"
530 " complicated to figure out the blame (patches welcome).\n"
531 "\n"
532 "Note:\n"
533 " This command will show the full name of directories and source files,\n"
534 " but when directories and source paths are written to the build file,\n"
535 " they will be adjusted to be relative to the build directory. So the\n"
536 " values for paths displayed by this command won't match (but should\n"
537 " mean the same thing).\n"
538 "\n"
539 "Examples:\n"
540 " gn desc out/Debug //base:base\n"
541 " Summarizes the given target.\n"
542 "\n"
543 " gn desc out/Foo :base_unittests deps --tree\n"
544 " Shows a dependency tree of the \"base_unittests\" project in\n"
545 " the current directory.\n"
546 "\n"
547 " gn desc out/Debug //base defines --blame\n"
548 " Shows defines set for the //base:base target, annotated by where\n"
549 " each one was set from.\n";
551 #define OUTPUT_CONFIG_VALUE(name, type) \
552 OutputRecursiveTargetConfig<type>(target, #name, &ConfigValues::name);
554 int RunDesc(const std::vector<std::string>& args) {
555 if (args.size() != 2 && args.size() != 3) {
556 Err(Location(), "You're holding it wrong.",
557 "Usage: \"gn desc <out_dir> <target_name> [<what to display>]\"")
558 .PrintToStdout();
559 return 1;
562 // Deliberately leaked to avoid expensive process teardown.
563 Setup* setup = new Setup;
564 if (!setup->DoSetup(args[0], false))
565 return 1;
566 if (!setup->Run())
567 return 1;
569 const Target* target = ResolveTargetFromCommandLineString(setup, args[1]);
570 if (!target)
571 return 1;
573 #define CONFIG_VALUE_HANDLER(name, type) \
574 } else if (what == #name) { OUTPUT_CONFIG_VALUE(name, type)
576 if (args.size() == 3) {
577 // User specified one thing to display.
578 const std::string& what = args[2];
579 if (what == variables::kConfigs) {
580 PrintConfigs(target, false);
581 } else if (what == variables::kPublicConfigs) {
582 PrintPublicConfigs(target, false);
583 } else if (what == variables::kAllDependentConfigs) {
584 PrintAllDependentConfigs(target, false);
585 } else if (what == variables::kForwardDependentConfigsFrom) {
586 PrintForwardDependentConfigsFrom(target, false);
587 } else if (what == variables::kSources) {
588 PrintSources(target, false);
589 } else if (what == variables::kPublic) {
590 PrintPublic(target, false);
591 } else if (what == variables::kCheckIncludes) {
592 PrintCheckIncludes(target, false);
593 } else if (what == variables::kAllowCircularIncludesFrom) {
594 PrintAllowCircularIncludesFrom(target, false);
595 } else if (what == variables::kVisibility) {
596 PrintVisibility(target, false);
597 } else if (what == variables::kTestonly) {
598 PrintTestonly(target, false);
599 } else if (what == variables::kInputs) {
600 PrintInputs(target, false);
601 } else if (what == variables::kScript) {
602 PrintScript(target, false);
603 } else if (what == variables::kArgs) {
604 PrintArgs(target, false);
605 } else if (what == variables::kDepfile) {
606 PrintDepfile(target, false);
607 } else if (what == variables::kOutputs) {
608 PrintOutputs(target, false);
609 } else if (what == variables::kDeps) {
610 PrintDeps(target, false);
611 } else if (what == variables::kLibDirs) {
612 PrintLibDirs(target, false);
613 } else if (what == variables::kLibs) {
614 PrintLibs(target, false);
616 CONFIG_VALUE_HANDLER(defines, std::string)
617 CONFIG_VALUE_HANDLER(include_dirs, SourceDir)
618 CONFIG_VALUE_HANDLER(cflags, std::string)
619 CONFIG_VALUE_HANDLER(cflags_c, std::string)
620 CONFIG_VALUE_HANDLER(cflags_cc, std::string)
621 CONFIG_VALUE_HANDLER(cflags_objc, std::string)
622 CONFIG_VALUE_HANDLER(cflags_objcc, std::string)
623 CONFIG_VALUE_HANDLER(ldflags, std::string)
625 } else {
626 OutputString("Don't know how to display \"" + what + "\".\n");
627 return 1;
630 #undef CONFIG_VALUE_HANDLER
631 return 0;
634 // Display summary.
636 // Display this only applicable to binary targets.
637 bool is_binary_output =
638 target->output_type() != Target::GROUP &&
639 target->output_type() != Target::COPY_FILES &&
640 target->output_type() != Target::ACTION &&
641 target->output_type() != Target::ACTION_FOREACH;
643 // Generally we only want to display toolchains on labels when the toolchain
644 // is different than the default one for this target (which we always print
645 // in the header).
646 Label target_toolchain = target->label().GetToolchainLabel();
648 // Header.
649 OutputString("Target: ", DECORATION_YELLOW);
650 OutputString(target->label().GetUserVisibleName(false) + "\n");
651 OutputString("Type: ", DECORATION_YELLOW);
652 OutputString(std::string(
653 Target::GetStringForOutputType(target->output_type())) + "\n");
654 OutputString("Toolchain: ", DECORATION_YELLOW);
655 OutputString(target_toolchain.GetUserVisibleName(false) + "\n");
657 PrintSources(target, true);
658 if (is_binary_output) {
659 PrintPublic(target, true);
660 PrintCheckIncludes(target, true);
661 PrintAllowCircularIncludesFrom(target, true);
663 PrintVisibility(target, true);
664 if (is_binary_output) {
665 PrintTestonly(target, true);
666 PrintConfigs(target, true);
669 PrintPublicConfigs(target, true);
670 PrintAllDependentConfigs(target, true);
671 PrintForwardDependentConfigsFrom(target, true);
673 PrintInputs(target, true);
675 if (is_binary_output) {
676 OUTPUT_CONFIG_VALUE(defines, std::string)
677 OUTPUT_CONFIG_VALUE(include_dirs, SourceDir)
678 OUTPUT_CONFIG_VALUE(cflags, std::string)
679 OUTPUT_CONFIG_VALUE(cflags_c, std::string)
680 OUTPUT_CONFIG_VALUE(cflags_cc, std::string)
681 OUTPUT_CONFIG_VALUE(cflags_objc, std::string)
682 OUTPUT_CONFIG_VALUE(cflags_objcc, std::string)
683 OUTPUT_CONFIG_VALUE(ldflags, std::string)
686 if (target->output_type() == Target::ACTION ||
687 target->output_type() == Target::ACTION_FOREACH) {
688 PrintScript(target, true);
689 PrintArgs(target, true);
690 PrintDepfile(target, true);
693 if (target->output_type() == Target::ACTION ||
694 target->output_type() == Target::ACTION_FOREACH ||
695 target->output_type() == Target::COPY_FILES) {
696 PrintOutputs(target, true);
699 // Libs can be part of any target and get recursively pushed up the chain,
700 // so always display them, even for groups and such.
701 PrintLibs(target, true);
702 PrintLibDirs(target, true);
704 PrintDeps(target, true);
706 return 0;
709 } // namespace commands