gerrit: add a --json option for further scripting

This lets people pipe their results into a diff tool to do further
parsing/analysis as they see fit.

BUG=None
TEST=`gerrit --json search 'assignee:self status:open' | python -mjson.tool` works
TEST=`gerrit todo` still works
TEST=`gerrit --raw todo` still works
TEST=`gerrit --raw -i todo` still works
TEST=`gerrit inspect 12345` still works

Change-Id: I81a57ec87705f45ff0466fbd1b78361fbe6d8b1a
Reviewed-on: https://chromium-review.googlesource.com/467968
Commit-Ready: Mike Frysinger <vapier@chromium.org>
Tested-by: Mike Frysinger <vapier@chromium.org>
Reviewed-by: Allen Li <ayatane@chromium.org>
diff --git a/scripts/gerrit.py b/scripts/gerrit.py
index bedfc79..94a7444 100644
--- a/scripts/gerrit.py
+++ b/scripts/gerrit.py
@@ -12,8 +12,9 @@
 from __future__ import print_function
 
 import inspect
-import pprint
+import json
 import re
+import sys
 
 from chromite.lib import config_lib
 from chromite.lib import constants
@@ -150,7 +151,7 @@
 
 
 def PrintCls(opts, cls, lims=None, show_approvals=True):
-  """Pretty print all results."""
+  """Print all results based on the requested format."""
   if opts.raw:
     pfx = ''
     # Special case internal Chrome GoB as that is what most devs use.
@@ -160,6 +161,9 @@
     for cl in cls:
       print('%s%s' % (pfx, cl['number']))
 
+  elif opts.json:
+    json.dump(cls, sys.stdout)
+
   else:
     if lims is None:
       lims = limits(cls)
@@ -444,7 +448,12 @@
 def UserActAccount(opts):
   """Get user account information."""
   helper, _ = GetGerrit(opts)
-  pprint.PrettyPrinter().pprint(helper.GetAccount())
+  acct = helper.GetAccount()
+  if opts.json:
+    json.dump(acct, sys.stdout)
+  else:
+    print('account_id:%i  %s <%s>' %
+          (acct['_account_id'], acct['name'], acct['email']))
 
 
 def main(argv):
@@ -474,6 +483,7 @@
 ready.
   $ gerrit ready `gerrit --raw -i mine` 1   # Mark *ALL* of your internal CLs \
 ready.
+  $ gerrit --json search 'assignee:self'    # Dump all pending CLs in JSON.
 
 Actions:"""
   indent = max([len(x) - len(act_pfx) for x in actions])
@@ -498,6 +508,8 @@
                       help='Key to sort on (number, project)')
   parser.add_argument('--raw', default=False, action='store_true',
                       help='Return raw results (suitable for scripting)')
+  parser.add_argument('--json', default=False, action='store_true',
+                      help='Return results in JSON (suitable for scripting)')
   parser.add_argument('-n', '--dry-run', default=False, action='store_true',
                       dest='dryrun',
                       help='Show what would be done, but do not make changes')