From 72ab852ca503d1c8e32e493edc3fa3e1157e930b Mon Sep 17 00:00:00 2001 From: Mike Frysinger Date: Tue, 1 Oct 2019 00:18:46 -0400 Subject: [PATCH] grep: handle errors gracefully If `git grep` fails in any project checkout (e.g. an incomplete sync), make sure we print that error clearly rather than blowing up, and exit non-zero in the process. Bug: https://crbug.com/gerrit/11613 Change-Id: I31de1134fdcc7aaa9814cf2eb6a67d398eebf9cf Reviewed-on: https://gerrit-review.googlesource.com/c/git-repo/+/239237 Reviewed-by: David Pursehouse Tested-by: Mike Frysinger --- subcmds/grep.py | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/subcmds/grep.py b/subcmds/grep.py index a588a78e..4dd85d57 100644 --- a/subcmds/grep.py +++ b/subcmds/grep.py @@ -15,15 +15,19 @@ # limitations under the License. from __future__ import print_function + import sys + from color import Coloring from command import PagedCommand +from error import GitError from git_command import git_require, GitCommand class GrepColoring(Coloring): def __init__(self, config): Coloring.__init__(self, config, 'grep') self.project = self.printer('project', attr='bold') + self.fail = self.printer('fail', fg='red') class Grep(PagedCommand): common = True @@ -184,15 +188,25 @@ contain a line that matches both expressions: cmd_argv.extend(opt.revision) cmd_argv.append('--') + git_failed = False bad_rev = False have_match = False for project in projects: - p = GitCommand(project, - cmd_argv, - bare = False, - capture_stdout = True, - capture_stderr = True) + try: + p = GitCommand(project, + cmd_argv, + bare=False, + capture_stdout=True, + capture_stderr=True) + except GitError as e: + git_failed = True + out.project('--- project %s ---' % project.relpath) + out.nl() + out.fail('%s', str(e)) + out.nl() + continue + if p.Wait() != 0: # no results # @@ -202,7 +216,7 @@ contain a line that matches both expressions: else: out.project('--- project %s ---' % project.relpath) out.nl() - out.write("%s", p.stderr) + out.fail('%s', p.stderr.strip()) out.nl() continue have_match = True @@ -231,7 +245,9 @@ contain a line that matches both expressions: for line in r: print(line) - if have_match: + if git_failed: + sys.exit(1) + elif have_match: sys.exit(0) elif have_rev and bad_rev: for r in opt.revision: