Skip to content
  • Sponsor commitizen-tools/commitizen

  • Notifications You must be signed in to change notification settings
  • Fork 291

refactor: improve types and avoid nested loop, add types for untyped functions #1466

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 30 commits into from
Jun 8, 2025
Merged
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
f4b81b7
style(tags): improve types
bearomorphism May 29, 2025
8b4a5fd
perf(tags): use set
bearomorphism May 29, 2025
51fdc4f
refactor: fix mypy output and better type
bearomorphism May 29, 2025
2ec92cc
refactor(conventional_commits): remove unnecessary checks
bearomorphism May 29, 2025
7ca5f79
refactor: make methods protected, better type
bearomorphism May 30, 2025
7179dd3
style: remove unnecessary noqa
bearomorphism May 30, 2025
9b13386
style: type untyped methods
bearomorphism May 30, 2025
b999189
style: remove Union
bearomorphism May 30, 2025
ea22ca4
style: better type
bearomorphism May 30, 2025
ce05562
style: add `-> None` to __init__
bearomorphism May 30, 2025
28ac03b
build(ruff,mypy): more strict rules
bearomorphism May 30, 2025
95c50e3
fix(BaseConfig): mypy error
bearomorphism May 31, 2025
32836b2
build(mypy): remove disallow_untyped_defs because it's already done b…
bearomorphism May 31, 2025
f0bdd55
refactor(bump): TypedDict for bump argument
bearomorphism May 30, 2025
32d7adb
refactor(changelog): type untyped arguments
bearomorphism May 31, 2025
a4b9ae9
refactor(check): remove unused argument
bearomorphism May 31, 2025
0493765
style(bump): rename class for consistency
bearomorphism May 31, 2025
e67ba23
refactor(check): type CheckArgs arguments
bearomorphism May 31, 2025
1f8c4bc
refactor(commit): type commit args
bearomorphism May 31, 2025
f771da3
refactor(commands): remove unused args, type version command args
bearomorphism May 31, 2025
d72e7ec
style(cli): shorten arg type
bearomorphism May 31, 2025
8562209
docs(bump): comment on a stupid looking pattern
bearomorphism May 31, 2025
9b99924
fix(Check): make parameters backward compatiable
bearomorphism May 31, 2025
92a92bc
style(changelog): rename parameter for consistency
bearomorphism May 31, 2025
95a9140
refactor(bump): improve readability and still bypass mypy check
bearomorphism May 31, 2025
19efaa8
refactor: remove unnecessary bool() and remove Any type from TypedDic…
bearomorphism May 31, 2025
38fe5bf
style(changelog): add TODO to fixable type ignores
bearomorphism Jun 4, 2025
24c8201
style(cli): more specific type ignore
bearomorphism Jun 4, 2025
ac9e742
style(cli): rename kwarg to values
bearomorphism Jun 4, 2025
667efef
refactor(bump): use any to replace 'or' chain
bearomorphism Jun 6, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions commitizen/changelog.py
Original file line number Diff line number Diff line change
@@ -29,7 +29,7 @@

import re
from collections import OrderedDict, defaultdict
from collections.abc import Generator, Iterable, Mapping
from collections.abc import Generator, Iterable, Mapping, Sequence
from dataclasses import dataclass
from datetime import date
from typing import TYPE_CHECKING, Any
@@ -63,7 +63,7 @@ class Metadata:
latest_version_position: int | None = None
latest_version_tag: str | None = None

def __post_init__(self):
def __post_init__(self) -> None:
if self.latest_version and not self.latest_version_tag:
# Test syntactic sugar
# latest version tag is optional if same as latest version
@@ -169,8 +169,8 @@ def process_commit_message(
commit: GitCommit,
changes: dict[str | None, list],
change_type_map: dict[str, str] | None = None,
):
message: dict = {
) -> None:
message: dict[str, Any] = {
"sha1": commit.rev,
"parents": commit.parents,
"author": commit.author,
@@ -225,7 +225,7 @@ def render_changelog(
tree: Iterable,
loader: BaseLoader,
template: str,
**kwargs,
**kwargs: Any,
) -> str:
jinja_template = get_changelog_template(loader, template)
changelog: str = jinja_template.render(tree=tree, **kwargs)
@@ -282,7 +282,7 @@ def incremental_build(


def get_smart_tag_range(
tags: list[GitTag], newest: str, oldest: str | None = None
tags: Sequence[GitTag], newest: str, oldest: str | None = None
) -> list[GitTag]:
"""Smart because it finds the N+1 tag.

@@ -308,10 +308,10 @@ def get_smart_tag_range(


def get_oldest_and_newest_rev(
tags: list[GitTag],
tags: Sequence[GitTag],
version: str,
rules: TagRules,
) -> tuple[str | None, str | None]:
) -> tuple[str | None, str]:
"""Find the tags for the given version.

`version` may come in different formats:
2 changes: 1 addition & 1 deletion commitizen/changelog_formats/__init__.py
Original file line number Diff line number Diff line change
@@ -25,7 +25,7 @@ class ChangelogFormat(Protocol):

config: BaseConfig

def __init__(self, config: BaseConfig):
def __init__(self, config: BaseConfig) -> None:
self.config = config

@property
2 changes: 1 addition & 1 deletion commitizen/changelog_formats/base.py
Original file line number Diff line number Diff line change
@@ -20,7 +20,7 @@ class BaseFormat(ChangelogFormat, metaclass=ABCMeta):
extension: ClassVar[str] = ""
alternative_extensions: ClassVar[set[str]] = set()

def __init__(self, config: BaseConfig):
def __init__(self, config: BaseConfig) -> None:
# Constructor needs to be redefined because `Protocol` prevent instantiation by default
# See: https://bugs.python.org/issue44807
self.config = config
27 changes: 15 additions & 12 deletions commitizen/cli.py
Original file line number Diff line number Diff line change
@@ -3,12 +3,11 @@
import argparse
import logging
import sys
from collections.abc import Sequence
from copy import deepcopy
from functools import partial
from pathlib import Path
from types import TracebackType
from typing import TYPE_CHECKING, Any, cast
from typing import TYPE_CHECKING, cast

import argcomplete
from decli import cli
@@ -48,17 +47,17 @@ def __call__(
self,
parser: argparse.ArgumentParser,
namespace: argparse.Namespace,
kwarg: str | Sequence[Any] | None,
values: object,
option_string: str | None = None,
):
if not isinstance(kwarg, str):
) -> None:
if not isinstance(values, str):
return
if "=" not in kwarg:
if "=" not in values:
raise InvalidCommandArgumentError(
f"Option {option_string} expect a key=value format"
)
kwargs = getattr(namespace, self.dest, None) or {}
key, value = kwarg.split("=", 1)
key, value = values.split("=", 1)
if not key:
raise InvalidCommandArgumentError(
f"Option {option_string} expect a key=value format"
@@ -550,8 +549,12 @@ def __call__(


def commitizen_excepthook(
type, value, traceback, debug=False, no_raise: list[int] | None = None
):
type: type[BaseException],
value: BaseException,
traceback: TracebackType | None,
debug: bool = False,
no_raise: list[int] | None = None,
) -> None:
traceback = traceback if isinstance(traceback, TracebackType) else None
if not isinstance(value, CommitizenException):
original_excepthook(type, value, traceback)
@@ -581,7 +584,7 @@ def parse_no_raise(comma_separated_no_raise: str) -> list[int]:
represents the exit code found in exceptions.
"""
no_raise_items: list[str] = comma_separated_no_raise.split(",")
no_raise_codes = []
no_raise_codes: list[int] = []
for item in no_raise_items:
if item.isdecimal():
no_raise_codes.append(int(item))
@@ -621,7 +624,7 @@ class Args(argparse.Namespace):
]


def main():
def main() -> None:
parser: argparse.ArgumentParser = cli(data)
argcomplete.autocomplete(parser)
# Show help if no arg provided
@@ -676,7 +679,7 @@ def main():
)
sys.excepthook = no_raise_debug_excepthook

args.func(conf, arguments)()
args.func(conf, arguments)() # type: ignore[arg-type]


if __name__ == "__main__":
5 changes: 4 additions & 1 deletion commitizen/cmd.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
from __future__ import annotations

import os
import subprocess
from collections.abc import Mapping
from typing import NamedTuple

from charset_normalizer import from_bytes
@@ -28,7 +31,7 @@ def _try_decode(bytes_: bytes) -> str:
raise CharacterSetDecodeError() from e


def run(cmd: str, env=None) -> Command:
def run(cmd: str, env: Mapping[str, str] | None = None) -> Command:
if env is not None:
env = {**os.environ, **env}
process = subprocess.Popen(
Loading