Skip to content

Commit

Permalink
mypy: Turn on return value checks
Browse files Browse the repository at this point in the history
Its a shame GvR is married to "return None"
python/mypy#7511
  • Loading branch information
kovidgoyal committed Oct 26, 2021
1 parent 5cb36a4 commit 4494ddd
Show file tree
Hide file tree
Showing 52 changed files with 124 additions and 49 deletions.
1 change: 1 addition & 0 deletions kittens/broadcast/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ def main(args: List[str]) -> Optional[Dict[str, Any]]:
loop = Loop()
handler = Broadcast(opts, items)
loop.loop(handler)
return None


if __name__ == '__main__':
Expand Down
1 change: 1 addition & 0 deletions kittens/diff/patch.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ def find_differ() -> Optional[str]:
return GIT_DIFF
if shutil.which('diff'):
return DIFF_DIFF
return None


def set_diff_command(opt: str) -> None:
Expand Down
1 change: 1 addition & 0 deletions kittens/hints/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -688,6 +688,7 @@ def main(args: List[str]) -> Optional[Dict[str, Any]]:
import traceback
traceback.print_exc()
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:
Expand Down
4 changes: 3 additions & 1 deletion kittens/remote_file/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def __enter__(self) -> 'ControlMaster':
self.dest = os.path.join(self.tdir, os.path.basename(self.remote_path))
return self

def __exit__(self, *a: Any) -> bool:
def __exit__(self, *a: Any) -> None:
subprocess.Popen(
self.batch_cmd_prefix + ['-O', 'exit', self.conn_data.hostname],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL
Expand Down Expand Up @@ -215,6 +215,7 @@ def main(args: List[str]) -> Result:
import traceback
traceback.print_exc()
show_error('Failed with unhandled exception')
return None


def save_as(conn_data: SSHConnectionData, remote_path: str, cli_opts: RemoteFileCLIOptions) -> None:
Expand Down Expand Up @@ -312,6 +313,7 @@ def handle_action(action: str, cli_opts: RemoteFileCLIOptions) -> Result:
elif action == 'save':
print('Saving', cli_opts.path, 'from', cli_opts.hostname)
save_as(conn_data, remote_path, cli_opts)
return None


@result_handler()
Expand Down
1 change: 1 addition & 0 deletions kittens/themes/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,7 @@ def set_colors_to_current_theme(self) -> bool:
col = color_as_sharp(color_from_int(o.color_table[i]))
cmds.append(f'{i};{col}')
self.print(end='\033]4;' + ';'.join(cmds) + '\033\\')
return True

def redraw_after_category_change(self) -> None:
self.themes_list.update_themes(self.all_themes.filtered(self.filter_map[self.current_category]))
Expand Down
2 changes: 2 additions & 0 deletions kittens/transfer/send.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,7 @@ def active_file(self) -> Optional[File]:
ans = self.files[self.active_idx]
if ans.state is FileState.transmitting:
return ans
return None

def activate_next_ready_file(self) -> Optional[File]:
if self.active_idx is not None:
Expand All @@ -325,6 +326,7 @@ def activate_next_ready_file(self) -> Optional[File]:
return f
self.active_idx = None
self.update_collective_statuses()
return None

def update_collective_statuses(self) -> None:
found_not_started = found_not_done = False
Expand Down
1 change: 1 addition & 0 deletions kittens/tui/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ def shortcut_action(self, key_event: KeyEventType) -> Optional[KeyActionType]:
for sc, action in self._key_shortcuts.items():
if key_event.matches(sc):
return action
return None

def __enter__(self) -> None:
if self._image_manager is not None:
Expand Down
2 changes: 2 additions & 0 deletions kittens/tui/path_completer.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ def __call__(self, text: str, state: int) -> Optional[str]:
options = self.cache[text] = tuple(find_completions(text))
if options and state < len(options):
return options[state]
return None

def __exit__(self, *a: Any) -> bool:
import readline
Expand All @@ -143,6 +144,7 @@ def __exit__(self, *a: Any) -> bool:
def input(self) -> str:
with self:
return input(self.prompt)
return ''


def develop() -> None:
Expand Down
1 change: 1 addition & 0 deletions kittens/unicode_input/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ def __init__(self, emoji_variation: str) -> None:
def current_codepoint(self) -> Optional[int]:
if self.codepoints:
return self.codepoints[self.current_idx]
return None

def set_codepoints(self, codepoints: List[int], mode: str = HEX, current_idx: int = 0) -> None:
self.codepoints = codepoints
Expand Down
86 changes: 45 additions & 41 deletions kitty/boss.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
from functools import partial
from gettext import gettext as _
from typing import (
Any, Callable, Dict, Generator, Iterable, List, Optional, Tuple, Union,
cast
Any, Callable, Dict, Iterable, Iterator, List, Optional, Tuple,
Union, cast
)
from weakref import WeakValueDictionary

Expand All @@ -27,16 +27,16 @@
)
from .fast_data_types import (
CLOSE_BEING_CONFIRMED, GLFW_MOD_ALT, GLFW_MOD_CONTROL, GLFW_MOD_SHIFT,
GLFW_MOD_SUPER, IMPERATIVE_CLOSE_REQUESTED, NO_CLOSE_REQUESTED,
ChildMonitor, KeyEvent, add_timer, apply_options_update,
background_opacity_of, change_background_opacity, change_os_window_state,
cocoa_set_menubar_title, create_os_window, GLFW_PRESS, GLFW_MOUSE_BUTTON_LEFT,
current_application_quit_request, current_os_window, destroy_global_data,
focus_os_window, get_clipboard_string, get_options, get_os_window_size,
global_font_size, mark_os_window_for_close, os_window_font_size,
patch_global_colors, redirect_mouse_handling, ring_bell, safe_pipe,
set_application_quit_request, set_background_image, set_boss,
set_clipboard_string, set_in_sequence_mode, set_options,
GLFW_MOD_SUPER, GLFW_MOUSE_BUTTON_LEFT, GLFW_PRESS,
IMPERATIVE_CLOSE_REQUESTED, NO_CLOSE_REQUESTED, ChildMonitor, KeyEvent,
add_timer, apply_options_update, background_opacity_of,
change_background_opacity, change_os_window_state, cocoa_set_menubar_title,
create_os_window, current_application_quit_request, current_os_window,
destroy_global_data, focus_os_window, get_clipboard_string, get_options,
get_os_window_size, global_font_size, mark_os_window_for_close,
os_window_font_size, patch_global_colors, redirect_mouse_handling,
ring_bell, safe_pipe, set_application_quit_request, set_background_image,
set_boss, set_clipboard_string, set_in_sequence_mode, set_options,
set_os_window_size, thread_write, toggle_fullscreen, toggle_maximized
)
from .key_encoding import get_name_to_functional_number_map
Expand Down Expand Up @@ -234,7 +234,7 @@ def add_os_window(
self.os_window_map[os_window_id] = tm
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():
active_tab, active_window = self.active_tab, self.active_window
active_tab_manager = self.active_tab_manager
Expand All @@ -249,20 +249,20 @@ def list_os_windows(self, self_window: Optional[Window] = None) -> Generator[OSW
}

@property
def all_tab_managers(self) -> Generator[TabManager, None, None]:
def all_tab_managers(self) -> Iterator[TabManager]:
yield from self.os_window_map.values()

@property
def all_tabs(self) -> Generator[Tab, None, None]:
def all_tabs(self) -> Iterator[Tab]:
for tm in self.all_tab_managers:
yield from tm

@property
def all_windows(self) -> Generator[Window, None, None]:
def all_windows(self) -> Iterator[Window]:
for tab in self.all_tabs:
yield from tab

def match_windows(self, match: str) -> Generator[Window, None, None]:
def match_windows(self, match: str) -> Iterator[Window]:
try:
field, exp = match.split(':', 1)
except ValueError:
Expand Down Expand Up @@ -305,8 +305,9 @@ def tab_for_window(self, window: Window) -> Optional[Tab]:
for w in tab:
if w.id == window.id:
return tab
return None

def match_tabs(self, match: str) -> Generator[Tab, None, None]:
def match_tabs(self, match: str) -> Iterator[Tab]:
try:
field, exp = match.split(':', 1)
except ValueError:
Expand Down Expand Up @@ -359,6 +360,7 @@ def set_active_window(self, window: Window, switch_os_window_if_needed: bool = F
if switch_os_window_if_needed and current_os_window() != os_window_id:
focus_os_window(os_window_id, True)
return os_window_id
return None

def _new_os_window(self, args: Union[SpecialWindowInstance, Iterable[str]], cwd_from: Optional[int] = None) -> int:
if isinstance(args, SpecialWindowInstance):
Expand All @@ -377,6 +379,7 @@ def active_window_for_cwd(self) -> Optional[Window]:
t = self.active_tab
if t is not None:
return t.active_window_for_cwd
return None

@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:
Expand Down Expand Up @@ -595,7 +598,7 @@ def start(self, first_os_window_id: int) -> None:
run_update_check(get_options().update_check_interval * 60 * 60)
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)
if tm is not None:
tm.handle_click_on_tab(x, button, modifiers, action)
Expand Down Expand Up @@ -751,20 +754,17 @@ def set_background_opacity(self, opacity: str) -> None:
@property
def active_tab_manager(self) -> Optional[TabManager]:
os_window_id = current_os_window()
if os_window_id is not None:
return self.os_window_map.get(os_window_id)
return None if os_window_id is None else self.os_window_map.get(os_window_id)

@property
def active_tab(self) -> Optional[Tab]:
tm = self.active_tab_manager
if tm is not None:
return tm.active_tab
return None if tm is None else tm.active_tab

@property
def active_window(self) -> Optional[Window]:
t = self.active_tab
if t is not None:
return t.active_window
return None if t is None else t.active_window

def set_pending_sequences(self, sequences: SubSequenceMap, default_pending_action: Optional[KeyAction] = None) -> None:
self.pending_sequences = sequences
Expand All @@ -783,6 +783,7 @@ def dispatch_possible_special_key(self, ev: KeyEvent) -> bool:
return True
elif isinstance(key_action, KeyAction):
return self.dispatch_action(key_action)
return False

def clear_pending_sequences(self) -> None:
self.pending_sequences = self.default_pending_action = None
Expand Down Expand Up @@ -1530,7 +1531,7 @@ def run_background_process(
else:
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)
window = self.active_window
cwd_from = window.child.pid_for_cwd if window else None
Expand Down Expand Up @@ -1559,6 +1560,7 @@ def create_window() -> SpecialWindowInstance:
else:
env, stdin = self.process_stdin_source(stdin=source, window=window)
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:
args = list(args)
Expand Down Expand Up @@ -1591,6 +1593,7 @@ def _new_tab(self, args: Union[SpecialWindowInstance, Iterable[str]], cwd_from:
tm = self.active_tab_manager
if tm is not None:
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:
as_neighbor = False
Expand All @@ -1615,21 +1618,22 @@ def new_tab_with_wd(self, wd: str) -> None:

def _new_window(self, args: List[str], cwd_from: Optional[int] = None) -> Optional[Window]:
tab = self.active_tab
if tab is not None:
allow_remote_control = False
location = None
if args and args[0].startswith('!'):
location = args[0][1:].lower()
args = args[1:]
if args and args[0] == '@':
args = args[1:]
allow_remote_control = True
if args:
return tab.new_special_window(
self.args_to_special_window(args, cwd_from=cwd_from),
location=location, allow_remote_control=allow_remote_control)
else:
return tab.new_window(cwd_from=cwd_from, location=location, allow_remote_control=allow_remote_control)
if tab is None:
return None
allow_remote_control = False
location = None
if args and args[0].startswith('!'):
location = args[0][1:].lower()
args = args[1:]
if args and args[0] == '@':
args = args[1:]
allow_remote_control = True
if args:
return tab.new_special_window(
self.args_to_special_window(args, cwd_from=cwd_from),
location=location, allow_remote_control=allow_remote_control)
else:
return tab.new_window(cwd_from=cwd_from, location=location, allow_remote_control=allow_remote_control)

@ac('win', 'Create a new window')
def new_window(self, *args: str) -> None:
Expand Down
2 changes: 2 additions & 0 deletions kitty/child.py
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,7 @@ def current_cwd(self) -> Optional[str]:
with suppress(Exception):
assert self.pid is not None
return cwd_of_process(self.pid)
return None

@property
def pid_for_cwd(self) -> Optional[int]:
Expand All @@ -349,6 +350,7 @@ def foreground_cwd(self) -> Optional[str]:
with suppress(Exception):
assert self.pid_for_cwd is not None
return cwd_of_process(self.pid_for_cwd) or None
return None

@property
def foreground_environ(self) -> Dict[str, str]:
Expand Down
1 change: 1 addition & 0 deletions kitty/file_transmission.py
Original file line number Diff line number Diff line change
Expand Up @@ -951,3 +951,4 @@ def start_send(self, aid: str) -> None:

def callback_after(self, callback: Callable[[Optional[int]], None], timeout: float = 0) -> Optional[int]:
callback(None)
return None
11 changes: 7 additions & 4 deletions kitty/fonts/box_drawing.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from functools import partial as p, wraps
from itertools import repeat
from typing import (
Any, Callable, Dict, Generator, Iterable, List, MutableSequence, Optional,
Any, Callable, Dict, Iterable, Iterator, List, MutableSequence, Optional,
Sequence, Tuple, cast
)

Expand Down Expand Up @@ -314,6 +314,7 @@ def pt_to_coords(p: str) -> Tuple[int, int]:
return width - 1, mid_y
if p == 'b':
return mid_x, height - 1
raise KeyError(f'Unknown p: {p}')

for x in pts:
p1, p2 = map(pt_to_coords, x)
Expand Down Expand Up @@ -353,7 +354,7 @@ def find_bezier_for_D(width: int, height: int) -> int:
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))
max_x = int(bezier_x(0.5))
last_t, t_limit = 0., 0.5
Expand Down Expand Up @@ -1043,8 +1044,9 @@ def render_missing_glyph(buf: BufType, width: int, height: int) -> None:

def test_char(ch: str, sz: int = 48) -> None:
# 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 .render import display_bitmap, setup_for_testing
with setup_for_testing('monospace', sz) as (_, width, height):
buf = bytearray(width * height)
try:
Expand All @@ -1062,9 +1064,10 @@ def join_cells(*cells: bytes) -> bytes:


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 .render import display_bitmap, setup_for_testing

with setup_for_testing(family, sz) as (_, width, height):
space = bytearray(width * height)

Expand Down
1 change: 1 addition & 0 deletions kitty/layout/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ def idx_for_id(win_id: int, windows: Iterable[WindowType]) -> Optional[int]:
for i, w in enumerate(windows):
if w.id == win_id:
return i
return None


def set_layout_options(opts: Options) -> None:
Expand Down
1 change: 1 addition & 0 deletions kitty/layout/grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ def on_col_done(col_windows: List[int]) -> None:
if idx == window_idx:
return row_num, col_num
row_num += 1
return 0, 0

row_num, col_num = position_for_window_idx(idx)

Expand Down

0 comments on commit 4494ddd

Please sign in to comment.