Fix no_check_targets logic and add a unit test.

Bug: 179
Change-Id: Ia3d844978c7181b679ea5a3cb28d129f7130812b
Reviewed-on: https://gn-review.googlesource.com/c/gn/+/9200
Reviewed-by: Brett Wilson <brettw@chromium.org>
Commit-Queue: Brett Wilson <brettw@chromium.org>
diff --git a/build/gen.py b/build/gen.py
index 34f349c..e7a86ec 100755
--- a/build/gen.py
+++ b/build/gen.py
@@ -624,6 +624,7 @@
         'src/gn/builder_unittest.cc',
         'src/gn/c_include_iterator_unittest.cc',
         'src/gn/command_format_unittest.cc',
+        'src/gn/commands_unittest.cc',
         'src/gn/compile_commands_writer_unittest.cc',
         'src/gn/config_unittest.cc',
         'src/gn/config_values_extractors_unittest.cc',
diff --git a/src/gn/commands.cc b/src/gn/commands.cc
index 8f1a1a7..97d2629 100644
--- a/src/gn/commands.cc
+++ b/src/gn/commands.cc
@@ -538,12 +538,16 @@
                                 const std::vector<LabelPattern>& filter,
                                 std::vector<const Target*>* output) {
   for (auto* target : input) {
+    bool match = false;
     for (const auto& pattern : filter) {
-      if (!pattern.Matches(target->label())) {
-        output->push_back(target);
+      if (pattern.Matches(target->label())) {
+        match = true;
         break;
       }
     }
+    if (!match) {
+      output->push_back(target);
+    }
   }
 }
 
diff --git a/src/gn/commands_unittest.cc b/src/gn/commands_unittest.cc
new file mode 100644
index 0000000..6d861cd
--- /dev/null
+++ b/src/gn/commands_unittest.cc
@@ -0,0 +1,35 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include <stddef.h>
+
+#include "gn/commands.h"
+#include "gn/label_pattern.h"
+#include "gn/target.h"
+#include "gn/test_with_scope.h"
+#include "util/test/test.h"
+
+TEST(Commands, FilterOutMatch) {
+  TestWithScope setup;
+  SourceDir current_dir("//");
+
+  Target target_afoo(setup.settings(), Label(SourceDir("//a/"), "foo"));
+  Target target_cbar(setup.settings(), Label(SourceDir("//c/"), "bar"));
+  std::vector<const Target*> targets{&target_afoo, &target_cbar};
+
+  Err err;
+  LabelPattern pattern_a = LabelPattern::GetPattern(
+      current_dir, std::string_view(), Value(nullptr, "//a:*"), &err);
+  EXPECT_FALSE(err.has_error());
+  LabelPattern pattern_ef = LabelPattern::GetPattern(
+      current_dir, std::string_view(), Value(nullptr, "//e:f"), &err);
+  EXPECT_FALSE(err.has_error());
+  std::vector<LabelPattern> label_patterns{pattern_a, pattern_ef};
+
+  std::vector<const Target*> output;
+  commands::FilterOutTargetsByPatterns(targets, label_patterns, &output);
+
+  EXPECT_EQ(1, output.size());
+  EXPECT_EQ(&target_cbar, output[0]);
+}