Skip to content

Restore branch #1512

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

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
59 commits
Select commit Hold shift + click to select a range
4fccd3d
refactor: improve readability and fix typos
bearomorphism May 15, 2025
ec1f894
refactor(version_scheme): cleanup
bearomorphism May 17, 2025
271d4f0
refactor(commit): simplify call
bearomorphism May 17, 2025
a9f0f9c
test(commit): when nothing is added to commit
bearomorphism May 17, 2025
e939217
refactor(git): code cleanup and better test coverage
bearomorphism May 15, 2025
1fe47d8
test(git): add test for from_rev_and_commit
bearomorphism May 17, 2025
1a029c5
docs(git): from_rev_and_commit docstring
bearomorphism May 17, 2025
6e79848
refactor(EOLType): add eol enum back and reorganize methods
bearomorphism May 18, 2025
b62867d
refactor(git): refactor get_tag_names
bearomorphism May 18, 2025
f602aa8
refactor(changelog): minor cleanup
bearomorphism May 19, 2025
326325f
refactor(BaseConfig): use setter
bearomorphism May 20, 2025
940e705
refactor(bump): add type for out, replace function with re escape
bearomorphism May 17, 2025
1cf91b3
refactor(bump): clean up
bearomorphism May 16, 2025
aaf9da8
test(bump): improve test coverage
bearomorphism May 16, 2025
f7ae081
fix(defaults): add non-capitalized default constants back and depreca…
bearomorphism May 22, 2025
1c213da
refactor: misc cleanup
bearomorphism May 17, 2025
abf1197
refactor(git): extract _create_commit_cmd_string
bearomorphism May 19, 2025
9293cdc
test(test_git): mock os
bearomorphism May 23, 2025
d8630ce
refactor(cli): early return and improve test coverage
bearomorphism May 23, 2025
26e7ab5
refactor(changelog): better typing, yield
bearomorphism May 24, 2025
cf93a88
refactor(mypy): remove `unused-ignore`
gbaian10 May 31, 2025
db43f44
refactor(cli.py): add type hints
gbaian10 May 31, 2025
3c70f0c
refactor: add comment clarifying `no_raise` parsing to `list[int]`
gbaian10 May 31, 2025
6c281e5
refactor: remove `TypeError` handling since `Python >=3.9` is required
gbaian10 May 31, 2025
a315248
fix(deprecated): mark deprecate in v5
bearomorphism Jun 1, 2025
6c3b69e
style(ruff): resolve F401
gbaian10 May 31, 2025
f71d524
build(ruff): add RUF022 & RUF100 rules
gbaian10 May 31, 2025
da3609f
style(ruff): run `ruff check --fix`
gbaian10 May 31, 2025
4e4ff1f
refactor(BaseCommitizen): remove unused process_commit
bearomorphism May 30, 2025
5ef020a
style(tags): improve types
bearomorphism May 29, 2025
d8f563b
perf(tags): use set
bearomorphism May 29, 2025
0f18416
refactor: fix mypy output and better type
bearomorphism May 29, 2025
6726868
refactor(conventional_commits): remove unnecessary checks
bearomorphism May 29, 2025
2c0a966
refactor: make methods protected, better type
bearomorphism May 30, 2025
e1cfe8b
style: type untyped methods
bearomorphism May 30, 2025
114d01f
style: remove Union
bearomorphism May 30, 2025
db200c2
style: better type
bearomorphism May 30, 2025
bc937a4
style: add `-> None` to __init__
bearomorphism May 30, 2025
75f26e9
build(ruff,mypy): more strict rules
bearomorphism May 30, 2025
15e28c8
fix(BaseConfig): mypy error
bearomorphism May 31, 2025
573e77b
build(mypy): remove disallow_untyped_defs because it's already done b…
bearomorphism May 31, 2025
fd89855
refactor(bump): TypedDict for bump argument
bearomorphism May 30, 2025
a78a084
refactor(changelog): type untyped arguments
bearomorphism May 31, 2025
ac95cdb
refactor(check): remove unused argument
bearomorphism May 31, 2025
27ab008
style(bump): rename class for consistency
bearomorphism May 31, 2025
31abd01
refactor(check): type CheckArgs arguments
bearomorphism May 31, 2025
b3dfd46
refactor(commit): type commit args
bearomorphism May 31, 2025
e70814e
refactor(commands): remove unused args, type version command args
bearomorphism May 31, 2025
8ee1ebf
style(cli): shorten arg type
bearomorphism May 31, 2025
fa45cc1
docs(bump): comment on a stupid looking pattern
bearomorphism May 31, 2025
cbf4520
fix(Check): make parameters backward compatiable
bearomorphism May 31, 2025
2c4a930
style(changelog): rename parameter for consistency
bearomorphism May 31, 2025
01531a4
refactor(bump): improve readability and still bypass mypy check
bearomorphism May 31, 2025
e5938cd
refactor: remove unnecessary bool() and remove Any type from TypedDic…
bearomorphism May 31, 2025
403cfca
style(changelog): add TODO to fixable type ignores
bearomorphism Jun 4, 2025
c941c4f
style(cli): more specific type ignore
bearomorphism Jun 4, 2025
6cc9c89
style(cli): rename kwarg to values
bearomorphism Jun 4, 2025
9a8f3bf
refactor(bump): use any to replace 'or' chain
bearomorphism Jun 6, 2025
89d9221
perf(bump): avoid unnecessary list construction and rename variable t…
bearomorphism Jun 5, 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
34 changes: 17 additions & 17 deletions commitizen/bump.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import os
import re
from collections import OrderedDict
from collections.abc import Iterable
from glob import iglob
from logging import getLogger
from string import Template
Expand Down Expand Up @@ -61,7 +62,7 @@ def find_increment(
def update_version_in_files(
current_version: str,
new_version: str,
files: list[str],
files: Iterable[str],
*,
check_consistency: bool = False,
encoding: str = ENCODING,
Expand All @@ -76,7 +77,7 @@ def update_version_in_files(
"""
# TODO: separate check step and write step
updated = []
for path, regex in files_and_regexs(files, current_version):
for path, regex in _files_and_regexes(files, current_version):
current_version_found, version_file = _bump_with_regex(
path,
current_version,
Expand All @@ -99,21 +100,22 @@ def update_version_in_files(
return updated


def files_and_regexs(patterns: list[str], version: str) -> list[tuple[str, str]]:
def _files_and_regexes(patterns: Iterable[str], version: str) -> list[tuple[str, str]]:
"""
Resolve all distinct files with their regexp from a list of glob patterns with optional regexp
"""
out = []
out: set[tuple[str, str]] = set()
for pattern in patterns:
drive, tail = os.path.splitdrive(pattern)
path, _, regex = tail.partition(":")
filepath = drive + path
if not regex:
regex = _version_to_regex(version)
regex = re.escape(version)

for path in iglob(filepath):
out.append((path, regex))
return sorted(list(set(out)))
for file in iglob(filepath):
out.add((file, regex))

return sorted(out)


def _bump_with_regex(
Expand All @@ -128,18 +130,16 @@ def _bump_with_regex(
pattern = re.compile(regex)
with open(version_filepath, encoding=encoding) as f:
for line in f:
if pattern.search(line):
bumped_line = line.replace(current_version, new_version)
if bumped_line != line:
current_version_found = True
lines.append(bumped_line)
else:
if not pattern.search(line):
lines.append(line)
return current_version_found, "".join(lines)
continue

bumped_line = line.replace(current_version, new_version)
if bumped_line != line:
current_version_found = True
lines.append(bumped_line)

def _version_to_regex(version: str) -> str:
return version.replace(".", r"\.").replace("+", r"\+")
return current_version_found, "".join(lines)


def create_commit_message(
Expand Down
49 changes: 26 additions & 23 deletions commitizen/changelog.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@

import re
from collections import OrderedDict, defaultdict
from collections.abc import Iterable
from collections.abc import Generator, Iterable, Mapping, Sequence
from dataclasses import dataclass
from datetime import date
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Any

from jinja2 import (
BaseLoader,
Expand Down Expand Up @@ -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
Expand All @@ -84,7 +84,7 @@ def generate_tree_from_commits(
changelog_message_builder_hook: MessageBuilderHook | None = None,
changelog_release_hook: ChangelogReleaseHook | None = None,
rules: TagRules | None = None,
) -> Iterable[dict]:
) -> Generator[dict[str, Any], None, None]:
pat = re.compile(changelog_pattern)
map_pat = re.compile(commit_parser, re.MULTILINE)
body_map_pat = re.compile(commit_parser, re.MULTILINE | re.DOTALL)
Expand Down Expand Up @@ -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,
Expand All @@ -187,24 +187,27 @@ def process_commit_message(
changes[change_type].append(msg)


def order_changelog_tree(tree: Iterable, change_type_order: list[str]) -> Iterable:
def generate_ordered_changelog_tree(
tree: Iterable[Mapping[str, Any]], change_type_order: list[str]
) -> Generator[dict[str, Any], None, None]:
if len(set(change_type_order)) != len(change_type_order):
raise InvalidConfigurationError(
f"Change types contain duplicates types ({change_type_order})"
f"Change types contain duplicated types ({change_type_order})"
)

sorted_tree = []
for entry in tree:
ordered_change_types = change_type_order + sorted(
set(entry["changes"].keys()) - set(change_type_order)
)
changes = [
(ct, entry["changes"][ct])
for ct in ordered_change_types
if ct in entry["changes"]
]
sorted_tree.append({**entry, **{"changes": OrderedDict(changes)}})
return sorted_tree
yield {
**entry,
"changes": _calculate_sorted_changes(change_type_order, entry["changes"]),
}


def _calculate_sorted_changes(
change_type_order: list[str], changes: Mapping[str, Any]
) -> OrderedDict[str, Any]:
remaining_change_types = set(changes.keys()) - set(change_type_order)
sorted_change_types = change_type_order + sorted(remaining_change_types)
return OrderedDict((ct, changes[ct]) for ct in sorted_change_types if ct in changes)


def get_changelog_template(loader: BaseLoader, template: str) -> Template:
Expand All @@ -222,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)
Expand Down Expand Up @@ -279,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.

Expand All @@ -305,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:
Expand Down
2 changes: 1 addition & 1 deletion commitizen/changelog_formats/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class ChangelogFormat(Protocol):

config: BaseConfig

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

@property
Expand Down
2 changes: 1 addition & 1 deletion commitizen/changelog_formats/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
91 changes: 57 additions & 34 deletions commitizen/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 Any
from typing import TYPE_CHECKING, cast

import argcomplete
from decli import cli
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -550,22 +549,27 @@ 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)
return

if not no_raise:
no_raise = []
if isinstance(value, CommitizenException):
if value.message:
value.output_method(value.message)
if debug:
original_excepthook(type, value, traceback)
exit_code = value.exit_code
if exit_code in no_raise:
exit_code = ExitCode.EXPECTED_EXIT
sys.exit(exit_code)
else:
if value.message:
value.output_method(value.message)
if debug:
original_excepthook(type, value, traceback)
exit_code = value.exit_code
if exit_code in no_raise:
exit_code = ExitCode.EXPECTED_EXIT
sys.exit(exit_code)


commitizen_debug_excepthook = partial(commitizen_excepthook, debug=True)
Expand All @@ -580,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))
Expand All @@ -595,8 +599,33 @@ def parse_no_raise(comma_separated_no_raise: str) -> list[int]:
return no_raise_codes


def main():
parser = cli(data)
if TYPE_CHECKING:

class Args(argparse.Namespace):
config: str | None = None
debug: bool = False
name: str | None = None
no_raise: str | None = None # comma-separated string, later parsed as list[int]
report: bool = False
project: bool = False
commitizen: bool = False
verbose: bool = False
func: type[
commands.Init # init
| commands.Commit # commit (c)
| commands.ListCz # ls
| commands.Example # example
| commands.Info # info
| commands.Schema # schema
| commands.Bump # bump
| commands.Changelog # changelog (ch)
| commands.Check # check
| commands.Version # version
]


def main() -> None:
parser: argparse.ArgumentParser = cli(data)
argcomplete.autocomplete(parser)
# Show help if no arg provided
if len(sys.argv) == 1:
Expand All @@ -606,11 +635,8 @@ def main():
# This is for the command required constraint in 2.0
try:
args, unknown_args = parser.parse_known_args()
except (TypeError, SystemExit) as e:
# https://github.com/commitizen-tools/commitizen/issues/429
# argparse raises TypeError when non exist command is provided on Python < 3.9
# but raise SystemExit with exit code == 2 on Python 3.9
if isinstance(e, TypeError) or (isinstance(e, SystemExit) and e.code == 2):
except SystemExit as e:
if e.code == 2:
raise NoCommandFoundError()
raise e

Expand All @@ -636,14 +662,11 @@ def main():
extra_args = " ".join(unknown_args[1:])
arguments["extra_cli_args"] = extra_args

if args.config:
conf = config.read_cfg(args.config)
else:
conf = config.read_cfg()

conf = config.read_cfg(args.config)
args = cast("Args", args)
if args.name:
conf.update({"name": args.name})
elif not args.name and not conf.path:
elif not conf.path:
conf.update({"name": "cz_conventional_commits"})

if args.debug:
Expand All @@ -656,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__":
Expand Down
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
Expand Down Expand Up @@ -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(
Expand Down
Loading