Refactor: More f-string for kittens
This commit is contained in:
parent
4110074580
commit
4a3ed62809
@ -101,7 +101,7 @@ def remote_hostname(path: str) -> Tuple[Optional[str], Optional[str]]:
|
|||||||
def resolve_remote_name(path: str, default: str) -> str:
|
def resolve_remote_name(path: str, default: str) -> str:
|
||||||
remote_dir, rh = remote_hostname(path)
|
remote_dir, rh = remote_hostname(path)
|
||||||
if remote_dir and rh:
|
if remote_dir and rh:
|
||||||
return rh + ':' + os.path.relpath(path, remote_dir)
|
return f'{rh}:{os.path.relpath(path, remote_dir)}'
|
||||||
return default
|
return default
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -97,7 +97,7 @@ def highlight_data(code: str, filename: str, aliases: Optional[Dict[str, str]] =
|
|||||||
base, ext = os.path.splitext(filename)
|
base, ext = os.path.splitext(filename)
|
||||||
alias = aliases.get(ext[1:])
|
alias = aliases.get(ext[1:])
|
||||||
if alias is not None:
|
if alias is not None:
|
||||||
filename = base + '.' + alias
|
filename = f'{base}.{alias}'
|
||||||
try:
|
try:
|
||||||
lexer = get_lexer_for_filename(filename, stripnl=False)
|
lexer = get_lexer_for_filename(filename, stripnl=False)
|
||||||
except ClassNotFound:
|
except ClassNotFound:
|
||||||
|
|||||||
@ -347,7 +347,7 @@ class DiffHandler(Handler):
|
|||||||
text = line.text
|
text = line.text
|
||||||
if line.image_data is not None:
|
if line.image_data is not None:
|
||||||
image_involved = True
|
image_involved = True
|
||||||
self.write('\r\x1b[K' + text + '\x1b[0m')
|
self.write(f'\r\x1b[K{text}\x1b[0m')
|
||||||
if self.current_search is not None:
|
if self.current_search is not None:
|
||||||
self.current_search.highlight_line(self.write, lpos)
|
self.current_search.highlight_line(self.write, lpos)
|
||||||
if i < num - 1:
|
if i < num - 1:
|
||||||
@ -465,7 +465,7 @@ class DiffHandler(Handler):
|
|||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
counts = styled(f'{len(self.current_search)} matches', fg=self.opts.margin_fg)
|
counts = styled(f'{len(self.current_search)} matches', fg=self.opts.margin_fg)
|
||||||
suffix = counts + ' ' + scroll_frac
|
suffix = f'{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)
|
||||||
text = '{}{}{}'.format(prefix, ' ' * filler, suffix)
|
text = '{}{}{}'.format(prefix, ' ' * filler, suffix)
|
||||||
|
|||||||
@ -244,14 +244,14 @@ class Differ:
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
return f'Running git diff for {left_path} vs. {right_path} generated an exception: {e}'
|
return f'Running git diff for {left_path} vs. {right_path} generated an exception: {e}'
|
||||||
if not ok:
|
if not ok:
|
||||||
return output + f'\nRunning git diff for {left_path} vs. {right_path} failed'
|
return f'{output}\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() + f'\nParsing diff for {left_path} vs. {right_path} failed'
|
return f'{traceback.format_exc()}\nParsing diff for {left_path} vs. {right_path} failed'
|
||||||
else:
|
else:
|
||||||
ans[key] = patch
|
ans[key] = patch
|
||||||
return ans
|
return ans
|
||||||
|
|||||||
@ -101,7 +101,7 @@ def human_readable(size: int, sep: str = ' ') -> str:
|
|||||||
s = s[:s.find(".")+2]
|
s = s[:s.find(".")+2]
|
||||||
if s.endswith('.0'):
|
if s.endswith('.0'):
|
||||||
s = s[:-2]
|
s = s[:-2]
|
||||||
return s + sep + suffix
|
return f'{s}{sep}{suffix}'
|
||||||
|
|
||||||
|
|
||||||
def fit_in(text: str, count: int) -> str:
|
def fit_in(text: str, count: int) -> str:
|
||||||
@ -110,7 +110,7 @@ def fit_in(text: str, count: int) -> str:
|
|||||||
return text
|
return text
|
||||||
if count > 1:
|
if count > 1:
|
||||||
p = truncate_point_for_length(text, count - 1)
|
p = truncate_point_for_length(text, count - 1)
|
||||||
return text[:p] + '…'
|
return f'{text[:p]}…'
|
||||||
|
|
||||||
|
|
||||||
def fill_in(text: str, sz: int) -> str:
|
def fill_in(text: str, sz: int) -> str:
|
||||||
@ -127,8 +127,8 @@ def place_in(text: str, sz: int) -> str:
|
|||||||
def format_func(which: str) -> Callable[[str], str]:
|
def format_func(which: str) -> Callable[[str], str]:
|
||||||
def formatted(text: str) -> str:
|
def formatted(text: str) -> str:
|
||||||
fmt = formats[which]
|
fmt = formats[which]
|
||||||
return '\x1b[' + fmt + 'm' + text + '\x1b[0m'
|
return f'\x1b[{fmt}m{text}\x1b[0m'
|
||||||
formatted.__name__ = which + '_format'
|
formatted.__name__ = f'{which}_format'
|
||||||
return formatted
|
return formatted
|
||||||
|
|
||||||
|
|
||||||
@ -148,8 +148,8 @@ highlight_map = {'remove': ('removed_highlight', 'removed'), 'add': ('added_high
|
|||||||
|
|
||||||
def highlight_boundaries(ltype: str) -> Tuple[str, str]:
|
def highlight_boundaries(ltype: str) -> Tuple[str, str]:
|
||||||
s, e = highlight_map[ltype]
|
s, e = highlight_map[ltype]
|
||||||
start = '\x1b[' + formats[s] + 'm'
|
start = f'\x1b[{formats[s]}m'
|
||||||
stop = '\x1b[' + formats[e] + 'm'
|
stop = f'\x1b[{formats[e]}m'
|
||||||
return start, stop
|
return start, stop
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -729,7 +729,7 @@ def linenum_handle_result(args: List[str], data: Dict[str, Any], target_window_i
|
|||||||
else:
|
else:
|
||||||
import shlex
|
import shlex
|
||||||
text = ' '.join(shlex.quote(arg) for arg in cmd)
|
text = ' '.join(shlex.quote(arg) for arg in cmd)
|
||||||
w.paste_bytes(text + '\r')
|
w.paste_bytes(f'{text}\r')
|
||||||
elif action == 'background':
|
elif action == 'background':
|
||||||
import subprocess
|
import subprocess
|
||||||
subprocess.Popen(cmd, cwd=data['cwd'])
|
subprocess.Popen(cmd, cwd=data['cwd'])
|
||||||
|
|||||||
@ -245,7 +245,7 @@ def main(args: List[str] = sys.argv) -> None:
|
|||||||
raise SystemExit(f'Unknown queries: {", ".join(extra)}')
|
raise SystemExit(f'Unknown queries: {", ".join(extra)}')
|
||||||
|
|
||||||
for key, val in do_queries(queries, cli_opts).items():
|
for key, val in do_queries(queries, cli_opts).items():
|
||||||
print(key + ':', val)
|
print(f'{key}:', val)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|||||||
@ -52,7 +52,7 @@ class KeysHandler(Handler):
|
|||||||
self.cmd.colored(etype + ' ', 'yellow')
|
self.cmd.colored(etype + ' ', 'yellow')
|
||||||
self.cmd.styled(key_event.text, italic=True)
|
self.cmd.styled(key_event.text, italic=True)
|
||||||
self.print()
|
self.print()
|
||||||
rep = 'CSI ' + encode_key_event(key_event)[2:]
|
rep = f'CSI {encode_key_event(key_event)[2:]}'
|
||||||
rep = rep.replace(';', ' ; ').replace(':', ' : ')[:-1] + ' ' + rep[-1]
|
rep = rep.replace(';', ' ; ').replace(':', ' : ')[:-1] + ' ' + rep[-1]
|
||||||
self.cmd.styled(rep, fg='magenta')
|
self.cmd.styled(rep, fg='magenta')
|
||||||
if (key_event.shifted_key or key_event.alternate_key):
|
if (key_event.shifted_key or key_event.alternate_key):
|
||||||
|
|||||||
@ -17,7 +17,7 @@ def print_key(raw: bytearray) -> None:
|
|||||||
unix = ''
|
unix = ''
|
||||||
for ch in raw:
|
for ch in raw:
|
||||||
if ch < len(ctrl_keys):
|
if ch < len(ctrl_keys):
|
||||||
unix += '^' + ctrl_keys[ch]
|
unix += f'^{ctrl_keys[ch]}'
|
||||||
elif ch == 127:
|
elif ch == 127:
|
||||||
unix += '^?'
|
unix += '^?'
|
||||||
else:
|
else:
|
||||||
|
|||||||
@ -281,7 +281,7 @@ def complete_choices(ans: Completions, prefix: str, title: str, choices: Iterabl
|
|||||||
if q.startswith(effective_prefix):
|
if q.startswith(effective_prefix):
|
||||||
if comma_separated:
|
if comma_separated:
|
||||||
tq = q
|
tq = q
|
||||||
q = hidden_prefix + q + ','
|
q = f'{hidden_prefix}{q},'
|
||||||
word_transforms[q] = tq
|
word_transforms[q] = tq
|
||||||
matches[q] = ''
|
matches[q] = ''
|
||||||
ans.add_match_group(title, matches, trailing_space=not comma_separated, word_transforms=word_transforms)
|
ans.add_match_group(title, matches, trailing_space=not comma_separated, word_transforms=word_transforms)
|
||||||
|
|||||||
@ -131,7 +131,7 @@ def get_ssh_cli() -> Tuple[Set[str], Set[str]]:
|
|||||||
other_ssh_args: Set[str] = set()
|
other_ssh_args: Set[str] = set()
|
||||||
boolean_ssh_args: Set[str] = set()
|
boolean_ssh_args: Set[str] = set()
|
||||||
for k, v in ssh_options().items():
|
for k, v in ssh_options().items():
|
||||||
k = '-' + k
|
k = f'-{k}'
|
||||||
if v:
|
if v:
|
||||||
other_ssh_args.add(k)
|
other_ssh_args.add(k)
|
||||||
else:
|
else:
|
||||||
@ -213,7 +213,7 @@ class InvalidSSHArgs(ValueError):
|
|||||||
|
|
||||||
def parse_ssh_args(args: List[str]) -> Tuple[List[str], List[str], bool]:
|
def parse_ssh_args(args: List[str]) -> Tuple[List[str], List[str], bool]:
|
||||||
boolean_ssh_args, other_ssh_args = get_ssh_cli()
|
boolean_ssh_args, other_ssh_args = get_ssh_cli()
|
||||||
passthrough_args = {'-' + x for x in 'Nnf'}
|
passthrough_args = {f'-{x}' for x in 'Nnf'}
|
||||||
ssh_args = []
|
ssh_args = []
|
||||||
server_args: List[str] = []
|
server_args: List[str] = []
|
||||||
expecting_option_val = False
|
expecting_option_val = False
|
||||||
@ -230,7 +230,7 @@ def parse_ssh_args(args: List[str]) -> Tuple[List[str], List[str], bool]:
|
|||||||
# could be a multi-character option
|
# could be a multi-character option
|
||||||
all_args = argument[1:]
|
all_args = argument[1:]
|
||||||
for i, arg in enumerate(all_args):
|
for i, arg in enumerate(all_args):
|
||||||
arg = '-' + arg
|
arg = f'-{arg}'
|
||||||
if arg in passthrough_args:
|
if arg in passthrough_args:
|
||||||
passthrough = True
|
passthrough = True
|
||||||
if arg in boolean_ssh_args:
|
if arg in boolean_ssh_args:
|
||||||
|
|||||||
@ -376,7 +376,7 @@ def fetch_themes(
|
|||||||
|
|
||||||
needs_delete = False
|
needs_delete = False
|
||||||
try:
|
try:
|
||||||
with tempfile.NamedTemporaryFile(suffix='-' + os.path.basename(dest_path), dir=os.path.dirname(dest_path), delete=False) as f:
|
with tempfile.NamedTemporaryFile(suffix=f'-{os.path.basename(dest_path)}', dir=os.path.dirname(dest_path), delete=False) as f:
|
||||||
needs_delete = True
|
needs_delete = True
|
||||||
shutil.copyfileobj(res, f)
|
shutil.copyfileobj(res, f)
|
||||||
f.flush()
|
f.flush()
|
||||||
@ -405,7 +405,7 @@ def theme_name_from_file_name(fname: str) -> str:
|
|||||||
ans = ans.replace('_', ' ')
|
ans = ans.replace('_', ' ')
|
||||||
|
|
||||||
def camel_case(m: 'Match[str]') -> str:
|
def camel_case(m: 'Match[str]') -> str:
|
||||||
return str(m.group(1) + ' ' + m.group(2))
|
return f'{m.group(1)} {m.group(2)}'
|
||||||
|
|
||||||
ans = re.sub(r'([a-z])([A-Z])', camel_case, ans)
|
ans = re.sub(r'([a-z])([A-Z])', camel_case, ans)
|
||||||
return ' '.join(x.capitalize() for x in filter(None, ans.split()))
|
return ' '.join(x.capitalize() for x in filter(None, ans.split()))
|
||||||
@ -533,7 +533,7 @@ class Theme:
|
|||||||
raw = ''
|
raw = ''
|
||||||
nraw = patch_conf(raw, self.name)
|
nraw = patch_conf(raw, self.name)
|
||||||
if raw:
|
if raw:
|
||||||
with open(confpath + '.bak', 'w') as f:
|
with open(f'{confpath}.bak', 'w') as f:
|
||||||
f.write(raw)
|
f.write(raw)
|
||||||
atomic_save(nraw.encode('utf-8'), confpath)
|
atomic_save(nraw.encode('utf-8'), confpath)
|
||||||
if reload_in == 'parent':
|
if reload_in == 'parent':
|
||||||
|
|||||||
@ -37,7 +37,7 @@ def limit_length(text: str, limit: int = 32) -> str:
|
|||||||
x = truncate_point_for_length(text, limit - 1)
|
x = truncate_point_for_length(text, limit - 1)
|
||||||
if x >= len(text):
|
if x >= len(text):
|
||||||
return text
|
return text
|
||||||
return text[:x] + '…'
|
return f'{text[:x]}…'
|
||||||
|
|
||||||
|
|
||||||
class State(Enum):
|
class State(Enum):
|
||||||
@ -332,7 +332,7 @@ class ThemesHandler(Handler):
|
|||||||
for line, width, is_current in self.themes_list.lines(num_rows):
|
for line, width, is_current in self.themes_list.lines(num_rows):
|
||||||
num_rows -= 1
|
num_rows -= 1
|
||||||
if is_current:
|
if is_current:
|
||||||
line = line.replace(MARK_AFTER, '\033[' + color_code('green') + 'm')
|
line = line.replace(MARK_AFTER, f'\033[{color_code("green")}m')
|
||||||
self.cmd.styled('>' if is_current else ' ', fg='green')
|
self.cmd.styled('>' if is_current else ' ', fg='green')
|
||||||
self.cmd.styled(line, bold=is_current, fg='green' if is_current else None)
|
self.cmd.styled(line, bold=is_current, fg='green' if is_current else None)
|
||||||
self.cmd.move_cursor_by(mw - width, 'right')
|
self.cmd.move_cursor_by(mw - width, 'right')
|
||||||
|
|||||||
@ -155,12 +155,12 @@ def develop() -> None:
|
|||||||
import sys
|
import sys
|
||||||
src = sys.argv[-1]
|
src = sys.argv[-1]
|
||||||
sig_loader = LoadSignature()
|
sig_loader = LoadSignature()
|
||||||
with open(src + '.sig', 'wb') as f:
|
with open(f'{src}.sig', 'wb') as f:
|
||||||
for chunk in signature_of_file(src):
|
for chunk in signature_of_file(src):
|
||||||
sig_loader.add_chunk(chunk)
|
sig_loader.add_chunk(chunk)
|
||||||
f.write(chunk)
|
f.write(chunk)
|
||||||
sig_loader.commit()
|
sig_loader.commit()
|
||||||
with open(src + '.delta', 'wb') as f, PatchFile(src, src + '.output') as patcher:
|
with open(f'{src}.delta', 'wb') as f, PatchFile(src, f'{src}.output') as patcher:
|
||||||
for chunk in delta_for_file(src, sig_loader.signature):
|
for chunk in delta_for_file(src, sig_loader.signature):
|
||||||
f.write(chunk)
|
f.write(chunk)
|
||||||
patcher.write(chunk)
|
patcher.write(chunk)
|
||||||
|
|||||||
@ -45,7 +45,7 @@ def render_path_in_width(path: str, width: int) -> str:
|
|||||||
if wcswidth(path) <= width:
|
if wcswidth(path) <= width:
|
||||||
return path
|
return path
|
||||||
x = truncate_point_for_length(path, width - 1)
|
x = truncate_point_for_length(path, width - 1)
|
||||||
return path[:x] + '…'
|
return f'{path[:x]}…'
|
||||||
|
|
||||||
|
|
||||||
def render_seconds(val: float) -> str:
|
def render_seconds(val: float) -> str:
|
||||||
|
|||||||
@ -331,7 +331,7 @@ class Dircolors:
|
|||||||
# change .xyz to *.xyz
|
# change .xyz to *.xyz
|
||||||
yield '*' + pair[0], pair[1]
|
yield '*' + pair[0], pair[1]
|
||||||
|
|
||||||
return ':'.join('%s=%s' % pair for pair in gen_pairs())
|
return ':'.join('{}={}'.format(*pair) for pair in gen_pairs())
|
||||||
|
|
||||||
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)
|
||||||
|
|||||||
@ -163,7 +163,7 @@ def set_scrolling_region(screen_size: Optional['ScreenSize'] = None, top: Option
|
|||||||
|
|
||||||
@cmd
|
@cmd
|
||||||
def scroll_screen(amt: int = 1) -> str:
|
def scroll_screen(amt: int = 1) -> str:
|
||||||
return '\033[' + str(abs(amt)) + ('T' if amt < 0 else 'S')
|
return f'\033[{abs(amt)}{"T" if amt < 0 else "S"}'
|
||||||
|
|
||||||
|
|
||||||
STANDARD_COLORS = {'black': 0, 'red': 1, 'green': 2, 'yellow': 3, 'blue': 4, 'magenta': 5, 'cyan': 6, 'gray': 7, 'white': 7}
|
STANDARD_COLORS = {'black': 0, 'red': 1, 'green': 2, 'yellow': 3, 'blue': 4, 'magenta': 5, 'cyan': 6, 'gray': 7, 'white': 7}
|
||||||
@ -465,7 +465,7 @@ def as_type_stub() -> str:
|
|||||||
for name, func in all_cmds.items():
|
for name, func in all_cmds.items():
|
||||||
args = ', '.join(func_sig(func))
|
args = ', '.join(func_sig(func))
|
||||||
if args:
|
if args:
|
||||||
args = ', ' + args
|
args = f', {args}'
|
||||||
methods.append(f' def {name}(self{args}) -> str: pass')
|
methods.append(f' def {name}(self{args}) -> str: pass')
|
||||||
ans += ['', '', 'class CMD:'] + methods
|
ans += ['', '', 'class CMD:'] + methods
|
||||||
|
|
||||||
|
|||||||
@ -192,7 +192,7 @@ class Table:
|
|||||||
if w < 2:
|
if w < 2:
|
||||||
text += ' ' * (2 - w)
|
text += ' ' * (2 - w)
|
||||||
if len(desc) > space_for_desc:
|
if len(desc) > space_for_desc:
|
||||||
text += desc[:space_for_desc - 1] + '…'
|
text += f'{desc[:space_for_desc - 1]}…'
|
||||||
else:
|
else:
|
||||||
text += desc
|
text += desc
|
||||||
extra = space_for_desc - len(desc)
|
extra = space_for_desc - len(desc)
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user