Add a --max-depth option to git cl split

For some types of changes, git cl split generates too many small CLs.
--max-depth provides one way of generating larger CLs when the author
judges that the larger CLs do not adversely affect reviewability (e.g.
20x 1 line CLs packed into 1x 20 line CL is generally fine).

Fixed: 777781
Change-Id: I64426ff4723fbc412fbc47f3cc12767433aeb8ae
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/3933974
Reviewed-by: Josip Sokcevic <sokcevic@google.com>
Commit-Queue: Daniel Cheng <dcheng@chromium.org>
diff --git a/split_cl.py b/split_cl.py
index 420c8ad..9afc3d3 100644
--- a/split_cl.py
+++ b/split_cl.py
@@ -140,7 +140,7 @@
                             publish=True)
 
 
-def GetFilesSplitByOwners(files):
+def GetFilesSplitByOwners(files, max_depth):
   """Returns a map of files split by OWNERS file.
 
   Returns:
@@ -149,7 +149,13 @@
   """
   files_split_by_owners = {}
   for action, path in files:
-    dir_with_owners = os.path.dirname(path)
+    # normpath() is important to normalize separators here, in prepration for
+    # str.split() before. It would be nicer to use something like pathlib here
+    # but alas...
+    dir_with_owners = os.path.normpath(os.path.dirname(path))
+    if max_depth >= 1:
+      dir_with_owners = os.path.join(
+          *dir_with_owners.split(os.path.sep)[:max_depth])
     # Find the closest parent directory with an OWNERS file.
     while (dir_with_owners not in files_split_by_owners
            and not os.path.isfile(os.path.join(dir_with_owners, 'OWNERS'))):
@@ -184,7 +190,7 @@
 
 
 def SplitCl(description_file, comment_file, changelist, cmd_upload, dry_run,
-            cq_dry_run, enable_auto_submit, repository_root):
+            cq_dry_run, enable_auto_submit, max_depth, repository_root):
   """"Splits a branch into smaller branches and uploads CLs.
 
   Args:
@@ -195,6 +201,8 @@
     dry_run: Whether this is a dry run (no branches or CLs created).
     cq_dry_run: If CL uploads should also do a cq dry run.
     enable_auto_submit: If CL uploads should also enable auto submit.
+    max_depth: The maximum directory depth to search for OWNERS files. A value
+               less than 1 means no limit.
 
   Returns:
     0 in case of success. 1 in case of error.
@@ -224,7 +232,7 @@
     assert refactor_branch_upstream, \
         "Branch %s must have an upstream." % refactor_branch
 
-    files_split_by_owners = GetFilesSplitByOwners(files)
+    files_split_by_owners = GetFilesSplitByOwners(files, max_depth)
 
     num_cls = len(files_split_by_owners)
     print('Will split current branch (' + refactor_branch + ') into ' +