Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 489d9f9

Browse files
authored
Merge pull request #1281 from pre-commit/py2_cleanup_more
Some manual python 2 cleanup
2 parents b2faf33 + 251721b commit 489d9f9

40 files changed

Lines changed: 228 additions & 389 deletions

pre_commit/clientlib.py

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import argparse
22
import functools
33
import logging
4-
import pipes
4+
import shlex
55
import sys
66
from typing import Any
77
from typing import Dict
@@ -25,18 +25,17 @@
2525
def check_type_tag(tag: str) -> None:
2626
if tag not in ALL_TAGS:
2727
raise cfgv.ValidationError(
28-
'Type tag {!r} is not recognized. '
29-
'Try upgrading identify and pre-commit?'.format(tag),
28+
f'Type tag {tag!r} is not recognized. '
29+
f'Try upgrading identify and pre-commit?',
3030
)
3131

3232

3333
def check_min_version(version: str) -> None:
3434
if parse_version(version) > parse_version(C.VERSION):
3535
raise cfgv.ValidationError(
36-
'pre-commit version {} is required but version {} is installed. '
37-
'Perhaps run `pip install --upgrade pre-commit`.'.format(
38-
version, C.VERSION,
39-
),
36+
f'pre-commit version {version} is required but version '
37+
f'{C.VERSION} is installed. '
38+
f'Perhaps run `pip install --upgrade pre-commit`.',
4039
)
4140

4241

@@ -142,19 +141,15 @@ def _entry(modname: str) -> str:
142141
runner, so to prevent issues with spaces and backslashes (on Windows)
143142
it must be quoted here.
144143
"""
145-
return '{} -m pre_commit.meta_hooks.{}'.format(
146-
pipes.quote(sys.executable), modname,
147-
)
144+
return f'{shlex.quote(sys.executable)} -m pre_commit.meta_hooks.{modname}'
148145

149146

150147
def warn_unknown_keys_root(
151148
extra: Sequence[str],
152149
orig_keys: Sequence[str],
153150
dct: Dict[str, str],
154151
) -> None:
155-
logger.warning(
156-
'Unexpected key(s) present at root: {}'.format(', '.join(extra)),
157-
)
152+
logger.warning(f'Unexpected key(s) present at root: {", ".join(extra)}')
158153

159154

160155
def warn_unknown_keys_repo(
@@ -163,9 +158,7 @@ def warn_unknown_keys_repo(
163158
dct: Dict[str, str],
164159
) -> None:
165160
logger.warning(
166-
'Unexpected key(s) present on {}: {}'.format(
167-
dct['repo'], ', '.join(extra),
168-
),
161+
f'Unexpected key(s) present on {dct["repo"]}: {", ".join(extra)}',
169162
)
170163

171164

pre_commit/commands/autoupdate.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -80,13 +80,12 @@ def _check_hooks_still_exist_at_rev(
8080
hooks_missing = hooks - {hook['id'] for hook in manifest}
8181
if hooks_missing:
8282
raise RepositoryCannotBeUpdatedError(
83-
'Cannot update because the tip of master is missing these hooks:\n'
84-
'{}'.format(', '.join(sorted(hooks_missing))),
83+
f'Cannot update because the tip of HEAD is missing these hooks:\n'
84+
f'{", ".join(sorted(hooks_missing))}',
8585
)
8686

8787

8888
REV_LINE_RE = re.compile(r'^(\s+)rev:(\s*)([^\s#]+)(.*)(\r?\n)$', re.DOTALL)
89-
REV_LINE_FMT = '{}rev:{}{}{}{}'
9089

9190

9291
def _original_lines(
@@ -122,13 +121,11 @@ def _write_new_config(path: str, rev_infos: List[Optional[RevInfo]]) -> None:
122121
new_rev = new_rev_s.split(':', 1)[1].strip()
123122
if rev_info.frozen is not None:
124123
comment = f' # frozen: {rev_info.frozen}'
125-
elif match.group(4).strip().startswith('# frozen:'):
124+
elif match[4].strip().startswith('# frozen:'):
126125
comment = ''
127126
else:
128-
comment = match.group(4)
129-
lines[idx] = REV_LINE_FMT.format(
130-
match.group(1), match.group(2), new_rev, comment, match.group(5),
131-
)
127+
comment = match[4]
128+
lines[idx] = f'{match[1]}rev:{match[2]}{new_rev}{comment}{match[5]}'
132129

133130
with open(path, 'w') as f:
134131
f.write(''.join(lines))

pre_commit/commands/install_uninstall.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
from pre_commit.repository import install_hook_envs
1515
from pre_commit.store import Store
1616
from pre_commit.util import make_executable
17-
from pre_commit.util import mkdirp
1817
from pre_commit.util import resource_text
1918

2019

@@ -78,7 +77,7 @@ def _install_hook_script(
7877
) -> None:
7978
hook_path, legacy_path = _hook_paths(hook_type, git_dir=git_dir)
8079

81-
mkdirp(os.path.dirname(hook_path))
80+
os.makedirs(os.path.dirname(hook_path), exist_ok=True)
8281

8382
# If we have an existing hook, move it to pre-commit.legacy
8483
if os.path.lexists(hook_path) and not is_our_script(hook_path):
@@ -89,8 +88,8 @@ def _install_hook_script(
8988
os.remove(legacy_path)
9089
elif os.path.exists(legacy_path):
9190
output.write_line(
92-
'Running in migration mode with existing hooks at {}\n'
93-
'Use -f to use only pre-commit.'.format(legacy_path),
91+
f'Running in migration mode with existing hooks at {legacy_path}\n'
92+
f'Use -f to use only pre-commit.',
9493
)
9594

9695
params = {
@@ -110,7 +109,7 @@ def _install_hook_script(
110109
hook_file.write(before + TEMPLATE_START)
111110
for line in to_template.splitlines():
112111
var = line.split()[0]
113-
hook_file.write('{} = {!r}\n'.format(var, params[var]))
112+
hook_file.write(f'{var} = {params[var]!r}\n')
114113
hook_file.write(TEMPLATE_END + after)
115114
make_executable(hook_path)
116115

pre_commit/commands/run.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import argparse
2+
import contextlib
23
import functools
34
import logging
45
import os
@@ -27,7 +28,6 @@
2728
from pre_commit.store import Store
2829
from pre_commit.util import cmd_output_b
2930
from pre_commit.util import EnvironT
30-
from pre_commit.util import noop_context
3131

3232

3333
logger = logging.getLogger('pre_commit')
@@ -173,7 +173,7 @@ def _run_single_hook(
173173

174174
if out.strip():
175175
output.write_line()
176-
output.write_line(out.strip(), logfile_name=hook.log_file)
176+
output.write_line_b(out.strip(), logfile_name=hook.log_file)
177177
output.write_line()
178178

179179
return files_modified or bool(retcode)
@@ -243,9 +243,10 @@ def _run_hooks(
243243
output.write_line('All changes made by hooks:')
244244
# args.color is a boolean.
245245
# See user_color function in color.py
246+
git_color_opt = 'always' if args.color else 'never'
246247
subprocess.call((
247248
'git', '--no-pager', 'diff', '--no-ext-diff',
248-
'--color={}'.format({True: 'always', False: 'never'}[args.color]),
249+
f'--color={git_color_opt}',
249250
))
250251

251252
return retval
@@ -271,7 +272,7 @@ def run(
271272
args: argparse.Namespace,
272273
environ: EnvironT = os.environ,
273274
) -> int:
274-
no_stash = args.all_files or bool(args.files)
275+
stash = not args.all_files and not args.files
275276

276277
# Check if we have unresolved merge conflict files and fail fast.
277278
if _has_unmerged_paths():
@@ -280,10 +281,10 @@ def run(
280281
if bool(args.source) != bool(args.origin):
281282
logger.error('Specify both --origin and --source.')
282283
return 1
283-
if _has_unstaged_config(config_file) and not no_stash:
284+
if stash and _has_unstaged_config(config_file):
284285
logger.error(
285-
'Your pre-commit configuration is unstaged.\n'
286-
'`git add {}` to fix this.'.format(config_file),
286+
f'Your pre-commit configuration is unstaged.\n'
287+
f'`git add {config_file}` to fix this.',
287288
)
288289
return 1
289290

@@ -292,12 +293,10 @@ def run(
292293
environ['PRE_COMMIT_ORIGIN'] = args.origin
293294
environ['PRE_COMMIT_SOURCE'] = args.source
294295

295-
if no_stash:
296-
ctx = noop_context()
297-
else:
298-
ctx = staged_files_only(store.directory)
296+
with contextlib.ExitStack() as exit_stack:
297+
if stash:
298+
exit_stack.enter_context(staged_files_only(store.directory))
299299

300-
with ctx:
301300
config = load_config(config_file)
302301
hooks = [
303302
hook
@@ -308,12 +307,13 @@ def run(
308307

309308
if args.hook and not hooks:
310309
output.write_line(
311-
'No hook with id `{}` in stage `{}`'.format(
312-
args.hook, args.hook_stage,
313-
),
310+
f'No hook with id `{args.hook}` in stage `{args.hook_stage}`',
314311
)
315312
return 1
316313

317314
install_hook_envs(hooks, store)
318315

319316
return _run_hooks(config, hooks, args, environ)
317+
318+
# https://github.com/python/mypy/issues/7726
319+
raise AssertionError('unreachable')

pre_commit/commands/try_repo.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import argparse
2-
import collections
32
import logging
43
import os.path
54
from typing import Tuple
@@ -62,8 +61,7 @@ def try_repo(args: argparse.Namespace) -> int:
6261
manifest = sorted(manifest, key=lambda hook: hook['id'])
6362
hooks = [{'id': hook['id']} for hook in manifest]
6463

65-
items = (('repo', repo), ('rev', ref), ('hooks', hooks))
66-
config = {'repos': [collections.OrderedDict(items)]}
64+
config = {'repos': [{'repo': repo, 'rev': ref, 'hooks': hooks}]}
6765
config_s = ordered_dump(config, **C.YAML_DUMP_KWARGS)
6866

6967
config_filename = os.path.join(tempdir, C.CONFIG_FILE)

pre_commit/error_handler.py

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,9 @@
33
import sys
44
import traceback
55
from typing import Generator
6-
from typing import Union
6+
from typing import Optional
77

88
import pre_commit.constants as C
9-
from pre_commit import five
109
from pre_commit import output
1110
from pre_commit.store import Store
1211

@@ -15,25 +14,24 @@ class FatalError(RuntimeError):
1514
pass
1615

1716

18-
def _to_bytes(exc: BaseException) -> bytes:
19-
return str(exc).encode('UTF-8')
20-
21-
2217
def _log_and_exit(msg: str, exc: BaseException, formatted: str) -> None:
2318
error_msg = b''.join((
24-
five.to_bytes(msg), b': ',
25-
five.to_bytes(type(exc).__name__), b': ',
26-
_to_bytes(exc),
19+
msg.encode(), b': ',
20+
type(exc).__name__.encode(), b': ',
21+
str(exc).encode(),
2722
))
28-
output.write_line(error_msg)
23+
output.write_line_b(error_msg)
2924
store = Store()
3025
log_path = os.path.join(store.directory, 'pre-commit.log')
3126
output.write_line(f'Check the log at {log_path}')
3227

3328
with open(log_path, 'wb') as log:
34-
def _log_line(s: Union[None, str, bytes] = None) -> None:
29+
def _log_line(s: Optional[str] = None) -> None:
3530
output.write_line(s, stream=log)
3631

32+
def _log_line_b(s: Optional[bytes] = None) -> None:
33+
output.write_line_b(s, stream=log)
34+
3735
_log_line('### version information')
3836
_log_line()
3937
_log_line('```')
@@ -50,7 +48,7 @@ def _log_line(s: Union[None, str, bytes] = None) -> None:
5048
_log_line('### error information')
5149
_log_line()
5250
_log_line('```')
53-
_log_line(error_msg)
51+
_log_line_b(error_msg)
5452
_log_line('```')
5553
_log_line()
5654
_log_line('```')

pre_commit/five.py

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

pre_commit/git.py

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ def is_in_merge_conflict() -> bool:
6969
def parse_merge_msg_for_conflicts(merge_msg: bytes) -> List[str]:
7070
# Conflicted files start with tabs
7171
return [
72-
line.lstrip(b'#').strip().decode('UTF-8')
72+
line.lstrip(b'#').strip().decode()
7373
for line in merge_msg.splitlines()
7474
# '#\t' for git 2.4.1
7575
if line.startswith((b'\t', b'#\t'))
@@ -183,13 +183,11 @@ def check_for_cygwin_mismatch() -> None:
183183
if is_cygwin_python ^ is_cygwin_git:
184184
exe_type = {True: '(cygwin)', False: '(windows)'}
185185
logger.warn(
186-
'pre-commit has detected a mix of cygwin python / git\n'
187-
'This combination is not supported, it is likely you will '
188-
'receive an error later in the program.\n'
189-
'Make sure to use cygwin git+python while using cygwin\n'
190-
'These can be installed through the cygwin installer.\n'
191-
' - python {}\n'
192-
' - git {}\n'.format(
193-
exe_type[is_cygwin_python], exe_type[is_cygwin_git],
194-
),
186+
f'pre-commit has detected a mix of cygwin python / git\n'
187+
f'This combination is not supported, it is likely you will '
188+
f'receive an error later in the program.\n'
189+
f'Make sure to use cygwin git+python while using cygwin\n'
190+
f'These can be installed through the cygwin installer.\n'
191+
f' - python {exe_type[is_cygwin_python]}\n'
192+
f' - git {exe_type[is_cygwin_git]}\n',
195193
)

pre_commit/languages/docker.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ def install_environment(
8181

8282
def get_docker_user() -> str: # pragma: windows no cover
8383
try:
84-
return '{}:{}'.format(os.getuid(), os.getgid())
84+
return f'{os.getuid()}:{os.getgid()}'
8585
except AttributeError:
8686
return '1000:1000'
8787

@@ -94,7 +94,7 @@ def docker_cmd() -> Tuple[str, ...]: # pragma: windows no cover
9494
# https://docs.docker.com/engine/reference/commandline/run/#mount-volumes-from-container-volumes-from
9595
# The `Z` option tells Docker to label the content with a private
9696
# unshared label. Only the current container can use a private volume.
97-
'-v', '{}:/src:rw,Z'.format(os.getcwd()),
97+
'-v', f'{os.getcwd()}:/src:rw,Z',
9898
'--workdir', '/src',
9999
)
100100

pre_commit/languages/fail.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,6 @@ def run_hook(
1818
file_args: Sequence[str],
1919
color: bool,
2020
) -> Tuple[int, bytes]:
21-
out = hook.entry.encode('UTF-8') + b'\n\n'
22-
out += b'\n'.join(f.encode('UTF-8') for f in file_args) + b'\n'
21+
out = hook.entry.encode() + b'\n\n'
22+
out += b'\n'.join(f.encode() for f in file_args) + b'\n'
2323
return 1, out

0 commit comments

Comments
 (0)