run pyupgrade to upgrade the codebase to python3.6

This commit is contained in:
Kovid Goyal 2021-10-21 12:43:55 +05:30
parent 8f0b3983ee
commit 6546c1da9b
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
159 changed files with 194 additions and 353 deletions

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os import os

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import sys import sys

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import sys import sys

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
from typing import Iterable, List, Union from typing import Iterable, List, Union

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os import os
@ -94,7 +93,7 @@ def main(args: List[str]) -> NoReturn:
data: Optional[bytes] = None data: Optional[bytes] = None
if not sys.stdin.isatty(): if not sys.stdin.isatty():
data = sys.stdin.buffer.read() data = sys.stdin.buffer.read()
sys.stdin = open(os.ctermid(), 'r') sys.stdin = open(os.ctermid())
loop = Loop() loop = Loop()
handler = Clipboard(data, cli_opts) handler = Clipboard(data, cli_opts)
loop.loop(handler) loop.loop(handler)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os import os

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os import os

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import concurrent import concurrent
@ -31,7 +30,7 @@ class DiffFormatter(Formatter):
except ClassNotFound: except ClassNotFound:
initialized = False initialized = False
if not initialized: if not initialized:
raise StyleNotFound('pygments style "{}" not found'.format(style)) raise StyleNotFound(f'pygments style "{style}" not found')
self.styles: Dict[str, Tuple[str, str]] = {} self.styles: Dict[str, Tuple[str, str]] = {}
for token, token_style in self.style: for token, token_style in self.style:
@ -153,7 +152,7 @@ def highlight_collection(collection: Collection, aliases: Optional[Dict[str, str
try: try:
highlights = future.result() highlights = future.result()
except Exception as e: except Exception as e:
return 'Running syntax highlighting for {} generated an exception: {}'.format(path, e) return f'Running syntax highlighting for {path} generated an exception: {e}'
ans[path] = highlights ans[path] = highlights
return ans return ans
@ -166,5 +165,5 @@ def main() -> None:
with open(sys.argv[-1]) as f: with open(sys.argv[-1]) as f:
highlighted = highlight_data(f.read(), f.name, defaults.syntax_aliases) highlighted = highlight_data(f.read(), f.name, defaults.syntax_aliases)
if highlighted is None: if highlighted is None:
raise SystemExit('Unknown filetype: {}'.format(sys.argv[-1])) raise SystemExit(f'Unknown filetype: {sys.argv[-1]}')
print(highlighted) print(highlighted)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import atexit import atexit
@ -428,7 +427,7 @@ class DiffHandler(Handler):
elif self.state is MESSAGE: elif self.state is MESSAGE:
self.cmd.styled(self.message, reverse=True) self.cmd.styled(self.message, reverse=True)
else: else:
sp = '{:.0%}'.format(self.scroll_pos/self.max_scroll_pos) if self.scroll_pos and self.max_scroll_pos else '0%' sp = f'{self.scroll_pos/self.max_scroll_pos:.0%}' if self.scroll_pos and self.max_scroll_pos else '0%'
scroll_frac = styled(sp, fg=self.opts.margin_fg) scroll_frac = styled(sp, fg=self.opts.margin_fg)
if self.current_search is None: if self.current_search is None:
counts = '{}{}{}'.format( counts = '{}{}{}'.format(
@ -437,7 +436,7 @@ class DiffHandler(Handler):
styled(str(self.removed_count), fg=self.opts.highlight_removed_bg) styled(str(self.removed_count), fg=self.opts.highlight_removed_bg)
) )
else: else:
counts = styled('{} matches'.format(len(self.current_search)), fg=self.opts.margin_fg) counts = styled(f'{len(self.current_search)} matches', fg=self.opts.margin_fg)
suffix = counts + ' ' + scroll_frac suffix = counts + ' ' + scroll_frac
prefix = styled(':', fg=self.opts.margin_fg) prefix = styled(':', fg=self.opts.margin_fg)
filler = self.screen_size.cols - wcswidth(prefix) - wcswidth(suffix) filler = self.screen_size.cols - wcswidth(prefix) - wcswidth(suffix)
@ -632,7 +631,7 @@ def main(args: List[str]) -> None:
raise SystemExit('The items to be diffed should both be either directories or files. Comparing a directory to a file is not valid.') raise SystemExit('The items to be diffed should both be either directories or files. Comparing a directory to a file is not valid.')
for f in left, right: for f in left, right:
if not os.path.exists(f): if not os.path.exists(f):
raise SystemExit('{} does not exist'.format(f)) raise SystemExit(f'{f} does not exist')
loop = Loop() loop = Loop()
handler = DiffHandler(cli_opts, opts, left, right) handler = DiffHandler(cli_opts, opts, left, right)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import concurrent.futures import concurrent.futures
@ -151,9 +150,9 @@ class Hunk:
# Sanity check # Sanity check
c = self.chunks[-1] c = self.chunks[-1]
if c.left_start + c.left_count != self.left_start + self.left_count: if c.left_start + c.left_count != self.left_start + self.left_count:
raise ValueError('Left side line mismatch {} != {}'.format(c.left_start + c.left_count, self.left_start + self.left_count)) raise ValueError(f'Left side line mismatch {c.left_start + c.left_count} != {self.left_start + self.left_count}')
if c.right_start + c.right_count != self.right_start + self.right_count: if c.right_start + c.right_count != self.right_start + self.right_count:
raise ValueError('Left side line mismatch {} != {}'.format(c.right_start + c.right_count, self.right_start + self.right_count)) raise ValueError(f'Left side line mismatch {c.right_start + c.right_count} != {self.right_start + self.right_count}')
for c in self.chunks: for c in self.chunks:
c.finalize() c.finalize()
@ -240,18 +239,18 @@ class Differ:
try: try:
ok, returncode, output = future.result() ok, returncode, output = future.result()
except FileNotFoundError as err: except FileNotFoundError as err:
return 'Could not find the {} executable. Is it in your PATH?'.format(err.filename) return f'Could not find the {err.filename} executable. Is it in your PATH?'
except Exception as e: except Exception as e:
return 'Running git diff for {} vs. {} generated an exception: {}'.format(left_path, right_path, e) return f'Running git diff for {left_path} vs. {right_path} generated an exception: {e}'
if not ok: if not ok:
return output + '\nRunning git diff for {} vs. {} failed'.format(left_path, right_path) return output + f'\nRunning git diff for {left_path} vs. {right_path} failed'
left_lines = lines_for_path(left_path) left_lines = lines_for_path(left_path)
right_lines = lines_for_path(right_path) right_lines = lines_for_path(right_path)
try: try:
patch = parse_patch(output) patch = parse_patch(output)
except Exception: except Exception:
import traceback import traceback
return traceback.format_exc() + '\nParsing diff for {} vs. {} failed'.format(left_path, right_path) return traceback.format_exc() + f'\nParsing diff for {left_path} vs. {right_path} failed'
else: else:
ans[key] = patch ans[key] = patch
return ans return ans

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import warnings import warnings
@ -42,7 +41,7 @@ class Ref:
def __repr__(self) -> str: def __repr__(self) -> str:
return '{}({})'.format(self.__class__.__name__, ', '.join( return '{}({})'.format(self.__class__.__name__, ', '.join(
'{}={}'.format(n, getattr(self, n)) for n in self.__slots__ if n != '_hash')) f'{n}={getattr(self, n)}' for n in self.__slots__ if n != '_hash'))
class LineRef(Ref): class LineRef(Ref):
@ -264,7 +263,7 @@ def render_diff_pair(
def hunk_title(hunk_num: int, hunk: Hunk, margin_size: int, available_cols: int) -> str: def hunk_title(hunk_num: int, hunk: Hunk, margin_size: int, available_cols: int) -> str:
m = hunk_margin_format(' ' * margin_size) m = hunk_margin_format(' ' * margin_size)
t = '@@ -{},{} +{},{} @@ {}'.format(hunk.left_start + 1, hunk.left_count, hunk.right_start + 1, hunk.right_count, hunk.title) t = f'@@ -{hunk.left_start + 1},{hunk.left_count} +{hunk.right_start + 1},{hunk.right_count} @@ {hunk.title}'
return m + hunk_format(place_in(t, available_cols)) return m + hunk_format(place_in(t, available_cols))
@ -539,7 +538,7 @@ class RenderDiff:
assert other_path is not None assert other_path is not None
ans = yield_lines_from(rename_lines(path, other_path, args, columns, margin_size), item_ref) ans = yield_lines_from(rename_lines(path, other_path, args, columns, margin_size), item_ref)
else: else:
raise ValueError('Unsupported item type: {}'.format(item_type)) raise ValueError(f'Unsupported item type: {item_type}')
yield from ans yield from ans
if i < last_item_num: if i < last_item_num:
yield Line('', item_ref) yield Line('', item_ref)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import re import re
@ -30,7 +29,7 @@ class Search:
try: try:
self.pat = re.compile(query, flags=re.UNICODE | re.IGNORECASE) self.pat = re.compile(query, flags=re.UNICODE | re.IGNORECASE)
except Exception: except Exception:
raise BadRegex('Not a valid regex: {}'.format(query)) raise BadRegex(f'Not a valid regex: {query}')
def __call__(self, diff_lines: Iterable['Line'], margin_size: int, cols: int) -> bool: def __call__(self, diff_lines: Iterable['Line'], margin_size: int, cols: int) -> bool:
self.matches = {} self.matches = {}
@ -68,6 +67,6 @@ class Search:
return False return False
write(self.style) write(self.style)
for start, text in highlights: for start, text in highlights:
write('\r\x1b[{}C{}'.format(start, text)) write(f'\r\x1b[{start}C{text}')
write('\x1b[m') write('\x1b[m')
return True return True

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os import os
@ -366,7 +365,7 @@ def functions_for(args: HintsCLIOptions) -> Tuple[str, List[PostprocessorFunc]]:
chars = args.word_characters chars = args.word_characters
if chars is None: if chars is None:
chars = kitty_common_opts()['select_by_word_characters'] chars = kitty_common_opts()['select_by_word_characters']
pattern = r'(?u)[{}\w]{{{},}}'.format(escape(chars), args.minimum_match_length) pattern = fr'(?u)[{escape(chars)}\w]{{{args.minimum_match_length},}}'
post_processors.extend((brackets, quotes)) post_processors.extend((brackets, quotes))
else: else:
pattern = args.regex pattern = args.regex

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import os import os

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
import contextlib import contextlib
@ -145,7 +144,7 @@ def get_screen_size() -> ScreenSize:
@run_once @run_once
def options_spec() -> str: def options_spec() -> str:
return OPTIONS.format(appname='{}-icat'.format(appname)) return OPTIONS.format(appname=f'{appname}-icat')
def write_gr_cmd(cmd: GraphicsCommand, payload: Optional[bytes] = None) -> None: def write_gr_cmd(cmd: GraphicsCommand, payload: Optional[bytes] = None) -> None:
@ -195,7 +194,7 @@ def set_cursor_for_place(place: 'Place', cmd: GraphicsCommand, width: int, heigh
extra_cells = (place.width - num_of_cells_needed) // 2 extra_cells = (place.width - num_of_cells_needed) // 2
elif align == 'right': elif align == 'right':
extra_cells = place.width - num_of_cells_needed extra_cells = place.width - num_of_cells_needed
sys.stdout.buffer.write('\033[{};{}H'.format(place.top + 1, x + extra_cells).encode('ascii')) sys.stdout.buffer.write(f'\033[{place.top + 1};{x + extra_cells}H'.encode('ascii'))
def write_chunked(cmd: GraphicsCommand, data: bytes) -> None: def write_chunked(cmd: GraphicsCommand, data: bytes) -> None:
@ -369,7 +368,7 @@ def scan(d: str) -> Generator[Tuple[str, str], None, None]:
def detect_support(wait_for: float = 10, silent: bool = False) -> bool: def detect_support(wait_for: float = 10, silent: bool = False) -> bool:
global can_transfer_with_files global can_transfer_with_files
if not silent: if not silent:
print('Checking for graphics ({}s max. wait)...'.format(wait_for), end='\r') print(f'Checking for graphics ({wait_for}s max. wait)...', end='\r')
sys.stdout.flush() sys.stdout.flush()
try: try:
received = b'' received = b''
@ -466,7 +465,7 @@ def process_single_item(
with socket_timeout(30): with socket_timeout(30):
urlretrieve(item, filename=tf.name) urlretrieve(item, filename=tf.name)
except Exception as e: except Exception as e:
raise SystemExit('Failed to download image at URL: {} with error: {}'.format(item, e)) raise SystemExit(f'Failed to download image at URL: {item} with error: {e}')
item = tf.name item = tf.name
is_tempfile = True is_tempfile = True
file_removed = process(item, args, parsed_opts, is_tempfile) file_removed = process(item, args, parsed_opts, is_tempfile)
@ -493,14 +492,14 @@ def process_single_item(
def main(args: List[str] = sys.argv) -> None: def main(args: List[str] = sys.argv) -> None:
global can_transfer_with_files global can_transfer_with_files
cli_opts, items_ = parse_args(args[1:], options_spec, usage, help_text, '{} +kitten icat'.format(appname), result_class=IcatCLIOptions) cli_opts, items_ = parse_args(args[1:], options_spec, usage, help_text, f'{appname} +kitten icat', result_class=IcatCLIOptions)
items: List[Union[str, bytes]] = list(items_) items: List[Union[str, bytes]] = list(items_)
if cli_opts.print_window_size: if cli_opts.print_window_size:
screen_size_function.cache_clear() screen_size_function.cache_clear()
with open(os.ctermid()) as tty: with open(os.ctermid()) as tty:
ss = screen_size_function(tty)() ss = screen_size_function(tty)()
print('{}x{}'.format(ss.width, ss.height), end='') print(f'{ss.width}x{ss.height}', end='')
raise SystemExit(0) raise SystemExit(0)
if not sys.stdout.isatty(): if not sys.stdout.isatty():
@ -511,7 +510,7 @@ def main(args: List[str] = sys.argv) -> None:
if stdin_data: if stdin_data:
items.insert(0, stdin_data) items.insert(0, stdin_data)
sys.stdin.close() sys.stdin.close()
sys.stdin = open(os.ctermid(), 'r') sys.stdin = open(os.ctermid())
screen_size = get_screen_size_function() screen_size = get_screen_size_function()
signal.signal(signal.SIGWINCH, lambda signum, frame: setattr(screen_size, 'changed', True)) signal.signal(signal.SIGWINCH, lambda signum, frame: setattr(screen_size, 'changed', True))
@ -526,12 +525,12 @@ def main(args: List[str] = sys.argv) -> None:
try: try:
parsed_opts.place = parse_place(cli_opts.place) parsed_opts.place = parse_place(cli_opts.place)
except Exception: except Exception:
raise SystemExit('Not a valid place specification: {}'.format(cli_opts.place)) raise SystemExit(f'Not a valid place specification: {cli_opts.place}')
try: try:
parsed_opts.z_index = parse_z_index(cli_opts.z_index) parsed_opts.z_index = parse_z_index(cli_opts.z_index)
except Exception: except Exception:
raise SystemExit('Not a valid z-index specification: {}'.format(cli_opts.z_index)) raise SystemExit(f'Not a valid z-index specification: {cli_opts.z_index}')
if cli_opts.detect_support: if cli_opts.detect_support:
if not detect_support(wait_for=cli_opts.detection_timeout, silent=True): if not detect_support(wait_for=cli_opts.detection_timeout, silent=True):

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import sys import sys

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os import os
@ -116,7 +115,7 @@ def setup_x11_window(win_id: int) -> None:
'-id', str(win_id), '-format', '_NET_WM_WINDOW_TYPE', '32a', '-id', str(win_id), '-format', '_NET_WM_WINDOW_TYPE', '32a',
'-set', '_NET_WM_WINDOW_TYPE', '_NET_WM_WINDOW_TYPE_DOCK' '-set', '_NET_WM_WINDOW_TYPE', '_NET_WM_WINDOW_TYPE_DOCK'
) )
func = globals()['create_{}_strut'.format(args.edge)] func = globals()[f'create_{args.edge}_strut']
func(win_id, window_width, window_height) func(win_id, window_width, window_height)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import re import re
@ -28,10 +27,10 @@ class Query:
def __init__(self) -> None: def __init__(self) -> None:
self.encoded_query_name = hexlify(self.query_name.encode('utf-8')).decode('ascii') self.encoded_query_name = hexlify(self.query_name.encode('utf-8')).decode('ascii')
self.pat = re.compile('\x1bP([01])\\+r{}(.*?)\x1b\\\\'.format(self.encoded_query_name).encode('ascii')) self.pat = re.compile(f'\x1bP([01])\\+r{self.encoded_query_name}(.*?)\x1b\\\\'.encode('ascii'))
def query_code(self) -> str: def query_code(self) -> str:
return "\x1bP+q{}\x1b\\".format(self.encoded_query_name) return f"\x1bP+q{self.encoded_query_name}\x1b\\"
def decode_response(self, res: bytes) -> str: def decode_response(self, res: bytes) -> str:
return unhexlify(res).decode('utf-8') return unhexlify(res).decode('utf-8')
@ -234,7 +233,7 @@ def main(args: List[str] = sys.argv) -> None:
options_spec, options_spec,
usage, usage,
help_text, help_text,
'{} +kitten query_terminal'.format(appname), f'{appname} +kitten query_terminal',
result_class=QueryTerminalCLIOptions result_class=QueryTerminalCLIOptions
) )
queries: List[str] = list(items_) queries: List[str] = list(items_)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
@ -43,7 +42,7 @@ class Resize(Handler):
if is_decrease: if is_decrease:
increment *= -1 increment *= -1
axis = 'reset' if reset else ('horizontal' if is_horizontal else 'vertical') axis = 'reset' if reset else ('horizontal' if is_horizontal else 'vertical')
cmdline = [resize_window.name, '--self', '--increment={}'.format(increment), '--axis=' + axis] cmdline = [resize_window.name, '--self', f'--increment={increment}', '--axis=' + axis]
opts, items = parse_subcommand_cli(resize_window, cmdline) opts, items = parse_subcommand_cli(resize_window, cmdline)
payload = resize_window.message_to_kitty(global_opts, opts, items) payload = resize_window.message_to_kitty(global_opts, opts, items)
send = {'cmd': resize_window.name, 'version': version, 'payload': payload, 'no_response': False} send = {'cmd': resize_window.name, 'version': version, 'payload': payload, 'no_response': False}
@ -96,7 +95,7 @@ class Resize(Handler):
print('Hold down {} to double step size'.format(styled('Ctrl', italic=True))) print('Hold down {} to double step size'.format(styled('Ctrl', italic=True)))
print() print()
print(styled('Sizes', bold=True, fg='white', fg_intense=True)) print(styled('Sizes', bold=True, fg='white', fg_intense=True))
print('Original: {} rows {} cols'.format(self.original_size.rows, self.original_size.cols)) print(f'Original: {self.original_size.rows} rows {self.original_size.cols} cols')
print('Current: {} rows {} cols'.format( print('Current: {} rows {} cols'.format(
styled(str(self.screen_size.rows), fg='magenta'), styled(str(self.screen_size.cols), fg='magenta'))) styled(str(self.screen_size.rows), fg='magenta'), styled(str(self.screen_size.cols), fg='magenta')))

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
@ -61,7 +60,7 @@ def import_kitten_main_module(config_dir: str, kitten: str) -> Dict[str, Any]:
return {'start': g['main'], 'end': hr} return {'start': g['main'], 'end': hr}
kitten = resolved_kitten(kitten) kitten = resolved_kitten(kitten)
m = importlib.import_module('kittens.{}.main'.format(kitten)) m = importlib.import_module(f'kittens.{kitten}.main')
return {'start': getattr(m, 'main'), 'end': getattr(m, 'handle_result', lambda *a, **k: None)} return {'start': getattr(m, 'main'), 'end': getattr(m, 'handle_result', lambda *a, **k: None)}
@ -111,7 +110,7 @@ def deserialize(output: str) -> Any:
prefix, sz, rest = output.split(' ', 2) prefix, sz, rest = output.split(' ', 2)
return json.loads(rest[:int(sz)]) return json.loads(rest[:int(sz)])
except Exception: except Exception:
raise ValueError('Failed to parse kitten output: {!r}'.format(output)) raise ValueError(f'Failed to parse kitten output: {output!r}')
def run_kitten(kitten: str, run_name: str = '__main__') -> None: def run_kitten(kitten: str, run_name: str = '__main__') -> None:
@ -120,7 +119,7 @@ def run_kitten(kitten: str, run_name: str = '__main__') -> None:
kitten = resolved_kitten(kitten) kitten = resolved_kitten(kitten)
set_debug(kitten) set_debug(kitten)
try: try:
runpy.run_module('kittens.{}.main'.format(kitten), run_name=run_name) runpy.run_module(f'kittens.{kitten}.main', run_name=run_name)
return return
except ImportError: except ImportError:
pass pass

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os import os

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
from kitty.key_encoding import ( from kitty.key_encoding import (

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import os import os

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os import os
@ -245,7 +244,7 @@ def parse_ssh_args(args: List[str]) -> Tuple[List[str], List[str], bool]:
else: else:
expecting_option_val = True expecting_option_val = True
break break
raise InvalidSSHArgs('unknown option -- {}'.format(arg[1:])) raise InvalidSSHArgs(f'unknown option -- {arg[1:]}')
continue continue
if expecting_option_val: if expecting_option_val:
ssh_args.append(arg) ssh_args.append(arg)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import datetime import datetime

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import os import os

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import os import os

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
from enum import auto from enum import auto

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import os import os

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import os import os
@ -336,11 +335,11 @@ class Dircolors:
def _format_code(self, text: str, code: str) -> str: def _format_code(self, text: str, code: str) -> str:
val = self.codes.get(code) val = self.codes.get(code)
return '\033[%sm%s\033[%sm' % (val, text, self.codes.get('rs', '0')) if val else text return '\033[{}m{}\033[{}m'.format(val, text, self.codes.get('rs', '0')) if val else text
def _format_ext(self, text: str, ext: str) -> str: def _format_ext(self, text: str, ext: str) -> str:
val = self.extensions.get(ext, '0') val = self.extensions.get(ext, '0')
return '\033[%sm%s\033[%sm' % (val, text, self.codes.get('rs', '0')) if val else text return '\033[{}m{}\033[{}m'.format(val, text, self.codes.get('rs', '0')) if val else text
def format_mode(self, text: str, sr: os.stat_result) -> str: def format_mode(self, text: str, sr: os.stat_result) -> str:
mode = sr.st_mode mode = sr.st_mode

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import codecs import codecs
@ -105,7 +104,7 @@ class OpenFailed(ValueError):
def __init__(self, path: str, message: str): def __init__(self, path: str, message: str):
ValueError.__init__( ValueError.__init__(
self, 'Failed to open image: {} with error: {}'.format(path, message) self, f'Failed to open image: {path} with error: {message}'
) )
self.path = path self.path = path
@ -114,7 +113,7 @@ class ConvertFailed(ValueError):
def __init__(self, path: str, message: str): def __init__(self, path: str, message: str):
ValueError.__init__( ValueError.__init__(
self, 'Failed to convert image: {} with error: {}'.format(path, message) self, f'Failed to convert image: {path} with error: {message}'
) )
self.path = path self.path = path
@ -212,7 +211,7 @@ def render_image(
scaled = True scaled = True
if scaled or width > available_width or height > available_height: if scaled or width > available_width or height > available_height:
width, height = fit_image(width, height, available_width, available_height) width, height = fit_image(width, height, available_width, available_height)
resize_cmd = ['-resize', '{}x{}!'.format(width, height)] resize_cmd = ['-resize', f'{width}x{height}!']
if get_multiple_frames: if get_multiple_frames:
# we have to coalesce, resize and de-coalesce all frames # we have to coalesce, resize and de-coalesce all frames
resize_cmd = ['-coalesce'] + resize_cmd + ['-deconstruct'] resize_cmd = ['-coalesce'] + resize_cmd + ['-deconstruct']
@ -373,7 +372,7 @@ class GraphicsCommand:
def serialize(self, payload: Union[bytes, str] = b'') -> bytes: def serialize(self, payload: Union[bytes, str] = b'') -> bytes:
items = [] items = []
for k, val in self._actual_values.items(): for k, val in self._actual_values.items():
items.append('{}={}'.format(k, val)) items.append(f'{k}={val}')
ans: List[bytes] = [] ans: List[bytes] = []
w = ans.append w = ans.append

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
from typing import Callable, Tuple from typing import Callable, Tuple

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import asyncio import asyncio

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import sys import sys
@ -57,13 +56,13 @@ def cmd(f: F) -> F:
@cmd @cmd
def set_mode(which: Mode) -> str: def set_mode(which: Mode) -> str:
num, private = which.value num, private = which.value
return '\033[{}{}h'.format(private, num) return f'\033[{private}{num}h'
@cmd @cmd
def reset_mode(which: Mode) -> str: def reset_mode(which: Mode) -> str:
num, private = which.value num, private = which.value
return '\033[{}{}l'.format(private, num) return f'\033[{private}{num}l'
@cmd @cmd
@ -127,7 +126,7 @@ def set_cursor_visible(yes_or_no: bool) -> str:
@cmd @cmd
def set_cursor_position(x: int = 0, y: int = 0) -> str: # (0, 0) is top left def set_cursor_position(x: int = 0, y: int = 0) -> str: # (0, 0) is top left
return '\033[{};{}H'.format(y + 1, x + 1) return f'\033[{y + 1};{x + 1}H'
@cmd @cmd
@ -141,7 +140,7 @@ def set_cursor_shape(shape: str = 'block', blink: bool = True) -> str:
val = {'block': 1, 'underline': 3, 'bar': 5}.get(shape, 1) val = {'block': 1, 'underline': 3, 'bar': 5}.get(shape, 1)
if not blink: if not blink:
val += 1 val += 1
return '\033[{} q'.format(val) return f'\033[{val} q'
@cmd @cmd
@ -156,7 +155,7 @@ def set_scrolling_region(screen_size: Optional['ScreenSize'] = None, top: Option
bottom = screen_size.rows - 1 + bottom bottom = screen_size.rows - 1 + bottom
else: else:
bottom += 1 bottom += 1
return '\033[{};{}r'.format(top + 1, bottom + 1) return f'\033[{top + 1};{bottom + 1}r'
@cmd @cmd
@ -178,7 +177,7 @@ def color_code(color: ColorSpec, intense: bool = False, base: int = 30) -> str:
if isinstance(color, str): if isinstance(color, str):
e = str((base + 60 if intense else base) + STANDARD_COLORS[color]) e = str((base + 60 if intense else base) + STANDARD_COLORS[color])
elif isinstance(color, int): elif isinstance(color, int):
e = '{}:5:{}'.format(base + 8, max(0, min(color, 255))) e = f'{base + 8}:5:{max(0, min(color, 255))}'
else: else:
e = '{}:2:{}:{}:{}'.format(base + 8, *color) e = '{}:2:{}:{}:{}'.format(base + 8, *color)
return e return e
@ -198,7 +197,7 @@ def colored(
reset_to_intense: bool = False reset_to_intense: bool = False
) -> str: ) -> str:
e = color_code(color, intense) e = color_code(color, intense)
return '\033[{}m{}\033[{}m'.format(e, text, 39 if reset_to is None else color_code(reset_to, reset_to_intense)) return f'\033[{e}m{text}\033[{39 if reset_to is None else color_code(reset_to, reset_to_intense)}m'
@cmd @cmd
@ -233,7 +232,7 @@ def styled(
start.append(color_code(underline_color, base=50)) start.append(color_code(underline_color, base=50))
end.append('59') end.append('59')
if underline is not None: if underline is not None:
start.append('4:{}'.format(UNDERLINE_STYLES[underline])) start.append(f'4:{UNDERLINE_STYLES[underline]}')
end.append('4:0') end.append('4:0')
if italic is not None: if italic is not None:
s, e = (start, end) if italic else (end, start) s, e = (start, end) if italic else (end, start)
@ -383,7 +382,7 @@ def set_default_colors(
def item(which: Optional[Union[Color, str]], num: int) -> None: def item(which: Optional[Union[Color, str]], num: int) -> None:
nonlocal ans nonlocal ans
if which is None: if which is None:
ans += '\x1b]1{}\x1b\\'.format(num) ans += f'\x1b]1{num}\x1b\\'
else: else:
if isinstance(which, Color): if isinstance(which, Color):
q = color_as_sharp(which) q = color_as_sharp(which)
@ -391,7 +390,7 @@ def set_default_colors(
x = to_color(which) x = to_color(which)
assert x is not None assert x is not None
q = color_as_sharp(x) q = color_as_sharp(x)
ans += '\x1b]{};{}\x1b\\'.format(num, q) ans += f'\x1b]{num};{q}\x1b\\'
item(fg, 10) item(fg, 10)
item(bg, 11) item(bg, 11)
@ -464,7 +463,7 @@ def as_type_stub() -> str:
args = ', '.join(func_sig(func)) args = ', '.join(func_sig(func))
if args: if args:
args = ', ' + args args = ', ' + args
methods.append(' def {}(self{}) -> str: pass'.format(name, args)) methods.append(f' def {name}(self{args}) -> str: pass')
ans += ['', '', 'class CMD:'] + methods ans += ['', '', 'class CMD:'] + methods
return '\n'.join(ans) + '\n\n\n' return '\n'.join(ans) + '\n\n\n'

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
from time import monotonic from time import monotonic

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import sys import sys

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os import os
import string import string
@ -110,7 +109,7 @@ def serialize_favorites(favorites: Iterable[int]) -> str:
'''.splitlines() '''.splitlines()
for cp in favorites: for cp in favorites:
ans.append('{:x} # {} {}'.format(cp, chr(cp), name(cp))) ans.append(f'{cp:x} # {chr(cp)} {name(cp)}')
return '\n'.join(ans) return '\n'.join(ans)
@ -381,7 +380,7 @@ class UnicodeInput(Handler):
def draw_title_bar(self) -> None: def draw_title_bar(self) -> None:
entries = [] entries = []
for name, key, mode in all_modes: for name, key, mode in all_modes:
entry = ' {} ({}) '.format(name, key) entry = f' {name} ({key}) '
if mode is self.mode: if mode is self.mode:
entry = styled(entry, reverse=False, bold=True) entry = styled(entry, reverse=False, bold=True)
entries.append(entry) entries.append(entry)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import inspect import inspect

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
from enum import IntFlag from enum import IntFlag

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
import atexit import atexit
@ -899,8 +898,8 @@ class Boss:
if w is None: if w is None:
return return
overlay_window = self._run_kitten('resize_window', args=[ overlay_window = self._run_kitten('resize_window', args=[
'--horizontal-increment={}'.format(get_options().window_resize_step_cells), f'--horizontal-increment={get_options().window_resize_step_cells}',
'--vertical-increment={}'.format(get_options().window_resize_step_lines) f'--vertical-increment={get_options().window_resize_step_lines}'
]) ])
if overlay_window is not None: if overlay_window is not None:
overlay_window.allow_remote_control = True overlay_window.allow_remote_control = True
@ -1178,7 +1177,7 @@ class Boss:
q = type_of_input.split('-') q = type_of_input.split('-')
data = w.last_cmd_output(as_ansi='ansi' in q, add_wrap_markers='screen' in q).encode('utf-8') data = w.last_cmd_output(as_ansi='ansi' in q, add_wrap_markers='screen' in q).encode('utf-8')
else: else:
raise ValueError('Unknown type_of_input: {}'.format(type_of_input)) raise ValueError(f'Unknown type_of_input: {type_of_input}')
else: else:
data = input_data if isinstance(input_data, bytes) else input_data.encode('utf-8') data = input_data if isinstance(input_data, bytes) else input_data.encode('utf-8')
copts = common_opts_as_dict(get_options()) copts = common_opts_as_dict(get_options())
@ -1766,12 +1765,12 @@ class Boss:
assert update_check_process.stdout is not None assert update_check_process.stdout is not None
raw = update_check_process.stdout.read().decode('utf-8') raw = update_check_process.stdout.read().decode('utf-8')
except Exception as e: except Exception as e:
log_error('Failed to read data from update check process, with error: {}'.format(e)) log_error(f'Failed to read data from update check process, with error: {e}')
else: else:
try: try:
process_current_release(raw) process_current_release(raw)
except Exception as e: except Exception as e:
log_error('Failed to process update check data {!r}, with error: {}'.format(raw, e)) log_error(f'Failed to process update check data {raw!r}, with error: {e}')
def dbus_notification_callback(self, activated: bool, a: int, b: Union[int, str]) -> None: def dbus_notification_callback(self, activated: bool, a: int, b: Union[int, str]) -> None:
from .notify import ( from .notify import (
@ -1787,7 +1786,7 @@ class Boss:
def show_bad_config_lines(self, bad_lines: Iterable[BadLine]) -> None: def show_bad_config_lines(self, bad_lines: Iterable[BadLine]) -> None:
def format_bad_line(bad_line: BadLine) -> str: def format_bad_line(bad_line: BadLine) -> str:
return '{}:{} in line: {}\n'.format(bad_line.number, bad_line.exception, bad_line.line) return f'{bad_line.number}:{bad_line.exception} in line: {bad_line.line}\n'
msg = '\n'.join(map(format_bad_line, bad_lines)).rstrip() msg = '\n'.join(map(format_bad_line, bad_lines)).rstrip()
self.show_error(_('Errors in kitty.conf'), msg) self.show_error(_('Errors in kitty.conf'), msg)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
import fcntl import fcntl
@ -41,15 +40,15 @@ if is_macos:
else: else:
def cmdline_of_process(pid: int) -> List[str]: def cmdline_of_process(pid: int) -> List[str]:
with open('/proc/{}/cmdline'.format(pid), 'rb') as f: with open(f'/proc/{pid}/cmdline', 'rb') as f:
return list(filter(None, f.read().decode('utf-8').split('\0'))) return list(filter(None, f.read().decode('utf-8').split('\0')))
def cwd_of_process(pid: int) -> str: def cwd_of_process(pid: int) -> str:
ans = '/proc/{}/cwd'.format(pid) ans = f'/proc/{pid}/cwd'
return os.path.realpath(ans) return os.path.realpath(ans)
def _environ_of_process(pid: int) -> str: def _environ_of_process(pid: int) -> str:
with open('/proc/{}/environ'.format(pid), 'rb') as f: with open(f'/proc/{pid}/environ', 'rb') as f:
return f.read().decode('utf-8') return f.read().decode('utf-8')
def process_group_map() -> DefaultDict[int, List[int]]: def process_group_map() -> DefaultDict[int, List[int]]:

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net>
import re import re

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
import re import re
@ -53,7 +52,7 @@ defaults for all users.
def surround(x: str, start: int, end: int) -> str: def surround(x: str, start: int, end: int) -> str:
if sys.stdout.isatty(): if sys.stdout.isatty():
x = '\033[{}m{}\033[{}m'.format(start, x, end) x = f'\033[{start}m{x}\033[{end}m'
return x return x
@ -185,7 +184,7 @@ def parse_option_spec(spec: Optional[str] = None) -> Tuple[OptionSpecSeq, Option
} }
state = METADATA state = METADATA
continue continue
raise ValueError('Invalid option spec, unexpected line: {}'.format(line)) raise ValueError(f'Invalid option spec, unexpected line: {line}')
elif state is METADATA: elif state is METADATA:
m = mpat.match(line) m = mpat.match(line)
if m is None: if m is None:
@ -243,7 +242,7 @@ def version(add_rev: bool = False) -> str:
rev = '' rev = ''
from . import fast_data_types from . import fast_data_types
if add_rev and hasattr(fast_data_types, 'KITTY_VCS_REV'): if add_rev and hasattr(fast_data_types, 'KITTY_VCS_REV'):
rev = ' ({})'.format(fast_data_types.KITTY_VCS_REV[:10]) rev = f' ({fast_data_types.KITTY_VCS_REV[:10]})'
return '{} {}{} created by {}'.format(italic(appname), green(str_version), rev, title('Kovid Goyal')) return '{} {}{} created by {}'.format(italic(appname), green(str_version), rev, title('Kovid Goyal'))
@ -334,7 +333,7 @@ class PrintHelpForSeq:
a('{}:'.format(title('Options'))) a('{}:'.format(title('Options')))
for opt in seq: for opt in seq:
if isinstance(opt, str): if isinstance(opt, str):
a('{}:'.format(title(opt))) a(f'{title(opt)}:')
continue continue
help_text = opt['help'] help_text = opt['help']
if help_text == '!': if help_text == '!':
@ -347,7 +346,7 @@ class PrintHelpForSeq:
t = help_text.replace('%default', str(defval)) t = help_text.replace('%default', str(defval))
wa(prettify(t.strip()), indent=4) wa(prettify(t.strip()), indent=4)
if defval is not None: if defval is not None:
wa('Default: {}'.format(defval), indent=4) wa(f'Default: {defval}', indent=4)
if opt.get('choices'): if opt.get('choices'):
wa('Choices: {}'.format(', '.join(opt['choices'])), indent=4) wa('Choices: {}'.format(', '.join(opt['choices'])), indent=4)
a('') a('')
@ -384,7 +383,7 @@ def seq_as_rst(
a('.. highlight:: sh') a('.. highlight:: sh')
a('.. code-block:: sh') a('.. code-block:: sh')
a('') a('')
a(' {} {}{}'.format(appname, optstring, usage)) a(f' {appname} {optstring}{usage}')
a('') a('')
message = message or default_msg message = message or default_msg
a(prettify_rst(message)) a(prettify_rst(message))
@ -412,7 +411,7 @@ def seq_as_rst(
a('') a('')
a(textwrap.indent(prettify_rst(t), ' ' * 4)) a(textwrap.indent(prettify_rst(t), ' ' * 4))
if defval is not None: if defval is not None:
a(textwrap.indent('Default: :code:`{}`'.format(defval), ' ' * 4)) a(textwrap.indent(f'Default: :code:`{defval}`', ' ' * 4))
if opt.get('choices'): if opt.get('choices'):
a(textwrap.indent('Choices: :code:`{}`'.format(', '.join(sorted(opt['choices']))), ' ' * 4)) a(textwrap.indent('Choices: :code:`{}`'.format(', '.join(sorted(opt['choices']))), ' ' * 4))
a('') a('')
@ -423,7 +422,7 @@ def seq_as_rst(
def as_type_stub(seq: OptionSpecSeq, disabled: OptionSpecSeq, class_name: str, extra_fields: Sequence[str] = ()) -> str: def as_type_stub(seq: OptionSpecSeq, disabled: OptionSpecSeq, class_name: str, extra_fields: Sequence[str] = ()) -> str:
from itertools import chain from itertools import chain
ans: List[str] = ['class {}:'.format(class_name)] ans: List[str] = [f'class {class_name}:']
for opt in chain(seq, disabled): for opt in chain(seq, disabled):
if isinstance(opt, str): if isinstance(opt, str):
continue continue
@ -443,10 +442,10 @@ def as_type_stub(seq: OptionSpecSeq, disabled: OptionSpecSeq, class_name: str, e
elif otype.startswith('bool-'): elif otype.startswith('bool-'):
t = 'bool' t = 'bool'
else: else:
raise ValueError('Unknown CLI option type: {}'.format(otype)) raise ValueError(f'Unknown CLI option type: {otype}')
ans.append(' {}: {}'.format(name, t)) ans.append(f' {name}: {t}')
for x in extra_fields: for x in extra_fields:
ans.append(' {}'.format(x)) ans.append(f' {x}')
return '\n'.join(ans) + '\n\n\n' return '\n'.join(ans) + '\n\n\n'
@ -485,7 +484,7 @@ class Options:
def opt_for_alias(self, alias: str) -> OptionDict: def opt_for_alias(self, alias: str) -> OptionDict:
opt = self.alias_map.get(alias) opt = self.alias_map.get(alias)
if opt is None: if opt is None:
raise SystemExit('Unknown option: {}'.format(emph(alias))) raise SystemExit(f'Unknown option: {emph(alias)}')
return opt return opt
def needs_arg(self, alias: str) -> bool: def needs_arg(self, alias: str) -> bool:
@ -546,7 +545,7 @@ def parse_cmdline(oc: Options, disabled: OptionSpecSeq, ans: Any, args: Optional
needs_arg = oc.needs_arg(parts[0]) needs_arg = oc.needs_arg(parts[0])
if not needs_arg: if not needs_arg:
if len(parts) != 1: if len(parts) != 1:
raise SystemExit('The {} option does not accept arguments'.format(emph(parts[0]))) raise SystemExit(f'The {emph(parts[0])} option does not accept arguments')
oc.process_arg(parts[0]) oc.process_arg(parts[0])
continue continue
if len(parts) == 1: if len(parts) == 1:
@ -561,7 +560,7 @@ def parse_cmdline(oc: Options, disabled: OptionSpecSeq, ans: Any, args: Optional
oc.process_arg(current_option, arg) oc.process_arg(current_option, arg)
current_option, state = None, NORMAL current_option, state = None, NORMAL
if state is EXPECTING_ARG: if state is EXPECTING_ARG:
raise SystemExit('An argument is required for the option: {}'.format(emph(arg))) raise SystemExit(f'An argument is required for the option: {emph(arg)}')
for key, val in oc.values_map.items(): for key, val in oc.values_map.items():
setattr(ans, key, val) setattr(ans, key, val)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
# Replay the log from --dump-commands. To use first run # Replay the log from --dump-commands. To use first run
@ -43,7 +42,7 @@ def screen_alternate_keypad_mode() -> None:
def screen_cursor_position(y: int, x: int) -> None: def screen_cursor_position(y: int, x: int) -> None:
write(CSI + '%s;%sH' % (y, x)) write(CSI + f'{y};{x}H')
def screen_cursor_forward(amt: int) -> None: def screen_cursor_forward(amt: int) -> None:

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os import os
@ -294,7 +293,7 @@ def bash_output_serializer(ans: Completions) -> str:
for word in matches: for word in matches:
if matches.trailing_space: if matches.trailing_space:
word += ' ' word += ' '
lines.append('COMPREPLY+=({})'.format(shlex.quote(word))) lines.append(f'COMPREPLY+=({shlex.quote(word)})')
# debug('\n'.join(lines)) # debug('\n'.join(lines))
return '\n'.join(lines) return '\n'.join(lines)
@ -685,7 +684,7 @@ def main(args: Sequence[str], entry_points: Iterable[str], namespaced_entry_poin
parser = parsers[cstyle] parser = parsers[cstyle]
serializer = serializers[cstyle] serializer = serializers[cstyle]
except KeyError: except KeyError:
raise SystemExit('Unknown completion style: {}'.format(cstyle)) raise SystemExit(f'Unknown completion style: {cstyle}')
words, new_word = parser(data) words, new_word = parser(data)
ans = find_completions(words, new_word, entry_points, namespaced_entry_points) ans = find_completions(words, new_word, entry_points, namespaced_entry_points)
print(serializer(ans), end='') print(serializer(ans), end='')

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
@ -105,7 +104,7 @@ def generate_class(defn: Definition, loc: str) -> Tuple[str, str]:
t(f' ans[{option.name!r}] = {func.__name__}(val)') t(f' ans[{option.name!r}] = {func.__name__}(val)')
tc_imports.add((func.__module__, func.__name__)) tc_imports.add((func.__module__, func.__name__))
cnum = int(option.name[5:]) cnum = int(option.name[5:])
color_table[cnum] = '0x{:06x}'.format(func(option.defval_as_string).__int__()) color_table[cnum] = f'0x{func(option.defval_as_string).__int__():06x}'
continue continue
else: else:
func, typ = option_type_data(option) func, typ = option_type_data(option)
@ -331,7 +330,7 @@ def generate_class(defn: Definition, loc: str) -> Tuple[str, str]:
t(' return True') t(' return True')
t(' return False') t(' return False')
preamble = ['# generated by gen-config.py DO NOT edit', '# vim:fileencoding=utf-8', ''] preamble = ['# generated by gen-config.py DO NOT edit', '']
a = preamble.append a = preamble.append
def output_imports(imports: Set, add_module_imports: bool = True) -> None: def output_imports(imports: Set, add_module_imports: bool = True) -> None:
@ -368,7 +367,7 @@ def generate_class(defn: Definition, loc: str) -> Tuple[str, str]:
a(' ' + pprint.pformat(tuple(sorted(option_names, key=natural_keys)))[1:] + ' # }}''}') a(' ' + pprint.pformat(tuple(sorted(option_names, key=natural_keys)))[1:] + ' # }}''}')
class_def = '\n'.join(preamble + ['', ''] + class_lines) class_def = '\n'.join(preamble + ['', ''] + class_lines)
preamble = ['# generated by gen-config.py DO NOT edit', '# vim:fileencoding=utf-8', ''] preamble = ['# generated by gen-config.py DO NOT edit', '']
a = preamble.append a = preamble.append
output_imports(tc_imports, False) output_imports(tc_imports, False)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import builtins import builtins
@ -35,7 +34,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)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os import os
@ -130,7 +129,7 @@ def parse_line(
return return
m = key_pat.match(line) m = key_pat.match(line)
if m is None: if m is None:
log_error('Ignoring invalid config line: {}'.format(line)) log_error(f'Ignoring invalid config line: {line}')
return return
key, val = m.groups() key, val = m.groups()
if key == 'include': if key == 'include':
@ -152,7 +151,7 @@ def parse_line(
) )
return return
if not parse_conf_item(key, val, ans): if not parse_conf_item(key, val, ans):
log_error('Ignoring unknown config key: {}'.format(key)) log_error(f'Ignoring unknown config key: {key}')
def _parse( def _parse(
@ -199,8 +198,7 @@ def resolve_config(SYSTEM_CONF: str, defconf: str, config_files_on_cmd_line: Seq
if config_files_on_cmd_line: if config_files_on_cmd_line:
if 'NONE' not in config_files_on_cmd_line: if 'NONE' not in config_files_on_cmd_line:
yield SYSTEM_CONF yield SYSTEM_CONF
for cf in config_files_on_cmd_line: yield from config_files_on_cmd_line
yield cf
else: else:
yield SYSTEM_CONF yield SYSTEM_CONF
yield defconf yield defconf
@ -240,7 +238,7 @@ def key_func() -> Tuple[Callable[..., Callable], Dict[str, Callable]]:
for name in names: for name in names:
if ans.setdefault(name, f) is not f: if ans.setdefault(name, f) is not f:
raise ValueError( raise ValueError(
'the args_func {} is being redefined'.format(name) f'the args_func {name} is being redefined'
) )
return f return f
@ -277,7 +275,7 @@ def parse_kittens_func_args(action: str, args_funcs: Dict[str, Callable]) -> Key
try: try:
func, args = parser(func, rest) func, args = parser(func, rest)
except Exception: except Exception:
raise ValueError('Unknown key action: {}'.format(action)) raise ValueError(f'Unknown key action: {action}')
if not isinstance(args, (list, tuple)): if not isinstance(args, (list, tuple)):
args = (args, ) args = (args, )

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
import json import json

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
import errno import errno
@ -89,7 +88,7 @@ def _get_config_dir() -> str:
try: try:
os.makedirs(ans, exist_ok=True) os.makedirs(ans, exist_ok=True)
except FileExistsError: except FileExistsError:
raise SystemExit('A file {} already exists. It must be a directory, not a file.'.format(ans)) raise SystemExit(f'A file {ans} already exists. It must be a directory, not a file.')
except PermissionError: except PermissionError:
make_tmp_conf() make_tmp_conf()
except OSError as err: except OSError as err:

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import os import os
@ -128,7 +127,7 @@ def compare_opts(opts: KittyOpts, print: Callable) -> None:
if f not in ignored and getattr(opts, f) != getattr(defaults, f) if f not in ignored and getattr(opts, f) != getattr(defaults, f)
] ]
field_len = max(map(len, changed_opts)) if changed_opts else 20 field_len = max(map(len, changed_opts)) if changed_opts else 20
fmt = '{{:{:d}s}}'.format(field_len) fmt = f'{{:{field_len:d}s}}'
colors = [] colors = []
for f in changed_opts: for f in changed_opts:
val = getattr(opts, f) val = getattr(opts, f)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import errno import errno

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
# #
@ -372,7 +371,7 @@ def get_bezier_limits(bezier_x: ParameterizedFunc, bezier_y: ParameterizedFunc)
if q > x: if q > x:
increment /= 2 increment /= 2
if increment < 1e-6: if increment < 1e-6:
raise ValueError('Failed to find t for x={}'.format(x)) raise ValueError(f'Failed to find t for x={x}')
else: else:
start_t += increment start_t += increment
increment = t_limit - start_t increment = t_limit - start_t
@ -1096,7 +1095,7 @@ def test_drawing(sz: int = 48, family: str = 'monospace', start: int = 0x2500, n
rgb_data = b''.join(rows) rgb_data = b''.join(rows)
width *= 32 width *= 32
height *= len(rows) height *= len(rows)
assert len(rgb_data) == width * height * 4, '{} != {}'.format(len(rgb_data), width * height * 4) assert len(rgb_data) == width * height * 4, f'{len(rgb_data)} != {width * height * 4}'
display_bitmap(rgb_data, width, height) display_bitmap(rgb_data, width, height)
finally: finally:
set_send_sprite_to_gpu(None) set_send_sprite_to_gpu(None)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
import re import re
@ -82,7 +81,7 @@ def find_best_match(family: str, bold: bool = False, italic: bool = False, ignor
# Let CoreText choose the font if the family exists, otherwise # Let CoreText choose the font if the family exists, otherwise
# fallback to Menlo # fallback to Menlo
if q not in font_map['family_map']: if q not in font_map['family_map']:
log_error('The font {} was not found, falling back to Menlo'.format(family)) log_error(f'The font {family} was not found, falling back to Menlo')
q = 'menlo' q = 'menlo'
candidates = font_map['family_map'][q] candidates = font_map['family_map'][q]
return sorted(candidates, key=score)[-1] return sorted(candidates, key=score)[-1]

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
import re import re
@ -84,7 +83,7 @@ def find_font_features(postscript_name: str) -> Tuple[FontFeature, ...]:
try: try:
parsed = parse_font_feature(feat) parsed = parse_font_feature(feat)
except ValueError: except ValueError:
log_error('Ignoring invalid font feature: {}'.format(feat)) log_error(f'Ignoring invalid font feature: {feat}')
else: else:
features.append(FontFeature(feat, parsed)) features.append(FontFeature(feat, parsed))

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
import sys import sys

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
import ctypes import ctypes

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import os import os

1
kitty/key_encoding.py generated
View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
from enum import IntEnum from enum import IntEnum

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net>
import sys import sys

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
from typing import Optional, Union from typing import Optional, Union

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from functools import partial from functools import partial

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from functools import lru_cache from functools import lru_cache

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from typing import Dict, Tuple, Type from typing import Dict, Tuple, Type

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from typing import ( from typing import (
@ -324,7 +323,7 @@ class Pair:
return 'top', 'bottom' return 'top', 'bottom'
return 'bottom', 'top' return 'bottom', 'top'
geometries = dict((group.id, group.geometry) for group in all_windows.groups if group.geometry) geometries = {group.id: group.geometry for group in all_windows.groups if group.geometry}
def extend(other: Union[int, 'Pair', None], edge: EdgeLiteral, which: EdgeLiteral) -> None: def extend(other: Union[int, 'Pair', None], edge: EdgeLiteral, which: EdgeLiteral) -> None:
if not ans[which] and other: if not ans[which] and other:

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from kitty.typing import WindowType from kitty.typing import WindowType

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from itertools import islice, repeat from itertools import islice, repeat

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from typing import Any, Dict, Generator, Iterable, List, Tuple from typing import Any, Dict, Generator, Iterable, List, Tuple

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
import locale import locale
@ -50,7 +49,7 @@ def set_custom_ibeam_cursor() -> None:
try: try:
set_custom_cursor(GLFW_IBEAM_CURSOR, images, 4, 8) set_custom_cursor(GLFW_IBEAM_CURSOR, images, 4, 8)
except Exception as e: except Exception as e:
log_error('Failed to set custom beam cursor with error: {}'.format(e)) log_error(f'Failed to set custom beam cursor with error: {e}')
def talk_to_instance(args: CLIOptions) -> None: def talk_to_instance(args: CLIOptions) -> None:
@ -61,7 +60,7 @@ def talk_to_instance(args: CLIOptions) -> None:
'cwd': os.getcwd()} 'cwd': os.getcwd()}
notify_socket = None notify_socket = None
if args.wait_for_single_instance_window_close: if args.wait_for_single_instance_window_close:
address = '\0{}-os-window-close-notify-{}-{}'.format(appname, os.getpid(), os.geteuid()) address = f'\0{appname}-os-window-close-notify-{os.getpid()}-{os.geteuid()}'
notify_socket = socket.socket(family=socket.AF_UNIX) notify_socket = socket.socket(family=socket.AF_UNIX)
try: try:
notify_socket.bind(address) notify_socket.bind(address)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import os import os
@ -45,8 +44,8 @@ def marker_from_multiple_regex(regexes: Iterable[Tuple[int, str]], flags: int =
expr = '' expr = ''
color_map = {} color_map = {}
for i, (color, spec) in enumerate(regexes): for i, (color, spec) in enumerate(regexes):
grp = 'mcg{}'.format(i) grp = f'mcg{i}'
expr += '|(?P<{}>{})'.format(grp, spec) expr += f'|(?P<{grp}>{spec})'
color_map[grp] = color color_map[grp] = color
expr = expr[1:] expr = expr[1:]
pat = re.compile(expr, flags=flags) pat = re.compile(expr, flags=flags)
@ -92,4 +91,4 @@ def marker_from_spec(ftype: str, spec: Union[str, Sequence[Tuple[int, str]]], fl
if not os.path.isabs(path): if not os.path.isabs(path):
path = os.path.join(config_dir, path) path = os.path.join(config_dir, path)
return marker_from_function(runpy.run_path(path, run_name='__marker__')["marker"]) return marker_from_function(runpy.run_path(path, run_name='__marker__')["marker"])
raise ValueError('Unknown marker type: {}'.format(ftype)) raise ValueError(f'Unknown marker type: {ftype}')

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
# Monkeypatch the stdlib multiprocessing module to work with the embedded python # Monkeypatch the stdlib multiprocessing module to work with the embedded python

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net>
from base64 import standard_b64decode from base64 import standard_b64decode

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
# After editing this file run ./gen-config.py to apply the changes # After editing this file run ./gen-config.py to apply the changes

View File

@ -1,5 +1,4 @@
# generated by gen-config.py DO NOT edit # generated by gen-config.py DO NOT edit
# vim:fileencoding=utf-8
import typing import typing
from kitty.conf.utils import ( from kitty.conf.utils import (

View File

@ -1,5 +1,4 @@
# generated by gen-config.py DO NOT edit # generated by gen-config.py DO NOT edit
# vim:fileencoding=utf-8
import typing import typing
from array import array from array import array

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
@ -104,7 +103,7 @@ def goto_tab_parse(func: str, rest: str) -> FuncArgsType:
@func_with_args('detach_window') @func_with_args('detach_window')
def detach_window_parse(func: str, rest: str) -> FuncArgsType: def detach_window_parse(func: str, rest: str) -> FuncArgsType:
if rest not in ('new', 'new-tab', 'ask', 'tab-prev', 'tab-left', 'tab-right'): if rest not in ('new', 'new-tab', 'ask', 'tab-prev', 'tab-left', 'tab-right'):
log_error('Ignoring invalid detach_window argument: {}'.format(rest)) log_error(f'Ignoring invalid detach_window argument: {rest}')
rest = 'new' rest = 'new'
return func, (rest,) return func, (rest,)
@ -112,7 +111,7 @@ def detach_window_parse(func: str, rest: str) -> FuncArgsType:
@func_with_args('detach_tab') @func_with_args('detach_tab')
def detach_tab_parse(func: str, rest: str) -> FuncArgsType: def detach_tab_parse(func: str, rest: str) -> FuncArgsType:
if rest not in ('new', 'ask'): if rest not in ('new', 'ask'):
log_error('Ignoring invalid detach_tab argument: {}'.format(rest)) log_error(f'Ignoring invalid detach_tab argument: {rest}')
rest = 'new' rest = 'new'
return func, (rest,) return func, (rest,)
@ -145,7 +144,7 @@ def signal_child_parse(func: str, rest: str) -> FuncArgsType:
def parse_change_font_size(func: str, rest: str) -> Tuple[str, Tuple[bool, Optional[str], float]]: def parse_change_font_size(func: str, rest: str) -> Tuple[str, Tuple[bool, Optional[str], float]]:
vals = rest.strip().split(maxsplit=1) vals = rest.strip().split(maxsplit=1)
if len(vals) != 2: if len(vals) != 2:
log_error('Invalid change_font_size specification: {}, treating it as default'.format(rest)) log_error(f'Invalid change_font_size specification: {rest}, treating it as default')
return func, (True, None, 0) return func, (True, None, 0)
c_all = vals[0].lower() == 'all' c_all = vals[0].lower() == 'all'
sign: Optional[str] = None sign: Optional[str] = None
@ -182,7 +181,7 @@ def neighboring_window(func: str, rest: str) -> FuncArgsType:
rest = rest.lower() rest = rest.lower()
rest = {'up': 'top', 'down': 'bottom'}.get(rest, rest) rest = {'up': 'top', 'down': 'bottom'}.get(rest, rest)
if rest not in ('left', 'right', 'top', 'bottom'): if rest not in ('left', 'right', 'top', 'bottom'):
log_error('Invalid neighbor specification: {}'.format(rest)) log_error(f'Invalid neighbor specification: {rest}')
rest = 'right' rest = 'right'
return func, [rest] return func, [rest]
@ -196,14 +195,14 @@ def resize_window(func: str, rest: str) -> FuncArgsType:
else: else:
quality = vals[0].lower() quality = vals[0].lower()
if quality not in ('taller', 'shorter', 'wider', 'narrower'): if quality not in ('taller', 'shorter', 'wider', 'narrower'):
log_error('Invalid quality specification: {}'.format(quality)) log_error(f'Invalid quality specification: {quality}')
quality = 'wider' quality = 'wider'
increment = 1 increment = 1
if len(vals) == 2: if len(vals) == 2:
try: try:
increment = int(vals[1]) increment = int(vals[1])
except Exception: except Exception:
log_error('Invalid increment specification: {}'.format(vals[1])) log_error(f'Invalid increment specification: {vals[1]}')
args = [quality, increment] args = [quality, increment]
return func, args return func, args
@ -217,7 +216,7 @@ def move_window(func: str, rest: str) -> FuncArgsType:
prest = int(prest) prest = int(prest)
except Exception: except Exception:
if prest not in ('left', 'right', 'top', 'bottom'): if prest not in ('left', 'right', 'top', 'bottom'):
log_error('Invalid move_window specification: {}'.format(rest)) log_error(f'Invalid move_window specification: {rest}')
prest = 0 prest = 0
return func, [prest] return func, [prest]
@ -269,9 +268,9 @@ def disable_ligatures_in(func: str, rest: str) -> FuncArgsType:
else: else:
where, strategy = parts where, strategy = parts
if where not in ('active', 'all', 'tab'): if where not in ('active', 'all', 'tab'):
raise ValueError('{} is not a valid set of windows to disable ligatures in'.format(where)) raise ValueError(f'{where} is not a valid set of windows to disable ligatures in')
if strategy not in ('never', 'always', 'cursor'): if strategy not in ('never', 'always', 'cursor'):
raise ValueError('{} is not a valid disable ligatures strategy'.format(strategy)) raise ValueError(f'{strategy} is not a valid disable ligatures strategy')
return func, [where, strategy] return func, [where, strategy]
@ -295,7 +294,7 @@ def parse_marker_spec(ftype: str, parts: Sequence[str]) -> Tuple[str, Union[str,
try: try:
color = max(1, min(int(parts[i]), 3)) color = max(1, min(int(parts[i]), 3))
except Exception: except Exception:
raise ValueError('color {} in marker specification is not an integer'.format(parts[i])) raise ValueError(f'color {parts[i]} in marker specification is not an integer')
sspec = parts[i + 1] sspec = parts[i + 1]
if 'regex' not in ftype: if 'regex' not in ftype:
sspec = re.escape(sspec) sspec = re.escape(sspec)
@ -305,7 +304,7 @@ def parse_marker_spec(ftype: str, parts: Sequence[str]) -> Tuple[str, Union[str,
elif ftype == 'function': elif ftype == 'function':
spec = ' '.join(parts) spec = ' '.join(parts)
else: else:
raise ValueError('Unknown marker type: {}'.format(ftype)) raise ValueError(f'Unknown marker type: {ftype}')
return ftype, spec, flags return ftype, spec, flags
@ -314,7 +313,7 @@ def toggle_marker(func: str, rest: str) -> FuncArgsType:
import shlex import shlex
parts = rest.split(maxsplit=1) parts = rest.split(maxsplit=1)
if len(parts) != 2: if len(parts) != 2:
raise ValueError('{} is not a valid marker specification'.format(rest)) raise ValueError(f'{rest} is not a valid marker specification')
ftype, spec = parts ftype, spec = parts
parts = shlex.split(spec) parts = shlex.split(spec)
return func, list(parse_marker_spec(ftype, parts)) return func, list(parse_marker_spec(ftype, parts))
@ -332,7 +331,7 @@ def scroll_to_mark(func: str, rest: str) -> FuncArgsType:
try: try:
return func, [True, max(0, min(int(q), 3))] return func, [True, max(0, min(int(q), 3))]
except Exception: except Exception:
raise ValueError('{} is not a valid scroll_to_mark destination'.format(rest)) raise ValueError(f'{rest} is not a valid scroll_to_mark destination')
return func, [parts[0] != 'next', max(0, min(int(parts[1]), 3))] return func, [parts[0] != 'next', max(0, min(int(parts[1]), 3))]
@ -371,7 +370,7 @@ def parse_mods(parts: Iterable[str], sc: str) -> Optional[int]:
mods |= getattr(defines, 'GLFW_MOD_' + map_mod(m.upper())) mods |= getattr(defines, 'GLFW_MOD_' + map_mod(m.upper()))
except AttributeError: except AttributeError:
if m.upper() != 'NONE': if m.upper() != 'NONE':
log_error('Shortcut: {} has unknown modifier, ignoring'.format(sc)) log_error(f'Shortcut: {sc} has unknown modifier, ignoring')
return None return None
return mods return mods
@ -493,9 +492,9 @@ def url_style(x: str) -> int:
return url_style_map.get(x, url_style_map['curly']) return url_style_map.get(x, url_style_map['curly'])
url_style_map = dict( url_style_map = {
((v, i) for i, v in enumerate('none single double curly'.split())) v: i for i, v in enumerate('none single double curly'.split())
) }
def url_prefixes(x: str) -> Tuple[str, ...]: def url_prefixes(x: str) -> Tuple[str, ...]:
@ -528,13 +527,13 @@ def parse_layout_names(parts: Iterable[str]) -> List[str]:
continue continue
name = p.partition(':')[0] name = p.partition(':')[0]
if name not in all_layouts: if name not in all_layouts:
raise ValueError('The window layout {} is unknown'.format(p)) raise ValueError(f'The window layout {p} is unknown')
ans.append(p) ans.append(p)
return uniq(ans) return uniq(ans)
def to_layout_names(raw: str) -> List[str]: def to_layout_names(raw: str) -> List[str]:
return parse_layout_names((x.strip() for x in raw.split(','))) return parse_layout_names(x.strip() for x in raw.split(','))
def window_border_width(x: Union[str, int, float]) -> Tuple[float, str]: def window_border_width(x: Union[str, int, float]) -> Tuple[float, str]:
@ -721,7 +720,7 @@ def font_features(val: str) -> Iterable[Tuple[str, Tuple[FontFeature, ...]]]:
return return
parts = val.split() parts = val.split()
if len(parts) < 2: if len(parts) < 2:
log_error("Ignoring invalid font_features {}".format(val)) log_error(f"Ignoring invalid font_features {val}")
return return
if parts[0]: if parts[0]:
features = [] features = []
@ -729,7 +728,7 @@ def font_features(val: str) -> Iterable[Tuple[str, Tuple[FontFeature, ...]]]:
try: try:
parsed = defines.parse_font_feature(feat) parsed = defines.parse_font_feature(feat)
except ValueError: except ValueError:
log_error('Ignoring invalid font feature: {}'.format(feat)) log_error(f'Ignoring invalid font feature: {feat}')
else: else:
features.append(FontFeature(feat, parsed)) features.append(FontFeature(feat, parsed))
yield parts[0], tuple(features) yield parts[0], tuple(features)
@ -886,7 +885,7 @@ def parse_map(val: str) -> Iterable[KeyDefinition]:
return return
if key == 0: if key == 0:
if mods is not None: if mods is not None:
log_error('Shortcut: {} has unknown key, ignoring'.format(sc)) log_error(f'Shortcut: {sc} has unknown key, ignoring')
return return
if trigger is None: if trigger is None:
trigger = SingleKey(mods, is_native, key) trigger = SingleKey(mods, is_native, key)
@ -900,7 +899,7 @@ def parse_map(val: str) -> Iterable[KeyDefinition]:
return return
if key == 0: if key == 0:
if mods is not None: if mods is not None:
log_error('Shortcut: {} has unknown key, ignoring'.format(sc)) log_error(f'Shortcut: {sc} has unknown key, ignoring')
return return
try: try:
paction = parse_key_action(action) paction = parse_key_action(action)
@ -961,7 +960,7 @@ def parse_mouse_map(val: str) -> Iterable[MouseMapping]:
def deprecated_hide_window_decorations_aliases(key: str, val: str, ans: Dict[str, Any]) -> None: def deprecated_hide_window_decorations_aliases(key: str, val: str, ans: Dict[str, Any]) -> None:
if not hasattr(deprecated_hide_window_decorations_aliases, key): if not hasattr(deprecated_hide_window_decorations_aliases, key):
setattr(deprecated_hide_window_decorations_aliases, key, True) setattr(deprecated_hide_window_decorations_aliases, key, True)
log_error('The option {} is deprecated. Use hide_window_decorations instead.'.format(key)) log_error(f'The option {key} is deprecated. Use hide_window_decorations instead.')
if to_bool(val): if to_bool(val):
if is_macos and key == 'macos_hide_titlebar' or (not is_macos and key == 'x11_hide_window_decorations'): if is_macos and key == 'macos_hide_titlebar' or (not is_macos and key == 'x11_hide_window_decorations'):
ans['hide_window_decorations'] = True ans['hide_window_decorations'] = True
@ -970,7 +969,7 @@ def deprecated_hide_window_decorations_aliases(key: str, val: str, ans: Dict[str
def deprecated_macos_show_window_title_in_menubar_alias(key: str, val: str, ans: Dict[str, Any]) -> None: def deprecated_macos_show_window_title_in_menubar_alias(key: str, val: str, ans: Dict[str, Any]) -> None:
if not hasattr(deprecated_macos_show_window_title_in_menubar_alias, key): if not hasattr(deprecated_macos_show_window_title_in_menubar_alias, key):
setattr(deprecated_macos_show_window_title_in_menubar_alias, 'key', True) setattr(deprecated_macos_show_window_title_in_menubar_alias, 'key', True)
log_error('The option {} is deprecated. Use macos_show_window_title_in menubar instead.'.format(key)) log_error(f'The option {key} is deprecated. Use macos_show_window_title_in menubar instead.')
macos_show_window_title_in = ans.get('macos_show_window_title_in', 'all') macos_show_window_title_in = ans.get('macos_show_window_title_in', 'all')
if to_bool(val): if to_bool(val):
if macos_show_window_title_in == 'none': if macos_show_window_title_in == 'none':
@ -996,6 +995,6 @@ def deprecated_send_text(key: str, val: str, ans: Dict[str, Any]) -> None:
return abort('Incomplete') return abort('Incomplete')
mode, sc = parts[:2] mode, sc = parts[:2]
text = ' '.join(parts[2:]) text = ' '.join(parts[2:])
key_str = '{} send_text {} {}'.format(sc, mode, text) key_str = f'{sc} send_text {mode} {text}'
for k in parse_map(key_str): for k in parse_map(key_str):
ans['map'].append(k) ans['map'].append(k)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from typing import Any, Callable, Dict, NamedTuple, Tuple from typing import Any, Callable, Dict, NamedTuple, Tuple

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from contextlib import suppress from contextlib import suppress
@ -37,7 +36,7 @@ class MatchError(ValueError):
hide_traceback = True hide_traceback = True
def __init__(self, expression: str, target: str = 'windows'): def __init__(self, expression: str, target: str = 'windows'):
ValueError.__init__(self, 'No matching {} for expression: {}'.format(target, expression)) ValueError.__init__(self, f'No matching {target} for expression: {expression}')
class OpacityError(ValueError): class OpacityError(ValueError):
@ -199,15 +198,15 @@ class RemoteCommand:
def cli_params_for(command: RemoteCommand) -> Tuple[Callable[[], str], str, str, str]: def cli_params_for(command: RemoteCommand) -> Tuple[Callable[[], str], str, str, str]:
return (command.options_spec or '\n').format, command.argspec, command.desc, '{} @ {}'.format(appname, command.name) return (command.options_spec or '\n').format, command.argspec, command.desc, f'{appname} @ {command.name}'
def parse_subcommand_cli(command: RemoteCommand, args: ArgsType) -> Tuple[Any, ArgsType]: def parse_subcommand_cli(command: RemoteCommand, args: ArgsType) -> Tuple[Any, ArgsType]:
opts, items = parse_args(args[1:], *cli_params_for(command), result_class=command.options_class) opts, items = parse_args(args[1:], *cli_params_for(command), result_class=command.options_class)
if command.args_count is not None and command.args_count != len(items): if command.args_count is not None and command.args_count != len(items):
if command.args_count == 0: if command.args_count == 0:
raise SystemExit('Unknown extra argument(s) supplied to {}'.format(command.name)) raise SystemExit(f'Unknown extra argument(s) supplied to {command.name}')
raise SystemExit('Must specify exactly {} argument(s) for {}'.format(command.args_count, command.name)) raise SystemExit(f'Must specify exactly {command.args_count} argument(s) for {command.name}')
return opts, items return opts, items

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from typing import TYPE_CHECKING, Optional from typing import TYPE_CHECKING, Optional

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from typing import TYPE_CHECKING, Optional from typing import TYPE_CHECKING, Optional

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from typing import TYPE_CHECKING, Optional, Union from typing import TYPE_CHECKING, Optional, Union

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from typing import Any, Optional from typing import Any, Optional

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from typing import TYPE_CHECKING, Optional from typing import TYPE_CHECKING, Optional

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>

Some files were not shown because too many files have changed in this diff Show More