From ba0f61d752d4a82b18049d147a19872e5e31bf49 Mon Sep 17 00:00:00 2001 From: pagedown Date: Sat, 29 Jan 2022 20:17:46 +0800 Subject: [PATCH] Refactor: More f-string for kitty --- glfw/glfw.py | 2 +- kitty/child.py | 4 ++-- kitty/cli_stub.py | 2 +- kitty/complete.py | 10 +++++----- kitty/config.py | 2 +- kitty/guess_mime_type.py | 2 +- kitty/key_encoding.py | 2 +- kitty/key_names.py | 2 +- kitty/launch.py | 2 +- kitty/layout/base.py | 2 +- kitty/main.py | 6 +++--- kitty/notify.py | 6 +++--- kitty/open_actions.py | 2 +- kitty/options/utils.py | 10 +++++----- kitty/rgb.py | 2 +- kitty/shell.py | 2 +- kitty/tab_bar.py | 6 +++--- kitty/terminfo.py | 4 ++-- 18 files changed, 34 insertions(+), 34 deletions(-) diff --git a/glfw/glfw.py b/glfw/glfw.py index 6cfb89650..e7a5cf0c7 100755 --- a/glfw/glfw.py +++ b/glfw/glfw.py @@ -80,7 +80,7 @@ def init_env( ) -> Env: ans = env.copy() ans.cflags.append('-fPIC') - ans.cppflags.append('-D_GLFW_' + module.upper()) + ans.cppflags.append(f'-D_GLFW_{module.upper()}') ans.cppflags.append('-D_GLFW_BUILD_DLL') with open(os.path.join(base, 'source-info.json')) as f: diff --git a/kitty/child.py b/kitty/child.py index 1bca54b7f..a8b990fc9 100644 --- a/kitty/child.py +++ b/kitty/child.py @@ -62,7 +62,7 @@ else: except Exception: continue try: - with open('/proc/' + x + '/stat', 'rb') as f: + with open(f'/proc/{x}/stat', 'rb') as f: raw = f.read().decode('utf-8') except OSError: continue @@ -268,7 +268,7 @@ class Child: # https://github.com/kovidgoyal/kitty/issues/1870 # xterm, urxvt, konsole and gnome-terminal do not do it in my # testing. - argv[0] = ('-' + exe.split('/')[-1]) + argv[0] = (f'-{exe.split("/")[-1]}') exe = which(exe) or exe pid = fast_data_types.spawn(exe, self.cwd, tuple(argv), env, master, slave, stdin_read_fd, stdin_write_fd, ready_read_fd, ready_write_fd) os.close(slave) diff --git a/kitty/cli_stub.py b/kitty/cli_stub.py index c14f83549..53714af3d 100644 --- a/kitty/cli_stub.py +++ b/kitty/cli_stub.py @@ -82,7 +82,7 @@ def generate_stub() -> None: for cmd_name in all_command_names(): cmd = command_for_name(cmd_name) if cmd.options_spec: - do(cmd.options_spec, cmd.__class__.__name__ + 'RCOptions') + do(cmd.options_spec, f'{cmd.__class__.__name__}RCOptions') save_type_stub(text, __file__) diff --git a/kitty/complete.py b/kitty/complete.py index dcaf14841..d3a49f978 100644 --- a/kitty/complete.py +++ b/kitty/complete.py @@ -270,7 +270,7 @@ def zsh_output_serializer(ans: Completions) -> str: yield ans for description, matches in ans.match_groups.items(): - cmd = ['compadd', '-U', '-J', shlex.quote(description), '-X', shlex.quote('%B' + description + '%b')] + cmd = ['compadd', '-U', '-J', shlex.quote(description), '-X', shlex.quote(f'%B{description}%b')] if not matches.trailing_space: cmd += ['-S', '""'] if matches.is_files: @@ -350,10 +350,10 @@ def fish2_output_serializer(ans: Completions) -> str: def completions_for_first_word(ans: Completions, prefix: str, entry_points: Iterable[str], namespaced_entry_points: Iterable[str]) -> None: - cmds = ['@' + c for c in remote_control_command_names()] + cmds = [f'@{c}' for c in remote_control_command_names()] ans.add_match_group('Entry points', { k: '' for k in - list(entry_points) + cmds + ['+' + k for k in namespaced_entry_points] + list(entry_points) + cmds + [f'+{k}' for k in namespaced_entry_points] if not prefix or k.startswith(prefix) }) if prefix: @@ -443,7 +443,7 @@ def complete_alias_map( long_opt = option_map.get(parts[0]) if long_opt is not None and complete_args is not None: complete_args(ans, long_opt, parts[1], Delegate()) - ans.add_prefix(parts[0] + '=') + ans.add_prefix(f'{parts[0]}=') return opt = option_map.get(w) if w is last_word and not new_word: @@ -682,7 +682,7 @@ def find_completions(words: Sequence[str], new_word: bool, entry_points: Iterabl if words[0].startswith('@'): if len(words) == 1 and not new_word: prefix = words[0] - ans.add_match_group('Remote control commands', {'@' + c: '' for c in remote_control_command_names() if c.startswith(prefix)}) + ans.add_match_group('Remote control commands', {f'@{c}': '' for c in remote_control_command_names() if c.startswith(prefix)}) else: complete_remote_command(ans, words[0][1:], words[1:], new_word) if words[0] == '+': diff --git a/kitty/config.py b/kitty/config.py index 1df21c944..745e1c07d 100644 --- a/kitty/config.py +++ b/kitty/config.py @@ -54,7 +54,7 @@ def atomic_save(data: bytes, path: str) -> None: @contextmanager def cached_values_for(name: str) -> Generator[Dict[str, Any], None, None]: - cached_path = os.path.join(cache_dir(), name + '.json') + cached_path = os.path.join(cache_dir(), f'{name}.json') cached_values: Dict[str, Any] = {} try: with open(cached_path, 'rb') as f: diff --git a/kitty/guess_mime_type.py b/kitty/guess_mime_type.py index cc03e8b6c..e392cacf8 100644 --- a/kitty/guess_mime_type.py +++ b/kitty/guess_mime_type.py @@ -58,7 +58,7 @@ def guess_type(path: str, allow_filesystem_access: bool = False) -> Optional[str ext = path.rpartition('.')[-1].lower() mt = known_extensions.get(ext) if mt in text_mimes: - mt = 'text/' + mt.split('/', 1)[-1] + mt = f'text/{mt.split("/", 1)[-1]}' if not mt and is_rc_file(path): mt = 'text/plain' if not mt and is_folder(path): diff --git a/kitty/key_encoding.py b/kitty/key_encoding.py index 02f1d38c7..49ab1ad58 100644 --- a/kitty/key_encoding.py +++ b/kitty/key_encoding.py @@ -181,7 +181,7 @@ class EventType(IntEnum): @lru_cache(maxsize=128) def parse_shortcut(spec: str) -> ParsedShortcut: if spec.endswith('+'): - spec = spec[:-1] + 'plus' + spec = f'{spec[:-1]}plus' parts = spec.split('+') key_name = parts[-1] key_name = functional_key_name_aliases.get(key_name.upper(), key_name) diff --git a/kitty/key_names.py b/kitty/key_names.py index 35e639193..edda8b252 100644 --- a/kitty/key_names.py +++ b/kitty/key_names.py @@ -63,7 +63,7 @@ else: import ctypes for suffix in ('.0', ''): with suppress(Exception): - lib = ctypes.CDLL('libxkbcommon.so' + suffix) + lib = ctypes.CDLL(f'libxkbcommon.so{suffix}') break else: from ctypes.util import find_library diff --git a/kitty/launch.py b/kitty/launch.py index 33365025b..f8b4ee932 100644 --- a/kitty/launch.py +++ b/kitty/launch.py @@ -369,7 +369,7 @@ def launch( if opts.stdin_add_formatting: if q in ('@screen', '@screen_scrollback', '@alternate', '@alternate_scrollback', '@first_cmd_output_on_screen', '@last_cmd_output', '@last_visited_cmd_output'): - q = '@ansi_' + q[1:] + q = f'@ansi_{q[1:]}' if opts.stdin_add_line_wrap_markers: q += '_wrap' penv, stdin = boss.process_stdin_source(window=active, stdin=q, copy_pipe_data=pipe_data) diff --git a/kitty/layout/base.py b/kitty/layout/base.py index 1843c6ae2..9310248bb 100644 --- a/kitty/layout/base.py +++ b/kitty/layout/base.py @@ -217,7 +217,7 @@ class Layout: self.blank_rects: List[Rect] = [] self.layout_opts = self.parse_layout_opts(layout_opts) assert self.name is not None - self.full_name = self.name + ((':' + layout_opts) if layout_opts else '') + self.full_name = f'{self.name}:{layout_opts}' if layout_opts else self.name self.remove_all_biases() def bias_increment_for_cell(self, is_horizontal: bool) -> float: diff --git a/kitty/main.py b/kitty/main.py index 458bb455e..6a1ba10fa 100644 --- a/kitty/main.py +++ b/kitty/main.py @@ -44,7 +44,7 @@ def set_custom_ibeam_cursor() -> None: data = f.read() rgba_data, width, height = load_png_data(data) c2x = os.path.splitext(beam_cursor_data_file) - with open(c2x[0] + '@2x' + c2x[1], 'rb') as f: + with open(f'{c2x[0]}@2x{c2x[1]}', 'rb') as f: data = f.read() rgba_data2, width2, height2 = load_png_data(data) images = (rgba_data, width, height), (rgba_data2, width2, height2) @@ -138,7 +138,7 @@ def get_macos_shortcut_for( def set_x11_window_icon() -> None: # max icon size on X11 64bits is 128x128 path, ext = os.path.splitext(logo_png_file) - set_default_window_icon(path + '-128' + ext) + set_default_window_icon(f'{path}-128{ext}') def _run_app(opts: Options, args: CLIOptions, bad_lines: Sequence[BadLine] = ()) -> None: @@ -220,7 +220,7 @@ def ensure_macos_locale() -> None: lang = 'en_US' else: log_error(f'Could not set LANG Cocoa returns language as: {lang}') - os.environ['LANG'] = lang + '.UTF-8' + os.environ['LANG'] = f'{lang}.UTF-8' @contextmanager diff --git a/kitty/notify.py b/kitty/notify.py index 2ed16bae4..00dfff5a6 100644 --- a/kitty/notify.py +++ b/kitty/notify.py @@ -113,7 +113,7 @@ def parse_osc_99(raw: str) -> NotificationCommand: elif k == 'd': cmd.done = v != '0' elif k == 'a': - cmd.actions += ',' + v + cmd.actions += f',{v}' if payload_type not in ('body', 'title'): log_error(f'Malformed OSC 99: unknown payload type: {payload_type}') return NotificationCommand() @@ -139,7 +139,7 @@ def limit_size(x: str) -> str: def merge_osc_99(prev: NotificationCommand, cmd: NotificationCommand) -> NotificationCommand: if prev.done or prev.identifier != cmd.identifier: return cmd - cmd.actions = limit_size(prev.actions + ',' + cmd.actions) + cmd.actions = limit_size(f'{prev.actions},{cmd.actions}') cmd.title = limit_size(prev.title + cmd.title) cmd.body = limit_size(prev.body + cmd.body) return cmd @@ -198,7 +198,7 @@ def notify_with_command(cmd: NotificationCommand, window_id: int, notify_impleme title = cmd.title or cmd.body body = cmd.body if cmd.title else '' if title: - identifier = 'i' + str(next(id_counter)) + identifier = f'i{next(id_counter)}' notify_implementation(title, body, identifier) register_identifier(identifier, cmd, window_id) diff --git a/kitty/open_actions.py b/kitty/open_actions.py index b4bf34698..5009b81da 100644 --- a/kitty/open_actions.py +++ b/kitty/open_actions.py @@ -114,7 +114,7 @@ def url_matches_criterion(purl: 'ParseResult', url: str, unquoted_path: str, mc: path = unquoted_path.lower() for ext in mc.value.split(','): ext = ext.strip() - if path.endswith('.' + ext): + if path.endswith(f'.{ext}'): return True return False diff --git a/kitty/options/utils.py b/kitty/options/utils.py index 1a735b62d..1e90097a7 100644 --- a/kitty/options/utils.py +++ b/kitty/options/utils.py @@ -379,7 +379,7 @@ def parse_mods(parts: Iterable[str], sc: str) -> Optional[int]: mods = 0 for m in parts: try: - mods |= getattr(defines, 'GLFW_MOD_' + map_mod(m.upper())) + mods |= getattr(defines, f'GLFW_MOD_{map_mod(m.upper())}') except AttributeError: if m.upper() != 'NONE': log_error(f'Shortcut: {sc} has unknown modifier, ignoring') @@ -394,7 +394,7 @@ def to_modifiers(val: str) -> int: def parse_shortcut(sc: str) -> SingleKey: if sc.endswith('+') and len(sc) > 1: - sc = sc[:-1] + 'plus' + sc = f'{sc[:-1]}plus' parts = sc.split('+') mods = 0 if len(parts) > 1: @@ -895,13 +895,13 @@ def resolve_aliases_and_parse_actions( parts = rest.split(maxsplit=1) if parts[0] != alias.name: continue - new_defn = possible_alias + ' ' + alias.value + ((' ' + parts[1]) if len(parts) > 1 else '') + new_defn = f'{possible_alias} {alias.value} {f" {parts[1]}" if len(parts) > 1 else ""}' new_aliases = aliases.copy() new_aliases[possible_alias] = [a for a in aliases[possible_alias] if a is not alias] yield from resolve_aliases_and_parse_actions(new_defn, new_aliases, map_type) return else: # action_alias - new_defn = alias.value + ((' ' + rest) if rest else '') + new_defn = f'{alias.value} {rest}' if rest else alias.value new_aliases = aliases.copy() new_aliases.pop(possible_alias) yield from resolve_aliases_and_parse_actions(new_defn, new_aliases, map_type) @@ -909,7 +909,7 @@ def resolve_aliases_and_parse_actions( if possible_alias == 'combine': sep, rest = rest.split(maxsplit=1) - parts = re.split(r'\s*' + re.escape(sep) + r'\s*', rest) + parts = re.split(fr'\s*{re.escape(sep)}\s*', rest) for x in parts: if x: yield from resolve_aliases_and_parse_actions(x, aliases, map_type) diff --git a/kitty/rgb.py b/kitty/rgb.py index ff0e9b3e6..3f81c1950 100644 --- a/kitty/rgb.py +++ b/kitty/rgb.py @@ -28,7 +28,7 @@ def parse_single_color(c: str) -> int: def parse_sharp(spec: str) -> Optional[Color]: if len(spec) in (3, 6, 9, 12): part_len = len(spec) // 3 - colors = re.findall(r'[a-fA-F0-9]{%d}' % part_len, spec) + colors = re.findall(fr'[a-fA-F0-9]{{{part_len}}}', spec) return Color(*map(parse_single_color, colors)) return None diff --git a/kitty/shell.py b/kitty/shell.py index 639837647..6bbedd732 100644 --- a/kitty/shell.py +++ b/kitty/shell.py @@ -221,7 +221,7 @@ def real_main(global_opts: RCOptions) -> None: if e.code != 0: print(end=output_prefix, flush=True) print_err(e) - print_err('Use "{}" to see how to use this command.'.format(emph('help ' + cmd))) + print_err('Use "{}" to see how to use this command.'.format(emph(f'help {cmd}'))) continue except Exception: print(end=output_prefix, flush=True) diff --git a/kitty/tab_bar.py b/kitty/tab_bar.py index 686a4356f..327dc3bcd 100644 --- a/kitty/tab_bar.py +++ b/kitty/tab_bar.py @@ -102,14 +102,14 @@ class ColorFormatter: ans = '9' elif q == 'tab': col = color_from_int((self.draw_data.tab_bg if self.which == '4' else self.draw_data.tab_fg)(self.tab_data)) - ans = '8' + color_as_sgr(col) + ans = f'8{color_as_sgr(col)}' else: if name.startswith('_'): - q = '#' + name[1:] + q = f'#{name[1:]}' c = to_color(q) if c is None: raise AttributeError(f'{name} is not a valid color') - ans = '8' + color_as_sgr(c) + ans = f'8{color_as_sgr(c)}' return f'\x1b[{self.which}{ans}m' diff --git a/kitty/terminfo.py b/kitty/terminfo.py index c487a8524..f14744928 100644 --- a/kitty/terminfo.py +++ b/kitty/terminfo.py @@ -471,8 +471,8 @@ def get_capabilities(query_string: str, opts: 'Options') -> Generator[str, None, def result(encoded_query_name: str, x: Optional[str] = None) -> str: if x is None: - return '0+r' + encoded_query_name - return '1+r' + encoded_query_name + '=' + hexlify(str(x).encode('utf-8')).decode('ascii') + return f'0+r{encoded_query_name}' + return f'1+r{encoded_query_name}={hexlify(str(x).encode("utf-8")).decode("ascii")}' for encoded_query_name in query_string.split(';'): name = qname = unhexlify(encoded_query_name).decode('utf-8')