Skip to content

fix(bump_rule): add BumpRule, enum SemVerIncrement and Prerelease #1431

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 36 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
03aa596
refactor(bump_rule): add bump_rule interface, DefaultBumpRule and its…
bearomorphism May 17, 2025
4dea3fa
refactor(bump_rule): add find_increment_by_callable
bearomorphism May 17, 2025
57205e4
refactor(bump_rule): deprecate wip
bearomorphism May 17, 2025
afa0063
refactor(bump_rule): add old school bump rule for backward compatibility
bearomorphism May 17, 2025
facb51c
test(bump_rule): raise error
bearomorphism May 17, 2025
be7cb23
refactor(command_bump): use bump rules
bearomorphism May 17, 2025
88efb61
docs(bump_rule): docstring
bearomorphism May 17, 2025
a4d6eaa
docs(bump_rule): add todo
bearomorphism May 17, 2025
39f8bc7
fix(bump_rule): support flexible bump map
bearomorphism May 17, 2025
42d965e
refactor(bump): remove unused var
bearomorphism May 18, 2025
166f768
refactor(bump_rule): use enum on increment
bearomorphism May 18, 2025
565ca9e
refactor(bump_rule): typing
bearomorphism May 18, 2025
d9292b1
refactor(bump_rule): rename and fix test
bearomorphism May 18, 2025
c77d672
refactor(bump_rule): renaming
bearomorphism May 18, 2025
17b82ad
test(bump_rule): try to fix test
bearomorphism May 18, 2025
7b3b9c6
test(bump_rule): try to fix test again
bearomorphism May 18, 2025
0265ad5
test(bump_rule): fix test again
bearomorphism May 18, 2025
5e81873
fix(SemVerIncrement): fix error handling and add test
bearomorphism May 18, 2025
db8e93a
docs(bump_rule): add docstring
bearomorphism May 18, 2025
ac709ec
refactor(ConventionalCommitBumpRule): refactor
bearomorphism May 18, 2025
4b72cf8
test(BumpRule): improve test coverage
bearomorphism May 18, 2025
83d6bde
refactor(Prerelease): use enum
bearomorphism May 18, 2025
86e35b7
refactor(SemVerIncrement): get_highest_by_message
bearomorphism May 18, 2025
6109d98
refactor(bump_rule): make bump_rule a property
bearomorphism May 18, 2025
537904e
refactor(BaseVersion): increment_base
bearomorphism May 18, 2025
5e612bf
Merge branch 'master' into bump-rule-interface
bearomorphism May 18, 2025
d820bf7
test(BaseCommitizen): align with test
bearomorphism May 18, 2025
261e754
refactor(SemVerIncrement): use IntEnum
bearomorphism May 18, 2025
30a36da
test(SemVerIncrement): safe_cast
bearomorphism May 18, 2025
47c994c
test(Prerelease): test
bearomorphism May 18, 2025
c45c96f
style(bump): remove redundant type hint
bearomorphism May 19, 2025
dd85165
docs(BaseCommitizen): doc bump_rule
bearomorphism May 19, 2025
7bf082d
refactor(BaseCommitizen): remove redundant vars
bearomorphism May 19, 2025
2c9af08
style(CustomBumpRule): replace type dict with Mapping
bearomorphism May 19, 2025
0245469
style(CustomBumpRule): rename var
bearomorphism May 19, 2025
2eaf52c
docs(CustomBumpRule): add docstring
bearomorphism May 19, 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
46 changes: 2 additions & 44 deletions commitizen/bump.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,62 +2,20 @@

import os
import re
from collections import OrderedDict
from glob import iglob
from logging import getLogger
from string import Template
from typing import cast

from commitizen.defaults import MAJOR, MINOR, PATCH, bump_message, encoding
from commitizen.exceptions import CurrentVersionNotFoundError
from commitizen.git import GitCommit, smart_open
from commitizen.version_schemes import Increment, Version
from commitizen.git import smart_open
from commitizen.version_schemes import Version

VERSION_TYPES = [None, PATCH, MINOR, MAJOR]

logger = getLogger("commitizen")


def find_increment(
commits: list[GitCommit], regex: str, increments_map: dict | OrderedDict
) -> Increment | None:
if isinstance(increments_map, dict):
increments_map = OrderedDict(increments_map)

# Most important cases are major and minor.
# Everything else will be considered patch.
select_pattern = re.compile(regex)
increment: str | None = None

for commit in commits:
for message in commit.message.split("\n"):
result = select_pattern.search(message)

if result:
found_keyword = result.group(1)
new_increment = None
for match_pattern in increments_map.keys():
if re.match(match_pattern, found_keyword):
new_increment = increments_map[match_pattern]
break

if new_increment is None:
logger.debug(
f"no increment needed for '{found_keyword}' in '{message}'"
)

if VERSION_TYPES.index(increment) < VERSION_TYPES.index(new_increment):
logger.debug(
f"increment detected is '{new_increment}' due to '{found_keyword}' in '{message}'"
)
increment = new_increment
Comment on lines -44 to -53
Copy link
Contributor Author

@bearomorphism bearomorphism May 17, 2025

Choose a reason for hiding this comment

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

I don't think we need these logs. The algorithm can be very simple as the current implementation of get_highest_by_messages


if increment == MAJOR:
break

return cast(Increment, increment)


def update_version_in_files(
current_version: str,
new_version: str,
Expand Down
143 changes: 143 additions & 0 deletions commitizen/bump_rule.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
from __future__ import annotations

import re
from collections.abc import Iterable
from functools import cached_property
from typing import Callable, Protocol

from commitizen.exceptions import NoPatternMapError
from commitizen.version_schemes import Increment

_VERSION_ORDERING = dict(zip((None, "PATCH", "MINOR", "MAJOR"), range(4)))


def find_increment_by_callable(
commit_messages: Iterable[str], get_increment: Callable[[str], Increment | None]
) -> Increment | None:
"""Find the highest version increment from a list of messages.

This function processes a list of messages and determines the highest version
increment needed based on the commit messages. It splits multi-line commit messages
and evaluates each line using the provided get_increment callable.

Args:
commit_messages: A list of messages to analyze.
get_increment: A callable that takes a commit message string and returns an
Increment value (MAJOR, MINOR, PATCH) or None if no increment is needed.

Returns:
The highest version increment needed (MAJOR, MINOR, PATCH) or None if no
increment is needed. The order of precedence is MAJOR > MINOR > PATCH.

Example:
>>> commit_messages = ["feat: new feature", "fix: bug fix"]
>>> rule = ConventionalCommitBumpRule()
>>> find_increment_by_callable(commit_messages, lambda x: rule.get_increment(x, False))
'MINOR'
"""
lines = (line for message in commit_messages for line in message.split("\n"))
increments = map(get_increment, lines)
return max(increments, key=lambda x: _VERSION_ORDERING[x], default=None)


class BumpRule(Protocol):
def get_increment(
self, commit_message: str, major_version_zero: bool
) -> Increment | None:
"""Determine the version increment based on a commit message.

This method analyzes a commit message to determine what kind of version increment
is needed according to the Conventional Commits specification. It handles special
cases for breaking changes and respects the major_version_zero flag.

Args:
commit_message: The commit message to analyze. Should follow conventional commit format.
major_version_zero: If True, breaking changes will result in a MINOR version bump
instead of MAJOR. This is useful for projects in 0.x.x versions.

Returns:
Increment | None: The type of version increment needed:
- "MAJOR": For breaking changes when major_version_zero is False
- "MINOR": For breaking changes when major_version_zero is True, or for new features
- "PATCH": For bug fixes, performance improvements, or refactors
- None: For commits that don't require a version bump (docs, style, etc.)
"""
...

Check warning on line 65 in commitizen/bump_rule.py

View check run for this annotation

Codecov / codecov/patch

commitizen/bump_rule.py#L65

Added line #L65 was not covered by tests
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I wonder how to bypass this Codecov warning.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

OK I see how



class ConventionalCommitBumpRule(BumpRule):
_PATCH_CHANGE_TYPES = set(["fix", "perf", "refactor"])
_BREAKING_CHANGE = r"BREAKING[\-\ ]CHANGE"
_RE_BREAKING_CHANGE = re.compile(_BREAKING_CHANGE)

def get_increment(
self, commit_message: str, major_version_zero: bool
) -> Increment | None:
if not (m := self._head_pattern.match(commit_message)):
return None

change_type = m.group("change_type")
if m.group("bang") or self._RE_BREAKING_CHANGE.match(change_type):
return "MINOR" if major_version_zero else "MAJOR"

if change_type == "feat":
return "MINOR"

if change_type in self._PATCH_CHANGE_TYPES:
return "PATCH"

return None
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This implementation is based on defaults.BUMP_XXX


@cached_property
def _head_pattern(self) -> re.Pattern:
change_types = [
self._BREAKING_CHANGE,
"fix",
"feat",
"docs",
"style",
"refactor",
"perf",
"test",
"build",
"ci",
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This makes the pattern matching more strict.

]
re_change_type = r"(?P<change_type>" + "|".join(change_types) + r")"
re_scope = r"(?P<scope>\(.+\))?"
re_bang = r"(?P<bang>!)?"
return re.compile(f"^{re_change_type}{re_scope}{re_bang}:")


class OldSchoolBumpRule(BumpRule):
"""TODO: rename?"""

def __init__(
self,
bump_pattern: str,
bump_map: dict[str, Increment],
bump_map_major_version_zero: dict[str, Increment],
):
if not bump_map or not bump_pattern or not bump_map_major_version_zero:
raise NoPatternMapError(
f"Invalid bump rule: {bump_pattern=} and {bump_map=} and {bump_map_major_version_zero=}"
)

self.bump_pattern = re.compile(bump_pattern)
self.bump_map = bump_map
self.bump_map_major_version_zero = bump_map_major_version_zero

def get_increment(
self, commit_message: str, major_version_zero: bool
) -> Increment | None:
if not (m := self.bump_pattern.search(commit_message)):
return None

bump_map = (
self.bump_map_major_version_zero if major_version_zero else self.bump_map
)

found_keyword = m.group(1)
for match_pattern, increment in bump_map.items():
if re.match(match_pattern, found_keyword):
return increment
return None
31 changes: 21 additions & 10 deletions commitizen/commands/bump.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import questionary

from commitizen import bump, factory, git, hooks, out
from commitizen.bump_rule import OldSchoolBumpRule, find_increment_by_callable
from commitizen.changelog_formats import get_changelog_format
from commitizen.commands.changelog import Changelog
from commitizen.config import BaseConfig
Expand Down Expand Up @@ -122,22 +123,32 @@ def is_initial_tag(
def find_increment(self, commits: list[git.GitCommit]) -> Increment | None:
# Update the bump map to ensure major version doesn't increment.
is_major_version_zero: bool = self.bump_settings["major_version_zero"]
# self.cz.bump_map = defaults.bump_map_major_version_zero
bump_map = (
self.cz.bump_map_major_version_zero
if is_major_version_zero
else self.cz.bump_map

# Fallback to old school bump rule if no bump rule is provided
rule = self.cz.bump_rule or OldSchoolBumpRule(
*self._get_validated_cz_bump(),
)
return find_increment_by_callable(
(commit.message for commit in commits),
lambda x: rule.get_increment(x, is_major_version_zero),
)
bump_pattern = self.cz.bump_pattern

if not bump_map or not bump_pattern:
def _get_validated_cz_bump(
self,
) -> tuple[str, dict[str, Increment], dict[str, Increment]]:
"""For fixing the type errors"""
bump_pattern = self.cz.bump_pattern
bump_map = self.cz.bump_map
bump_map_major_version_zero = self.cz.bump_map_major_version_zero
if not bump_pattern or not bump_map or not bump_map_major_version_zero:
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 cast(
tuple[str, dict[str, Increment], dict[str, Increment]],
(bump_pattern, bump_map, bump_map_major_version_zero),
)
return increment

def __call__(self) -> None: # noqa: C901
"""Steps executed to bump."""
Expand Down
5 changes: 5 additions & 0 deletions commitizen/cz/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from prompt_toolkit.styles import Style, merge_styles

from commitizen import git
from commitizen.bump_rule import BumpRule
from commitizen.config.base_config import BaseConfig
from commitizen.defaults import Questions

Expand All @@ -25,9 +26,13 @@ def __call__(


class BaseCommitizen(metaclass=ABCMeta):
bump_rule: BumpRule | None = None

# TODO: deprecate these
bump_pattern: str | None = None
bump_map: dict[str, str] | None = None
bump_map_major_version_zero: dict[str, str] | None = None
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Not sure how to address these fields if we decide to check in the bump_rule change.


default_style_config: list[tuple[str, str]] = [
("qmark", "fg:#ff9d00 bold"),
("question", "bold"),
Expand Down
11 changes: 7 additions & 4 deletions commitizen/cz/conventional_commits/conventional_commits.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import re

from commitizen import defaults
from commitizen.bump_rule import ConventionalCommitBumpRule
from commitizen.cz.base import BaseCommitizen
from commitizen.cz.utils import multiple_line_breaker, required_validator
from commitizen.defaults import Questions
Expand All @@ -28,17 +29,19 @@ def parse_subject(text):


class ConventionalCommitsCz(BaseCommitizen):
bump_pattern = defaults.bump_pattern
bump_map = defaults.bump_map
bump_map_major_version_zero = defaults.bump_map_major_version_zero
bump_rule = ConventionalCommitBumpRule()

bump_pattern = defaults.BUMP_PATTERN
bump_map = defaults.BUMP_MAP
bump_map_major_version_zero = defaults.BUMP_MAP_MAJOR_VERSION_ZERO
commit_parser = r"^((?P<change_type>feat|fix|refactor|perf|BREAKING CHANGE)(?:\((?P<scope>[^()\r\n]*)\)|\()?(?P<breaking>!)?|\w+!):\s(?P<message>.*)?" # noqa
change_type_map = {
"feat": "Feat",
"fix": "Fix",
"refactor": "Refactor",
"perf": "Perf",
}
changelog_pattern = defaults.bump_pattern
changelog_pattern = defaults.BUMP_PATTERN

def questions(self) -> Questions:
questions: Questions = [
Expand Down
6 changes: 3 additions & 3 deletions commitizen/cz/customize/customize.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@


class CustomizeCommitsCz(BaseCommitizen):
bump_pattern = defaults.bump_pattern
bump_map = defaults.bump_map
bump_map_major_version_zero = defaults.bump_map_major_version_zero
bump_pattern = defaults.BUMP_PATTERN
bump_map = defaults.BUMP_MAP
bump_map_major_version_zero = defaults.BUMP_MAP_MAJOR_VERSION_ZERO
change_type_order = defaults.change_type_order

def __init__(self, config: BaseConfig):
Expand Down
6 changes: 3 additions & 3 deletions commitizen/defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,8 @@ class Settings(TypedDict, total=False):

CHANGELOG_FORMAT = "markdown"

bump_pattern = r"^((BREAKING[\-\ ]CHANGE|\w+)(\(.+\))?!?):"
bump_map = OrderedDict(
BUMP_PATTERN = r"^((BREAKING[\-\ ]CHANGE|\w+)(\(.+\))?!?):"
BUMP_MAP = OrderedDict(
(
(r"^.+!$", MAJOR),
(r"^BREAKING[\-\ ]CHANGE", MAJOR),
Expand All @@ -125,7 +125,7 @@ class Settings(TypedDict, total=False):
(r"^perf", PATCH),
)
)
bump_map_major_version_zero = OrderedDict(
BUMP_MAP_MAJOR_VERSION_ZERO = OrderedDict(
(
(r"^.+!$", MINOR),
(r"^BREAKING[\-\ ]CHANGE", MINOR),
Expand Down
Loading