Skip to content

build(.gitignore): ignore pyrightconfig.json and poetry.toml #1483

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

Open
wants to merge 30 commits into
base: refactors
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
985b8b4
refactor: improve readability and fix typos
bearomorphism May 15, 2025
6bba6e7
refactor(version_scheme): cleanup
bearomorphism May 17, 2025
1088d54
refactor(commit): simplify call
bearomorphism May 17, 2025
220eb0c
test(commit): when nothing is added to commit
bearomorphism May 17, 2025
9710307
refactor(git): code cleanup and better test coverage
bearomorphism May 15, 2025
040f4a4
test(git): add test for from_rev_and_commit
bearomorphism May 17, 2025
416db96
docs(git): from_rev_and_commit docstring
bearomorphism May 17, 2025
1955293
refactor(EOLType): add eol enum back and reorganize methods
bearomorphism May 18, 2025
2aa74b2
refactor(git): refactor get_tag_names
bearomorphism May 18, 2025
619479d
refactor(changelog): minor cleanup
bearomorphism May 19, 2025
75d0029
refactor(BaseConfig): use setter
bearomorphism May 20, 2025
afce314
build(poetry): upgrade mypy version to ^1.15.0
bearomorphism May 20, 2025
3176086
refactor(bump): add type for out, replace function with re escape
bearomorphism May 17, 2025
f85d2cf
refactor(bump): clean up
bearomorphism May 16, 2025
a75ecac
test(bump): improve test coverage
bearomorphism May 16, 2025
60f2f0d
fix(defaults): add non-capitalized default constants back and depreca…
bearomorphism May 22, 2025
1dc19fa
refactor: misc cleanup
bearomorphism May 17, 2025
41f7527
refactor(git): extract _create_commit_cmd_string
bearomorphism May 19, 2025
2cc2c12
test(test_git): mock os
bearomorphism May 23, 2025
2de45e9
refactor(cli): early return and improve test coverage
bearomorphism May 23, 2025
56ea076
build(termcolor): remove termcolor <3 restriction
bearomorphism May 23, 2025
a02aab0
build: specify importlib-metadata version to fix unit tests
bearomorphism May 25, 2025
81f2181
build(poetry): regenerate lock file
Lee-W May 27, 2025
c0220cd
refactor(changelog): better typing, yield
bearomorphism May 24, 2025
7ab7f55
build(deps-dev): bump mypy to 1.16.0
gbaian10 May 31, 2025
5c9932d
refactor(mypy): remove `unused-ignore`
gbaian10 May 31, 2025
dedd29c
refactor(cli.py): add type hints
gbaian10 May 31, 2025
3a88f03
refactor: add comment clarifying `no_raise` parsing to `list[int]`
gbaian10 May 31, 2025
59fd3f5
refactor: remove `TypeError` handling since `Python >=3.9` is required
gbaian10 May 31, 2025
852b71d
build(.gitignore): ignore `pyrightconfig.json` and `poetry.toml`
gbaian10 May 31, 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
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,10 @@ venv.bak/

# ruff
.ruff_cache

# LSP config files
pyrightconfig.json
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would suggest adding it to your ~/.gitignore instead. I don't like to add things to ignore that's not directly related to commitizen (yep ".vscode" is kinda not my taste either)


### Python Patch ###
# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
poetry.toml
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm kinda curious what the behavior you decide but we shouldn't add it to commitizen

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
66 changes: 43 additions & 23 deletions commitizen/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from functools import partial
from pathlib import Path
from types import TracebackType
from typing import Any
from typing import TYPE_CHECKING, Any, cast

import argcomplete
from decli import cli
Expand Down Expand Up @@ -553,19 +553,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 @@ -595,8 +596,33 @@ def parse_no_raise(comma_separated_no_raise: str) -> list[int]:
return no_raise_codes


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():
parser = cli(data)
parser: argparse.ArgumentParser = cli(data)
argcomplete.autocomplete(parser)
# Show help if no arg provided
if len(sys.argv) == 1:
Expand All @@ -606,11 +632,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 +659,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 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
Loading