Skip to content

Commit

Permalink
Refactor: More f-string for tools
Browse files Browse the repository at this point in the history
  • Loading branch information
page-down committed Jan 29, 2022
1 parent 9f250fd commit a22f37b
Show file tree
Hide file tree
Showing 7 changed files with 39 additions and 38 deletions.
14 changes: 7 additions & 7 deletions .github/workflows/ci.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def install_deps():

def build_kitty():
python = shutil.which('python3') if is_bundle else sys.executable
cmd = '{} setup.py build --verbose'.format(python)
cmd = f'{python} setup.py build --verbose'
if os.environ.get('KITTY_SANITIZE') == '1':
cmd += ' --debug --sanitize'
run(cmd)
Expand All @@ -59,8 +59,8 @@ def test_kitty():


def package_kitty():
py = 'python3' if is_macos else 'python'
run(py + ' setup.py linux-package --update-check-interval=0 --verbose')
python = 'python3' if is_macos else 'python'
run(f'{python} setup.py linux-package --update-check-interval=0 --verbose')
if is_macos:
run('python3 setup.py kitty.app --update-check-interval=0 --verbose')
run('kitty.app/Contents/MacOS/kitty +runpy "from kitty.constants import *; print(kitty_exe())"')
Expand All @@ -76,11 +76,11 @@ def replace_in_file(path, src, dest):
def setup_bundle_env():
global SW
os.environ['SW'] = SW = '/Users/Shared/kitty-build/sw/sw' if is_macos else os.path.join(os.environ['GITHUB_WORKSPACE'], 'sw')
os.environ['PKG_CONFIG_PATH'] = SW + '/lib/pkgconfig'
os.environ['PKG_CONFIG_PATH'] = os.path.join(SW, 'lib', 'pkgconfig')
if is_macos:
os.environ['PATH'] = '{}:{}'.format('/usr/local/opt/sphinx-doc/bin', os.environ['PATH'])
else:
os.environ['LD_LIBRARY_PATH'] = SW + '/lib'
os.environ['LD_LIBRARY_PATH'] = os.path.join(SW, 'lib')
os.environ['PYTHONHOME'] = SW
os.environ['PATH'] = '{}:{}'.format(os.path.join(SW, 'bin'), os.environ['PATH'])

Expand Down Expand Up @@ -111,7 +111,7 @@ def main():
setup_bundle_env()
else:
if not is_macos and 'pythonLocation' in os.environ:
os.environ['LD_LIBRARY_PATH'] = '{}/lib'.format(os.environ['pythonLocation'])
os.environ['LD_LIBRARY_PATH'] = os.path.join(os.environ['pythonLocation'], 'lib')
action = sys.argv[-1]
if action in ('build', 'package'):
install_deps()
Expand All @@ -122,7 +122,7 @@ def main():
elif action == 'test':
test_kitty()
else:
raise SystemExit('Unknown action: ' + action)
raise SystemExit(f'Unknown action: {action}')


if __name__ == '__main__':
Expand Down
2 changes: 1 addition & 1 deletion build-terminfo
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import tempfile

def compile_terminfo(base):
with tempfile.TemporaryDirectory() as tdir:
proc = subprocess.run(['tic', '-x', '-o' + tdir, 'terminfo/kitty.terminfo'], check=True, stderr=subprocess.PIPE)
proc = subprocess.run(['tic', '-x', f'-o{tdir}', 'terminfo/kitty.terminfo'], check=True, stderr=subprocess.PIPE)
regex = '^"terminfo/kitty.terminfo", line [0-9]+, col [0-9]+, terminal \'xterm-kitty\': older tic versions may treat the description field as an alias$'
for error in proc.stderr.decode('utf-8').splitlines():
if not re.match(regex, error):
Expand Down
16 changes: 9 additions & 7 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,15 +217,17 @@ def write_cli_docs(all_kitten_names: Iterable[str]) -> None:
from kitty.remote_control import cli_msg, global_options_spec
with open('generated/cli-kitty-at.rst', 'w') as f:
p = partial(print, file=f)
p('kitty @\n' + '-' * 80)
p('kitty @')
p('-' * 80)
p('.. program::', 'kitty @')
p('\n\n' + as_rst(
global_options_spec, message=cli_msg, usage='command ...', appname='kitty @'))
from kitty.rc.base import cli_params_for
for cmd_name in sorted(all_command_names()):
func = command_for_name(cmd_name)
p(f'.. _at_{func.name}:\n')
p('kitty @', func.name + '\n' + '-' * 120)
p('kitty @', func.name)
p('-' * 120)
p('.. program::', 'kitty @', func.name)
p('\n\n' + as_rst(*cli_params_for(func)))
from kittens.runner import get_kitten_cli_docs
Expand All @@ -234,12 +236,12 @@ def write_cli_docs(all_kitten_names: Iterable[str]) -> None:
if data:
with open(f'generated/cli-kitten-{kitten}.rst', 'w') as f:
p = partial(print, file=f)
p('.. program::', f'kitty +kitten {kitten}')
p(f'\nSource code for {kitten}')
p('.. program::', 'kitty +kitten', kitten)
p('\nSource code for', kitten)
p('-' * 72)
p(f'\nThe source code for this kitten is `available on GitHub <https://github.com/kovidgoyal/kitty/tree/master/kittens/{kitten}>`_.')
p('\nCommand Line Interface')
p('-' * 72, file=f)
p('-' * 72)
p('\n\n' + option_spec_as_rst(
data['options'], message=data['help_text'], usage=data['usage'], appname=f'kitty +kitten {kitten}',
heading_char='^'))
Expand Down Expand Up @@ -370,8 +372,8 @@ def expand_opt_references(conf_name: str, text: str) -> str:
def expand(m: Match[str]) -> str:
ref = m.group(1)
if '<' not in ref and '.' not in ref:
full_ref = conf_name + ref
return f':opt:`{ref} <{full_ref}>`'
# full ref
return f':opt:`{ref} <{conf_name}{ref}>`'
return str(m.group())

return re.sub(r':opt:`(.+?)`', expand, text)
Expand Down
2 changes: 1 addition & 1 deletion gen-apc-parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def group(atype: str, conv: str) -> Tuple[str, str]:
flag_fmt, flag_attrs = [], []
cv = {'flag': 'c', 'int': 'i', 'uint': 'I'}[atype]
for ch in type_map[atype]:
flag_fmt.append('s' + cv)
flag_fmt.append(f's{cv}')
attr = keymap[ch][0]
flag_attrs.append(f'"{attr}", {conv}g.{attr}')
return ' '.join(flag_fmt), ', '.join(flag_attrs)
Expand Down
4 changes: 2 additions & 2 deletions gen-key-constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ def patch_file(path: str, what: str, text: str, start_marker: str = '/* ', end_m
end = raw.index(end_q)
except ValueError:
raise SystemExit(f'Failed to find "{end_q}" in {path}')
raw = raw[:start] + start_q + '\n' + text + '\n' + raw[end:]
raw = f'{raw[:start]}{start_q}\n{text}\n{raw[end:]}'
f.seek(0)
f.truncate(0)
f.write(raw)
Expand Down Expand Up @@ -368,7 +368,7 @@ def generate_ctrl_mapping() -> None:
val = str(ctrl_mapping[k])
items.append(val)
if k in "\\'":
k = '\\' + k
k = f'\\{k}'
mi.append(f" case '{k}': return {val};")

for line_items in chunks(items, 6):
Expand Down
35 changes: 17 additions & 18 deletions publish.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def echo_cmd(cmd: Iterable[str]) -> None:
isatty = sys.stdout.isatty()
end = '\n'
if isatty:
end = '\x1b[m' + end
end = f'\x1b[m{end}'
print('\x1b[92m', end='')
print(shlex.join(cmd), end=end, flush=True)

Expand Down Expand Up @@ -146,11 +146,11 @@ def run_website(args: Any) -> None:


def sign_file(path: str) -> None:
dest = path + '.sig'
dest = f'{path}.sig'
with suppress(FileNotFoundError):
os.remove(dest)
subprocess.check_call([
os.environ['PENV'] + '/gpg-as-kovid', '--output', path + '.sig',
os.environ['PENV'] + '/gpg-as-kovid', '--output', f'{path}.sig',
'--detach-sig', path
])

Expand All @@ -159,17 +159,17 @@ def run_sdist(args: Any) -> None:
with tempfile.TemporaryDirectory() as tdir:
base = os.path.join(tdir, f'kitty-{version}')
os.mkdir(base)
subprocess.check_call('git archive HEAD | tar -x -C ' + base, shell=True)
subprocess.check_call(f'git archive HEAD | tar -x -C {base}', shell=True)
dest = os.path.join(base, 'docs', '_build')
os.mkdir(dest)
for x in 'html man'.split():
shutil.copytree(os.path.join(docs_dir, '_build', x), os.path.join(dest, x))
dest = os.path.abspath(os.path.join('build', f'kitty-{version}.tar'))
subprocess.check_call(['tar', '-cf', dest, os.path.basename(base)], cwd=tdir)
with suppress(FileNotFoundError):
os.remove(dest + '.xz')
os.remove(f'{dest}.xz')
subprocess.check_call(['xz', '-9', dest])
sign_file(dest + '.xz')
sign_file(f'{dest}.xz')


class ReadFileWithProgressReporting(io.FileIO): # {{{
Expand Down Expand Up @@ -231,7 +231,7 @@ def warn(self, *args: Any, **kwargs: Any) -> None:

class GitHub(Base): # {{{

API = 'https://api.github.com/'
API = 'https://api.github.com'

def __init__(
self,
Expand All @@ -244,12 +244,12 @@ def __init__(
):
self.files, self.reponame, self.version, self.username, self.password, self.replace = (
files, reponame, version, username, password, replace)
self.current_tag_name = self.version if self.version == 'nightly' else ('v' + self.version)
self.current_tag_name = self.version if self.version == 'nightly' else f'v{self.version}'
self.is_nightly = self.current_tag_name == 'nightly'
self.requests = s = requests.Session()
s.auth = (self.username, self.password)
s.headers.update({'Accept': 'application/vnd.github.v3+json'})
self.url_base = f'{self.API}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)
Expand All @@ -262,7 +262,7 @@ def patch(self, url: str, fail_msg: str, **data: Any) -> None:
self.fail(r, fail_msg)

def update_nightly_description(self, release_id: int) -> None:
url = self.url_base + str(release_id)
url = f'{self.url_base}/{release_id}'
now = str(datetime.datetime.utcnow()).split('.')[0] + ' UTC'
with open('.git/refs/heads/master') as f:
commit = f.read().strip()
Expand All @@ -276,7 +276,7 @@ def __call__(self) -> None:
# self.clean_older_releases(releases)
release = self.create_release()
upload_url = release['upload_url'].partition('{')[0]
asset_url = self.url_base + 'assets/{}'
asset_url = f'{self.url_base}/assets/{{}}'
existing_assets = self.existing_assets(release['id'])
if self.is_nightly:
for fname in existing_assets:
Expand Down Expand Up @@ -308,7 +308,7 @@ def clean_older_releases(self, releases: Iterable[Dict[str, Any]]) -> None:
self.info(f'\nDeleting old released installers from: {release["tag_name"]}')
for asset in release['assets']:
r = self.requests.delete(
f'{self.API}repos/{self.username}/{self.reponame}/releases/assets/{asset["id"]}')
f'{self.url_base}/assets/{asset["id"]}')
if r.status_code != 204:
self.fail(r, f'Failed to delete obsolete asset: {asset["name"]} for release: {release["tag_name"]}')

Expand Down Expand Up @@ -336,7 +336,7 @@ def already_exists(self, r: requests.Response) -> bool:
return bool(error_code == 'already_exists')

def existing_assets(self, release_id: str) -> Dict[str, str]:
url = f'{self.API}repos/{self.username}/{self.reponame}/releases/{release_id}/assets'
url = f'{self.url_base}/{release_id}/assets'
r = self.requests.get(url)
if r.status_code != 200:
self.fail(r, 'Failed to get assets for release')
Expand All @@ -345,15 +345,14 @@ def existing_assets(self, release_id: str) -> Dict[str, str]:
def create_release(self) -> Dict[str, Any]:
' Create a release on GitHub or if it already exists, return the existing release '
# Check for existing release
url = f'{self.API}repos/{self.username}/{self.reponame}/releases/tags/{self.current_tag_name}'
url = f'{self.url_base}/tags/{self.current_tag_name}'
r = self.requests.get(url)
if r.status_code == 200:
return dict(r.json())
if self.is_nightly:
raise SystemExit('No existing nightly release found on GitHub')
url = f'{self.API}repos/{self.username}/{self.reponame}/releases'
r = self.requests.post(
url,
self.url_base,
data=json.dumps({
'tag_name': self.current_tag_name,
'target_commitish': 'master',
Expand Down Expand Up @@ -394,7 +393,7 @@ def files_for_upload() -> Dict[str, str]:
files[f'build/kitty-{version}.tar.xz.sig'] = 'Source code GPG signature'
for path, desc in signatures.items():
sign_file(path)
files[path + '.sig'] = desc
files[f'{path}.sig'] = desc
for f in files:
if not os.path.exists(f):
raise SystemExit(f'The release artifact {f} does not exist')
Expand Down Expand Up @@ -460,7 +459,7 @@ def exec_actions(actions: Iterable[str], args: Any) -> None:
for action in actions:
print('Running', action)
cwd = os.getcwd()
globals()['run_' + action](args)
globals()[f'run_{action}'](args)
os.chdir(cwd)


Expand Down
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -710,7 +710,7 @@ def compile_c_extension(
def on_success() -> None:
os.rename(dest, real_dest)

compilation_database.add_command(desc, cmd, partial(newer, real_dest, *objects), on_success=on_success, key=CompileKey('', module + '.so'))
compilation_database.add_command(desc, cmd, partial(newer, real_dest, *objects), on_success=on_success, key=CompileKey('', f'{module}.so'))


def find_c_files() -> Tuple[List[str], List[str]]:
Expand Down Expand Up @@ -1112,7 +1112,7 @@ def create_macos_app_icon(where: str = 'Resources') -> None:
'iconutil', '-c', 'icns', iconset_dir, '-o', icns_dir
])
except FileNotFoundError:
print(error('iconutil not found') + ', using png2icns (without retina support) to convert the logo', file=sys.stderr)
print(f'{error("iconutil not found")}, using png2icns (without retina support) to convert the logo', file=sys.stderr)
subprocess.check_call([
'png2icns', icns_dir
] + [os.path.join(iconset_dir, logo) for logo in [
Expand Down

0 comments on commit a22f37b

Please sign in to comment.