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
159 changed files with 194 additions and 353 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import atexit
@@ -428,7 +427,7 @@ class DiffHandler(Handler):
elif self.state is MESSAGE:
self.cmd.styled(self.message, reverse=True)
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)
if self.current_search is None:
counts = '{}{}{}'.format(
@@ -437,7 +436,7 @@ class DiffHandler(Handler):
styled(str(self.removed_count), fg=self.opts.highlight_removed_bg)
)
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
prefix = styled(':', fg=self.opts.margin_fg)
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.')
for f in left, right:
if not os.path.exists(f):
raise SystemExit('{} does not exist'.format(f))
raise SystemExit(f'{f} does not exist')
loop = Loop()
handler = DiffHandler(cli_opts, opts, left, right)

View File

@@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import concurrent.futures
@@ -151,9 +150,9 @@ class Hunk:
# Sanity check
c = self.chunks[-1]
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:
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:
c.finalize()
@@ -240,18 +239,18 @@ class Differ:
try:
ok, returncode, output = future.result()
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:
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:
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)
right_lines = lines_for_path(right_path)
try:
patch = parse_patch(output)
except Exception:
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:
ans[key] = patch
return ans

View File

@@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import warnings
@@ -42,7 +41,7 @@ class Ref:
def __repr__(self) -> str:
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):
@@ -264,7 +263,7 @@ def render_diff_pair(
def hunk_title(hunk_num: int, hunk: Hunk, margin_size: int, available_cols: int) -> str:
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))
@@ -539,7 +538,7 @@ class RenderDiff:
assert other_path is not None
ans = yield_lines_from(rename_lines(path, other_path, args, columns, margin_size), item_ref)
else:
raise ValueError('Unsupported item type: {}'.format(item_type))
raise ValueError(f'Unsupported item type: {item_type}')
yield from ans
if i < last_item_num:
yield Line('', item_ref)

View File

@@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import re
@@ -30,7 +29,7 @@ class Search:
try:
self.pat = re.compile(query, flags=re.UNICODE | re.IGNORECASE)
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:
self.matches = {}
@@ -68,6 +67,6 @@ class Search:
return False
write(self.style)
for start, text in highlights:
write('\r\x1b[{}C{}'.format(start, text))
write(f'\r\x1b[{start}C{text}')
write('\x1b[m')
return True

View File

@@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os
@@ -366,7 +365,7 @@ def functions_for(args: HintsCLIOptions) -> Tuple[str, List[PostprocessorFunc]]:
chars = args.word_characters
if chars is None:
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))
else:
pattern = args.regex

View File

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

View File

@@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
import contextlib
@@ -145,7 +144,7 @@ def get_screen_size() -> ScreenSize:
@run_once
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:
@@ -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
elif align == 'right':
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:
@@ -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:
global can_transfer_with_files
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()
try:
received = b''
@@ -466,7 +465,7 @@ def process_single_item(
with socket_timeout(30):
urlretrieve(item, filename=tf.name)
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
is_tempfile = True
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:
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_)
if cli_opts.print_window_size:
screen_size_function.cache_clear()
with open(os.ctermid()) as 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)
if not sys.stdout.isatty():
@@ -511,7 +510,7 @@ def main(args: List[str] = sys.argv) -> None:
if stdin_data:
items.insert(0, stdin_data)
sys.stdin.close()
sys.stdin = open(os.ctermid(), 'r')
sys.stdin = open(os.ctermid())
screen_size = get_screen_size_function()
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:
parsed_opts.place = parse_place(cli_opts.place)
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:
parsed_opts.z_index = parse_z_index(cli_opts.z_index)
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 not detect_support(wait_for=cli_opts.detection_timeout, silent=True):

View File

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

View File

@@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os
@@ -116,7 +115,7 @@ def setup_x11_window(win_id: int) -> None:
'-id', str(win_id), '-format', '_NET_WM_WINDOW_TYPE', '32a',
'-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)

View File

@@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import re
@@ -28,10 +27,10 @@ class Query:
def __init__(self) -> None:
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:
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:
return unhexlify(res).decode('utf-8')
@@ -234,7 +233,7 @@ def main(args: List[str] = sys.argv) -> None:
options_spec,
usage,
help_text,
'{} +kitten query_terminal'.format(appname),
f'{appname} +kitten query_terminal',
result_class=QueryTerminalCLIOptions
)
queries: List[str] = list(items_)

View File

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

View File

@@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
@@ -43,7 +42,7 @@ class Resize(Handler):
if is_decrease:
increment *= -1
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)
payload = resize_window.message_to_kitty(global_opts, opts, items)
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()
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(
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
# vim:fileencoding=utf-8
# 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}
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)}
@@ -111,7 +110,7 @@ def deserialize(output: str) -> Any:
prefix, sz, rest = output.split(' ', 2)
return json.loads(rest[:int(sz)])
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:
@@ -120,7 +119,7 @@ def run_kitten(kitten: str, run_name: str = '__main__') -> None:
kitten = resolved_kitten(kitten)
set_debug(kitten)
try:
runpy.run_module('kittens.{}.main'.format(kitten), run_name=run_name)
runpy.run_module(f'kittens.{kitten}.main', run_name=run_name)
return
except ImportError:
pass

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import os
@@ -336,11 +335,11 @@ class Dircolors:
def _format_code(self, text: str, code: str) -> str:
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:
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:
mode = sr.st_mode

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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