git-map: Refactor and add simple tests

Change-Id: I8fd0034f6a6d7623792620f92208b25961fa174e
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/1990142
Reviewed-by: Anthony Polito <apolito@google.com>
Commit-Queue: Edward Lesmes <ehmaldonado@chromium.org>
diff --git a/git_map.py b/git_map.py
index f76d0df..e8d4513 100755
--- a/git_map.py
+++ b/git_map.py
@@ -4,6 +4,8 @@
 # found in the LICENSE file.
 
 """
+usage: git map [-h] [--help] [<args>]
+
 Enhances `git log --graph` view with information on commit branches + tags that
 point to them. Items are colorized as follows:
 
@@ -15,130 +17,150 @@
   * Blue background - The currently checked out commit
 """
 
+from __future__ import unicode_literals
+
+import os
 import sys
 
+import git_common
+import setup_color
 import subprocess2
 
-from git_common import current_branch, branches, tags, get_config_list, GIT_EXE
-from git_common import get_or_create_merge_base, root
-
 from third_party import colorama
 
-CYAN = colorama.Fore.CYAN
-GREEN = colorama.Fore.GREEN
-MAGENTA = colorama.Fore.MAGENTA
-RED = colorama.Fore.RED
-WHITE = colorama.Fore.WHITE
 
-BLUEBAK = colorama.Back.BLUE
+if sys.version_info.major == 2:
+  # On Python 3, BrokenPipeError is raised instead.
+  BrokenPipeError = IOError
 
-BRIGHT = colorama.Style.BRIGHT
+
 RESET = colorama.Fore.RESET + colorama.Back.RESET + colorama.Style.RESET_ALL
+BRIGHT = colorama.Style.BRIGHT
 
-# Git emits combined color
-BRIGHT_RED = '\x1b[1;31m'
+BLUE_BACK = colorama.Back.BLUE + BRIGHT
+BRIGHT_RED = colorama.Fore.RED + BRIGHT
+CYAN = colorama.Fore.CYAN + BRIGHT
+GREEN = colorama.Fore.GREEN + BRIGHT
+MAGENTA = colorama.Fore.MAGENTA + BRIGHT
+RED = colorama.Fore.RED
+WHITE = colorama.Fore.WHITE + BRIGHT
+YELLOW = colorama.Fore.YELLOW
 
 
-def print_help():
+def _print_help(outbuf):
   names = {
     'Cyan': CYAN,
     'Green': GREEN,
     'Magenta': MAGENTA,
     'Red': RED,
     'White': WHITE,
-    'Blue background': BLUEBAK,
+    'Blue background': BLUE_BACK,
   }
-  msg = "usage: git map [-h] [<args>]\n"
-
+  msg = ''
   for line in __doc__.splitlines():
-    for key in names.keys():
-      if key in line:
-        msg += line.replace('* ', '* ' + names[key])+RESET+'\n'
+    for name, color in names.items():
+      if name in line:
+        msg += line.replace('* ' + name, color + '* ' + name + RESET) + '\n'
         break
     else:
       msg += line + '\n'
-  sys.stdout.write(msg)
+  outbuf.write(msg.encode('utf-8', 'replace'))
 
 
-def main(argv):
-  if '-h' in argv:
-    print_help()
+def _color_branch(branch, all_branches, all_tags, current):
+  if branch == current or branch == 'HEAD -> ' + current:
+    color = CYAN
+    current = None
+  elif branch in all_branches:
+    color = GREEN
+    all_branches.remove(branch)
+  elif branch in all_tags:
+    color = MAGENTA
+  elif branch.startswith('tag: '):
+    color = MAGENTA
+    branch = branch[len('tag: '):]
+  else:
+    color = RED
+  return color + branch + RESET
+
+
+def _color_branch_list(branch_list, all_branches, all_tags, current):
+  if not branch_list:
+    return ''
+  colored_branches = (GREEN + ', ').join(
+      _color_branch(branch, all_branches, all_tags, current)
+      for branch in branch_list if branch != 'HEAD')
+  return (GREEN + '(' + colored_branches + GREEN + ') ' + RESET)
+
+
+def _parse_log_line(line):
+  graph, branch_list, commit_date, subject = (
+      line.decode('utf-8', 'replace').strip().split('\x00'))
+  branch_list = [] if not branch_list else branch_list.split(', ')
+  commit = graph.split()[-1]
+  graph = graph[:-len(commit)]
+  return graph, commit, branch_list, commit_date, subject
+
+
+def main(argv, outbuf):
+  if '-h' in argv or '--help' in argv:
+    _print_help(outbuf)
     return 0
 
-  map_extra = get_config_list('depot_tools.map_extra')
-  fmt = '%C(red bold)%h%x09%Creset%C(green)%d%Creset %C(yellow)%cd%Creset ~ %s'
-  log_proc = subprocess2.Popen(
-    [GIT_EXE, 'log', '--graph', '--branches', '--tags', root(),
-     '--color=always', '--date=short', ('--pretty=format:' + fmt)
-    ] + map_extra + argv,
-    stdout=subprocess2.PIPE,
-    shell=False)
+  map_extra = git_common.get_config_list('depot_tools.map_extra')
+  cmd = [
+      git_common.GIT_EXE, 'log', git_common.root(),
+      '--graph', '--branches', '--tags', '--color=always', '--date=short',
+      '--pretty=format:%H%x00%D%x00%cd%x00%s'
+  ] + map_extra + argv
 
-  current = current_branch()
-  all_branches = set(branches())
-  merge_base_map = {b: get_or_create_merge_base(b) for b in all_branches}
-  merge_base_map = {b: v for b, v in merge_base_map.items() if v}
+  log_proc = subprocess2.Popen(cmd, stdout=subprocess2.PIPE, shell=False)
+
+  current = git_common.current_branch()
+  all_tags = set(git_common.tags())
+  all_branches = set(git_common.branches())
   if current in all_branches:
     all_branches.remove(current)
-  all_tags = set(tags())
-  try:
-    for line in log_proc.stdout.xreadlines():
-      if merge_base_map:
-        commit = line[line.find(BRIGHT_RED)+len(BRIGHT_RED):line.find('\t')]
-        base_for_branches = set()
-        for branch, sha in merge_base_map.items():
-          if sha.startswith(commit):
-            base_for_branches.add(branch)
-        if base_for_branches:
-          newline = '\r\n' if line.endswith('\r\n') else '\n'
-          line = line.rstrip(newline)
-          line += ''.join(
-              (BRIGHT, WHITE, '    <(%s)' % (', '.join(base_for_branches)),
-               RESET, newline))
-          for b in base_for_branches:
-            del merge_base_map[b]
 
-      start = line.find(GREEN+' (')
-      end   = line.find(')', start)
-      if start != -1 and end != -1:
-        start += len(GREEN) + 2
-        branch_list = line[start:end].split(', ')
-        branches_str = ''
-        if branch_list:
-          colored_branches = []
-          head_marker = ''
-          for b in branch_list:
-            if b == "HEAD":
-              head_marker = BLUEBAK+BRIGHT+'*'
-              continue
-            if b == current:
-              colored_branches.append(CYAN+BRIGHT+b+RESET)
-              current = None
-            elif b in all_branches:
-              colored_branches.append(GREEN+BRIGHT+b+RESET)
-              all_branches.remove(b)
-            elif b in all_tags:
-              colored_branches.append(MAGENTA+BRIGHT+b+RESET)
-            elif b.startswith('tag: '):
-              colored_branches.append(MAGENTA+BRIGHT+b[5:]+RESET)
-            else:
-              colored_branches.append(RED+b)
-            branches_str = '(%s) ' % ((GREEN+", ").join(colored_branches)+GREEN)
-          line = "%s%s%s" % (line[:start-1], branches_str, line[end+5:])
-          if head_marker:
-            line = line.replace('*', head_marker, 1)
-      sys.stdout.write(line)
-  except (IOError, KeyboardInterrupt):
+  merge_base_map = {}
+  for branch in all_branches:
+    merge_base = git_common.get_or_create_merge_base(branch)
+    if merge_base:
+      merge_base_map.setdefault(merge_base, set()).add(branch)
+
+  for merge_base, branches in merge_base_map.items():
+    merge_base_map[merge_base] = ', '.join(branches)
+
+  try:
+    for line in log_proc.stdout:
+      if b'\x00' not in line:
+        outbuf.write(line)
+        continue
+
+      graph, commit, branch_list, commit_date, subject = _parse_log_line(line)
+
+      if 'HEAD' in branch_list:
+        graph = graph.replace('*', BLUE_BACK + '*')
+
+      line = '{graph}{commit}\t{branches}{date} ~ {subject}'.format(
+          graph=graph,
+          commit=BRIGHT_RED + commit[:10] + RESET,
+          branches=_color_branch_list(
+              branch_list, all_branches, all_tags, current),
+          date=YELLOW + commit_date + RESET,
+          subject=subject)
+
+      if commit in merge_base_map:
+        line += '    <({})'.format(WHITE + merge_base_map[commit] + RESET)
+
+      line += os.linesep
+      outbuf.write(line.encode('utf-8', 'replace'))
+  except (BrokenPipeError, KeyboardInterrupt):
     pass
-  finally:
-    sys.stderr.close()
-    sys.stdout.close()
   return 0
 
 
 if __name__ == '__main__':
-  try:
-    sys.exit(main(sys.argv[1:]))
-  except KeyboardInterrupt:
-    sys.stderr.write('interrupted\n')
-    sys.exit(1)
+  setup_color.init()
+  with git_common.less() as less_input:
+    sys.exit(main(sys.argv[1:], less_input))