Skip to content

fix(question): strict type with pydantic for questions #1467

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
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
036b269
refactor: improve readability and fix typos
bearomorphism May 15, 2025
c8e8959
refactor(version_scheme): cleanup
bearomorphism May 17, 2025
404afbb
refactor(commit): simplify call
bearomorphism May 17, 2025
0050be8
test(commit): when nothing is added to commit
bearomorphism May 17, 2025
0bd6ae4
refactor(git): code cleanup and better test coverage
bearomorphism May 15, 2025
04e47a7
test(git): add test for from_rev_and_commit
bearomorphism May 17, 2025
1b06258
docs(git): from_rev_and_commit docstring
bearomorphism May 17, 2025
fe00c41
refactor(EOLType): add eol enum back and reorganize methods
bearomorphism May 18, 2025
b17bbd2
refactor(git): refactor get_tag_names
bearomorphism May 18, 2025
a656a04
refactor(changelog): minor cleanup
bearomorphism May 19, 2025
06eacae
refactor(BaseConfig): use setter
bearomorphism May 20, 2025
9ca9678
build(poetry): upgrade mypy version to ^1.15.0
bearomorphism May 20, 2025
7e67154
refactor(bump): add type for out, replace function with re escape
bearomorphism May 17, 2025
b923735
refactor(bump): clean up
bearomorphism May 16, 2025
c2c8e3b
test(bump): improve test coverage
bearomorphism May 16, 2025
856ca4f
fix(defaults): add non-capitalized default constants back and depreca…
bearomorphism May 22, 2025
d0db72c
refactor: misc cleanup
bearomorphism May 17, 2025
f229e42
refactor(git): extract _create_commit_cmd_string
bearomorphism May 19, 2025
9584c49
test(test_git): mock os
bearomorphism May 23, 2025
83be38a
refactor(cli): early return and improve test coverage
bearomorphism May 23, 2025
07b68f8
build(termcolor): remove termcolor <3 restriction
bearomorphism May 23, 2025
2259b3a
build: specify importlib-metadata version to fix unit tests
bearomorphism May 25, 2025
0c7bcb8
build(poetry): regenerate lock file
Lee-W May 27, 2025
a3919c9
refactor(changelog): better typing, yield
bearomorphism May 24, 2025
c9b2ba7
fix(question): strict type with pydantic for questions
bearomorphism May 29, 2025
148babc
build: use pydantic >=1.10
bearomorphism May 30, 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
24 changes: 11 additions & 13 deletions commitizen/bump.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,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,17 +99,17 @@ 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: list[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: list[tuple[str, str]] = []
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))
Expand All @@ -128,18 +128,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
35 changes: 19 additions & 16 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
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 @@ -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 @@ -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 Down
29 changes: 13 additions & 16 deletions commitizen/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -554,19 +554,20 @@ def commitizen_excepthook(
type, value, traceback, debug=False, no_raise: list[int] | 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 Down Expand Up @@ -637,14 +638,10 @@ 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)
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 Down
34 changes: 15 additions & 19 deletions commitizen/commands/bump.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def __init__(self, config: BaseConfig, arguments: dict):
"template",
"file_name",
]
if arguments[key] is not None
if arguments.get(key) is not None
},
}
self.cz = factory.committer_factory(self.config)
Expand Down Expand Up @@ -105,19 +105,18 @@ def is_initial_tag(
self, current_tag: git.GitTag | None, is_yes: bool = False
) -> bool:
"""Check if reading the whole git tree up to HEAD is needed."""
is_initial = False
if not current_tag:
if is_yes:
is_initial = True
else:
out.info("No tag matching configuration could not be found.")
out.info(
"Possible causes:\n"
"- version in configuration is not the current version\n"
"- tag_format or legacy_tag_formats is missing, check them using 'git tag --list'\n"
)
is_initial = questionary.confirm("Is this the first tag created?").ask()
return is_initial
if current_tag:
return False
if is_yes:
return True

out.info("No tag matching configuration could be found.")
out.info(
"Possible causes:\n"
"- version in configuration is not the current version\n"
"- tag_format or legacy_tag_formats is missing, check them using 'git tag --list'\n"
)
return bool(questionary.confirm("Is this the first tag created?").ask())

def find_increment(self, commits: list[git.GitCommit]) -> Increment | None:
# Update the bump map to ensure major version doesn't increment.
Expand All @@ -134,10 +133,7 @@ def find_increment(self, commits: list[git.GitCommit]) -> Increment | None:
raise NoPatternMapError(
f"'{self.config.settings['name']}' rule does not support bump"
)
increment = bump.find_increment(
commits, regex=bump_pattern, increments_map=bump_map
)
return increment
return bump.find_increment(commits, regex=bump_pattern, increments_map=bump_map)

def __call__(self) -> None: # noqa: C901
"""Steps executed to bump."""
Expand All @@ -148,7 +144,7 @@ def __call__(self) -> None: # noqa: C901
except TypeError:
raise NoVersionSpecifiedError()

bump_commit_message: str = self.bump_settings["bump_message"]
bump_commit_message: str | None = self.bump_settings["bump_message"]
version_files: list[str] = self.bump_settings["version_files"]
major_version_zero: bool = self.bump_settings["major_version_zero"]
prerelease_offset: int = self.bump_settings["prerelease_offset"]
Expand Down
49 changes: 25 additions & 24 deletions commitizen/commands/changelog.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@

import os
import os.path
from collections.abc import Generator
from difflib import SequenceMatcher
from operator import itemgetter
from pathlib import Path
from typing import Callable, cast

from commitizen import changelog, defaults, factory, git, out
from commitizen.changelog_formats import get_changelog_format
Expand All @@ -32,9 +32,10 @@ def __init__(self, config: BaseConfig, args):
if not git.is_git_project():
raise NotAGitProjectError()

self.config: BaseConfig = config
changelog_file_name = args.get("file_name") or cast(
str, self.config.settings.get("changelog_file")
self.config = config

changelog_file_name = args.get("file_name") or self.config.settings.get(
"changelog_file"
)
if not isinstance(changelog_file_name, str):
raise NotAllowed(
Expand Down Expand Up @@ -114,28 +115,28 @@ def _find_incremental_rev(self, latest_version: str, tags: list[GitTag]) -> str:
on our experience.
"""
SIMILARITY_THRESHOLD = 0.89
tag_ratio = map(
lambda tag: (
SequenceMatcher(
scores_and_tag_names: Generator[tuple[float, str]] = (
(
score,
tag.name,
)
for tag in tags
if (
score := SequenceMatcher(
None, latest_version, strip_local_version(tag.name)
).ratio(),
tag,
),
tags,
).ratio()
)
>= SIMILARITY_THRESHOLD
)
try:
score, tag = max(tag_ratio, key=itemgetter(0))
_, start_rev = max(scores_and_tag_names, key=itemgetter(0))
except ValueError:
raise NoRevisionError()
if score < SIMILARITY_THRESHOLD:
raise NoRevisionError()
start_rev = tag.name
return start_rev

def write_changelog(
self, changelog_out: str, lines: list[str], changelog_meta: changelog.Metadata
):
changelog_hook: Callable | None = self.cz.changelog_hook
with smart_open(self.file_name, "w", encoding=self.encoding) as changelog_file:
partial_changelog: str | None = None
if self.incremental:
Expand All @@ -145,8 +146,8 @@ def write_changelog(
changelog_out = "".join(new_lines)
partial_changelog = changelog_out

if changelog_hook:
changelog_out = changelog_hook(changelog_out, partial_changelog)
if self.cz.changelog_hook:
changelog_out = self.cz.changelog_hook(changelog_out, partial_changelog)

changelog_file.write(changelog_out)

Expand Down Expand Up @@ -214,21 +215,21 @@ def __call__(self):
rules=self.tag_rules,
)
if self.change_type_order:
tree = changelog.order_changelog_tree(tree, self.change_type_order)
tree = changelog.generate_ordered_changelog_tree(
tree, self.change_type_order
)

extras = self.cz.template_extras.copy()
extras.update(self.config.settings["extras"])
extras.update(self.extras)
changelog_out = changelog.render_changelog(
tree, loader=self.cz.template_loader, template=self.template, **extras
)
changelog_out = changelog_out.lstrip("\n")
).lstrip("\n")

# Dry_run is executed here to avoid checking and reading the files
if self.dry_run:
changelog_hook: Callable | None = self.cz.changelog_hook
if changelog_hook:
changelog_out = changelog_hook(changelog_out, "")
if self.cz.changelog_hook:
changelog_out = self.cz.changelog_hook(changelog_out, "")
out.write(changelog_out)
raise DryRunExit()

Expand Down
Loading