Merge pull request #632 from pre-commit/small_cleanups

Small cleanups
This commit is contained in:
Anthony Sottile 2017-09-30 17:20:07 -07:00 committed by GitHub
commit a543190f7b
17 changed files with 40 additions and 58 deletions

View file

@ -10,7 +10,7 @@ from identify.identify import ALL_TAGS
import pre_commit.constants as C import pre_commit.constants as C
from pre_commit import schema from pre_commit import schema
from pre_commit.errors import FatalError from pre_commit.error_handler import FatalError
from pre_commit.languages.all import all_languages from pre_commit.languages.all import all_languages
@ -51,8 +51,7 @@ MANIFEST_HOOK_DICT = schema.Map(
'', '',
), ),
schema.Optional( schema.Optional(
'exclude', 'exclude', schema.check_and(schema.check_string, schema.check_regex),
schema.check_and(schema.check_string, schema.check_regex),
'^$', '^$',
), ),
schema.Optional('types', schema.check_array(check_type_tag), ['file']), schema.Optional('types', schema.check_array(check_type_tag), ['file']),

View file

@ -47,7 +47,4 @@ def use_color(setting):
if setting not in COLOR_CHOICES: if setting not in COLOR_CHOICES:
raise InvalidColorSetting(setting) raise InvalidColorSetting(setting)
return ( return setting == 'always' or (setting == 'auto' and sys.stdout.isatty())
setting == 'always' or
(setting == 'auto' and sys.stdout.isatty())
)

View file

@ -1,3 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals from __future__ import unicode_literals
from ctypes import POINTER from ctypes import POINTER
@ -19,8 +20,7 @@ def bool_errcheck(result, func, args):
GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)( GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)(
("GetStdHandle", windll.kernel32), ("GetStdHandle", windll.kernel32), ((1, "nStdHandle"),),
((1, "nStdHandle"), ),
) )
GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))( GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))(
@ -42,7 +42,6 @@ def enable_virtual_terminal_processing():
More info on the escape sequences supported: More info on the escape sequences supported:
https://msdn.microsoft.com/en-us/library/windows/desktop/mt638032(v=vs.85).aspx https://msdn.microsoft.com/en-us/library/windows/desktop/mt638032(v=vs.85).aspx
""" """
stdout = GetStdHandle(STD_OUTPUT_HANDLE) stdout = GetStdHandle(STD_OUTPUT_HANDLE)
flags = GetConsoleMode(stdout) flags = GetConsoleMode(stdout)

View file

@ -32,8 +32,7 @@ def _get_skips(environ):
def _hook_msg_start(hook, verbose): def _hook_msg_start(hook, verbose):
return '{}{}'.format( return '{}{}'.format(
'[{}] '.format(hook['id']) if verbose else '', '[{}] '.format(hook['id']) if verbose else '', hook['name'],
hook['name'],
) )
@ -99,8 +98,7 @@ def _run_single_hook(filenames, hook, repo, args, skips, cols):
'git', 'diff', '--no-ext-diff', retcode=None, encoding=None, 'git', 'diff', '--no-ext-diff', retcode=None, encoding=None,
) )
retcode, stdout, stderr = repo.run_hook( retcode, stdout, stderr = repo.run_hook(
hook, hook, tuple(filenames) if hook['pass_filenames'] else (),
tuple(filenames) if hook['pass_filenames'] else (),
) )
diff_after = cmd_output( diff_after = cmd_output(
'git', 'diff', '--no-ext-diff', retcode=None, encoding=None, 'git', 'diff', '--no-ext-diff', retcode=None, encoding=None,

View file

@ -1,3 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals from __future__ import unicode_literals
import pkg_resources import pkg_resources

View file

@ -10,14 +10,12 @@ UNSET = collections.namedtuple('UNSET', ())()
Var = collections.namedtuple('Var', ('name', 'default')) Var = collections.namedtuple('Var', ('name', 'default'))
setattr(Var.__new__, '__defaults__', ('',)) Var.__new__.__defaults__ = ('',)
def format_env(parts, env): def format_env(parts, env):
return ''.join( return ''.join(
env.get(part.name, part.default) env.get(part.name, part.default) if isinstance(part, Var) else part
if isinstance(part, Var)
else part
for part in parts for part in parts
) )

View file

@ -10,10 +10,13 @@ import six
from pre_commit import five from pre_commit import five
from pre_commit import output from pre_commit import output
from pre_commit.errors import FatalError
from pre_commit.store import Store from pre_commit.store import Store
class FatalError(RuntimeError):
pass
def _to_bytes(exc): def _to_bytes(exc):
try: try:
return bytes(exc) return bytes(exc)
@ -46,7 +49,5 @@ def error_handler():
_log_and_exit('An error has occurred', e, traceback.format_exc()) _log_and_exit('An error has occurred', e, traceback.format_exc())
except Exception as e: except Exception as e:
_log_and_exit( _log_and_exit(
'An unexpected error has occurred', 'An unexpected error has occurred', e, traceback.format_exc(),
e,
traceback.format_exc(),
) )

View file

@ -1,6 +0,0 @@
from __future__ import absolute_import
from __future__ import unicode_literals
class FatalError(RuntimeError):
pass

View file

@ -1,3 +1,6 @@
from __future__ import absolute_import
from __future__ import unicode_literals
import contextlib import contextlib
import errno import errno

View file

@ -1,3 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals from __future__ import unicode_literals
import six import six

View file

@ -4,7 +4,7 @@ import logging
import os.path import os.path
import sys import sys
from pre_commit.errors import FatalError from pre_commit.error_handler import FatalError
from pre_commit.util import CalledProcessError from pre_commit.util import CalledProcessError
from pre_commit.util import cmd_output from pre_commit.util import cmd_output
@ -114,7 +114,6 @@ def check_for_cygwin_mismatch():
'These can be installed through the cygwin installer.\n' 'These can be installed through the cygwin installer.\n'
' - python {}\n' ' - python {}\n'
' - git {}\n'.format( ' - git {}\n'.format(
exe_type[is_cygwin_python], exe_type[is_cygwin_python], exe_type[is_cygwin_git],
exe_type[is_cygwin_git],
), ),
) )

View file

@ -23,12 +23,12 @@ class LoggingHandler(logging.Handler):
def emit(self, record): def emit(self, record):
output.write_line( output.write_line(
'{}{}'.format( '{} {}'.format(
color.format_color( color.format_color(
'[{}]'.format(record.levelname), '[{}]'.format(record.levelname),
LOG_LEVEL_COLORS[record.levelname], LOG_LEVEL_COLORS[record.levelname],
self.use_color, self.use_color,
) + ' ', ),
record.getMessage(), record.getMessage(),
), ),
) )

View file

@ -2,12 +2,14 @@ from __future__ import absolute_import
from __future__ import print_function from __future__ import print_function
from __future__ import unicode_literals from __future__ import unicode_literals
import argparse
import os.path import os.path
import tarfile import tarfile
from pre_commit import output from pre_commit import output
from pre_commit.util import cmd_output from pre_commit.util import cmd_output
from pre_commit.util import cwd from pre_commit.util import cwd
from pre_commit.util import resource_filename
from pre_commit.util import rmtree from pre_commit.util import rmtree
from pre_commit.util import tmpdir from pre_commit.util import tmpdir
@ -27,11 +29,6 @@ REPOS = (
) )
RESOURCES_DIR = os.path.abspath(
os.path.join(os.path.dirname(__file__), 'resources'),
)
def make_archive(name, repo, ref, destdir): def make_archive(name, repo, ref, destdir):
"""Makes an archive of a repository in the given destdir. """Makes an archive of a repository in the given destdir.
@ -59,12 +56,15 @@ def make_archive(name, repo, ref, destdir):
return output_path return output_path
def main(): def main(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument('--dest', default=resource_filename())
args = parser.parse_args(argv)
for archive_name, repo, ref in REPOS: for archive_name, repo, ref in REPOS:
output.write_line('Making {}.tar.gz for {}@{}'.format( output.write_line('Making {}.tar.gz for {}@{}'.format(
archive_name, repo, ref, archive_name, repo, ref,
)) ))
make_archive(archive_name, repo, ref, RESOURCES_DIR) make_archive(archive_name, repo, ref, args.dest)
if __name__ == '__main__': if __name__ == '__main__':

View file

@ -93,18 +93,16 @@ def tmpdir():
rmtree(tempdir) rmtree(tempdir)
def resource_filename(filename): def resource_filename(*segments):
return pkg_resources.resource_filename( return pkg_resources.resource_filename(
'pre_commit', 'pre_commit', os.path.join('resources', *segments),
os.path.join('resources', filename),
) )
def make_executable(filename): def make_executable(filename):
original_mode = os.stat(filename).st_mode original_mode = os.stat(filename).st_mode
os.chmod( os.chmod(
filename, filename, original_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH,
original_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH,
) )

View file

@ -11,7 +11,6 @@ import mock
import pytest import pytest
from pre_commit import error_handler from pre_commit import error_handler
from pre_commit.errors import FatalError
from testing.util import cmd_output_mocked_pre_commit_home from testing.util import cmd_output_mocked_pre_commit_home
@ -28,7 +27,7 @@ def test_error_handler_no_exception(mocked_log_and_exit):
def test_error_handler_fatal_error(mocked_log_and_exit): def test_error_handler_fatal_error(mocked_log_and_exit):
exc = FatalError('just a test') exc = error_handler.FatalError('just a test')
with error_handler.error_handler(): with error_handler.error_handler():
raise exc raise exc
@ -46,7 +45,7 @@ def test_error_handler_fatal_error(mocked_log_and_exit):
r' File ".+tests.error_handler_test.py", line \d+, ' r' File ".+tests.error_handler_test.py", line \d+, '
r'in test_error_handler_fatal_error\n' r'in test_error_handler_fatal_error\n'
r' raise exc\n' r' raise exc\n'
r'(pre_commit\.errors\.)?FatalError: just a test\n', r'(pre_commit\.error_handler\.)?FatalError: just a test\n',
mocked_log_and_exit.call_args[0][2], mocked_log_and_exit.call_args[0][2],
) )
@ -77,7 +76,7 @@ def test_error_handler_uncaught_error(mocked_log_and_exit):
def test_log_and_exit(cap_out, mock_out_store_directory): def test_log_and_exit(cap_out, mock_out_store_directory):
with pytest.raises(SystemExit): with pytest.raises(SystemExit):
error_handler._log_and_exit( error_handler._log_and_exit(
'msg', FatalError('hai'), "I'm a stacktrace", 'msg', error_handler.FatalError('hai'), "I'm a stacktrace",
) )
printed = cap_out.get() printed = cap_out.get()

View file

@ -7,7 +7,7 @@ import os.path
import pytest import pytest
from pre_commit import git from pre_commit import git
from pre_commit.errors import FatalError from pre_commit.error_handler import FatalError
from pre_commit.util import cmd_output from pre_commit.util import cmd_output
from pre_commit.util import cwd from pre_commit.util import cwd
from testing.fixtures import git_dir from testing.fixtures import git_dir

View file

@ -4,7 +4,6 @@ from __future__ import unicode_literals
import os.path import os.path
import tarfile import tarfile
import mock
import pytest import pytest
from pre_commit import make_archives from pre_commit import make_archives
@ -53,12 +52,8 @@ def test_make_archive(tempdir_factory):
@skipif_slowtests_false @skipif_slowtests_false
@pytest.mark.integration @pytest.mark.integration
def test_main(tempdir_factory): def test_main(tmpdir):
path = tempdir_factory.get() make_archives.main(('--dest', tmpdir.strpath))
# Don't actually want to make these in the current repo
with mock.patch.object(make_archives, 'RESOURCES_DIR', path):
make_archives.main()
for archive, _, _ in make_archives.REPOS: for archive, _, _ in make_archives.REPOS:
assert os.path.exists(os.path.join(path, archive + '.tar.gz')) assert tmpdir.join('{}.tar.gz'.format(archive)).exists()