Skip to content

Commit d5010d8

Browse files
committed
refactor: fix mypy output and better type
1 parent acf41e1 commit d5010d8

File tree

17 files changed

+91
-62
lines changed

17 files changed

+91
-62
lines changed

commitizen/changelog.py

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

3030
import re
3131
from collections import OrderedDict, defaultdict
32-
from collections.abc import Generator, Iterable, Mapping
32+
from collections.abc import Generator, Iterable, Mapping, Sequence
3333
from dataclasses import dataclass
3434
from datetime import date
3535
from typing import TYPE_CHECKING, Any
@@ -225,7 +225,7 @@ def render_changelog(
225225
tree: Iterable,
226226
loader: BaseLoader,
227227
template: str,
228-
**kwargs,
228+
**kwargs: Any,
229229
) -> str:
230230
jinja_template = get_changelog_template(loader, template)
231231
changelog: str = jinja_template.render(tree=tree, **kwargs)
@@ -282,7 +282,7 @@ def incremental_build(
282282

283283

284284
def get_smart_tag_range(
285-
tags: list[GitTag], newest: str, oldest: str | None = None
285+
tags: Sequence[GitTag], newest: str, oldest: str | None = None
286286
) -> list[GitTag]:
287287
"""Smart because it finds the N+1 tag.
288288
@@ -308,10 +308,10 @@ def get_smart_tag_range(
308308

309309

310310
def get_oldest_and_newest_rev(
311-
tags: list[GitTag],
311+
tags: Sequence[GitTag],
312312
version: str,
313313
rules: TagRules,
314-
) -> tuple[str | None, str | None]:
314+
) -> tuple[str | None, str]:
315315
"""Find the tags for the given version.
316316
317317
`version` may come in different formats:

commitizen/cli.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def __call__(
5050
namespace: argparse.Namespace,
5151
kwarg: str | Sequence[Any] | None,
5252
option_string: str | None = None,
53-
):
53+
) -> None:
5454
if not isinstance(kwarg, str):
5555
return
5656
if "=" not in kwarg:
@@ -551,8 +551,12 @@ def __call__(
551551

552552

553553
def commitizen_excepthook(
554-
type, value, traceback, debug=False, no_raise: list[int] | None = None
555-
):
554+
type: type,
555+
value: Exception,
556+
traceback: TracebackType | None,
557+
debug: bool = False,
558+
no_raise: list[int] | None = None,
559+
) -> None:
556560
traceback = traceback if isinstance(traceback, TracebackType) else None
557561
if not isinstance(value, CommitizenException):
558562
original_excepthook(type, value, traceback)
@@ -572,7 +576,7 @@ def commitizen_excepthook(
572576

573577
commitizen_debug_excepthook = partial(commitizen_excepthook, debug=True)
574578

575-
sys.excepthook = commitizen_excepthook
579+
sys.excepthook = commitizen_excepthook # type: ignore
576580

577581

578582
def parse_no_raise(comma_separated_no_raise: str) -> list[int]:
@@ -582,7 +586,7 @@ def parse_no_raise(comma_separated_no_raise: str) -> list[int]:
582586
represents the exit code found in exceptions.
583587
"""
584588
no_raise_items: list[str] = comma_separated_no_raise.split(",")
585-
no_raise_codes = []
589+
no_raise_codes: list[int] = []
586590
for item in no_raise_items:
587591
if item.isdecimal():
588592
no_raise_codes.append(int(item))
@@ -597,7 +601,7 @@ def parse_no_raise(comma_separated_no_raise: str) -> list[int]:
597601
return no_raise_codes
598602

599603

600-
def main():
604+
def main() -> None:
601605
parser = cli(data)
602606
argcomplete.autocomplete(parser)
603607
# Show help if no arg provided

commitizen/cmd.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import os
22
import subprocess
3-
from typing import NamedTuple
3+
from collections.abc import Mapping
4+
from typing import NamedTuple, Union
45

56
from charset_normalizer import from_bytes
67

@@ -28,7 +29,7 @@ def _try_decode(bytes_: bytes) -> str:
2829
raise CharacterSetDecodeError() from e
2930

3031

31-
def run(cmd: str, env=None) -> Command:
32+
def run(cmd: str, env: Union[Mapping[str, str], None] = None) -> Command:
3233
if env is not None:
3334
env = {**os.environ, **env}
3435
process = subprocess.Popen(

commitizen/commands/changelog.py

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,11 @@
22

33
import os
44
import os.path
5-
from collections.abc import Generator
5+
from collections.abc import Generator, Iterable, Mapping
66
from difflib import SequenceMatcher
77
from operator import itemgetter
88
from pathlib import Path
9+
from typing import Any, cast
910

1011
from commitizen import changelog, defaults, factory, git, out
1112
from commitizen.changelog_formats import get_changelog_format
@@ -28,7 +29,7 @@
2829
class Changelog:
2930
"""Generate a changelog based on the commit history."""
3031

31-
def __init__(self, config: BaseConfig, args):
32+
def __init__(self, config: BaseConfig, args: Mapping[str, Any]):
3233
if not git.is_git_project():
3334
raise NotAGitProjectError()
3435

@@ -76,10 +77,11 @@ def __init__(self, config: BaseConfig, args):
7677
self.change_type_map = (
7778
self.config.settings.get("change_type_map") or self.cz.change_type_map
7879
)
79-
self.change_type_order = (
80+
self.change_type_order = cast(
81+
list[str],
8082
self.config.settings.get("change_type_order")
8183
or self.cz.change_type_order
82-
or defaults.CHANGE_TYPE_ORDER
84+
or defaults.CHANGE_TYPE_ORDER,
8385
)
8486
self.rev_range = args.get("rev_range")
8587
self.tag_format: str = (
@@ -102,7 +104,7 @@ def __init__(self, config: BaseConfig, args):
102104
self.extras = args.get("extras") or {}
103105
self.export_template_to = args.get("export_template")
104106

105-
def _find_incremental_rev(self, latest_version: str, tags: list[GitTag]) -> str:
107+
def _find_incremental_rev(self, latest_version: str, tags: Iterable[GitTag]) -> str:
106108
"""Try to find the 'start_rev'.
107109
108110
We use a similarity approach. We know how to parse the version from the markdown
@@ -151,18 +153,18 @@ def write_changelog(
151153

152154
changelog_file.write(changelog_out)
153155

154-
def export_template(self):
156+
def export_template(self) -> None:
155157
tpl = changelog.get_changelog_template(self.cz.template_loader, self.template)
156-
src = Path(tpl.filename)
157-
Path(self.export_template_to).write_text(src.read_text())
158+
src = Path(tpl.filename) # type: ignore
159+
Path(self.export_template_to).write_text(src.read_text()) # type: ignore
158160

159-
def __call__(self):
161+
def __call__(self) -> None:
160162
commit_parser = self.cz.commit_parser
161163
changelog_pattern = self.cz.changelog_pattern
162164
start_rev = self.start_rev
163165
unreleased_version = self.unreleased_version
164166
changelog_meta = changelog.Metadata()
165-
change_type_map: dict | None = self.change_type_map
167+
change_type_map: dict[str, str] | None = self.change_type_map # type: ignore
166168
changelog_message_builder_hook: MessageBuilderHook | None = (
167169
self.cz.changelog_message_builder_hook
168170
)
@@ -190,7 +192,7 @@ def __call__(self):
190192
changelog_meta = self.changelog_format.get_metadata(self.file_name)
191193
if changelog_meta.latest_version:
192194
start_rev = self._find_incremental_rev(
193-
strip_local_version(changelog_meta.latest_version_tag), tags
195+
strip_local_version(changelog_meta.latest_version_tag or ""), tags
194196
)
195197
if self.rev_range:
196198
start_rev, end_rev = changelog.get_oldest_and_newest_rev(

commitizen/commands/check.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@
1717
class Check:
1818
"""Check if the current commit msg matches the commitizen format."""
1919

20-
def __init__(self, config: BaseConfig, arguments: dict[str, Any], cwd=os.getcwd()):
20+
def __init__(
21+
self, config: BaseConfig, arguments: dict[str, Any], cwd: str = os.getcwd()
22+
):
2123
"""Initial check command.
2224
2325
Args:
@@ -48,7 +50,7 @@ def __init__(self, config: BaseConfig, arguments: dict[str, Any], cwd=os.getcwd(
4850
self.encoding = config.settings["encoding"]
4951
self.cz = factory.committer_factory(self.config)
5052

51-
def _valid_command_argument(self):
53+
def _valid_command_argument(self) -> None:
5254
num_exclusive_args_provided = sum(
5355
arg is not None
5456
for arg in (self.commit_msg_file, self.commit_msg, self.rev_range)
@@ -61,7 +63,7 @@ def _valid_command_argument(self):
6163
"See 'cz check -h' for more information"
6264
)
6365

64-
def __call__(self):
66+
def __call__(self) -> None:
6567
"""Validate if commit messages follows the conventional pattern.
6668
6769
Raises:
@@ -97,7 +99,7 @@ def _get_commit_message(self) -> str | None:
9799
# Get commit message from file (--commit-msg-file)
98100
return commit_file.read()
99101

100-
def _get_commits(self):
102+
def _get_commits(self) -> list[git.GitCommit]:
101103
if (msg := self._get_commit_message()) is not None:
102104
return [git.GitCommit(rev="", title="", body=self._filter_comments(msg))]
103105

commitizen/commands/commit.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
import shutil
66
import subprocess
77
import tempfile
8+
from pathlib import Path
9+
from typing import Union, cast
810

911
import questionary
1012

@@ -105,11 +107,13 @@ def _get_message(self) -> str:
105107
return self.read_backup_message() or self.prompt_commit_questions()
106108
return self.prompt_commit_questions()
107109

108-
def __call__(self):
109-
extra_args: str = self.arguments.get("extra_cli_args", "")
110-
dry_run: bool = self.arguments.get("dry_run")
111-
write_message_to_file: bool = self.arguments.get("write_message_to_file")
112-
signoff: bool = self.arguments.get("signoff")
110+
def __call__(self) -> None:
111+
extra_args = cast(str, self.arguments.get("extra_cli_args", ""))
112+
dry_run = cast(bool, self.arguments.get("dry_run"))
113+
write_message_to_file = cast(
114+
Union[Path, None], self.arguments.get("write_message_to_file")
115+
)
116+
signoff = cast(bool, self.arguments.get("signoff"))
113117

114118
if self.arguments.get("all"):
115119
git.add("-u")

commitizen/commands/info.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@
55
class Info:
66
"""Show in depth explanation of your rules."""
77

8-
def __init__(self, config: BaseConfig, *args):
8+
def __init__(self, config: BaseConfig, *args: object):
99
self.config: BaseConfig = config
1010
self.cz = factory.committer_factory(self.config)
1111

12-
def __call__(self):
12+
def __call__(self) -> None:
1313
out.write(self.cz.info())

commitizen/commands/init.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ def _ask_tag(self) -> str:
207207
raise NoAnswersError("Tag is required!")
208208
return latest_tag
209209

210-
def _ask_tag_format(self, latest_tag) -> str:
210+
def _ask_tag_format(self, latest_tag: str) -> str:
211211
is_correct_format = False
212212
if latest_tag.startswith("v"):
213213
tag_format = r"v$version"
@@ -302,7 +302,7 @@ def _ask_update_changelog_on_bump(self) -> bool:
302302
).unsafe_ask()
303303
return update_changelog_on_bump
304304

305-
def _exec_install_pre_commit_hook(self, hook_types: list[str]):
305+
def _exec_install_pre_commit_hook(self, hook_types: list[str]) -> None:
306306
cmd_str = self._gen_pre_commit_cmd(hook_types)
307307
c = cmd.run(cmd_str)
308308
if c.return_code != 0:
@@ -323,7 +323,7 @@ def _gen_pre_commit_cmd(self, hook_types: list[str]) -> str:
323323
)
324324
return cmd_str
325325

326-
def _install_pre_commit_hook(self, hook_types: list[str] | None = None):
326+
def _install_pre_commit_hook(self, hook_types: list[str] | None = None) -> None:
327327
pre_commit_config_filename = ".pre-commit-config.yaml"
328328
cz_hook_config = {
329329
"repo": "https://github.com/commitizen-tools/commitizen",
@@ -369,6 +369,6 @@ def _install_pre_commit_hook(self, hook_types: list[str] | None = None):
369369
self._exec_install_pre_commit_hook(hook_types)
370370
out.write("commitizen pre-commit hook is now installed in your '.git'\n")
371371

372-
def _update_config_file(self, values: dict[str, Any]):
372+
def _update_config_file(self, values: dict[str, Any]) -> None:
373373
for key, value in values.items():
374374
self.config.set_key(key, value)

commitizen/commands/list_cz.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66
class ListCz:
77
"""List currently installed rules."""
88

9-
def __init__(self, config: BaseConfig, *args):
9+
def __init__(self, config: BaseConfig, *args: object):
1010
self.config: BaseConfig = config
1111

12-
def __call__(self):
12+
def __call__(self) -> None:
1313
out.write("\n".join(registry.keys()))

commitizen/commands/version.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import platform
22
import sys
3+
from collections.abc import Mapping
4+
from typing import Any
35

46
from commitizen import out
57
from commitizen.__version__ import __version__
@@ -10,13 +12,13 @@
1012
class Version:
1113
"""Get the version of the installed commitizen or the current project."""
1214

13-
def __init__(self, config: BaseConfig, *args):
15+
def __init__(self, config: BaseConfig, *args: Mapping[str, Any]):
1416
self.config: BaseConfig = config
1517
self.parameter = args[0]
1618
self.operating_system = platform.system()
1719
self.python_version = sys.version
1820

19-
def __call__(self):
21+
def __call__(self) -> None:
2022
if self.parameter.get("report"):
2123
out.write(f"Commitizen Version: {__version__}")
2224
out.write(f"Python Version: {self.python_version}")

commitizen/config/base_config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77

88
class BaseConfig:
9-
def __init__(self):
9+
def __init__(self) -> None:
1010
self._settings: Settings = DEFAULT_SETTINGS.copy()
1111
self.encoding = self.settings["encoding"]
1212
self._path: Path | None = None

commitizen/cz/conventional_commits/conventional_commits.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
__all__ = ["ConventionalCommitsCz"]
1010

1111

12-
def parse_scope(text):
12+
def parse_scope(text: str) -> str:
1313
if not text:
1414
return ""
1515

@@ -20,7 +20,7 @@ def parse_scope(text):
2020
return "-".join(scope)
2121

2222

23-
def parse_subject(text):
23+
def parse_subject(text: str) -> str:
2424
if isinstance(text, str):
2525
text = text.strip(".").strip()
2626

commitizen/cz/utils.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,21 @@
11
import os
22
import re
33
import tempfile
4+
from typing import Union
45

56
from commitizen import git
67
from commitizen.cz import exceptions
78

89
_RE_LOCAL_VERSION = re.compile(r"\+.+")
910

1011

11-
def required_validator(answer, msg=None):
12+
def required_validator(answer: str, msg: Union[str, None] = None) -> str:
1213
if not answer:
1314
raise exceptions.AnswerRequiredError(msg)
1415
return answer
1516

1617

17-
def multiple_line_breaker(answer, sep="|"):
18+
def multiple_line_breaker(answer: str, sep: str = "|") -> str:
1819
return "\n".join(line.strip() for line in answer.split(sep) if line)
1920

2021

0 commit comments

Comments
 (0)