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 <dpursehouse@collab.net>
Tested-by: Mike Frysinger <vapier@google.com>
This commit is contained in:
Mike Frysinger 2019-10-01 00:18:46 -04:00
parent 0a9265e2d6
commit 72ab852ca5

View File

@ -15,15 +15,19 @@
# limitations under the License. # limitations under the License.
from __future__ import print_function from __future__ import print_function
import sys import sys
from color import Coloring from color import Coloring
from command import PagedCommand from command import PagedCommand
from error import GitError
from git_command import git_require, GitCommand from git_command import git_require, GitCommand
class GrepColoring(Coloring): class GrepColoring(Coloring):
def __init__(self, config): def __init__(self, config):
Coloring.__init__(self, config, 'grep') Coloring.__init__(self, config, 'grep')
self.project = self.printer('project', attr='bold') self.project = self.printer('project', attr='bold')
self.fail = self.printer('fail', fg='red')
class Grep(PagedCommand): class Grep(PagedCommand):
common = True common = True
@ -184,15 +188,25 @@ contain a line that matches both expressions:
cmd_argv.extend(opt.revision) cmd_argv.extend(opt.revision)
cmd_argv.append('--') cmd_argv.append('--')
git_failed = False
bad_rev = False bad_rev = False
have_match = False have_match = False
for project in projects: for project in projects:
try:
p = GitCommand(project, p = GitCommand(project,
cmd_argv, cmd_argv,
bare = False, bare=False,
capture_stdout = True, capture_stdout=True,
capture_stderr = 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: if p.Wait() != 0:
# no results # no results
# #
@ -202,7 +216,7 @@ contain a line that matches both expressions:
else: else:
out.project('--- project %s ---' % project.relpath) out.project('--- project %s ---' % project.relpath)
out.nl() out.nl()
out.write("%s", p.stderr) out.fail('%s', p.stderr.strip())
out.nl() out.nl()
continue continue
have_match = True have_match = True
@ -231,7 +245,9 @@ contain a line that matches both expressions:
for line in r: for line in r:
print(line) print(line)
if have_match: if git_failed:
sys.exit(1)
elif have_match:
sys.exit(0) sys.exit(0)
elif have_rev and bad_rev: elif have_rev and bad_rev:
for r in opt.revision: for r in opt.revision: