Add check for a valid CQ-DEPEND field.

Common errors I've seen in the past:
  CQ-DEPENDS=1234
  CQ-DEPEND:1234

This CL catches all of the above plus more.

BUG=chromium:206541
CQ-DEPEND=CL:47271
TEST=Test with valid and invalid CQ-DEPEND fields.

Change-Id: Iafa4cb351d8f870289d72b09542218321ee6fa3c
Reviewed-on: https://gerrit.chromium.org/gerrit/47239
Tested-by: David James <davidjames@chromium.org>
Reviewed-by: Ryan Cui <rcui@chromium.org>
Commit-Queue: David James <davidjames@chromium.org>
diff --git a/pre-upload.py b/pre-upload.py
index b4f00f7..c2b2a7f 100755
--- a/pre-upload.py
+++ b/pre-upload.py
@@ -16,6 +16,14 @@
 from errors import (VerifyException, HookFailure, PrintErrorForProject,
                     PrintErrorsForCommit)
 
+# If repo imports us, the __name__ will be __builtin__, and the wrapper will
+# be in $CHROMEOS_CHECKOUT/.repo/repo/main.py, so we need to go two directories
+# up. The same logic also happens to work if we're executed directly.
+if __name__ in ('__builtin__', '__main__'):
+  sys.path.insert(0, os.path.join(os.path.dirname(sys.argv[0]), '..', '..'))
+
+from chromite.lib import patch
+
 
 COMMON_INCLUDED_PATHS = [
   # C++ and friends
@@ -324,6 +332,16 @@
     return HookFailure(msg)
 
 
+def _check_change_has_valid_cq_depend(project, commit):
+  """Check for a correctly formatted CQ-DEPEND field in the commit message."""
+  msg = 'Changelist has invalid CQ-DEPEND target.'
+  example = 'Example: CQ-DEPEND=CL:1234, CL:2345'
+  try:
+    patch.GetPaladinDeps(_get_commit_desc(commit))
+  except ValueError as ex:
+    return HookFailure(msg, [example, str(ex)])
+
+
 def _check_change_has_bug_field(project, commit):
   """Check for a correctly formatted 'BUG=' field in the commit message."""
   OLD_BUG_RE = r'\nBUG=.*chromium-os'
@@ -459,6 +477,7 @@
 # A list of hooks that are not project-specific
 _COMMON_HOOKS = [
     _check_change_has_bug_field,
+    _check_change_has_valid_cq_depend,
     _check_change_has_test_field,
     _check_change_has_proper_changeid,
     _check_no_stray_whitespace,
diff --git a/pre-upload_unittest.py b/pre-upload_unittest.py
index 946b4a4..9812a61 100755
--- a/pre-upload_unittest.py
+++ b/pre-upload_unittest.py
@@ -5,10 +5,14 @@
 # found in the LICENSE file.
 
 import mox
+import os
+import sys
 import unittest
 
 
 # pylint: disable=W0212
+if __name__ == '__main__':
+  sys.path.insert(0, os.path.join(os.path.dirname(sys.argv[0]), '..', '..'))
 
 pre_upload = __import__('pre-upload')