Skip to content

Commit 258fcbf

Browse files
committed
refactor: Add mypy annotations (monkeytype + manual edits)
1 parent dd49e6b commit 258fcbf

22 files changed

+239
-147
lines changed

src/tmuxp/cli/load.py

+1-1
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 config
113113
"""

src/tmuxp/config.py

+20-12
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,15 @@
66
"""
77
import logging
88
import os
9-
from typing import Dict
9+
from pathlib import PosixPath
10+
from typing import Any, Dict, List, Optional, Union
1011

1112
from . import exc
1213

1314
logger = logging.getLogger(__name__)
1415

1516

16-
def validate_schema(session_config):
17+
def validate_schema(session_config: Any) -> bool:
1718
"""
1819
Return True if config schema is correct.
1920
@@ -45,7 +46,9 @@ def validate_schema(session_config):
4546
return True
4647

4748

48-
def is_config_file(filename, extensions=[".yml", ".yaml", ".json"]):
49+
def is_config_file(
50+
filename: str, extensions: List[str] = [".yml", ".yaml", ".json"]
51+
) -> bool:
4952
"""
5053
Return True if file has a valid config file type.
5154
@@ -65,8 +68,9 @@ def is_config_file(filename, extensions=[".yml", ".yaml", ".json"]):
6568

6669

6770
def in_dir(
68-
config_dir=os.path.expanduser("~/.tmuxp"), extensions=[".yml", ".yaml", ".json"]
69-
):
71+
config_dir: PosixPath = os.path.expanduser("~/.tmuxp"),
72+
extensions: List[str] = [".yml", ".yaml", ".json"],
73+
) -> List[str]:
7074
"""
7175
Return a list of configs in ``config_dir``.
7276
@@ -90,7 +94,7 @@ def in_dir(
9094
return configs
9195

9296

93-
def in_cwd():
97+
def in_cwd() -> List[str]:
9498
"""
9599
Return list of configs in current working directory.
96100
@@ -115,7 +119,7 @@ def in_cwd():
115119
return configs
116120

117121

118-
def expandshell(_path):
122+
def expandshell(_path: str) -> str:
119123
"""
120124
Return expanded path based on user's ``$HOME`` and ``env``.
121125
@@ -134,7 +138,7 @@ def expandshell(_path):
134138
return os.path.expandvars(os.path.expanduser(_path))
135139

136140

137-
def inline(session_config):
141+
def inline(session_config: Dict[str, Any]) -> Any:
138142
"""
139143
Return config in inline form, opposite of :meth:`config.expand`.
140144
@@ -210,7 +214,11 @@ def expand_cmd(p: Dict) -> Dict:
210214
return p
211215

212216

213-
def expand(session_config, cwd=None, parent=None):
217+
def expand(
218+
session_config: Any,
219+
cwd: Optional[Union[str, PosixPath]] = None,
220+
parent: Optional[Any] = None,
221+
) -> Dict[str, Any]:
214222
"""Return config with shorthand and inline properties expanded.
215223
216224
This is necessary to keep the code in the :class:`WorkspaceBuilder` clean
@@ -330,7 +338,7 @@ def expand(session_config, cwd=None, parent=None):
330338
return session_config
331339

332340

333-
def trickle(session_config):
341+
def trickle(session_config: Dict[str, Any]) -> Dict[str, Any]:
334342
"""Return a dict with "trickled down" / inherited config values.
335343
336344
This will only work if config has been expanded to full form with
@@ -414,7 +422,7 @@ def trickle(session_config):
414422
return session_config
415423

416424

417-
def import_tmuxinator(session_config):
425+
def import_tmuxinator(session_config: Dict[str, Any]) -> Dict[str, Any]:
418426
"""Return tmuxp config from a `tmuxinator`_ yaml config.
419427
420428
.. _tmuxinator: https://github.com/aziz/tmuxinator
@@ -508,7 +516,7 @@ def import_tmuxinator(session_config):
508516
return tmuxp_config
509517

510518

511-
def import_teamocil(session_config):
519+
def import_teamocil(session_config: Dict[str, Any]) -> Dict[str, Any]:
512520
"""Return tmuxp config from a `teamocil`_ yaml config.
513521
514522
.. _teamocil: https://github.com/remiprev/teamocil

src/tmuxp/exc.py

+6-2
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

+12-5
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

+20-13
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import typing as t
12
from distutils.version import LooseVersion
23

34
import libtmux
@@ -28,17 +29,17 @@
2829
class TmuxpPlugin:
2930
def __init__(
3031
self,
31-
plugin_name="tmuxp-plugin",
32-
tmux_min_version=TMUX_MIN_VERSION,
33-
tmux_max_version=TMUX_MAX_VERSION,
34-
tmux_version_incompatible=None,
35-
libtmux_min_version=LIBTMUX_MIN_VERSION,
36-
libtmux_max_version=LIBTMUX_MAX_VERSION,
37-
libtmux_version_incompatible=None,
38-
tmuxp_min_version=TMUXP_MIN_VERSION,
39-
tmuxp_max_version=TMUXP_MAX_VERSION,
40-
tmuxp_version_incompatible=None,
41-
):
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:
4243
"""
4344
Initialize plugin.
4445
@@ -115,7 +116,7 @@ def __init__(
115116

116117
self._version_check()
117118

118-
def _version_check(self):
119+
def _version_check(self) -> None:
119120
"""
120121
Check all dependency versions for compatibility.
121122
"""
@@ -131,7 +132,13 @@ def _version_check(self):
131132
)
132133
)
133134

134-
def _pass_version_check(self, version, vmin, vmax, incompatible):
135+
def _pass_version_check(
136+
self,
137+
version: t.Union[str, LooseVersion],
138+
vmin: str,
139+
vmax: t.Optional[str],
140+
incompatible: t.List[t.Union[t.Any, str]],
141+
) -> bool:
135142
"""
136143
Provide affirmative if version compatibility is correct.
137144
"""

src/tmuxp/shell.py

+8-6
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

+23-7
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,18 @@
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
from libtmux.exc import LibTmuxException
17+
from libtmux.pane import Pane
18+
from libtmux.server import Server
19+
from libtmux.session import Session
20+
from libtmux.window import Window
1521

1622
from . import exc
1723

@@ -20,7 +26,9 @@
2026
PY2 = sys.version_info[0] == 2
2127

2228

23-
def run_before_script(script_file, cwd=None):
29+
def run_before_script(
30+
script_file: t.Union[str, pathlib.Path], cwd: t.Optional[pathlib.Path] = None
31+
) -> int:
2432
"""Function to wrap try/except for subprocess.check_call()."""
2533
try:
2634
proc = subprocess.Popen(
@@ -51,7 +59,7 @@ def run_before_script(script_file, cwd=None):
5159
raise e
5260

5361

54-
def oh_my_zsh_auto_title():
62+
def oh_my_zsh_auto_title() -> None:
5563
"""Give warning and offer to fix ``DISABLE_AUTO_TITLE``.
5664
5765
see: https://github.com/robbyrussell/oh-my-zsh/pull/257
@@ -75,7 +83,7 @@ def oh_my_zsh_auto_title():
7583
)
7684

7785

78-
def raise_if_tmux_not_running(server):
86+
def raise_if_tmux_not_running(server: Server) -> None:
7987
"""Raise exception if not running. More descriptive error if no server found."""
8088
try:
8189
server.sessions
@@ -92,7 +100,7 @@ def raise_if_tmux_not_running(server):
92100
raise e
93101

94102

95-
def get_current_pane(server):
103+
def get_current_pane(server: Server) -> t.Optional[t.Dict[str, str]]:
96104
"""Return Pane if one found in env"""
97105
if os.getenv("TMUX_PANE") is not None:
98106
try:
@@ -105,7 +113,11 @@ def get_current_pane(server):
105113
pass
106114

107115

108-
def get_session(server, session_name=None, current_pane=None):
116+
def get_session(
117+
server: Server,
118+
session_name: t.Optional[str] = None,
119+
current_pane: t.Optional[t.Dict[str, str]] = None,
120+
) -> Session:
109121
if session_name:
110122
session = server.find_where({"session_name": session_name})
111123
elif current_pane is not None:
@@ -126,7 +138,11 @@ def get_session(server, session_name=None, current_pane=None):
126138
return session
127139

128140

129-
def get_window(session, window_name=None, current_pane=None):
141+
def get_window(
142+
session: Session,
143+
window_name: t.Optional[str] = None,
144+
current_pane: t.Optional[t.Dict[str, str]] = None,
145+
) -> Window:
130146
if window_name:
131147
window = session.find_where({"window_name": window_name})
132148
if not window:
@@ -139,7 +155,7 @@ def get_window(session, window_name=None, current_pane=None):
139155
return window
140156

141157

142-
def get_pane(window, current_pane=None):
158+
def get_pane(window: Window, current_pane: t.Optional[t.Dict[str, str]] = None) -> Pane:
143159
try:
144160
if current_pane is not None:
145161
pane = window.find_where({"pane_id": current_pane["pane_id"]}) # NOQA: F841

0 commit comments

Comments
 (0)