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

View File

@ -108,7 +108,7 @@ features of the graphics protocol:
def serialize_gr_command(**cmd): def serialize_gr_command(**cmd):
payload = cmd.pop('payload', None) 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 = [] ans = []
w = ans.append w = ans.append
w(b'\033_G'), w(cmd.encode('ascii')) 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: def wayland_protocol_file_name(base: str, ext: str = 'c') -> str:
base = os.path.basename(base).rpartition('.')[0] base = os.path.basename(base).rpartition('.')[0]
return 'wayland-{}-client-protocol.{}'.format(base, ext) return f'wayland-{base}-client-protocol.{ext}'
def init_env( def init_env(
@ -150,14 +150,14 @@ def build_wayland_protocols(
for protocol in env.wayland_protocols: for protocol in env.wayland_protocols:
src = os.path.join(env.wayland_packagedir, protocol) src = os.path.join(env.wayland_packagedir, protocol)
if not os.path.exists(src): 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': for ext in 'hc':
dest = wayland_protocol_file_name(src, ext) dest = wayland_protocol_file_name(src, ext)
dest = os.path.join(dest_dir, dest) dest = os.path.join(dest_dir, dest)
if newer(dest, src): if newer(dest, src):
q = 'client-header' if ext == 'h' else env.wayland_scanner_code q = 'client-header' if ext == 'h' else env.wayland_scanner_code
items.append(Command( 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)) [env.wayland_scanner, q, src, dest], lambda: True))
if items: if items:
parallel_run(items) parallel_run(items)
@ -174,7 +174,7 @@ class Arg:
self.type = self.type + '*' self.type = self.type + '*'
def __repr__(self) -> str: def __repr__(self) -> str:
return 'Arg({}, {})'.format(self.type, self.name) return f'Arg({self.type}, {self.name})'
class Function: class Function:

View File

@ -32,8 +32,7 @@ class Segment:
self.end_code: Optional[str] = None self.end_code: Optional[str] = None
def __repr__(self) -> str: def __repr__(self) -> str:
return 'Segment(start={!r}, start_code={!r}, end={!r}, end_code={!r})'.format( return f'Segment(start={self.start!r}, start_code={self.start_code!r}, end={self.end!r}, end_code={self.end_code!r})'
self.start, self.start_code, self.end, self.end_code)
class Collection: 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] parser = args_funcs[func]
except KeyError as e: except KeyError as e:
raise KeyError( raise KeyError(
'Unknown action: {}. Check if map action: ' f'Unknown action: {func}. Check if map action: {action} is valid'
'{} is valid'.format(func, action)
) from e ) from e
try: try:

View File

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

View File

@ -323,8 +323,7 @@ def render_special(
try: try:
f(ans, cell_width, *a) f(ans, cell_width, *a)
except Exception as e: except Exception as e:
log_error('Failed to render {} at cell_width={} and cell_height={} with error: {}'.format( log_error(f'Failed to render {f.__name__} at cell_width={cell_width} and cell_height={cell_height} with error: {e}')
f.__name__, cell_width, cell_height, e))
if underline: if underline:
t = underline_thickness 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(' ') parts = val.split(' ')
def abort(msg: str) -> None: def abort(msg: str) -> None:
log_error('Send text: {} is invalid ({}), ignoring'.format( log_error(f'Send text: {val} is invalid ({msg}), ignoring')
val, msg))
if len(parts) < 3: if len(parts) < 3:
return abort('Incomplete') return abort('Incomplete')

View File

@ -43,7 +43,7 @@ cause ligatures to be changed in all windows.
' never, always or cursor') ' never, always or cursor')
strategy = args[0] strategy = args[0]
if strategy not in ('never', 'always', 'cursor'): 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 { return {
'strategy': strategy, 'match_window': opts.match, 'match_tab': opts.match_tab, 'strategy': strategy, 'match_window': opts.match, 'match_tab': opts.match_tab,
'all': opts.all, 'all': opts.all,

View File

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

View File

@ -19,7 +19,7 @@ def run(*args):
try: try:
subprocess.check_call(args) subprocess.check_call(args)
except OSError: 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): def render(output, sz=256, src=unframed_src):

View File

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

View File

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

View File

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