Skip to content

Commit c8630d8

Browse files
committed
refactor: Add mypy annotations (monkeytype + manual edits)
1 parent b14fcb4 commit c8630d8

24 files changed

+237
-108
lines changed

src/tmuxp/cli/load.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ def set_layout_hook(session: Session, hook_name: str) -> None:
107107
session.cmd(*cmd)
108108

109109

110-
def load_plugins(sconf: t.Any) -> t.List[t.Any]:
110+
def load_plugins(sconf: t.Dict[str, t.Any]) -> t.List[t.Any]:
111111
"""
112112
Load and return plugins in workspace
113113
"""

src/tmuxp/config_reader.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,11 @@ class ConfigReader:
2222
'{\n "session_name": "my session"\n}'
2323
"""
2424

25-
def __init__(self, content: "RawConfigData"):
25+
def __init__(self, content: "RawConfigData") -> None:
2626
self.content = content
2727

2828
@staticmethod
29-
def _load(format: "FormatLiteral", content: str):
29+
def _load(format: "FormatLiteral", content: str) -> t.Dict[str, t.Any]:
3030
"""Load raw config data and directly return it.
3131
3232
>>> ConfigReader._load("json", '{ "session_name": "my session" }')
@@ -46,7 +46,7 @@ def _load(format: "FormatLiteral", content: str):
4646
raise NotImplementedError(f"{format} not supported in configuration")
4747

4848
@classmethod
49-
def load(cls, format: "FormatLiteral", content: str):
49+
def load(cls, format: "FormatLiteral", content: str) -> "ConfigReader":
5050
"""Load raw config data into a ConfigReader instance (to dump later).
5151
5252
>>> cfg = ConfigReader.load("json", '{ "session_name": "my session" }')
@@ -69,7 +69,7 @@ def load(cls, format: "FormatLiteral", content: str):
6969
)
7070

7171
@classmethod
72-
def _from_file(cls, path: pathlib.Path):
72+
def _from_file(cls, path: pathlib.Path) -> t.Dict[str, t.Any]:
7373
r"""Load data from file path directly to dictionary.
7474
7575
**YAML file**
@@ -114,7 +114,7 @@ def _from_file(cls, path: pathlib.Path):
114114
)
115115

116116
@classmethod
117-
def from_file(cls, path: pathlib.Path):
117+
def from_file(cls, path: pathlib.Path) -> "ConfigReader":
118118
r"""Load data from file path
119119
120120
**YAML file**

src/tmuxp/exc.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
~~~~~~~~~
55
66
"""
7+
import typing as t
8+
79
from ._compat import implements_to_string
810

911

@@ -28,7 +30,7 @@ class TmuxpPluginException(TmuxpException):
2830

2931

3032
class BeforeLoadScriptNotExists(OSError):
31-
def __init__(self, *args, **kwargs):
33+
def __init__(self, *args, **kwargs) -> None:
3234
super().__init__(*args, **kwargs)
3335

3436
self.strerror = "before_script file '%s' doesn't exist." % self.strerror
@@ -41,7 +43,9 @@ class BeforeLoadScriptError(Exception):
4143
:meth:`tmuxp.util.run_before_script`.
4244
"""
4345

44-
def __init__(self, returncode, cmd, output=None):
46+
def __init__(
47+
self, returncode: int, cmd: str, output: t.Optional[str] = None
48+
) -> None:
4549
self.returncode = returncode
4650
self.cmd = cmd
4751
self.output = output

src/tmuxp/log.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,9 @@
2929
}
3030

3131

32-
def setup_logger(logger=None, level="INFO"):
32+
def setup_logger(
33+
logger: t.Optional[logging.Logger] = None, level: str = "INFO"
34+
) -> None:
3335
"""
3436
Setup logging for CLI use.
3537
@@ -49,8 +51,13 @@ def setup_logger(logger=None, level="INFO"):
4951

5052

5153
def set_style(
52-
message, stylized, style_before=None, style_after=None, prefix="", suffix=""
53-
):
54+
message: str,
55+
stylized: bool,
56+
style_before: t.Optional[str] = None,
57+
style_after: t.Optional[str] = None,
58+
prefix: str = "",
59+
suffix: str = "",
60+
) -> str:
5461
if stylized:
5562
return prefix + style_before + message + style_after + suffix
5663

@@ -112,10 +119,10 @@ def default_log_template(
112119
class LogFormatter(logging.Formatter):
113120
template = default_log_template
114121

115-
def __init__(self, color=True, *args, **kwargs):
122+
def __init__(self, color: bool = True, *args, **kwargs) -> None:
116123
logging.Formatter.__init__(self, *args, **kwargs)
117124

118-
def format(self, record):
125+
def format(self, record: logging.LogRecord) -> str:
119126
try:
120127
record.message = record.getMessage()
121128
except Exception as e:

src/tmuxp/plugin.py

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import typing as t
2+
13
import libtmux
24
from libtmux._compat import LegacyVersion as Version
35
from libtmux.common import get_version
@@ -27,17 +29,17 @@
2729
class TmuxpPlugin:
2830
def __init__(
2931
self,
30-
plugin_name="tmuxp-plugin",
31-
tmux_min_version=TMUX_MIN_VERSION,
32-
tmux_max_version=TMUX_MAX_VERSION,
33-
tmux_version_incompatible=None,
34-
libtmux_min_version=LIBTMUX_MIN_VERSION,
35-
libtmux_max_version=LIBTMUX_MAX_VERSION,
36-
libtmux_version_incompatible=None,
37-
tmuxp_min_version=TMUXP_MIN_VERSION,
38-
tmuxp_max_version=TMUXP_MAX_VERSION,
39-
tmuxp_version_incompatible=None,
40-
):
32+
plugin_name: str = "tmuxp-plugin",
33+
tmux_min_version: str = TMUX_MIN_VERSION,
34+
tmux_max_version: t.Optional[str] = TMUX_MAX_VERSION,
35+
tmux_version_incompatible: t.Optional[t.List[str]] = None,
36+
libtmux_min_version: str = LIBTMUX_MIN_VERSION,
37+
libtmux_max_version: t.Optional[str] = LIBTMUX_MAX_VERSION,
38+
libtmux_version_incompatible: t.Optional[t.List[str]] = None,
39+
tmuxp_min_version: str = TMUXP_MIN_VERSION,
40+
tmuxp_max_version: t.Optional[str] = TMUXP_MAX_VERSION,
41+
tmuxp_version_incompatible: t.Optional[t.List[str]] = None,
42+
) -> None:
4143
"""
4244
Initialize plugin.
4345
@@ -114,7 +116,7 @@ def __init__(
114116

115117
self._version_check()
116118

117-
def _version_check(self):
119+
def _version_check(self) -> None:
118120
"""
119121
Check all dependency versions for compatibility.
120122
"""
@@ -130,7 +132,13 @@ def _version_check(self):
130132
)
131133
)
132134

133-
def _pass_version_check(self, version, vmin, vmax, incompatible):
135+
def _pass_version_check(
136+
self,
137+
version: t.Union[str, Version],
138+
vmin: str,
139+
vmax: t.Optional[str],
140+
incompatible: t.List[t.Union[t.Any, str]],
141+
) -> bool:
134142
"""
135143
Provide affirmative if version compatibility is correct.
136144
"""

src/tmuxp/shell.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
logger = logging.getLogger(__name__)
1111

1212

13-
def has_ipython():
13+
def has_ipython() -> bool:
1414
try:
1515
from IPython import start_ipython # NOQA F841
1616
except ImportError:
@@ -22,7 +22,7 @@ def has_ipython():
2222
return True
2323

2424

25-
def has_ptpython():
25+
def has_ptpython() -> bool:
2626
try:
2727
from ptpython.repl import embed, run_config # NOQA F841
2828
except ImportError:
@@ -34,7 +34,7 @@ def has_ptpython():
3434
return True
3535

3636

37-
def has_ptipython():
37+
def has_ptipython() -> bool:
3838
try:
3939
from ptpython.ipython import embed # NOQA F841
4040
from ptpython.repl import run_config # NOQA F841
@@ -48,15 +48,15 @@ def has_ptipython():
4848
return True
4949

5050

51-
def has_bpython():
51+
def has_bpython() -> bool:
5252
try:
5353
from bpython import embed # NOQA F841
5454
except ImportError:
5555
return False
5656
return True
5757

5858

59-
def detect_best_shell():
59+
def detect_best_shell() -> str:
6060
if has_ptipython():
6161
return "ptipython"
6262
elif has_ptpython():
@@ -220,7 +220,9 @@ def launch_code():
220220
return launch_code
221221

222222

223-
def launch(shell="best", use_pythonrc=False, use_vi_mode=False, **kwargs):
223+
def launch(
224+
shell: str = "best", use_pythonrc: bool = False, use_vi_mode: bool = False, **kwargs
225+
) -> None:
224226
# Also allowing passing shell='code' to force using code.interact
225227
imported_objects = get_launch_args(**kwargs)
226228

src/tmuxp/util.py

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,20 +6,30 @@
66
"""
77
import logging
88
import os
9+
import pathlib
910
import shlex
1011
import subprocess
1112
import sys
13+
import typing as t
1214

1315
from libtmux._compat import console_to_str
1416

1517
from . import exc
1618

19+
if t.TYPE_CHECKING:
20+
from libtmux.pane import Pane
21+
from libtmux.server import Server
22+
from libtmux.session import Session
23+
from libtmux.window import Window
24+
1725
logger = logging.getLogger(__name__)
1826

1927
PY2 = sys.version_info[0] == 2
2028

2129

22-
def run_before_script(script_file, cwd=None):
30+
def run_before_script(
31+
script_file: t.Union[str, pathlib.Path], cwd: t.Optional[pathlib.Path] = None
32+
) -> int:
2333
"""Function to wrap try/except for subprocess.check_call()."""
2434
try:
2535
proc = subprocess.Popen(
@@ -50,7 +60,7 @@ def run_before_script(script_file, cwd=None):
5060
raise e
5161

5262

53-
def oh_my_zsh_auto_title():
63+
def oh_my_zsh_auto_title() -> None:
5464
"""Give warning and offer to fix ``DISABLE_AUTO_TITLE``.
5565
5666
see: https://github.com/robbyrussell/oh-my-zsh/pull/257
@@ -74,7 +84,7 @@ def oh_my_zsh_auto_title():
7484
)
7585

7686

77-
def get_current_pane(server):
87+
def get_current_pane(server: "Server") -> t.Optional[t.Dict[str, str]]:
7888
"""Return Pane if one found in env"""
7989
if os.getenv("TMUX_PANE") is not None:
8090
try:
@@ -83,7 +93,11 @@ def get_current_pane(server):
8393
pass
8494

8595

86-
def get_session(server, session_name=None, current_pane=None):
96+
def get_session(
97+
server: "Server",
98+
session_name: t.Optional[str] = None,
99+
current_pane: t.Optional[t.Dict[str, str]] = None,
100+
) -> "Session":
87101
try:
88102
if session_name:
89103
session = server.sessions.get(session_name=session_name)
@@ -107,7 +121,11 @@ def get_session(server, session_name=None, current_pane=None):
107121
return session
108122

109123

110-
def get_window(session, window_name=None, current_pane=None):
124+
def get_window(
125+
session: "Session",
126+
window_name: t.Optional[str] = None,
127+
current_pane: t.Optional[t.Dict[str, str]] = None,
128+
) -> "Window":
111129
try:
112130
if window_name:
113131
window = session.windows.get(window_name=window_name)
@@ -129,7 +147,9 @@ def get_window(session, window_name=None, current_pane=None):
129147
return window
130148

131149

132-
def get_pane(window, current_pane=None):
150+
def get_pane(
151+
window: "Window", current_pane: t.Optional[t.Dict[str, str]] = None
152+
) -> "Pane":
133153
try:
134154
if current_pane is not None:
135155
pane = window.panes.get(pane_id=current_pane.pane_id) # NOQA: F841

0 commit comments

Comments
 (0)