Skip to content

feat(parser-conventional-monorepo): add new conventional-commits standard parser for monorepos #1143

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 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
6 changes: 4 additions & 2 deletions src/semantic_release/cli/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
from semantic_release.commit_parser import (
AngularCommitParser,
CommitParser,
ConventionalCommitMonorepoParser,
ConventionalCommitParser,
EmojiCommitParser,
ParseResult,
Expand Down Expand Up @@ -71,9 +72,10 @@ class HvcsClient(str, Enum):
GITEA = "gitea"


_known_commit_parsers: Dict[str, type[CommitParser]] = {
"conventional": ConventionalCommitParser,
_known_commit_parsers: dict[str, type[CommitParser[Any, Any]]] = {
"angular": AngularCommitParser,
"conventional": ConventionalCommitParser,
"conventional-monorepo": ConventionalCommitMonorepoParser,
"emoji": EmojiCommitParser,
"scipy": ScipyCommitParser,
"tag": TagCommitParser,
Expand Down
23 changes: 23 additions & 0 deletions src/semantic_release/commit_parser/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
AngularParserOptions,
)
from semantic_release.commit_parser.conventional import (
ConventionalCommitMonorepoParser,
ConventionalCommitMonorepoParserOptions,
ConventionalCommitParser,
ConventionalCommitParserOptions,
)
Expand All @@ -28,3 +30,24 @@
ParseResult,
ParseResultType,
)

__all__ = [
"CommitParser",
"ParserOptions",
"AngularCommitParser",
"AngularParserOptions",
"ConventionalCommitParser",
"ConventionalCommitParserOptions",
"ConventionalCommitMonorepoParser",
"ConventionalCommitMonorepoParserOptions",
"EmojiCommitParser",
"EmojiParserOptions",
"ScipyCommitParser",
"ScipyParserOptions",
"TagCommitParser",
"TagParserOptions",
"ParsedCommit",
"ParseError",
"ParseResult",
"ParseResultType",
]
17 changes: 17 additions & 0 deletions src/semantic_release/commit_parser/conventional/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from semantic_release.commit_parser.conventional.options import (
ConventionalCommitParserOptions,
)
from semantic_release.commit_parser.conventional.options_monorepo import (
ConventionalCommitMonorepoParserOptions,
)
from semantic_release.commit_parser.conventional.parser import ConventionalCommitParser
from semantic_release.commit_parser.conventional.parser_monorepo import (
ConventionalCommitMonorepoParser,
)

__all__ = [
"ConventionalCommitParser",
"ConventionalCommitParserOptions",
"ConventionalCommitMonorepoParser",
"ConventionalCommitMonorepoParserOptions",
]
72 changes: 72 additions & 0 deletions src/semantic_release/commit_parser/conventional/options.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
from __future__ import annotations

from itertools import zip_longest
from typing import Tuple

from pydantic.dataclasses import dataclass

from semantic_release.commit_parser._base import ParserOptions
from semantic_release.enums import LevelBump


@dataclass
class ConventionalCommitParserOptions(ParserOptions):
"""Options dataclass for the ConventionalCommitParser."""

minor_tags: Tuple[str, ...] = ("feat",)
"""Commit-type prefixes that should result in a minor release bump."""

patch_tags: Tuple[str, ...] = ("fix", "perf")
"""Commit-type prefixes that should result in a patch release bump."""

other_allowed_tags: Tuple[str, ...] = (
"build",
"chore",
"ci",
"docs",
"style",
"refactor",
"test",
)
"""Commit-type prefixes that are allowed but do not result in a version bump."""

allowed_tags: Tuple[str, ...] = (
*minor_tags,
*patch_tags,
*other_allowed_tags,
)
"""
All commit-type prefixes that are allowed.

These are used to identify a valid commit message. If a commit message does not start with
one of these prefixes, it will not be considered a valid commit message.
"""

default_bump_level: LevelBump = LevelBump.NO_RELEASE
"""The minimum bump level to apply to valid commit message."""

parse_squash_commits: bool = True
"""Toggle flag for whether or not to parse squash commits"""

ignore_merge_commits: bool = True
"""Toggle flag for whether or not to ignore merge commits"""

@property
def tag_to_level(self) -> dict[str, LevelBump]:
"""A mapping of commit tags to the level bump they should result in."""
return self._tag_to_level

def __post_init__(self) -> None:
self._tag_to_level: dict[str, LevelBump] = {
str(tag): level
for tag, level in [
# we have to do a type ignore as zip_longest provides a type that is not specific enough
# for our expected output. Due to the empty second array, we know the first is always longest
# and that means no values in the first entry of the tuples will ever be a LevelBump. We
# apply a str() to make mypy happy although it will never happen.
*zip_longest(self.allowed_tags, (), fillvalue=self.default_bump_level),
*zip_longest(self.patch_tags, (), fillvalue=LevelBump.PATCH),
*zip_longest(self.minor_tags, (), fillvalue=LevelBump.MINOR),
]
if "|" not in str(tag)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
from __future__ import annotations

from pathlib import Path
from typing import TYPE_CHECKING, Any, Iterable, Tuple

from pydantic import Field, field_validator
from pydantic.dataclasses import dataclass

# typing_extensions is for Python 3.8, 3.9, 3.10 compatibility
from typing_extensions import Annotated

from semantic_release.commit_parser.conventional.options import (
ConventionalCommitParserOptions,
)

if TYPE_CHECKING: # pragma: no cover
pass


@dataclass
class ConventionalCommitMonorepoParserOptions(ConventionalCommitParserOptions):
"""Options dataclass for ConventionalCommitMonorepoParser."""

path_filters: Annotated[Tuple[Path, ...], Field(validate_default=True)] = (
Path("."),
)
"""
A set of relative paths to filter commits by. Only commits with file changes that
match these file paths or its subdirectories will be considered valid commits.

Syntax is similar to .gitignore with file path globs and inverse file match globs
via `!` prefix. Paths should be relative to the current working directory.
"""

scope_prefix: str = ""
"""
A prefix that will be striped from the scope when parsing commit messages.

If set, it will cause unscoped commits to be ignored. Use this in tandem with
the `path_filters` option to filter commits by directory and scope.
"""

@classmethod
@field_validator("path_filters", mode="before")
def convert_strs_to_paths(cls, value: Any) -> tuple[Path, ...]:
values = value if isinstance(value, Iterable) else [value]
results: list[Path] = []

for val in values:
if isinstance(val, (str, Path)):
results.append(Path(val))
continue

raise TypeError(f"Invalid type: {type(val)}, expected str or Path.")

return tuple(results)

@classmethod
@field_validator("path_filters", mode="after")
def resolve_path(cls, dir_paths: tuple[Path, ...]) -> tuple[Path, ...]:
return tuple(
(
Path(f"!{Path(str_path[1:]).expanduser().absolute().resolve()}")
# maintains the negation prefix if it exists
if (str_path := str(path)).startswith("!")
# otherwise, resolve the path normally
else path.expanduser().absolute().resolve()
)
for path in dir_paths
)
Loading
Loading