Adding PRESUBMIT check on orphan headers files.

We want all .h files to be tracked by a GN target. This CL adds a
presubmit check to ensure that newly added targets are tracked by
GN.

In this CL we add a directory called 'presubmit_checks_lib' so we
can avoid to put everything in PRESUBMIT.py (especially if we want
to test some checks). I tried to use 'tools-webrtc' but it is not
easy to include a python module from a directory with '-' in the
name.

BUG=webrtc:7514

Review-Url: https://codereview.webrtc.org/2872493002
Cr-Commit-Position: refs/heads/master@{#18069}
diff --git a/PRESUBMIT.py b/PRESUBMIT.py
index 694624e..e13c9a0 100755
--- a/PRESUBMIT.py
+++ b/PRESUBMIT.py
@@ -575,6 +575,7 @@
   results.extend(_CheckJSONParseErrors(input_api, output_api))
   results.extend(_RunPythonTests(input_api, output_api))
   results.extend(_CheckUsageOfGoogleProtobufNamespace(input_api, output_api))
+  results.extend(_CheckOrphanHeaders(input_api, output_api))
   return results
 
 
@@ -602,3 +603,33 @@
       input_api, output_api,
       json_url='http://webrtc-status.appspot.com/current?format=json'))
   return results
+
+
+def _CheckOrphanHeaders(input_api, output_api):
+  # We need to wait until we have an input_api object and use this
+  # roundabout construct to import prebubmit_checks_lib because this file is
+  # eval-ed and thus doesn't have __file__.
+  error_msg = """Header file {} is not listed in any GN target.
+  Please create a target or add it to an existing one in {}"""
+  results = []
+  original_sys_path = sys.path
+  try:
+    sys.path = sys.path + [input_api.os_path.join(
+        input_api.PresubmitLocalPath(), 'tools_webrtc', 'presubmit_checks_lib')]
+    from check_orphan_headers import GetBuildGnPathFromFilePath
+    from check_orphan_headers import IsHeaderInBuildGn
+  finally:
+    # Restore sys.path to what it was before.
+    sys.path = original_sys_path
+
+  for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
+    if f.LocalPath().endswith('.h'):
+      file_path = os.path.abspath(f.LocalPath())
+      root_dir = os.getcwd()
+      gn_file_path = GetBuildGnPathFromFilePath(file_path, os.path.exists,
+                                                root_dir)
+      in_build_gn = IsHeaderInBuildGn(file_path, gn_file_path)
+      if not in_build_gn:
+        results.append(output_api.PresubmitError(error_msg.format(
+            file_path, gn_file_path)))
+  return results