Skip to content

Commit 9000e9d

Browse files
committed
Some manual .format() -> f-strings
1 parent aefbe71 commit 9000e9d

27 files changed

+133
-173
lines changed

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: 3 additions & 6 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(
@@ -126,9 +125,7 @@ def _write_new_config(path: str, rev_infos: List[Optional[RevInfo]]) -> None:
126125
comment = ''
127126
else:
128127
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-
)
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: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -89,8 +89,8 @@ def _install_hook_script(
8989
os.remove(legacy_path)
9090
elif os.path.exists(legacy_path):
9191
output.write_line(
92-
'Running in migration mode with existing hooks at {}\n'
93-
'Use -f to use only pre-commit.'.format(legacy_path),
92+
f'Running in migration mode with existing hooks at {legacy_path}\n'
93+
f'Use -f to use only pre-commit.',
9494
)
9595

9696
params = {
@@ -110,7 +110,7 @@ def _install_hook_script(
110110
hook_file.write(before + TEMPLATE_START)
111111
for line in to_template.splitlines():
112112
var = line.split()[0]
113-
hook_file.write('{} = {!r}\n'.format(var, params[var]))
113+
hook_file.write(f'{var} = {params[var]!r}\n')
114114
hook_file.write(TEMPLATE_END + after)
115115
make_executable(hook_path)
116116

pre_commit/commands/run.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -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
@@ -282,8 +283,8 @@ def run(
282283
return 1
283284
if _has_unstaged_config(config_file) and not no_stash:
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

@@ -308,9 +309,7 @@ def run(
308309

309310
if args.hook and not hooks:
310311
output.write_line(
311-
'No hook with id `{}` in stage `{}`'.format(
312-
args.hook, args.hook_stage,
313-
),
312+
f'No hook with id `{args.hook}` in stage `{args.hook_stage}`',
314313
)
315314
return 1
316315

pre_commit/git.py

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -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/helpers.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,8 @@ def assert_no_additional_deps(
5151
) -> None:
5252
if additional_deps:
5353
raise AssertionError(
54-
'For now, pre-commit does not support '
55-
'additional_dependencies for {}'.format(lang),
54+
f'For now, pre-commit does not support '
55+
f'additional_dependencies for {lang}',
5656
)
5757

5858

pre_commit/languages/node.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def _envdir(prefix: Prefix, version: str) -> str:
3333
def get_env_patch(venv: str) -> PatchesT: # pragma: windows no cover
3434
if sys.platform == 'cygwin': # pragma: no cover
3535
_, win_venv, _ = cmd_output('cygpath', '-w', venv)
36-
install_prefix = r'{}\bin'.format(win_venv.strip())
36+
install_prefix = fr'{win_venv.strip()}\bin'
3737
lib_dir = 'lib'
3838
elif sys.platform == 'win32': # pragma: no cover
3939
install_prefix = bin_dir(venv)

pre_commit/languages/pygrep.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ def _process_filename_at_once(pattern: Pattern[bytes], filename: str) -> int:
3939
if match:
4040
retv = 1
4141
line_no = contents[:match.start()].count(b'\n')
42-
output.write('{}:{}:'.format(filename, line_no + 1))
42+
output.write(f'{filename}:{line_no + 1}:')
4343

4444
matched_lines = match.group().split(b'\n')
4545
matched_lines[0] = contents.split(b'\n')[line_no]

pre_commit/languages/python.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,10 @@ def _find_by_py_launcher(
4747
version: str,
4848
) -> Optional[str]: # pragma: no cover (windows only)
4949
if version.startswith('python'):
50+
num = version[len('python'):]
5051
try:
5152
return cmd_output(
52-
'py', '-{}'.format(version[len('python'):]),
53-
'-c', 'import sys; print(sys.executable)',
53+
'py', f'-{num}', '-c', 'import sys; print(sys.executable)',
5454
)[1].strip()
5555
except CalledProcessError:
5656
pass
@@ -88,15 +88,16 @@ def get_default_version() -> str: # pragma: no cover (platform dependent)
8888
return exe
8989

9090
# Next try the `pythonX.X` executable
91-
exe = 'python{}.{}'.format(*sys.version_info)
91+
exe = f'python{sys.version_info[0]}.{sys.version_info[1]}'
9292
if find_executable(exe):
9393
return exe
9494

9595
if _find_by_py_launcher(exe):
9696
return exe
9797

9898
# Give a best-effort try for windows
99-
if os.path.exists(r'C:\{}\python.exe'.format(exe.replace('.', ''))):
99+
default_folder_name = exe.replace('.', '')
100+
if os.path.exists(fr'C:\{default_folder_name}\python.exe'):
100101
return exe
101102

102103
# We tried!
@@ -135,7 +136,8 @@ def norm_version(version: str) -> str:
135136
# If it is in the form pythonx.x search in the default
136137
# place on windows
137138
if version.startswith('python'):
138-
return r'C:\{}\python.exe'.format(version.replace('.', ''))
139+
default_folder_name = version.replace('.', '')
140+
return fr'C:\{default_folder_name}\python.exe'
139141

140142
# Otherwise assume it is a path
141143
return os.path.expanduser(version)

0 commit comments

Comments
 (0)