Add --with-transitive-deps to gn check

Chromium wants to run "gn check --check-generated" on CQ builders. They
reuse the out dir and build only the targets affected by a CL, so
generated files of other targets can be stale and fail the check.

With --with-transitive-deps, "gn check" also checks the transitive deps
of the targets matching the label patterns and applies check_targets,
no_check_targets and no_check_generated_targets from .gn, so a builder
can check exactly what it built. Label patterns without
--with-transitive-deps behave as before.

Bug: 577807023
Change-Id: I925972477c94a7128a2a57c83f84ccdd4874a29d
Reviewed-on: https://gn-review.googlesource.com/c/gn/+/27840
Commit-Queue: Ryosuke Miyake <rysk@google.com>
Reviewed-by: Takuto Ikuta <tikuta@google.com>
diff --git a/docs/reference.md b/docs/reference.md
index 925db25..dd43a0f 100644
--- a/docs/reference.md
+++ b/docs/reference.md
@@ -368,8 +368,9 @@
     arguments).
 ```
 ### <a name="cmd_check"></a>**gn check &lt;out_dir&gt; [&lt;label_pattern&gt;...] [\--force] [\--check-generated] [\--fix]**&nbsp;[Back to Top](#gn-reference)
-
 ```
+      [--with-transitive-deps]
+
   GN's include header checker validates that the includes for C-like source
   files match the build dependency graph.
 
@@ -411,6 +412,12 @@
   --force
       Ignores specifications of "check_includes = false" and checks all
       target's files that match the target label.
+
+  --with-transitive-deps
+      Also checks the transitive dependencies, including data_deps, of the
+      targets that match the label patterns. These are the targets that
+      building the matching targets builds. The lists in the .gn file are
+      applied (see "What gets checked").
 ```
 
 #### **What gets checked**
@@ -421,7 +428,8 @@
   specify a list of targets not to be checked in no_check_targets. It may also
   list targets whose generated files are not checked with --check-generated in
   no_check_generated_targets. If a label pattern is specified on the command
-  line, none of these lists is used.
+  line, none of these lists is used unless --with-transitive-deps is
+  given.
 
   Targets can opt-out from checking with "check_includes = false" (see
   "gn help check_includes").
@@ -511,6 +519,10 @@
 
   gn check out/Default "//foo/*
       Check only the files in targets in the //foo directory tree.
+
+  gn check out/Default --with-transitive-deps //foo:bar //foo:baz
+      Check the files in //foo:bar, //foo:baz and their transitive
+      dependencies, except targets excluded by the lists in the .gn file.
 ```
 ### <a name="cmd_clean"></a>**gn clean &lt;out_dir&gt;...**&nbsp;[Back to Top](#gn-reference)
 
@@ -7699,7 +7711,8 @@
       no_check_targets (see below) is specified, all targets will be checked.
       It is an error to specify both check_targets and no_check_targets. If it
       is the empty list, no targets will be checked. To bypass this list,
-      request an explicit check of targets, like "//*".
+      request an explicit check of targets, like "//*", without
+      --with-transitive-deps.
 
       The format of this list is identical to that of "visibility" so see "gn
       help visibility" for examples.
@@ -7721,7 +7734,7 @@
       Generated files are the target's files in the output directory, such as
       action outputs listed in its sources. This list can be combined with
       check_targets or no_check_targets. To bypass it, request an explicit
-      check of targets, like "//*".
+      check of targets, like "//*", without --with-transitive-deps.
 
       The format of this list is identical to that of "visibility" so see "gn
       help visibility" for examples.
diff --git a/src/gn/command_check.cc b/src/gn/command_check.cc
index 13eaf09..61d9194 100644
--- a/src/gn/command_check.cc
+++ b/src/gn/command_check.cc
@@ -12,6 +12,7 @@
 #include "base/command_line.h"
 #include "base/strings/stringprintf.h"
 #include "gn/commands.h"
+#include "gn/deps_iterator.h"
 #include "gn/header_checker.h"
 #include "gn/setup.h"
 #include "gn/standard_out.h"
@@ -61,6 +62,7 @@
 const char kCheck_HelpShort[] = "check: Check header dependencies.";
 const char kCheck_Help[] =
     R"(gn check <out_dir> [<label_pattern>...] [--force] [--check-generated] [--fix]
+      [--with-transitive-deps]
 
   GN's include header checker validates that the includes for C-like source
   files match the build dependency graph.
@@ -96,6 +98,12 @@
       Ignores specifications of "check_includes = false" and checks all
       target's files that match the target label.
 
+  --with-transitive-deps
+      Also checks the transitive dependencies, including data_deps, of the
+      targets that match the label patterns. These are the targets that
+      building the matching targets builds. The lists in the .gn file are
+      applied (see "What gets checked").
+
 What gets checked
 
   The .gn file may specify a list of targets to be checked in the list
@@ -103,7 +111,8 @@
   specify a list of targets not to be checked in no_check_targets. It may also
   list targets whose generated files are not checked with --check-generated in
   no_check_generated_targets. If a label pattern is specified on the command
-  line, none of these lists is used.
+  line, none of these lists is used unless --with-transitive-deps is
+  given.
 
   Targets can opt-out from checking with "check_includes = false" (see
   "gn help check_includes").
@@ -189,15 +198,21 @@
 
   gn check out/Default "//foo/*
       Check only the files in targets in the //foo directory tree.
+
+  gn check out/Default --with-transitive-deps //foo:bar //foo:baz
+      Check the files in //foo:bar, //foo:baz and their transitive
+      dependencies, except targets excluded by the lists in the .gn file.
 )";
 
 namespace {
 
-// Returns the targets matching label_patterns. Returns std::nullopt if the
-// patterns are invalid or match no target.
+// Returns the targets matching label_patterns, and their transitive deps if
+// with_transitive_deps is set. Returns std::nullopt if the patterns are
+// invalid or match no target.
 std::optional<std::vector<const Target*>> ResolveCandidates(
     Setup* setup,
     const std::vector<std::string>& label_patterns,
+    bool with_transitive_deps,
     bool default_toolchain_only) {
   UniqueVector<const Target*> target_matches;
   UniqueVector<const Config*> config_matches;
@@ -212,6 +227,16 @@
     OutputString("No matching targets.\n");
     return std::nullopt;
   }
+
+  if (with_transitive_deps) {
+    // Walk all public, private and data deps, which are what a build of the
+    // matching targets builds. target_matches grows while it is iterated.
+    for (size_t i = 0; i < target_matches.size(); i++) {
+      const Target* target = target_matches[i];
+      for (const auto& pair : target->GetDeps(Target::DEPS_ALL))
+        target_matches.push_back(pair.ptr);
+    }
+  }
   return target_matches.release();
 }
 
@@ -221,18 +246,20 @@
     Setup* setup,
     const std::vector<const Target*>& all_targets,
     const std::vector<std::string>& label_patterns,
+    bool with_transitive_deps,
     bool default_toolchain_only) {
   TargetsToCheck result;
   if (label_patterns.empty()) {
     result.candidates = all_targets;
-  } else if (auto resolved = ResolveCandidates(setup, label_patterns,
-                                               default_toolchain_only)) {
+  } else if (auto resolved =
+                 ResolveCandidates(setup, label_patterns, with_transitive_deps,
+                                   default_toolchain_only)) {
     result.candidates = std::move(*resolved);
   } else {
     return std::nullopt;
   }
 
-  if (!label_patterns.empty()) {
+  if (!label_patterns.empty() && !with_transitive_deps) {
     // An explicit check of targets bypasses the lists in the .gn file.
     result.to_check = result.candidates;
     return result;
@@ -269,6 +296,7 @@
 
   const base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess();
   bool default_toolchain_only = cmdline->HasSwitch(switches::kDefaultToolchain);
+  bool with_transitive_deps = cmdline->HasSwitch("with-transitive-deps");
   bool force = cmdline->HasSwitch("force");
   bool check_generated = cmdline->HasSwitch("check-generated");
   bool check_system =
@@ -276,10 +304,19 @@
   bool fix = cmdline->HasSwitch("fix");
 
   std::vector<std::string> label_patterns(args.begin() + 1, args.end());
+  if (with_transitive_deps && label_patterns.empty()) {
+    Err(Location(), "--with-transitive-deps requires a label pattern.",
+        "Usage: \"gn check <out_dir> --with-transitive-deps "
+        "<label_pattern>...\"")
+        .PrintToStdout();
+    return 1;
+  }
+
   std::vector<const Target*> all_targets =
       setup->builder().GetAllResolvedTargets();
-  std::optional<TargetsToCheck> targets = GetTargetsToCheck(
-      setup, all_targets, label_patterns, default_toolchain_only);
+  std::optional<TargetsToCheck> targets =
+      GetTargetsToCheck(setup, all_targets, label_patterns,
+                        with_transitive_deps, default_toolchain_only);
   if (!targets)
     return 1;
 
diff --git a/src/gn/command_check_unittest.cc b/src/gn/command_check_unittest.cc
index 33c0247..c55a30c 100644
--- a/src/gn/command_check_unittest.cc
+++ b/src/gn/command_check_unittest.cc
@@ -124,6 +124,7 @@
   TestProject project;
   std::optional<commands::TargetsToCheck> targets =
       commands::GetTargetsToCheck(project.setup(), project.all_targets(), {},
+                                  /*with_transitive_deps=*/false,
                                   /*default_toolchain_only=*/false);
   ASSERT_TRUE(targets);
 
@@ -140,6 +141,7 @@
   TestProject project;
   std::optional<commands::TargetsToCheck> targets = commands::GetTargetsToCheck(
       project.setup(), project.all_targets(), {"//:b", "//:d"},
+      /*with_transitive_deps=*/false,
       /*default_toolchain_only=*/false);
   ASSERT_TRUE(targets);
 
@@ -156,6 +158,7 @@
 )");
   std::optional<commands::TargetsToCheck> targets =
       commands::GetTargetsToCheck(project.setup(), project.all_targets(), {},
+                                  /*with_transitive_deps=*/false,
                                   /*default_toolchain_only=*/false);
   ASSERT_TRUE(targets);
 
@@ -166,9 +169,58 @@
   EXPECT_TRUE(targets->no_check_generated.empty());
 }
 
+TEST_F(CommandCheckTest, WithTransitiveDeps) {
+  TestProject project;
+  std::optional<commands::TargetsToCheck> targets =
+      commands::GetTargetsToCheck(project.setup(), project.all_targets(),
+                                  {"//:a"}, /*with_transitive_deps=*/true,
+                                  /*default_toolchain_only=*/false);
+  ASSERT_TRUE(targets);
+
+  EXPECT_EQ((std::set<std::string>{"//:a", "//:b", "//:c", "//:d"}),
+            Labels(targets->candidates));
+  EXPECT_EQ((std::set<std::string>{"//:a", "//:b", "//:c"}),
+            Labels(targets->to_check));
+  EXPECT_EQ((std::set<std::string>{"//:b"}),
+            Labels(targets->no_check_generated));
+}
+
+TEST_F(CommandCheckTest, WithTransitiveDepsMultipleLabelPatterns) {
+  TestProject project;
+  std::optional<commands::TargetsToCheck> targets = commands::GetTargetsToCheck(
+      project.setup(), project.all_targets(), {"//:c", "//:b"},
+      /*with_transitive_deps=*/true,
+      /*default_toolchain_only=*/false);
+  ASSERT_TRUE(targets);
+
+  EXPECT_EQ((std::set<std::string>{"//:b", "//:c", "//:d"}),
+            Labels(targets->candidates));
+  EXPECT_EQ((std::set<std::string>{"//:b", "//:c"}), Labels(targets->to_check));
+  EXPECT_EQ((std::set<std::string>{"//:b"}),
+            Labels(targets->no_check_generated));
+}
+
+TEST_F(CommandCheckTest, WithTransitiveDepsCheckTargets) {
+  TestProject project(R"(
+buildconfig = "//BUILDCONFIG.gn"
+check_targets = [ "//:a", "//:c" ]
+)");
+  std::optional<commands::TargetsToCheck> targets =
+      commands::GetTargetsToCheck(project.setup(), project.all_targets(),
+                                  {"//:a"}, /*with_transitive_deps=*/true,
+                                  /*default_toolchain_only=*/false);
+  ASSERT_TRUE(targets);
+
+  EXPECT_EQ((std::set<std::string>{"//:a", "//:b", "//:c", "//:d"}),
+            Labels(targets->candidates));
+  EXPECT_EQ((std::set<std::string>{"//:a", "//:c"}), Labels(targets->to_check));
+  EXPECT_TRUE(targets->no_check_generated.empty());
+}
+
 TEST_F(CommandCheckTest, NoMatchingTargets) {
   TestProject project;
   EXPECT_FALSE(commands::GetTargetsToCheck(
       project.setup(), project.all_targets(), {"//nonexistent/*"},
+      /*with_transitive_deps=*/true,
       /*default_toolchain_only=*/false));
 }
diff --git a/src/gn/commands.h b/src/gn/commands.h
index 60de9e4..f9228a3 100644
--- a/src/gn/commands.h
+++ b/src/gn/commands.h
@@ -419,7 +419,8 @@
 // The targets that "gn check" checks. See GetTargetsToCheck().
 struct TargetsToCheck {
   // All targets if no label pattern is given, or else the targets matching the
-  // label patterns.
+  // label patterns and, with --with-transitive-deps, their transitive public,
+  // private and data deps.
   std::vector<const Target*> candidates;
 
   // The candidates allowed by check_targets or no_check_targets in the .gn
@@ -432,14 +433,15 @@
 
 // Computes the targets that "gn check" checks. |all_targets| must be all
 // resolved targets in the build; they are the candidates if |label_patterns|
-// is empty. Label patterns bypass the .gn lists: |to_check| gets all candidates
-// and |no_check_generated| stays empty.
+// is empty. Label patterns without |with_transitive_deps| bypass the .gn lists:
+// |to_check| gets all candidates and |no_check_generated| stays empty.
 //
 // On failure, prints the error and returns std::nullopt.
 std::optional<TargetsToCheck> GetTargetsToCheck(
     Setup* setup,
     const std::vector<const Target*>& all_targets,
     const std::vector<std::string>& label_patterns,
+    bool with_transitive_deps,
     bool default_toolchain_only);
 
 // Runs the header checker. All targets in the build should be given in
diff --git a/src/gn/setup.cc b/src/gn/setup.cc
index 71033c6..526e864 100644
--- a/src/gn/setup.cc
+++ b/src/gn/setup.cc
@@ -103,7 +103,8 @@
       no_check_targets (see below) is specified, all targets will be checked.
       It is an error to specify both check_targets and no_check_targets. If it
       is the empty list, no targets will be checked. To bypass this list,
-      request an explicit check of targets, like "//*".
+      request an explicit check of targets, like "//*", without
+      --with-transitive-deps.
 
       The format of this list is identical to that of "visibility" so see "gn
       help visibility" for examples.
@@ -125,7 +126,7 @@
       Generated files are the target's files in the output directory, such as
       action outputs listed in its sources. This list can be combined with
       check_targets or no_check_targets. To bypass it, request an explicit
-      check of targets, like "//*".
+      check of targets, like "//*", without --with-transitive-deps.
 
       The format of this list is identical to that of "visibility" so see "gn
       help visibility" for examples.