8000 feat(parser-conventional-monorepo): add new conventional-commits standard parser for monorepos by codejedi365 · Pull Request #1143 · python-semantic-release/python-semantic-release · GitHub
[go: up one dir, main page]

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

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter
8000

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
50 changes: 50 additions & 0 deletions docs/configuration/configuration.rst 8000
8000
Original file line number Diff line number Diff line change
Expand Up @@ -813,6 +813,22 @@ For more information see :ref:`commit_parsing`.
``commit_parser_options``
"""""""""""""""""""""""""

This section defines configuration options that modify commit parser options.

.. note::
**pyproject.toml:** ``[tool.semantic_release.commit_parser_options]``

**releaserc.toml:** ``[semantic_release.commit_parser_options]``

**releaserc.json:** ``{ "semantic_release": { "commit_parser_options": {} } }``

----

.. _config-commit_parser_options-types:

``allowed_types``/``minor_types``/``patch_types``
*************************************************

**Type:** ``dict[str, Any]``

This set of options are passed directly to the commit parser class specified in
Expand All @@ -826,6 +842,40 @@ For more information (to include defaults), see

----

.. _config-commit_parser_options-path_filters:

``path_filters``
***************************

**Type:** ``list[str]``

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.

**Default:** ``["."]``

----

.. _config-commit_parser_options-scope_prefix:

``scope_prefix``
***************************

**Type:** ``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 :ref:`config-commit_parser_options-path_filters` option to filter commits by
directory and scope.

**Default:** ``""``

----

.. _config-logging_use_named_masks:

``logging_use_named_masks``
Expand Down
4 changes: 3 additions & 1 deletion src/semantic_release/cli/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
from typing_extensions import Annotated, Self
from urllib3.util.url import parse_url

from semantic_release.commit_parser.conventional_monorepo import ConventionalCommitMonorepoParser
import semantic_release.hvcs as hvcs
from semantic_release.changelog.context import ChangelogMode
from semantic_release.changelog.template import environment
Expand Down Expand Up @@ -72,8 +73,9 @@ class HvcsClient(str, Enum):


_known_commit_parsers: Dict[str, type[CommitParser]] = {
"conventional": ConventionalCommitParser,
"angular": AngularCommitParser,
"conventional": ConventionalCommitParser,
"conventional-monorepo": ConventionalCommitMonorepoParser,
"emoji": EmojiCommitParser,
"scipy": ScipyCommitParser,
"tag": TagCommitParser,
Expand Down
11 changes: 11 additions & 0 deletions src/semantic_release/commit_parser/conventional/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from .options import ConventionalCommitParserOptions
from .options_monorepo import ConventionalMonorepoParserOptions
from .parser import ConventionalCommitParser
from .parser_monorepo import ConventionalCommitMonorepoParser

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

from itertools import zip_longest

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,68 @@
from __future__ import annotations

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

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 .options import ConventionalCommitParserOptions

if TYPE_CHECKING: # pragma: no cover
pass


@dataclass
class ConventionalMonorepoParserOptions(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.
"""

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

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)

@field_validator("path_filters", mode="after")
@classmethod
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
0