Implement 'negate' to simplify pcre

This commit is contained in:
Anthony Sottile 2016-03-21 19:56:41 -07:00
parent b7d395410b
commit a932315a15
5 changed files with 51 additions and 39 deletions

View file

@ -2,7 +2,6 @@ from __future__ import unicode_literals
from sys import platform
from pre_commit.util import shell_escape
from pre_commit.xargs import xargs
@ -19,21 +18,12 @@ def install_environment(
def run_hook(repo_cmd_runner, hook, file_args):
grep_command = '{0} -H -n -P'.format(
'ggrep' if platform == 'darwin' else 'grep',
)
# For PCRE the entry is the regular expression to match
return xargs(
(
'sh', '-c',
# Grep usually returns 0 for matches, and nonzero for non-matches
# so we flip it here.
'! {0} {1} {2} $@'.format(
grep_command, ' '.join(hook['args']),
shell_escape(hook['entry']),
),
'--',
),
file_args,
)
cmd = (
'ggrep' if platform == 'darwin' else 'grep',
'-H', '-n', '-P',
) + tuple(hook['args']) + (hook['entry'],)
# Grep usually returns 0 for matches, and nonzero for non-matches so we
# negate it here.
return xargs(cmd, file_args, negate=True)

View file

@ -67,10 +67,6 @@ def noop_context():
yield
def shell_escape(arg):
return "'" + arg.replace("'", "'\"'\"'".strip()) + "'"
def no_git_env():
# Too many bugs dealing with environment variables and GIT:
# https://github.com/pre-commit/pre-commit/issues/300

View file

@ -42,17 +42,31 @@ def partition(cmd, varargs, _max_length=MAX_LENGTH):
return tuple(ret)
def xargs(cmd, varargs):
"""A simplified implementation of xargs."""
def xargs(cmd, varargs, **kwargs):
"""A simplified implementation of xargs.
negate: Make nonzero successful and zero a failure
"""
negate = kwargs.pop('negate', False)
retcode = 0
stdout = b''
stderr = b''
for run_cmd in partition(cmd, varargs):
for run_cmd in partition(cmd, varargs, **kwargs):
proc_retcode, proc_out, proc_err = cmd_output(
*run_cmd, encoding=None, retcode=None
)
retcode |= proc_retcode
# This is *slightly* too clever so I'll explain it.
# First the xor boolean table:
# T | F |
# +-------+
# T | F | T |
# --+-------+
# F | T | F |
# --+-------+
# When negate is True, it has the effect of flipping the return code
# Otherwise, the retuncode is unchanged
retcode |= bool(proc_retcode) ^ negate
stdout += proc_out
stderr += proc_err