Refactor: More f-string

This commit is contained in:
pagedown 2022-01-28 19:34:13 +08:00
parent e0c4a90aa3
commit dc61adf9d8
No known key found for this signature in database
GPG Key ID: E921CF18AC8FF6EB
14 changed files with 35 additions and 54 deletions

View File

@ -371,7 +371,7 @@ def expand_opt_references(conf_name: str, text: str) -> str:
ref = m.group(1)
if '<' not in ref and '.' not in ref:
full_ref = conf_name + ref
return ':opt:`{} <{}>`'.format(ref, full_ref)
return f':opt:`{ref} <{full_ref}>`'
return str(m.group())
return re.sub(r':opt:`(.+?)`', expand, text)
@ -399,7 +399,7 @@ def parse_opt_node(env: Any, sig: str, signode: Any) -> str:
opt_aliases[optname] = firstname
count += 1
if not firstname:
raise ValueError('{} is not a valid opt'.format(sig))
raise ValueError(f'{sig} is not a valid opt')
return firstname
@ -426,7 +426,7 @@ def process_shortcut_link(env: Any, refnode: Any, has_explicit_title: bool, titl
try:
target, stitle = shortcut_slugs[full_name]
except KeyError:
logger.warning('Unknown shortcut: {}'.format(target), location=refnode)
logger.warning(f'Unknown shortcut: {target}', location=refnode)
else:
if not has_explicit_title:
title = stitle

View File

@ -108,7 +108,7 @@ features of the graphics protocol:
def serialize_gr_command(**cmd):
payload = cmd.pop('payload', None)
cmd = ','.join('{}={}'.format(k, v) for k, v in cmd.items())
cmd = ','.join(f'{k}={v}' for k, v in cmd.items())
ans = []
w = ans.append
w(b'\033_G'), w(cmd.encode('ascii'))

View File

@ -67,7 +67,7 @@ class Env:
def wayland_protocol_file_name(base: str, ext: str = 'c') -> str:
base = os.path.basename(base).rpartition('.')[0]
return 'wayland-{}-client-protocol.{}'.format(base, ext)
return f'wayland-{base}-client-protocol.{ext}'
def init_env(
@ -150,14 +150,14 @@ def build_wayland_protocols(
for protocol in env.wayland_protocols:
src = os.path.join(env.wayland_packagedir, protocol)
if not os.path.exists(src):
raise SystemExit('The wayland-protocols package on your system is missing the {} protocol definition file'.format(protocol))
raise SystemExit(f'The wayland-protocols package on your system is missing the {protocol} protocol definition file')
for ext in 'hc':
dest = wayland_protocol_file_name(src, ext)
dest = os.path.join(dest_dir, dest)
if newer(dest, src):
q = 'client-header' if ext == 'h' else env.wayland_scanner_code
items.append(Command(
'Generating {} ...'.format(emphasis(os.path.basename(dest))),
f'Generating {emphasis(os.path.basename(dest))} ...',
[env.wayland_scanner, q, src, dest], lambda: True))
if items:
parallel_run(items)
@ -174,7 +174,7 @@ class Arg:
self.type = self.type + '*'
def __repr__(self) -> str:
return 'Arg({}, {})'.format(self.type, self.name)
return f'Arg({self.type}, {self.name})'
class Function:

View File

@ -32,8 +32,7 @@ class Segment:
self.end_code: Optional[str] = None
def __repr__(self) -> str:
return 'Segment(start={!r}, start_code={!r}, end={!r}, end_code={!r})'.format(
self.start, self.start_code, self.end, self.end_code)
return f'Segment(start={self.start!r}, start_code={self.start_code!r}, end={self.end!r}, end_code={self.end_code!r})'
class Collection:

View File

@ -323,8 +323,7 @@ def parse_kittens_func_args(action: str, args_funcs: Dict[str, KeyFunc[Tuple[str
parser = args_funcs[func]
except KeyError as e:
raise KeyError(
'Unknown action: {}. Check if map action: '
'{} is valid'.format(func, action)
f'Unknown action: {func}. Check if map action: {action} is valid'
) from e
try:

View File

@ -49,8 +49,7 @@ def atomic_save(data: bytes, path: str) -> None:
except FileNotFoundError:
pass
except Exception as err:
log_error('Failed to delete temp file {} for atomic save with error: {}'.format(
p, err))
log_error(f'Failed to delete temp file {p} for atomic save with error: {err}')
@contextmanager
@ -63,8 +62,7 @@ def cached_values_for(name: str) -> Generator[Dict[str, Any], None, None]:
except FileNotFoundError:
pass
except Exception as err:
log_error('Failed to load cached in {} values with error: {}'.format(
name, err))
log_error(f'Failed to load cached in {name} values with error: {err}')
yield cached_values
@ -72,8 +70,7 @@ def cached_values_for(name: str) -> Generator[Dict[str, Any], None, None]:
data = json.dumps(cached_values).encode('utf-8')
atomic_save(data, cached_path)
except Exception as err:
log_error('Failed to save cached values with error: {}'.format(
err))
log_error(f'Failed to save cached values with error: {err}')
def commented_out_default_config() -> str:

View File

@ -323,8 +323,7 @@ def render_special(
try:
f(ans, cell_width, *a)
except Exception as e:
log_error('Failed to render {} at cell_width={} and cell_height={} with error: {}'.format(
f.__name__, cell_width, cell_height, e))
log_error(f'Failed to render {f.__name__} at cell_width={cell_width} and cell_height={cell_height} with error: {e}')
if underline:
t = underline_thickness

View File

@ -1104,8 +1104,7 @@ def deprecated_send_text(key: str, val: str, ans: Dict[str, Any]) -> None:
parts = val.split(' ')
def abort(msg: str) -> None:
log_error('Send text: {} is invalid ({}), ignoring'.format(
val, msg))
log_error(f'Send text: {val} is invalid ({msg}), ignoring')
if len(parts) < 3:
return abort('Incomplete')

View File

@ -43,7 +43,7 @@ cause ligatures to be changed in all windows.
' never, always or cursor')
strategy = args[0]
if strategy not in ('never', 'always', 'cursor'):
self.fatal('{} is not a valid disable_ligatures strategy'.format('strategy'))
self.fatal(f'{strategy} is not a valid disable_ligatures strategy')
return {
'strategy': strategy, 'match_window': opts.match, 'match_tab': opts.match_tab,
'all': opts.all,

View File

@ -449,8 +449,7 @@ class Window:
return self.override_title or self.child_title
def __repr__(self) -> str:
return 'Window(title={}, id={})'.format(
self.title, self.id)
return f'Window(title={self.title}, id={self.id})'
def as_dict(self, is_focused: bool = False, is_self: bool = False) -> WindowDict:
return dict(

View File

@ -19,7 +19,7 @@ def run(*args):
try:
subprocess.check_call(args)
except OSError:
raise SystemExit('You are missing the {} program needed to generate the kitty logo'.format(args[0]))
raise SystemExit(f'You are missing the {args[0]} program needed to generate the kitty logo')
def render(output, sz=256, src=unframed_src):

View File

@ -249,7 +249,7 @@ class GitHub(Base): # {{{
self.requests = s = requests.Session()
s.auth = (self.username, self.password)
s.headers.update({'Accept': 'application/vnd.github.v3+json'})
self.url_base = self.API + f'repos/{self.username}/{self.reponame}/releases/'
self.url_base = f'{self.API}repos/{self.username}/{self.reponame}/releases/'
def patch(self, url: str, fail_msg: str, **data: Any) -> None:
rdata = json.dumps(data)
@ -283,7 +283,7 @@ class GitHub(Base): # {{{
self.info(f'Deleting {fname} from GitHub')
r = self.requests.delete(asset_url.format(existing_assets[fname]))
if r.status_code not in (204, 404):
self.fail(r, 'Failed to delete %s from GitHub' % fname)
self.fail(r, f'Failed to delete {fname} from GitHub')
self.update_nightly_description(release['id'])
for path, desc in self.files.items():
self.info('')
@ -305,17 +305,12 @@ class GitHub(Base): # {{{
if release.get(
'assets',
None) and release['tag_name'] != self.current_tag_name:
self.info('\nDeleting old released installers from: %s' %
release['tag_name'])
self.info(f'\nDeleting old released installers from: {release["tag_name"]}')
for asset in release['assets']:
r = self.requests.delete(
self.API + 'repos/{}/{}/releases/assets/{}'.format(
self.username, self.reponame, asset['id']))
f'{self.API}repos/{self.username}/{self.reponame}/releases/assets/{asset["id"]}')
if r.status_code != 204:
self.fail(
r,
'Failed to delete obsolete asset: %s for release: %s'
% (asset['name'], release['tag_name']))
self.fail(r, f'Failed to delete obsolete asset: {asset["name"]} for release: {release["tag_name"]}')
def do_upload(self, url: str, path: str, desc: str, fname: str) -> requests.Response:
mime_type = mimetypes.guess_type(fname)[0] or 'application/octet-stream'
@ -331,8 +326,8 @@ class GitHub(Base): # {{{
data=cast(IO[bytes], f))
def fail(self, r: requests.Response, msg: str) -> None:
print(msg, ' Status Code: %s' % r.status_code, file=sys.stderr)
print("JSON from response:", file=sys.stderr)
print(msg, f' Status Code: {r.status_code}', file=sys.stderr)
print('JSON from response:', file=sys.stderr)
pprint.pprint(dict(r.json()), stream=sys.stderr)
raise SystemExit(1)
@ -341,8 +336,7 @@ class GitHub(Base): # {{{
return bool(error_code == 'already_exists')
def existing_assets(self, release_id: str) -> Dict[str, str]:
url = self.API + 'repos/{}/{}/releases/{}/assets'.format(
self.username, self.reponame, release_id)
url = f'{self.API}repos/{self.username}/{self.reponame}/releases/{release_id}/assets'
r = self.requests.get(url)
if r.status_code != 200:
self.fail(r, 'Failed to get assets for release')
@ -357,13 +351,13 @@ class GitHub(Base): # {{{
return dict(r.json())
if self.is_nightly:
raise SystemExit('No existing nightly release found on GitHub')
url = self.API + f'repos/{self.username}/{self.reponame}/releases'
url = f'{self.API}repos/{self.username}/{self.reponame}/releases'
r = self.requests.post(
url,
data=json.dumps({
'tag_name': self.current_tag_name,
'target_commitish': 'master',
'name': 'version %s' % self.version,
'name': f'version {self.version}',
'body': f'Release version {self.version}.'
' For changelog, see https://sw.kovidgoyal.net/kitty/changelog/'
' GPG key used for signing tarballs is: https://calibre-ebook.com/signatures/kovid.gpg',
@ -371,8 +365,7 @@ class GitHub(Base): # {{{
'prerelease': False
}))
if r.status_code != 201:
self.fail(r, 'Failed to create release for version: %s' %
self.version)
self.fail(r, f'Failed to create release for version: {self.version}')
return dict(r.json())
# }}}

View File

@ -130,11 +130,7 @@ def at_least_version(package: str, major: int, minor: int = 0) -> None:
except Exception:
ver = 'not found'
if qmajor < major or (qmajor == major and qminor < minor):
raise SystemExit(
'{} >= {}.{} is required, found version: {}'.format(
error(package), major, minor, ver
)
)
raise SystemExit(f'{error(package)} >= {major}.{minor} is required, found version: {ver}')
def cc_version() -> Tuple[List[str], Tuple[int, int]]:
@ -880,7 +876,7 @@ def build_launcher(args: Options, launcher_dir: str = '.', bundle_type: str = 's
cmd = env.cc + cppflags + cflags + [
src, '-o', dest] + ldflags + libs + pylib
key = CompileKey('launcher.c', 'kitty')
desc = 'Building {}...'.format(emphasis('launcher'))
desc = f'Building {emphasis("launcher")} ...'
args.compilation_database.add_command(desc, cmd, partial(newer, dest, src), key=key, keyfile=src)
args.compilation_database.build_all()
@ -948,7 +944,7 @@ def compile_python(base_path: str) -> None:
def create_linux_bundle_gunk(ddir: str, libdir_name: str) -> None:
if not os.path.exists('docs/_build/html'):
make = "gmake" if is_freebsd else "make"
make = 'gmake' if is_freebsd else 'make'
run_tool([make, 'docs'])
copy_man_pages(ddir)
copy_html_docs(ddir)

View File

@ -16,17 +16,17 @@ if False:
dmg = sys.argv[-1]
mp = tempfile.mkdtemp()
atexit.register(os.rmdir, mp)
subprocess.check_call('hdiutil attach {} -mountpoint {}'.format(dmg, mp).split())
subprocess.check_call(f'hdiutil attach {dmg} -mountpoint {mp}'.split())
try:
os.chdir(mp)
for app in glob.glob('*.app'):
d = os.path.join('/Applications', app)
if os.path.exists(d):
shutil.rmtree(d)
subprocess.check_call('ditto -v {} {}'.format(app, os.path.join('/Applications', app)).split())
subprocess.check_call(f'ditto -v {app} {d}'.split())
finally:
os.chdir('/')
subprocess.check_call('hdiutil detach {}'.format(mp).split())
subprocess.check_call(f'hdiutil detach {mp}'.split())
# EOF_REMOTE