mypy: Turn on return value checks

Its a shame GvR is married to "return None"
https://github.com/python/mypy/issues/7511
This commit is contained in:
Kovid Goyal 2021-10-26 22:39:14 +05:30
parent 5cb36a4632
commit 4494ddd8ff
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
52 changed files with 124 additions and 49 deletions

View File

@ -106,6 +106,7 @@ def main(args: List[str]) -> Optional[Dict[str, Any]]:
loop = Loop() loop = Loop()
handler = Broadcast(opts, items) handler = Broadcast(opts, items)
loop.loop(handler) loop.loop(handler)
return None
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -24,6 +24,7 @@ def find_differ() -> Optional[str]:
return GIT_DIFF return GIT_DIFF
if shutil.which('diff'): if shutil.which('diff'):
return DIFF_DIFF return DIFF_DIFF
return None
def set_diff_command(opt: str) -> None: def set_diff_command(opt: str) -> None:

View File

@ -688,6 +688,7 @@ def main(args: List[str]) -> Optional[Dict[str, Any]]:
import traceback import traceback
traceback.print_exc() traceback.print_exc()
input(_('Press Enter to quit')) input(_('Press Enter to quit'))
return None
def linenum_handle_result(args: List[str], data: Dict[str, Any], target_window_id: int, boss: BossType, extra_cli_args: Sequence[str], *a: Any) -> None: def linenum_handle_result(args: List[str], data: Dict[str, Any], target_window_id: int, boss: BossType, extra_cli_args: Sequence[str], *a: Any) -> None:

View File

@ -132,7 +132,7 @@ class ControlMaster:
self.dest = os.path.join(self.tdir, os.path.basename(self.remote_path)) self.dest = os.path.join(self.tdir, os.path.basename(self.remote_path))
return self return self
def __exit__(self, *a: Any) -> bool: def __exit__(self, *a: Any) -> None:
subprocess.Popen( subprocess.Popen(
self.batch_cmd_prefix + ['-O', 'exit', self.conn_data.hostname], self.batch_cmd_prefix + ['-O', 'exit', self.conn_data.hostname],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL
@ -215,6 +215,7 @@ def main(args: List[str]) -> Result:
import traceback import traceback
traceback.print_exc() traceback.print_exc()
show_error('Failed with unhandled exception') show_error('Failed with unhandled exception')
return None
def save_as(conn_data: SSHConnectionData, remote_path: str, cli_opts: RemoteFileCLIOptions) -> None: def save_as(conn_data: SSHConnectionData, remote_path: str, cli_opts: RemoteFileCLIOptions) -> None:
@ -312,6 +313,7 @@ def handle_action(action: str, cli_opts: RemoteFileCLIOptions) -> Result:
elif action == 'save': elif action == 'save':
print('Saving', cli_opts.path, 'from', cli_opts.hostname) print('Saving', cli_opts.path, 'from', cli_opts.hostname)
save_as(conn_data, remote_path, cli_opts) save_as(conn_data, remote_path, cli_opts)
return None
@result_handler() @result_handler()

View File

@ -203,6 +203,7 @@ class ThemesHandler(Handler):
col = color_as_sharp(color_from_int(o.color_table[i])) col = color_as_sharp(color_from_int(o.color_table[i]))
cmds.append(f'{i};{col}') cmds.append(f'{i};{col}')
self.print(end='\033]4;' + ';'.join(cmds) + '\033\\') self.print(end='\033]4;' + ';'.join(cmds) + '\033\\')
return True
def redraw_after_category_change(self) -> None: def redraw_after_category_change(self) -> None:
self.themes_list.update_themes(self.all_themes.filtered(self.filter_map[self.current_category])) self.themes_list.update_themes(self.all_themes.filtered(self.filter_map[self.current_category]))

View File

@ -312,6 +312,7 @@ class SendManager:
ans = self.files[self.active_idx] ans = self.files[self.active_idx]
if ans.state is FileState.transmitting: if ans.state is FileState.transmitting:
return ans return ans
return None
def activate_next_ready_file(self) -> Optional[File]: def activate_next_ready_file(self) -> Optional[File]:
if self.active_idx is not None: if self.active_idx is not None:
@ -325,6 +326,7 @@ class SendManager:
return f return f
self.active_idx = None self.active_idx = None
self.update_collective_statuses() self.update_collective_statuses()
return None
def update_collective_statuses(self) -> None: def update_collective_statuses(self) -> None:
found_not_started = found_not_done = False found_not_started = found_not_done = False

View File

@ -83,6 +83,7 @@ class Handler:
for sc, action in self._key_shortcuts.items(): for sc, action in self._key_shortcuts.items():
if key_event.matches(sc): if key_event.matches(sc):
return action return action
return None
def __enter__(self) -> None: def __enter__(self) -> None:
if self._image_manager is not None: if self._image_manager is not None:

View File

@ -132,6 +132,7 @@ class PathCompleter:
options = self.cache[text] = tuple(find_completions(text)) options = self.cache[text] = tuple(find_completions(text))
if options and state < len(options): if options and state < len(options):
return options[state] return options[state]
return None
def __exit__(self, *a: Any) -> bool: def __exit__(self, *a: Any) -> bool:
import readline import readline
@ -143,6 +144,7 @@ class PathCompleter:
def input(self) -> str: def input(self) -> str:
with self: with self:
return input(self.prompt) return input(self.prompt)
return ''
def develop() -> None: def develop() -> None:

View File

@ -157,6 +157,7 @@ class Table:
def current_codepoint(self) -> Optional[int]: def current_codepoint(self) -> Optional[int]:
if self.codepoints: if self.codepoints:
return self.codepoints[self.current_idx] return self.codepoints[self.current_idx]
return None
def set_codepoints(self, codepoints: List[int], mode: str = HEX, current_idx: int = 0) -> None: def set_codepoints(self, codepoints: List[int], mode: str = HEX, current_idx: int = 0) -> None:
self.codepoints = codepoints self.codepoints = codepoints

View File

@ -9,8 +9,8 @@ from contextlib import suppress
from functools import partial from functools import partial
from gettext import gettext as _ from gettext import gettext as _
from typing import ( from typing import (
Any, Callable, Dict, Generator, Iterable, List, Optional, Tuple, Union, Any, Callable, Dict, Iterable, Iterator, List, Optional, Tuple,
cast Union, cast
) )
from weakref import WeakValueDictionary from weakref import WeakValueDictionary
@ -27,16 +27,16 @@ from .constants import (
) )
from .fast_data_types import ( from .fast_data_types import (
CLOSE_BEING_CONFIRMED, GLFW_MOD_ALT, GLFW_MOD_CONTROL, GLFW_MOD_SHIFT, CLOSE_BEING_CONFIRMED, GLFW_MOD_ALT, GLFW_MOD_CONTROL, GLFW_MOD_SHIFT,
GLFW_MOD_SUPER, IMPERATIVE_CLOSE_REQUESTED, NO_CLOSE_REQUESTED, GLFW_MOD_SUPER, GLFW_MOUSE_BUTTON_LEFT, GLFW_PRESS,
ChildMonitor, KeyEvent, add_timer, apply_options_update, IMPERATIVE_CLOSE_REQUESTED, NO_CLOSE_REQUESTED, ChildMonitor, KeyEvent,
background_opacity_of, change_background_opacity, change_os_window_state, add_timer, apply_options_update, background_opacity_of,
cocoa_set_menubar_title, create_os_window, GLFW_PRESS, GLFW_MOUSE_BUTTON_LEFT, change_background_opacity, change_os_window_state, cocoa_set_menubar_title,
current_application_quit_request, current_os_window, destroy_global_data, create_os_window, current_application_quit_request, current_os_window,
focus_os_window, get_clipboard_string, get_options, get_os_window_size, destroy_global_data, focus_os_window, get_clipboard_string, get_options,
global_font_size, mark_os_window_for_close, os_window_font_size, get_os_window_size, global_font_size, mark_os_window_for_close,
patch_global_colors, redirect_mouse_handling, ring_bell, safe_pipe, os_window_font_size, patch_global_colors, redirect_mouse_handling,
set_application_quit_request, set_background_image, set_boss, ring_bell, safe_pipe, set_application_quit_request, set_background_image,
set_clipboard_string, set_in_sequence_mode, set_options, set_boss, set_clipboard_string, set_in_sequence_mode, set_options,
set_os_window_size, thread_write, toggle_fullscreen, toggle_maximized set_os_window_size, thread_write, toggle_fullscreen, toggle_maximized
) )
from .key_encoding import get_name_to_functional_number_map from .key_encoding import get_name_to_functional_number_map
@ -234,7 +234,7 @@ class Boss:
self.os_window_map[os_window_id] = tm self.os_window_map[os_window_id] = tm
return os_window_id return os_window_id
def list_os_windows(self, self_window: Optional[Window] = None) -> Generator[OSWindowDict, None, None]: def list_os_windows(self, self_window: Optional[Window] = None) -> Iterator[OSWindowDict]:
with cached_process_data(): with cached_process_data():
active_tab, active_window = self.active_tab, self.active_window active_tab, active_window = self.active_tab, self.active_window
active_tab_manager = self.active_tab_manager active_tab_manager = self.active_tab_manager
@ -249,20 +249,20 @@ class Boss:
} }
@property @property
def all_tab_managers(self) -> Generator[TabManager, None, None]: def all_tab_managers(self) -> Iterator[TabManager]:
yield from self.os_window_map.values() yield from self.os_window_map.values()
@property @property
def all_tabs(self) -> Generator[Tab, None, None]: def all_tabs(self) -> Iterator[Tab]:
for tm in self.all_tab_managers: for tm in self.all_tab_managers:
yield from tm yield from tm
@property @property
def all_windows(self) -> Generator[Window, None, None]: def all_windows(self) -> Iterator[Window]:
for tab in self.all_tabs: for tab in self.all_tabs:
yield from tab yield from tab
def match_windows(self, match: str) -> Generator[Window, None, None]: def match_windows(self, match: str) -> Iterator[Window]:
try: try:
field, exp = match.split(':', 1) field, exp = match.split(':', 1)
except ValueError: except ValueError:
@ -305,8 +305,9 @@ class Boss:
for w in tab: for w in tab:
if w.id == window.id: if w.id == window.id:
return tab return tab
return None
def match_tabs(self, match: str) -> Generator[Tab, None, None]: def match_tabs(self, match: str) -> Iterator[Tab]:
try: try:
field, exp = match.split(':', 1) field, exp = match.split(':', 1)
except ValueError: except ValueError:
@ -359,6 +360,7 @@ class Boss:
if switch_os_window_if_needed and current_os_window() != os_window_id: if switch_os_window_if_needed and current_os_window() != os_window_id:
focus_os_window(os_window_id, True) focus_os_window(os_window_id, True)
return os_window_id return os_window_id
return None
def _new_os_window(self, args: Union[SpecialWindowInstance, Iterable[str]], cwd_from: Optional[int] = None) -> int: def _new_os_window(self, args: Union[SpecialWindowInstance, Iterable[str]], cwd_from: Optional[int] = None) -> int:
if isinstance(args, SpecialWindowInstance): if isinstance(args, SpecialWindowInstance):
@ -377,6 +379,7 @@ class Boss:
t = self.active_tab t = self.active_tab
if t is not None: if t is not None:
return t.active_window_for_cwd return t.active_window_for_cwd
return None
@ac('win', 'New OS Window with the same working directory as the currently active window') @ac('win', 'New OS Window with the same working directory as the currently active window')
def new_os_window_with_cwd(self, *args: str) -> None: def new_os_window_with_cwd(self, *args: str) -> None:
@ -595,7 +598,7 @@ class Boss:
run_update_check(get_options().update_check_interval * 60 * 60) run_update_check(get_options().update_check_interval * 60 * 60)
self.update_check_started = True self.update_check_started = True
def handle_click_on_tab(self, os_window_id: int, x: int, button: int, modifiers: int, action: int) -> int: def handle_click_on_tab(self, os_window_id: int, x: int, button: int, modifiers: int, action: int) -> None:
tm = self.os_window_map.get(os_window_id) tm = self.os_window_map.get(os_window_id)
if tm is not None: if tm is not None:
tm.handle_click_on_tab(x, button, modifiers, action) tm.handle_click_on_tab(x, button, modifiers, action)
@ -751,20 +754,17 @@ class Boss:
@property @property
def active_tab_manager(self) -> Optional[TabManager]: def active_tab_manager(self) -> Optional[TabManager]:
os_window_id = current_os_window() os_window_id = current_os_window()
if os_window_id is not None: return None if os_window_id is None else self.os_window_map.get(os_window_id)
return self.os_window_map.get(os_window_id)
@property @property
def active_tab(self) -> Optional[Tab]: def active_tab(self) -> Optional[Tab]:
tm = self.active_tab_manager tm = self.active_tab_manager
if tm is not None: return None if tm is None else tm.active_tab
return tm.active_tab
@property @property
def active_window(self) -> Optional[Window]: def active_window(self) -> Optional[Window]:
t = self.active_tab t = self.active_tab
if t is not None: return None if t is None else t.active_window
return t.active_window
def set_pending_sequences(self, sequences: SubSequenceMap, default_pending_action: Optional[KeyAction] = None) -> None: def set_pending_sequences(self, sequences: SubSequenceMap, default_pending_action: Optional[KeyAction] = None) -> None:
self.pending_sequences = sequences self.pending_sequences = sequences
@ -783,6 +783,7 @@ class Boss:
return True return True
elif isinstance(key_action, KeyAction): elif isinstance(key_action, KeyAction):
return self.dispatch_action(key_action) return self.dispatch_action(key_action)
return False
def clear_pending_sequences(self) -> None: def clear_pending_sequences(self) -> None:
self.pending_sequences = self.default_pending_action = None self.pending_sequences = self.default_pending_action = None
@ -1530,7 +1531,7 @@ class Boss:
else: else:
subprocess.Popen(cmd, env=env, cwd=cwd) subprocess.Popen(cmd, env=env, cwd=cwd)
def pipe(self, source: str, dest: str, exe: str, *args: str) -> Window: def pipe(self, source: str, dest: str, exe: str, *args: str) -> Optional[Window]:
cmd = [exe] + list(args) cmd = [exe] + list(args)
window = self.active_window window = self.active_window
cwd_from = window.child.pid_for_cwd if window else None cwd_from = window.child.pid_for_cwd if window else None
@ -1559,6 +1560,7 @@ class Boss:
else: else:
env, stdin = self.process_stdin_source(stdin=source, window=window) env, stdin = self.process_stdin_source(stdin=source, window=window)
self.run_background_process(cmd, cwd_from=cwd_from, stdin=stdin, env=env) self.run_background_process(cmd, cwd_from=cwd_from, stdin=stdin, env=env)
return None
def args_to_special_window(self, args: Iterable[str], cwd_from: Optional[int] = None) -> SpecialWindowInstance: def args_to_special_window(self, args: Iterable[str], cwd_from: Optional[int] = None) -> SpecialWindowInstance:
args = list(args) args = list(args)
@ -1591,6 +1593,7 @@ class Boss:
tm = self.active_tab_manager tm = self.active_tab_manager
if tm is not None: if tm is not None:
return tm.new_tab(special_window=special_window, cwd_from=cwd_from, as_neighbor=as_neighbor) return tm.new_tab(special_window=special_window, cwd_from=cwd_from, as_neighbor=as_neighbor)
return None
def _create_tab(self, args: List[str], cwd_from: Optional[int] = None) -> None: def _create_tab(self, args: List[str], cwd_from: Optional[int] = None) -> None:
as_neighbor = False as_neighbor = False
@ -1615,7 +1618,8 @@ class Boss:
def _new_window(self, args: List[str], cwd_from: Optional[int] = None) -> Optional[Window]: def _new_window(self, args: List[str], cwd_from: Optional[int] = None) -> Optional[Window]:
tab = self.active_tab tab = self.active_tab
if tab is not None: if tab is None:
return None
allow_remote_control = False allow_remote_control = False
location = None location = None
if args and args[0].startswith('!'): if args and args[0].startswith('!'):

View File

@ -333,6 +333,7 @@ class Child:
with suppress(Exception): with suppress(Exception):
assert self.pid is not None assert self.pid is not None
return cwd_of_process(self.pid) return cwd_of_process(self.pid)
return None
@property @property
def pid_for_cwd(self) -> Optional[int]: def pid_for_cwd(self) -> Optional[int]:
@ -349,6 +350,7 @@ class Child:
with suppress(Exception): with suppress(Exception):
assert self.pid_for_cwd is not None assert self.pid_for_cwd is not None
return cwd_of_process(self.pid_for_cwd) or None return cwd_of_process(self.pid_for_cwd) or None
return None
@property @property
def foreground_environ(self) -> Dict[str, str]: def foreground_environ(self) -> Dict[str, str]:

View File

@ -951,3 +951,4 @@ class TestFileTransmission(FileTransmission):
def callback_after(self, callback: Callable[[Optional[int]], None], timeout: float = 0) -> Optional[int]: def callback_after(self, callback: Callable[[Optional[int]], None], timeout: float = 0) -> Optional[int]:
callback(None) callback(None)
return None

View File

@ -10,7 +10,7 @@ import math
from functools import partial as p, wraps from functools import partial as p, wraps
from itertools import repeat from itertools import repeat
from typing import ( from typing import (
Any, Callable, Dict, Generator, Iterable, List, MutableSequence, Optional, Any, Callable, Dict, Iterable, Iterator, List, MutableSequence, Optional,
Sequence, Tuple, cast Sequence, Tuple, cast
) )
@ -314,6 +314,7 @@ def mid_lines(buf: SSByteArray, width: int, height: int, level: int = 1, pts: It
return width - 1, mid_y return width - 1, mid_y
if p == 'b': if p == 'b':
return mid_x, height - 1 return mid_x, height - 1
raise KeyError(f'Unknown p: {p}')
for x in pts: for x in pts:
p1, p2 = map(pt_to_coords, x) p1, p2 = map(pt_to_coords, x)
@ -353,7 +354,7 @@ def find_bezier_for_D(width: int, height: int) -> int:
cx += 1 cx += 1
def get_bezier_limits(bezier_x: ParameterizedFunc, bezier_y: ParameterizedFunc) -> Generator[Tuple[float, float], None, int]: def get_bezier_limits(bezier_x: ParameterizedFunc, bezier_y: ParameterizedFunc) -> Iterator[Tuple[float, float]]:
start_x = int(bezier_x(0)) start_x = int(bezier_x(0))
max_x = int(bezier_x(0.5)) max_x = int(bezier_x(0.5))
last_t, t_limit = 0., 0.5 last_t, t_limit = 0., 0.5
@ -1043,8 +1044,9 @@ def render_missing_glyph(buf: BufType, width: int, height: int) -> None:
def test_char(ch: str, sz: int = 48) -> None: def test_char(ch: str, sz: int = 48) -> None:
# kitty +runpy "from kitty.fonts.box_drawing import test_char; test_char('XXX')" # kitty +runpy "from kitty.fonts.box_drawing import test_char; test_char('XXX')"
from .render import display_bitmap, setup_for_testing
from kitty.fast_data_types import concat_cells, set_send_sprite_to_gpu from kitty.fast_data_types import concat_cells, set_send_sprite_to_gpu
from .render import display_bitmap, setup_for_testing
with setup_for_testing('monospace', sz) as (_, width, height): with setup_for_testing('monospace', sz) as (_, width, height):
buf = bytearray(width * height) buf = bytearray(width * height)
try: try:
@ -1062,9 +1064,10 @@ def test_char(ch: str, sz: int = 48) -> None:
def test_drawing(sz: int = 48, family: str = 'monospace', start: int = 0x2500, num_rows: int = 10, num_cols: int = 16) -> None: def test_drawing(sz: int = 48, family: str = 'monospace', start: int = 0x2500, num_rows: int = 10, num_cols: int = 16) -> None:
from .render import display_bitmap, setup_for_testing
from kitty.fast_data_types import concat_cells, set_send_sprite_to_gpu from kitty.fast_data_types import concat_cells, set_send_sprite_to_gpu
from .render import display_bitmap, setup_for_testing
with setup_for_testing(family, sz) as (_, width, height): with setup_for_testing(family, sz) as (_, width, height):
space = bytearray(width * height) space = bytearray(width * height)

View File

@ -69,6 +69,7 @@ def idx_for_id(win_id: int, windows: Iterable[WindowType]) -> Optional[int]:
for i, w in enumerate(windows): for i, w in enumerate(windows):
if w.id == win_id: if w.id == win_id:
return i return i
return None
def set_layout_options(opts: Options) -> None: def set_layout_options(opts: Options) -> None:

View File

@ -81,6 +81,7 @@ class Grid(Layout):
if idx == window_idx: if idx == window_idx:
return row_num, col_num return row_num, col_num
row_num += 1 row_num += 1
return 0, 0
row_num, col_num = position_for_window_idx(idx) row_num, col_num = position_for_window_idx(idx)

View File

@ -86,6 +86,7 @@ class Pair:
for q in root.self_and_descendants(): for q in root.self_and_descendants():
if q.one is self or q.two is self: if q.one is self or q.two is self:
return q return q
return None
def remove_windows(self, window_ids: Collection[int]) -> None: def remove_windows(self, window_ids: Collection[int]) -> None:
if isinstance(self.one, int) and self.one in window_ids: if isinstance(self.one, int) and self.one in window_ids:
@ -548,6 +549,7 @@ class Splits(Layout):
if swap: if swap:
pair.one, pair.two = pair.two, pair.one pair.one, pair.two = pair.two, pair.one
return True return True
return None
def layout_state(self) -> Dict[str, Any]: def layout_state(self) -> Dict[str, Any]:

View File

@ -203,6 +203,7 @@ class Tall(Layout):
if self.layout_opts.full_size > 1: if self.layout_opts.full_size > 1:
self.layout_opts.full_size -= 1 self.layout_opts.full_size -= 1
return True return True
return None
def minimal_borders(self, all_windows: WindowList) -> Generator[BorderLine, None, None]: def minimal_borders(self, all_windows: WindowList) -> Generator[BorderLine, None, None]:
num = all_windows.num_groups num = all_windows.num_groups

View File

@ -218,3 +218,4 @@ def handle_notification_cmd(
cmd = parse_osc_777(raw_data) cmd = parse_osc_777(raw_data)
notify_with_command(cmd, window_id, notify_implementation) notify_with_command(cmd, window_id, notify_implementation)
return cmd return cmd
return None

View File

@ -764,7 +764,7 @@ def kitten_alias(val: str) -> Iterable[Tuple[str, List[str]]]:
def symbol_map(val: str) -> Iterable[Tuple[Tuple[int, int], str]]: def symbol_map(val: str) -> Iterable[Tuple[Tuple[int, int], str]]:
parts = val.split() parts = val.split()
def abort() -> Dict[Tuple[int, int], str]: def abort() -> None:
log_error(f'Symbol map: {val} is invalid, ignoring') log_error(f'Symbol map: {val} is invalid, ignoring')
if len(parts) < 2: if len(parts) < 2:

View File

@ -35,6 +35,7 @@ If specified close the tab of the window this command is run in, rather than the
for tab in self.tabs_for_match_payload(boss, window, payload_get): for tab in self.tabs_for_match_payload(boss, window, payload_get):
if tab: if tab:
boss.close_tab_no_confirm(tab) boss.close_tab_no_confirm(tab)
return None
close_tab = CloseTab() close_tab = CloseTab()

View File

@ -34,6 +34,7 @@ If specified close the window this command is run in, rather than the active win
for window in self.windows_for_match_payload(boss, window, payload_get): for window in self.windows_for_match_payload(boss, window, payload_get):
if window: if window:
boss.close_window(window) boss.close_window(window)
return None
close_window = CloseWindow() close_window = CloseWindow()

View File

@ -45,6 +45,7 @@ If specified apply marker to the window this command is run in, rather than the
args = payload_get('marker_spec') args = payload_get('marker_spec')
for window in self.windows_for_match_payload(boss, window, payload_get): for window in self.windows_for_match_payload(boss, window, payload_get):
window.set_marker(args) window.set_marker(args)
return None
create_marker = CreateMarker() create_marker = CreateMarker()

View File

@ -57,6 +57,7 @@ If specified detach the tab this command is run in, rather than the active tab.
for tab in tabs: for tab in tabs:
boss._move_tab_to(tab=tab, **kwargs) boss._move_tab_to(tab=tab, **kwargs)
return None
detach_tab = DetachTab() detach_tab = DetachTab()

View File

@ -53,6 +53,7 @@ If specified detach the window this command is run in, rather than the active wi
kwargs = {'target_os_window_id': newval} if target_tab_id is None else {'target_tab_id': target_tab_id} kwargs = {'target_os_window_id': newval} if target_tab_id is None else {'target_tab_id': target_tab_id}
for window in windows: for window in windows:
boss._move_window_to(window=window, **kwargs) boss._move_window_to(window=window, **kwargs)
return None
detach_window = DetachWindow() detach_window = DetachWindow()

View File

@ -52,6 +52,7 @@ cause ligatures to be changed in all windows.
def response_from_kitty(self, boss: Boss, window: Optional[Window], payload_get: PayloadGetType) -> ResponseType: def response_from_kitty(self, boss: Boss, window: Optional[Window], payload_get: PayloadGetType) -> ResponseType:
windows = self.windows_for_payload(boss, window, payload_get) windows = self.windows_for_payload(boss, window, payload_get)
boss.disable_ligatures_in(windows, payload_get('strategy')) boss.disable_ligatures_in(windows, payload_get('strategy'))
return None
# }}} # }}}

View File

@ -43,6 +43,7 @@ class Env(RemoteCommand):
else: else:
env.pop(k, None) env.pop(k, None)
set_default_env(env) set_default_env(env)
return None
env = Env() env = Env()

View File

@ -41,6 +41,7 @@ using this option means that you will not be notified of failures.
if tab: if tab:
boss.set_active_tab(tab) boss.set_active_tab(tab)
break break
return None
focus_tab = FocusTab() focus_tab = FocusTab()

View File

@ -43,6 +43,7 @@ the command will exit with a success code.
if os_window_id: if os_window_id:
focus_os_window(os_window_id, True) focus_os_window(os_window_id, True)
break break
return None
focus_window = FocusWindow() focus_window = FocusWindow()

View File

@ -47,6 +47,7 @@ class GotoLayout(RemoteCommand):
tab.goto_layout(payload_get('layout'), raise_exception=True) tab.goto_layout(payload_get('layout'), raise_exception=True)
except ValueError: except ValueError:
raise UnknownLayout('The layout {} is unknown or disabled'.format(payload_get('layout'))) raise UnknownLayout('The layout {} is unknown or disabled'.format(payload_get('layout')))
return None
goto_layout = GotoLayout() goto_layout = GotoLayout()

View File

@ -51,6 +51,7 @@ class Kitten(RemoteCommand):
break break
if isinstance(retval, (str, bool)): if isinstance(retval, (str, bool)):
return retval return retval
return None
kitten = Kitten() kitten = Kitten()

View File

@ -45,6 +45,7 @@ the command will exit with a success code.
for tab in self.tabs_for_match_payload(boss, window, payload_get): for tab in self.tabs_for_match_payload(boss, window, payload_get):
if tab: if tab:
tab.last_used_layout() tab.last_used_layout()
return None
last_used_layout = LastUsedLayout() last_used_layout = LastUsedLayout()

View File

@ -34,6 +34,7 @@ If specified apply marker to the window this command is run in, rather than the
def response_from_kitty(self, boss: Boss, window: Optional[Window], payload_get: PayloadGetType) -> ResponseType: def response_from_kitty(self, boss: Boss, window: Optional[Window], payload_get: PayloadGetType) -> ResponseType:
for window in self.windows_for_match_payload(boss, window, payload_get): for window in self.windows_for_match_payload(boss, window, payload_get):
window.remove_marker() window.remove_marker()
return None
remove_marker = RemoveMarker() remove_marker = RemoveMarker()

View File

@ -96,6 +96,7 @@ using this option means that you will not be notified of failures.
boss.toggle_fullscreen(os_window_id) boss.toggle_fullscreen(os_window_id)
elif ac == 'toggle-maximized': elif ac == 'toggle-maximized':
boss.toggle_maximized(os_window_id) boss.toggle_maximized(os_window_id)
return None
resize_os_window = ResizeOSWindow() resize_os_window = ResizeOSWindow()

View File

@ -69,6 +69,7 @@ class ScrollWindow(RemoteCommand):
func = getattr(window, f'scroll_{unit}_{direction}') func = getattr(window, f'scroll_{unit}_{direction}')
for i in range(abs(amt)): for i in range(abs(amt)):
func() func()
return None
scroll_window = ScrollWindow() scroll_window = ScrollWindow()

View File

@ -161,6 +161,7 @@ Do not send text to the active window, even if it is one of the matched windows.
window.write_to_child(kdata) window.write_to_child(kdata)
else: else:
window.write_to_child(data) window.write_to_child(data)
return None
send_text = SendText() send_text = SendText()

View File

@ -124,6 +124,7 @@ failed, the command will exit with a success code.
except ValueError as err: except ValueError as err:
err.hide_traceback = True # type: ignore err.hide_traceback = True # type: ignore
raise raise
return None
set_background_image = SetBackgroundImage() set_background_image = SetBackgroundImage()

View File

@ -53,6 +53,7 @@ cause colors to be changed in all windows.
windows = self.windows_for_payload(boss, window, payload_get) windows = self.windows_for_payload(boss, window, payload_get)
for os_window_id in {w.os_window_id for w in windows}: for os_window_id in {w.os_window_id for w in windows}:
boss._set_os_window_background_opacity(os_window_id, payload_get('opacity')) boss._set_os_window_background_opacity(os_window_id, payload_get('opacity'))
return None
set_background_opacity = SetBackgroundOpacity() set_background_opacity = SetBackgroundOpacity()

View File

@ -107,6 +107,7 @@ this option, any color arguments are ignored and --configured and --all are impl
if default_bg_changed: if default_bg_changed:
boss.default_bg_changed_for(w.id) boss.default_bg_changed_for(w.id)
w.refresh() w.refresh()
return None
set_colors = SetColors() set_colors = SetColors()

View File

@ -64,6 +64,7 @@ as well.
for tab in tabs: for tab in tabs:
if tab: if tab:
tab.set_enabled_layouts(layouts) tab.set_enabled_layouts(layouts)
return None
set_enabled_layouts = SetEnabledLayouts() set_enabled_layouts = SetEnabledLayouts()

View File

@ -49,6 +49,7 @@ the font size for any newly created OS Windows in the future.
boss.change_font_size( boss.change_font_size(
payload_get('all'), payload_get('all'),
payload_get('increment_op'), payload_get('size')) payload_get('increment_op'), payload_get('size'))
return None
set_font_size = SetFontSize() set_font_size = SetFontSize()

View File

@ -119,6 +119,7 @@ windows).
for tab in dirtied_tabs.values(): for tab in dirtied_tabs.values():
tab.relayout() tab.relayout()
return None
set_spacing = SetSpacing() set_spacing = SetSpacing()

View File

@ -76,6 +76,7 @@ If specified close the tab this command is run in, rather than the active tab.
for k, v in s.items(): for k, v in s.items():
setattr(tab, k, v) setattr(tab, k, v)
tab.mark_tab_bar_dirty() tab.mark_tab_bar_dirty()
return None
set_tab_color = SetTabColor() set_tab_color = SetTabColor()

View File

@ -37,6 +37,7 @@ class SetTabTitle(RemoteCommand):
for tab in self.tabs_for_match_payload(boss, window, payload_get): for tab in self.tabs_for_match_payload(boss, window, payload_get):
if tab: if tab:
tab.set_title(payload_get('title')) tab.set_title(payload_get('title'))
return None
set_tab_title = SetTabTitle() set_tab_title = SetTabTitle()

View File

@ -57,6 +57,7 @@ want to allow other programs to change it afterwards, use this option.
window.title_changed(payload_get('title')) window.title_changed(payload_get('title'))
else: else:
window.set_title(payload_get('title')) window.set_title(payload_get('title'))
return None
set_window_title = SetWindowTitle() set_window_title = SetWindowTitle()

View File

@ -47,6 +47,7 @@ class SignalChild(RemoteCommand):
for window in windows: for window in windows:
if window: if window:
window.signal_child(*signals) window.signal_child(*signals)
return None
signal_child = SignalChild() signal_child = SignalChild()

View File

@ -61,7 +61,7 @@ def setup_bash_integration() -> None:
setup_integration('bash', os.path.expanduser('~/.bashrc')) setup_integration('bash', os.path.expanduser('~/.bashrc'))
def atomic_symlink(destination: str, in_directory: str) -> str: def atomic_symlink(destination: str, in_directory: str) -> None:
os.makedirs(in_directory, exist_ok=True) os.makedirs(in_directory, exist_ok=True)
name = os.path.basename(destination) name = os.path.basename(destination)
tmpname = os.path.join(in_directory, f'{name}-{os.getpid()}-{time.monotonic()}') tmpname = os.path.join(in_directory, f'{name}-{os.getpid()}-{time.monotonic()}')
@ -97,6 +97,7 @@ def get_supported_shell_name(path: str) -> Optional[str]:
name = os.path.basename(path).split('.')[0].lower() name = os.path.basename(path).split('.')[0].lower()
if name in SUPPORTED_SHELLS: if name in SUPPORTED_SHELLS:
return name return name
return None
@run_once @run_once

View File

@ -578,3 +578,4 @@ class TabBar:
for i, (a, b) in enumerate(self.cell_ranges): for i, (a, b) in enumerate(self.cell_ranges):
if a <= x <= b: if a <= x <= b:
return i return i
return None

View File

@ -500,6 +500,7 @@ class Tab: # {{{
def get_nth_window(self, n: int) -> Optional[Window]: def get_nth_window(self, n: int) -> Optional[Window]:
if self.windows: if self.windows:
return self.current_layout.nth_window(self.windows, n) return self.current_layout.nth_window(self.windows, n)
return None
@ac('win', ''' @ac('win', '''
Focus the nth window if positive or the previously active windows if negative Focus the nth window if positive or the previously active windows if negative
@ -541,6 +542,7 @@ class Tab: # {{{
if groups: if groups:
return groups[0] return groups[0]
return None
def nth_active_window_id(self, n: int = 0) -> int: def nth_active_window_id(self, n: int = 0) -> int:
if n <= 0: if n <= 0:
@ -553,6 +555,7 @@ class Tab: # {{{
candidates = neighbors.get(which) candidates = neighbors.get(which)
if candidates: if candidates:
return self.most_recent_group(candidates) return self.most_recent_group(candidates)
return None
@ac('win', ''' @ac('win', '''
Focus the neighboring window in the current tab Focus the neighboring window in the current tab
@ -794,6 +797,7 @@ class TabManager: # {{{
delta = -1 if loc == 'left' else 1 delta = -1 if loc == 'left' else 1
idx = (len(self.tabs) + self.active_tab_idx + delta) % len(self.tabs) idx = (len(self.tabs) + self.active_tab_idx + delta) % len(self.tabs)
return self.tabs[idx] return self.tabs[idx]
return None
def goto_tab(self, tab_num: int) -> None: def goto_tab(self, tab_num: int) -> None:
if tab_num >= len(self.tabs): if tab_num >= len(self.tabs):
@ -856,6 +860,7 @@ class TabManager: # {{{
t = self.active_tab t = self.active_tab
if t is not None: if t is not None:
return t.active_window return t.active_window
return None
@property @property
def number_of_windows_with_running_programs(self) -> int: def number_of_windows_with_running_programs(self) -> int:
@ -875,6 +880,7 @@ class TabManager: # {{{
for t in self.tabs: for t in self.tabs:
if t.id == tab_id: if t.id == tab_id:
return t return t
return None
def move_tab(self, delta: int = 1) -> None: def move_tab(self, delta: int = 1) -> None:
if len(self.tabs) > 1: if len(self.tabs) > 1:

View File

@ -61,6 +61,7 @@ def platform_window_id(os_window_id: int) -> Optional[int]:
from .fast_data_types import x11_window_id from .fast_data_types import x11_window_id
with suppress(Exception): with suppress(Exception):
return x11_window_id(os_window_id) return x11_window_id(os_window_id)
return None
def load_shaders(name: str, vertex_name: str = '', fragment_name: str = '') -> Tuple[str, str]: def load_shaders(name: str, vertex_name: str = '', fragment_name: str = '') -> Tuple[str, str]:
@ -284,6 +285,7 @@ def init_startup_notification(window_handle: Optional[int], startup_id: Optional
except Exception: except Exception:
import traceback import traceback
traceback.print_exc() traceback.print_exc()
return None
def end_startup_notification(ctx: Optional['StartupCtx']) -> None: def end_startup_notification(ctx: Optional['StartupCtx']) -> None:
@ -500,6 +502,7 @@ def resolve_editor_cmd(editor: str, shell_env: Mapping[str, str]) -> Optional[st
q = shutil.which(editor_exe, path=shell_env['PATH']) q = shutil.which(editor_exe, path=shell_env['PATH'])
if q: if q:
return patched(q) return patched(q)
return None
def get_editor_from_env(env: Mapping[str, str]) -> Optional[str]: def get_editor_from_env(env: Mapping[str, str]) -> Optional[str]:
@ -509,6 +512,7 @@ def get_editor_from_env(env: Mapping[str, str]) -> Optional[str]:
editor = resolve_editor_cmd(editor, env) editor = resolve_editor_cmd(editor, env)
if editor: if editor:
return editor return editor
return None
def get_editor_from_env_vars(opts: Optional[Options] = None) -> List[str]: def get_editor_from_env_vars(opts: Optional[Options] = None) -> List[str]:

View File

@ -594,6 +594,7 @@ class Window:
if not text: if not text:
return True return True
self.write_to_child(text) self.write_to_child(text)
return False
@ac('debug', 'Show a dump of the current lines in the scrollback + screen with their line attributes') @ac('debug', 'Show a dump of the current lines in the scrollback + screen with their line attributes')
def dump_lines_with_attrs(self) -> None: def dump_lines_with_attrs(self) -> None:

View File

@ -108,6 +108,7 @@ class WindowGroup:
if self.windows: if self.windows:
w: WindowType = self.windows[-1] w: WindowType = self.windows[-1]
return w.geometry return w.geometry
return None
@property @property
def is_visible_in_layout(self) -> bool: def is_visible_in_layout(self) -> bool:
@ -195,6 +196,7 @@ class WindowList:
for i, gr in enumerate(self.groups): for i, gr in enumerate(self.groups):
if gr.id == group_id: if gr.id == group_id:
return self.set_active_group_idx(i) return self.set_active_group_idx(i)
return False
def change_tab(self, tab: TabType) -> None: def change_tab(self, tab: TabType) -> None:
self.tabref = weakref.ref(tab) self.tabref = weakref.ref(tab)
@ -241,32 +243,38 @@ class WindowList:
for g in self.groups: for g in self.groups:
if q in g: if q in g:
return g return g
return None
def group_idx_for_window(self, x: WindowOrId) -> Optional[int]: def group_idx_for_window(self, x: WindowOrId) -> Optional[int]:
q = self.id_map[x] if isinstance(x, int) else x q = self.id_map[x] if isinstance(x, int) else x
for i, g in enumerate(self.groups): for i, g in enumerate(self.groups):
if q in g: if q in g:
return i return i
return None
def windows_in_group_of(self, x: WindowOrId) -> Iterator[WindowType]: def windows_in_group_of(self, x: WindowOrId) -> Iterator[WindowType]:
g = self.group_for_window(x) g = self.group_for_window(x)
if g is not None: if g is not None:
return iter(g) return iter(g)
return iter(())
@property @property
def active_group(self) -> Optional[WindowGroup]: def active_group(self) -> Optional[WindowGroup]:
with suppress(Exception): with suppress(Exception):
return self.groups[self.active_group_idx] return self.groups[self.active_group_idx]
return None
@property @property
def active_window(self) -> Optional[WindowType]: def active_window(self) -> Optional[WindowType]:
with suppress(Exception): with suppress(Exception):
return self.id_map[self.groups[self.active_group_idx].active_window_id] return self.id_map[self.groups[self.active_group_idx].active_window_id]
return None
@property @property
def active_group_base(self) -> Optional[WindowType]: def active_group_base(self) -> Optional[WindowType]:
with suppress(Exception): with suppress(Exception):
return self.id_map[self.groups[self.active_group_idx].base_window_id] return self.id_map[self.groups[self.active_group_idx].base_window_id]
return None
def set_active_window_group_for(self, x: WindowOrId) -> None: def set_active_window_group_for(self, x: WindowOrId) -> None:
try: try:
@ -350,6 +358,7 @@ class WindowList:
n = max(0, min(n, self.num_groups - 1)) n = max(0, min(n, self.num_groups - 1))
if 0 <= n < self.num_groups: if 0 <= n < self.num_groups:
return self.id_map.get(self.groups[n].active_window_id) return self.id_map.get(self.groups[n].active_window_id)
return None
def activate_next_window_group(self, delta: int) -> None: def activate_next_window_group(self, delta: int) -> None:
self.set_active_group_idx(wrap_increment(self.active_group_idx, self.num_groups, delta)) self.set_active_group_idx(wrap_increment(self.active_group_idx, self.num_groups, delta))

View File

@ -22,7 +22,6 @@ warn_redundant_casts = True
warn_unused_ignores = True warn_unused_ignores = True
warn_return_any = True warn_return_any = True
warn_unreachable = True warn_unreachable = True
warn_no_return = False
warn_unused_configs = True warn_unused_configs = True
check_untyped_defs = True check_untyped_defs = True
disallow_untyped_defs = True disallow_untyped_defs = True