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.
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"
27 // Prints the given directory in a nice way for the user to view.
28 std::string
FormatSourceDir(const SourceDir
& dir
) {
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.
43 void RecursiveCollectChildDeps(const Target
* target
,
44 std::set
<const Target
*>* result
);
46 void RecursiveCollectDeps(const Target
* target
,
47 std::set
<const Target
*>* result
) {
48 if (result
->find(target
) != result
->end())
49 return; // Already did this target.
50 result
->insert(target
);
52 RecursiveCollectChildDeps(target
, result
);
55 void RecursiveCollectChildDeps(const Target
* target
,
56 std::set
<const Target
*>* result
) {
57 for (const auto& pair
: target
->GetDeps(Target::DEPS_ALL
))
58 RecursiveCollectDeps(pair
.ptr
, result
);
61 // Prints dependencies of the given target (not the target itself). If the
62 // set is non-null, new targets encountered will be added to the set, and if
63 // a dependency is in the set already, it will not be recused into. When the
64 // set is null, all dependencies will be printed.
65 void RecursivePrintDeps(const Target
* target
,
66 const Label
& default_toolchain
,
67 std::set
<const Target
*>* seen_targets
,
69 // Combine all deps into one sorted list.
70 std::vector
<LabelTargetPair
> sorted_deps
;
71 for (const auto& pair
: target
->GetDeps(Target::DEPS_ALL
))
72 sorted_deps
.push_back(pair
);
73 std::sort(sorted_deps
.begin(), sorted_deps
.end(),
74 LabelPtrLabelLess
<Target
>());
76 std::string
indent(indent_level
* 2, ' ');
77 for (const auto& pair
: sorted_deps
) {
78 const Target
* cur_dep
= pair
.ptr
;
81 cur_dep
->label().GetUserVisibleName(default_toolchain
));
82 bool print_children
= true;
84 if (seen_targets
->find(cur_dep
) == seen_targets
->end()) {
85 // New target, mark it visited.
86 seen_targets
->insert(cur_dep
);
89 print_children
= false;
90 // Only print "..." if something is actually elided, which means that
91 // the current target has children.
92 if (!cur_dep
->public_deps().empty() ||
93 !cur_dep
->private_deps().empty() ||
94 !cur_dep
->data_deps().empty())
100 if (print_children
) {
101 RecursivePrintDeps(cur_dep
, default_toolchain
, seen_targets
,
107 void PrintDeps(const Target
* target
, bool display_header
) {
108 const base::CommandLine
* cmdline
= base::CommandLine::ForCurrentProcess();
109 Label toolchain_label
= target
->label().GetToolchainLabel();
111 // Tree mode is separate.
112 if (cmdline
->HasSwitch("tree")) {
114 OutputString("\nDependency tree:\n");
116 if (cmdline
->HasSwitch("all")) {
117 // Show all tree deps with no eliding.
118 RecursivePrintDeps(target
, toolchain_label
, nullptr, 1);
120 // Don't recurse into duplicates.
121 std::set
<const Target
*> seen_targets
;
122 RecursivePrintDeps(target
, toolchain_label
, &seen_targets
, 1);
127 // Collect the deps to display.
128 if (cmdline
->HasSwitch("all")) {
129 // Show all dependencies.
131 OutputString("\nAll recursive dependencies:\n");
133 std::set
<const Target
*> all_deps
;
134 RecursiveCollectChildDeps(target
, &all_deps
);
135 FilterAndPrintTargetSet(display_header
, all_deps
);
137 std::vector
<const Target
*> deps
;
138 // Show direct dependencies only.
139 if (display_header
) {
141 "\nDirect dependencies "
142 "(try also \"--all\", \"--tree\", or even \"--all --tree\"):\n");
144 for (const auto& pair
: target
->GetDeps(Target::DEPS_ALL
))
145 deps
.push_back(pair
.ptr
);
146 std::sort(deps
.begin(), deps
.end());
147 FilterAndPrintTargets(display_header
, &deps
);
151 void PrintForwardDependentConfigsFrom(const Target
* target
,
152 bool display_header
) {
153 if (target
->forward_dependent_configs().empty())
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
173 void PrintLibDirs(const Target
* target
, bool display_header
) {
174 const OrderedSet
<SourceDir
>& lib_dirs
= target
->all_lib_dirs();
175 if (lib_dirs
.empty())
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();
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
) {
199 OutputString("\npublic:\n");
201 if (target
->all_headers_public()) {
202 OutputString(" [All headers listed in the sources are public.]\n");
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
) {
214 OutputString("\ncheck_includes:\n");
216 if (target
->check_includes())
217 OutputString(" true\n");
219 OutputString(" false\n");
222 void PrintAllowCircularIncludesFrom(const Target
* target
, bool 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
) {
233 OutputString("\nvisibility:\n");
235 OutputString(target
->visibility().Describe(2, false));
238 void PrintTestonly(const Target
* target
, bool display_header
) {
240 OutputString("\ntestonly:\n");
242 if (target
->testonly())
243 OutputString(" true\n");
245 OutputString(" false\n");
248 void PrintConfigsVector(const Target
* target
,
249 const LabelConfigVector
& configs
,
250 const std::string
& heading
,
251 bool display_header
) {
255 // Don't sort since the order determines how things are processed.
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
++) {
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
) {
273 // Don't sort since the order determines how things are processed.
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
++) {
280 configs
[i
].label
.GetUserVisibleName(toolchain_label
) + "\n");
284 void PrintConfigs(const Target
* target
, bool display_header
) {
285 PrintConfigsVector(target
, target
->configs().vector(), "configs",
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
,
302 bool 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
) {
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();
334 target
->action_values().outputs().list()[i
].AsString() +
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
) {
360 OutputString("\nscript:\n");
361 OutputString(" " + target
->action_values().script().value() + "\n");
364 void PrintArgs(const Target
* target
, bool display_header
) {
366 OutputString("\nargs:\n");
367 for (size_t i
= 0; i
< target
->action_values().args().list().size(); i
++) {
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())
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
) {
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) {
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())
420 // Optional blame sub-head.
422 const Config
* config
= iter
.GetCurrentConfig();
424 // Source of this value is a config.
425 out
<< " From " << config
->label().GetUserVisibleName(false) << "\n";
426 OutputSourceOfDep(iter
.origin(), out
);
428 // Source of this value is the target itself.
429 out
<< " From " << target
->label().GetUserVisibleName(false) << "\n";
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
);
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>] [--blame]\n"
454 " Displays information about a given labeled target for the given build.\n"
455 " The build parameters will be taken for the build in the given\n"
458 "Possibilities for <what to show>\n"
459 " (If unspecified an overall summary will be displayed.)\n"
465 " Additional input dependencies.\n"
468 " Public header files.\n"
471 " Whether \"gn check\" checks this target for include usage.\n"
473 " allow_circular_includes_from\n"
474 " Permit includes from these targets.\n"
477 " Prints which targets can depend on this one.\n"
480 " Whether this target may only be used in tests.\n"
483 " Shows configs applied to the given target, sorted in the order\n"
484 " they're specified. This includes both configs specified in the\n"
485 " \"configs\" variable, as well as configs pushed onto this target\n"
486 " via dependencies specifying \"all\" or \"direct\" dependent\n"
490 " Show immediate or recursive dependencies. See below for flags that\n"
491 " control deps printing.\n"
494 " all_dependent_configs\n"
495 " Shows the labels of configs applied to targets that depend on this\n"
496 " one (either directly or all of them).\n"
498 " forward_dependent_configs_from\n"
499 " Shows the labels of dependencies for which dependent configs will\n"
500 " be pushed to targets depending on the current one.\n"
505 " Actions only. The script and related values.\n"
508 " Outputs for script and copy target types.\n"
510 " defines [--blame]\n"
511 " include_dirs [--blame]\n"
512 " cflags [--blame]\n"
513 " cflags_cc [--blame]\n"
514 " cflags_cxx [--blame]\n"
515 " ldflags [--blame]\n"
518 " Shows the given values taken from the target and all configs\n"
519 " applying. See \"--blame\" below.\n"
522 " Used with any value specified by a config, this will name\n"
523 " the config that specified the value. This doesn't currently work\n"
524 " for libs and lib_dirs because those are inherited and are more\n"
525 " complicated to figure out the blame (patches welcome).\n"
527 "Flags that control how deps are printed\n"
530 " Collects all recursive dependencies and prints a sorted flat list.\n"
531 " Also usable with --tree (see below).\n"
533 TARGET_PRINTING_MODE_COMMAND_LINE_HELP
535 TARGET_TESTONLY_FILTER_COMMAND_LINE_HELP
538 " Print a dependency tree. By default, duplicates will be elided\n"
539 " with \"...\" but when --all and -tree are used together, no\n"
540 " eliding will be performed.\n"
542 " The \"deps\", \"public_deps\", and \"data_deps\" will all be\n"
543 " included in the tree.\n"
545 " Tree output can not be used with the filtering or output flags:\n"
546 " --as, --type, --testonly.\n"
548 TARGET_TYPE_FILTER_COMMAND_LINE_HELP
552 " This command will show the full name of directories and source files,\n"
553 " but when directories and source paths are written to the build file,\n"
554 " they will be adjusted to be relative to the build directory. So the\n"
555 " values for paths displayed by this command won't match (but should\n"
556 " mean the same thing).\n"
560 " gn desc out/Debug //base:base\n"
561 " Summarizes the given target.\n"
563 " gn desc out/Foo :base_unittests deps --tree\n"
564 " Shows a dependency tree of the \"base_unittests\" project in\n"
565 " the current directory.\n"
567 " gn desc out/Debug //base defines --blame\n"
568 " Shows defines set for the //base:base target, annotated by where\n"
569 " each one was set from.\n";
571 #define OUTPUT_CONFIG_VALUE(name, type) \
572 OutputRecursiveTargetConfig<type>(target, #name, &ConfigValues::name);
574 int RunDesc(const std::vector
<std::string
>& args
) {
575 if (args
.size() != 2 && args
.size() != 3) {
576 Err(Location(), "You're holding it wrong.",
577 "Usage: \"gn desc <out_dir> <target_name> [<what to display>]\"")
582 // Deliberately leaked to avoid expensive process teardown.
583 Setup
* setup
= new Setup
;
584 if (!setup
->DoSetup(args
[0], false))
589 const Target
* target
= ResolveTargetFromCommandLineString(setup
, args
[1]);
593 #define CONFIG_VALUE_HANDLER(name, type) \
594 } else if (what == #name) { OUTPUT_CONFIG_VALUE(name, type)
596 if (args
.size() == 3) {
597 // User specified one thing to display.
598 const std::string
& what
= args
[2];
599 if (what
== variables::kConfigs
) {
600 PrintConfigs(target
, false);
601 } else if (what
== variables::kPublicConfigs
) {
602 PrintPublicConfigs(target
, false);
603 } else if (what
== variables::kAllDependentConfigs
) {
604 PrintAllDependentConfigs(target
, false);
605 } else if (what
== variables::kForwardDependentConfigsFrom
) {
606 PrintForwardDependentConfigsFrom(target
, false);
607 } else if (what
== variables::kSources
) {
608 PrintSources(target
, false);
609 } else if (what
== variables::kPublic
) {
610 PrintPublic(target
, false);
611 } else if (what
== variables::kCheckIncludes
) {
612 PrintCheckIncludes(target
, false);
613 } else if (what
== variables::kAllowCircularIncludesFrom
) {
614 PrintAllowCircularIncludesFrom(target
, false);
615 } else if (what
== variables::kVisibility
) {
616 PrintVisibility(target
, false);
617 } else if (what
== variables::kTestonly
) {
618 PrintTestonly(target
, false);
619 } else if (what
== variables::kInputs
) {
620 PrintInputs(target
, false);
621 } else if (what
== variables::kScript
) {
622 PrintScript(target
, false);
623 } else if (what
== variables::kArgs
) {
624 PrintArgs(target
, false);
625 } else if (what
== variables::kDepfile
) {
626 PrintDepfile(target
, false);
627 } else if (what
== variables::kOutputs
) {
628 PrintOutputs(target
, false);
629 } else if (what
== variables::kDeps
) {
630 PrintDeps(target
, false);
631 } else if (what
== variables::kLibDirs
) {
632 PrintLibDirs(target
, false);
633 } else if (what
== variables::kLibs
) {
634 PrintLibs(target
, false);
636 CONFIG_VALUE_HANDLER(defines
, std::string
)
637 CONFIG_VALUE_HANDLER(include_dirs
, SourceDir
)
638 CONFIG_VALUE_HANDLER(cflags
, std::string
)
639 CONFIG_VALUE_HANDLER(cflags_c
, std::string
)
640 CONFIG_VALUE_HANDLER(cflags_cc
, std::string
)
641 CONFIG_VALUE_HANDLER(cflags_objc
, std::string
)
642 CONFIG_VALUE_HANDLER(cflags_objcc
, std::string
)
643 CONFIG_VALUE_HANDLER(ldflags
, std::string
)
646 OutputString("Don't know how to display \"" + what
+ "\".\n");
650 #undef CONFIG_VALUE_HANDLER
656 // Display this only applicable to binary targets.
657 bool is_binary_output
=
658 target
->output_type() != Target::GROUP
&&
659 target
->output_type() != Target::COPY_FILES
&&
660 target
->output_type() != Target::ACTION
&&
661 target
->output_type() != Target::ACTION_FOREACH
;
663 // Generally we only want to display toolchains on labels when the toolchain
664 // is different than the default one for this target (which we always print
666 Label target_toolchain
= target
->label().GetToolchainLabel();
669 OutputString("Target: ", DECORATION_YELLOW
);
670 OutputString(target
->label().GetUserVisibleName(false) + "\n");
671 OutputString("Type: ", DECORATION_YELLOW
);
672 OutputString(std::string(
673 Target::GetStringForOutputType(target
->output_type())) + "\n");
674 OutputString("Toolchain: ", DECORATION_YELLOW
);
675 OutputString(target_toolchain
.GetUserVisibleName(false) + "\n");
677 PrintSources(target
, true);
678 if (is_binary_output
) {
679 PrintPublic(target
, true);
680 PrintCheckIncludes(target
, true);
681 PrintAllowCircularIncludesFrom(target
, true);
683 PrintVisibility(target
, true);
684 if (is_binary_output
) {
685 PrintTestonly(target
, true);
686 PrintConfigs(target
, true);
689 PrintPublicConfigs(target
, true);
690 PrintAllDependentConfigs(target
, true);
691 PrintForwardDependentConfigsFrom(target
, true);
693 PrintInputs(target
, true);
695 if (is_binary_output
) {
696 OUTPUT_CONFIG_VALUE(defines
, std::string
)
697 OUTPUT_CONFIG_VALUE(include_dirs
, SourceDir
)
698 OUTPUT_CONFIG_VALUE(cflags
, std::string
)
699 OUTPUT_CONFIG_VALUE(cflags_c
, std::string
)
700 OUTPUT_CONFIG_VALUE(cflags_cc
, std::string
)
701 OUTPUT_CONFIG_VALUE(cflags_objc
, std::string
)
702 OUTPUT_CONFIG_VALUE(cflags_objcc
, std::string
)
703 OUTPUT_CONFIG_VALUE(ldflags
, std::string
)
706 if (target
->output_type() == Target::ACTION
||
707 target
->output_type() == Target::ACTION_FOREACH
) {
708 PrintScript(target
, true);
709 PrintArgs(target
, true);
710 PrintDepfile(target
, true);
713 if (target
->output_type() == Target::ACTION
||
714 target
->output_type() == Target::ACTION_FOREACH
||
715 target
->output_type() == Target::COPY_FILES
) {
716 PrintOutputs(target
, true);
719 // Libs can be part of any target and get recursively pushed up the chain,
720 // so always display them, even for groups and such.
721 PrintLibs(target
, true);
722 PrintLibDirs(target
, true);
724 PrintDeps(target
, true);
729 } // namespace commands