Skip to content

Commit df40e86

Browse files
committed
More miscellaneous cleanup
1 parent 489d9f9 commit df40e86

33 files changed

+209
-296
lines changed

.coveragerc

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ omit =
77
setup.py
88
# Don't complain if non-runnable code isn't run
99
*/__main__.py
10-
pre_commit/color_windows.py
1110
pre_commit/resources/*
1211

1312
[report]

pre_commit/clientlib.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -192,19 +192,20 @@ def warn_unknown_keys_repo(
192192
cfgv.Required('id', cfgv.check_one_of(tuple(k for k, _ in _meta))),
193193
# language must be system
194194
cfgv.Optional('language', cfgv.check_one_of({'system'}), 'system'),
195-
*([
195+
*(
196196
# default to the hook definition for the meta hooks
197197
cfgv.ConditionalOptional(key, cfgv.check_any, value, 'id', hook_id)
198198
for hook_id, values in _meta
199199
for key, value in values
200-
] + [
200+
),
201+
*(
201202
# default to the "manifest" parsing
202203
cfgv.OptionalNoDefault(item.key, item.check_fn)
203204
# these will always be defaulted above
204205
if item.key in {'name', 'language', 'entry'} else
205206
item
206207
for item in MANIFEST_HOOK_DICT.items
207-
]),
208+
),
208209
)
209210
CONFIG_HOOK_DICT = cfgv.Map(
210211
'Hook', 'id',
@@ -215,11 +216,11 @@ def warn_unknown_keys_repo(
215216
# are optional.
216217
# No defaults are provided here as the config is merged on top of the
217218
# manifest.
218-
*[
219+
*(
219220
cfgv.OptionalNoDefault(item.key, item.check_fn)
220221
for item in MANIFEST_HOOK_DICT.items
221222
if item.key != 'id'
222-
],
223+
),
223224
)
224225
CONFIG_REPO_DICT = cfgv.Map(
225226
'Repository', 'repo',
@@ -245,7 +246,7 @@ def warn_unknown_keys_repo(
245246
DEFAULT_LANGUAGE_VERSION = cfgv.Map(
246247
'DefaultLanguageVersion', None,
247248
cfgv.NoAdditionalKeys(all_languages),
248-
*[cfgv.Optional(x, cfgv.check_string, C.DEFAULT) for x in all_languages],
249+
*(cfgv.Optional(x, cfgv.check_string, C.DEFAULT) for x in all_languages),
249250
)
250251
CONFIG_SCHEMA = cfgv.Map(
251252
'Config', None,

pre_commit/color.py

Lines changed: 52 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,64 @@
11
import os
22
import sys
33

4-
terminal_supports_color = True
54
if sys.platform == 'win32': # pragma: no cover (windows)
6-
from pre_commit.color_windows import enable_virtual_terminal_processing
5+
def _enable() -> None:
6+
from ctypes import POINTER
7+
from ctypes import windll
8+
from ctypes import WinError
9+
from ctypes import WINFUNCTYPE
10+
from ctypes.wintypes import BOOL
11+
from ctypes.wintypes import DWORD
12+
from ctypes.wintypes import HANDLE
13+
14+
STD_OUTPUT_HANDLE = -11
15+
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4
16+
17+
def bool_errcheck(result, func, args):
18+
if not result:
19+
raise WinError()
20+
return args
21+
22+
GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)(
23+
('GetStdHandle', windll.kernel32), ((1, 'nStdHandle'),),
24+
)
25+
26+
GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))(
27+
('GetConsoleMode', windll.kernel32),
28+
((1, 'hConsoleHandle'), (2, 'lpMode')),
29+
)
30+
GetConsoleMode.errcheck = bool_errcheck
31+
32+
SetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, DWORD)(
33+
('SetConsoleMode', windll.kernel32),
34+
((1, 'hConsoleHandle'), (1, 'dwMode')),
35+
)
36+
SetConsoleMode.errcheck = bool_errcheck
37+
38+
# As of Windows 10, the Windows console supports (some) ANSI escape
39+
# sequences, but it needs to be enabled using `SetConsoleMode` first.
40+
#
41+
# More info on the escape sequences supported:
42+
# https://msdn.microsoft.com/en-us/library/windows/desktop/mt638032(v=vs.85).aspx
43+
stdout = GetStdHandle(STD_OUTPUT_HANDLE)
44+
flags = GetConsoleMode(stdout)
45+
SetConsoleMode(stdout, flags | ENABLE_VIRTUAL_TERMINAL_PROCESSING)
46+
747
try:
8-
enable_virtual_terminal_processing()
48+
_enable()
949
except OSError:
1050
terminal_supports_color = False
51+
else:
52+
terminal_supports_color = True
53+
else: # pragma: windows no cover
54+
terminal_supports_color = True
1155

1256
RED = '\033[41m'
1357
GREEN = '\033[42m'
1458
YELLOW = '\033[43;30m'
1559
TURQUOISE = '\033[46;30m'
1660
SUBTLE = '\033[2m'
17-
NORMAL = '\033[0m'
18-
19-
20-
class InvalidColorSetting(ValueError):
21-
pass
61+
NORMAL = '\033[m'
2262

2363

2464
def format_color(text: str, color: str, use_color_setting: bool) -> str:
@@ -29,10 +69,10 @@ def format_color(text: str, color: str, use_color_setting: bool) -> str:
2969
color - The color start string
3070
use_color_setting - Whether or not to color
3171
"""
32-
if not use_color_setting:
33-
return text
34-
else:
72+
if use_color_setting:
3573
return f'{color}{text}{NORMAL}'
74+
else:
75+
return text
3676

3777

3878
COLOR_CHOICES = ('auto', 'always', 'never')
@@ -45,7 +85,7 @@ def use_color(setting: str) -> bool:
4585
setting - Either `auto`, `always`, or `never`
4686
"""
4787
if setting not in COLOR_CHOICES:
48-
raise InvalidColorSetting(setting)
88+
raise ValueError(setting)
4989

5090
return (
5191
setting == 'always' or (

pre_commit/color_windows.py

Lines changed: 0 additions & 49 deletions
This file was deleted.

pre_commit/commands/init_templatedir.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,5 @@ def init_templatedir(
2929
dest = os.path.realpath(directory)
3030
if configured_path != dest:
3131
logger.warning('`init.templateDir` not set to the target directory')
32-
logger.warning(
33-
f'maybe `git config --global init.templateDir {dest}`?',
34-
)
32+
logger.warning(f'maybe `git config --global init.templateDir {dest}`?')
3533
return 0

pre_commit/commands/migrate_config.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,18 +28,17 @@ def _migrate_map(contents: str) -> str:
2828
# If they are using the "default" flow style of yaml, this operation
2929
# will yield a valid configuration
3030
try:
31-
trial_contents = header + 'repos:\n' + rest
31+
trial_contents = f'{header}repos:\n{rest}'
3232
ordered_load(trial_contents)
3333
contents = trial_contents
3434
except yaml.YAMLError:
35-
contents = header + 'repos:\n' + _indent(rest)
35+
contents = f'{header}repos:\n{_indent(rest)}'
3636

3737
return contents
3838

3939

4040
def _migrate_sha_to_rev(contents: str) -> str:
41-
reg = re.compile(r'(\n\s+)sha:')
42-
return reg.sub(r'\1rev:', contents)
41+
return re.sub(r'(\n\s+)sha:', r'\1rev:', contents)
4342

4443

4544
def migrate_config(config_file: str, quiet: bool = False) -> int:

pre_commit/commands/run.py

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
from pre_commit import git
2121
from pre_commit import output
2222
from pre_commit.clientlib import load_config
23-
from pre_commit.output import get_hook_message
2423
from pre_commit.repository import all_hooks
2524
from pre_commit.repository import Hook
2625
from pre_commit.repository import install_hook_envs
@@ -33,6 +32,25 @@
3332
logger = logging.getLogger('pre_commit')
3433

3534

35+
def _start_msg(*, start: str, cols: int, end_len: int) -> str:
36+
dots = '.' * (cols - len(start) - end_len - 1)
37+
return f'{start}{dots}'
38+
39+
40+
def _full_msg(
41+
*,
42+
start: str,
43+
cols: int,
44+
end_msg: str,
45+
end_color: str,
46+
use_color: bool,
47+
postfix: str = '',
48+
) -> str:
49+
dots = '.' * (cols - len(start) - len(postfix) - len(end_msg) - 1)
50+
end = color.format_color(end_msg, end_color, use_color)
51+
return f'{start}{dots}{postfix}{end}\n'
52+
53+
3654
def filter_by_include_exclude(
3755
names: Collection[str],
3856
include: str,
@@ -106,8 +124,8 @@ def _run_single_hook(
106124

107125
if hook.id in skips or hook.alias in skips:
108126
output.write(
109-
get_hook_message(
110-
hook.name,
127+
_full_msg(
128+
start=hook.name,
111129
end_msg=SKIPPED,
112130
end_color=color.YELLOW,
113131
use_color=use_color,
@@ -120,8 +138,8 @@ def _run_single_hook(
120138
out = b''
121139
elif not filenames and not hook.always_run:
122140
output.write(
123-
get_hook_message(
124-
hook.name,
141+
_full_msg(
142+
start=hook.name,
125143
postfix=NO_FILES,
126144
end_msg=SKIPPED,
127145
end_color=color.TURQUOISE,
@@ -135,7 +153,7 @@ def _run_single_hook(
135153
out = b''
136154
else:
137155
# print hook and dots first in case the hook takes a while to run
138-
output.write(get_hook_message(hook.name, end_len=6, cols=cols))
156+
output.write(_start_msg(start=hook.name, end_len=6, cols=cols))
139157

140158
diff_cmd = ('git', 'diff', '--no-ext-diff')
141159
diff_before = cmd_output_b(*diff_cmd, retcode=None)
@@ -218,9 +236,8 @@ def _run_hooks(
218236
"""Actually run the hooks."""
219237
skips = _get_skips(environ)
220238
cols = _compute_cols(hooks)
221-
filenames = _all_filenames(args)
222239
filenames = filter_by_include_exclude(
223-
filenames, config['files'], config['exclude'],
240+
_all_filenames(args), config['files'], config['exclude'],
224241
)
225242
classifier = Classifier(filenames)
226243
retval = 0

pre_commit/commands/try_repo.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import argparse
22
import logging
33
import os.path
4+
from typing import Optional
45
from typing import Tuple
56

67
from aspy.yaml import ordered_dump
@@ -18,9 +19,9 @@
1819
logger = logging.getLogger(__name__)
1920

2021

21-
def _repo_ref(tmpdir: str, repo: str, ref: str) -> Tuple[str, str]:
22+
def _repo_ref(tmpdir: str, repo: str, ref: Optional[str]) -> Tuple[str, str]:
2223
# if `ref` is explicitly passed, use it
23-
if ref:
24+
if ref is not None:
2425
return repo, ref
2526

2627
ref = git.head_rev(repo)

pre_commit/constants.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,7 @@
88
CONFIG_FILE = '.pre-commit-config.yaml'
99
MANIFEST_FILE = '.pre-commit-hooks.yaml'
1010

11-
YAML_DUMP_KWARGS = {
12-
'default_flow_style': False,
13-
# Use unicode
14-
'encoding': None,
15-
'indent': 4,
16-
}
11+
YAML_DUMP_KWARGS = {'default_flow_style': False, 'indent': 4}
1712

1813
# Bump when installation changes in a backwards / forwards incompatible way
1914
INSTALLED_STATE_VERSION = '1'

pre_commit/error_handler.py

Lines changed: 6 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import contextlib
2+
import functools
23
import os.path
34
import sys
45
import traceback
56
from typing import Generator
6-
from typing import Optional
77

88
import pre_commit.constants as C
99
from pre_commit import output
@@ -15,22 +15,13 @@ class FatalError(RuntimeError):
1515

1616

1717
def _log_and_exit(msg: str, exc: BaseException, formatted: str) -> None:
18-
error_msg = b''.join((
19-
msg.encode(), b': ',
20-
type(exc).__name__.encode(), b': ',
21-
str(exc).encode(),
22-
))
23-
output.write_line_b(error_msg)
24-
store = Store()
25-
log_path = os.path.join(store.directory, 'pre-commit.log')
18+
error_msg = f'{msg}: {type(exc).__name__}: {exc}'
19+
output.write_line(error_msg)
20+
log_path = os.path.join(Store().directory, 'pre-commit.log')
2621
output.write_line(f'Check the log at {log_path}')
2722

2823
with open(log_path, 'wb') as log:
29-
def _log_line(s: Optional[str] = None) -> None:
30-
output.write_line(s, stream=log)
31-
32-
def _log_line_b(s: Optional[bytes] = None) -> None:
33-
output.write_line_b(s, stream=log)
24+
_log_line = functools.partial(output.write_line, stream=log)
3425

3526
_log_line('### version information')
3627
_log_line()
@@ -48,7 +39,7 @@ def _log_line_b(s: Optional[bytes] = None) -> None:
4839
_log_line('### error information')
4940
_log_line()
5041
_log_line('```')
51-
_log_line_b(error_msg)
42+
_log_line(error_msg)
5243
_log_line('```')
5344
_log_line()
5445
_log_line('```')

0 commit comments

Comments
 (0)