Skip to content
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
21 changes: 21 additions & 0 deletions src/semantic_release/changelog/release_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,21 @@
from semantic_release.version.version import Version


def _prepare_changed_path_index(
repo: Repo, commit_parser: CommitParser[ParseResult, ParserOptions]
) -> None:
"""
Let the commit parser precompute path-filter relevance, if it supports it.

Parsers like the conventional-monorepo parser otherwise need one subprocess
per commit (via ``Commit.stats``) to learn which files a commit changed,
which dominates the runtime of the full-history walk in from_git_history.
"""
prepare_changed_paths = getattr(commit_parser, "prepare_changed_paths", None)
if callable(prepare_changed_paths):
prepare_changed_paths(repo)


class ReleaseHistory:
@classmethod
def from_git_history(
Expand All @@ -56,6 +71,12 @@ def from_git_history(
and getattr(commit_parser.options, "ignore_merge_commits") # noqa: B009
)

# Performance optimization: let the commit parser precompute
# per-commit path-filter relevance in a single git pass (e.g. the
# monorepo parser), instead of spawning one subprocess per commit
# during the full-history walk below.
_prepare_changed_path_index(repo, commit_parser)

# Strategy:
# Loop through commits in history, parsing as we go.
# Add these commits to `unreleased` as a key-value mapping
Expand Down
115 changes: 109 additions & 6 deletions src/semantic_release/commit_parser/conventional/parser_monorepo.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@
from semantic_release.errors import InvalidParserOptions

if TYPE_CHECKING: # pragma: no cover
from typing import Iterable, Sequence

from git.objects.commit import Commit
from git.repo.base import Repo


class ConventionalCommitMonorepoParser(
Expand Down Expand Up @@ -121,6 +124,12 @@ def __init__(
)
)

# Optional lookup index built by prepare_changed_paths(): maps a commit
# sha to whether its changed files match the configured path filters.
# None when not prepared, in which case every commit falls back to the
# per-commit stats lookup in _has_relevant_changed_files().
self._changed_paths_index: dict[str, bool] | None = None

def get_default_options(self) -> ConventionalCommitMonorepoParserOptions:
return ConventionalCommitMonorepoParserOptions()

Expand Down Expand Up @@ -408,6 +417,15 @@ def unsquash_commit_message(self, message: str) -> list[str]:
return self._base_parser.unsquash_commit_message(message)

def _has_relevant_changed_files(self, commit: Commit) -> bool:
# Fast path: consult the index precomputed by prepare_changed_paths().
# A commit missing from the index (e.g. a merge or empty commit, which
# produce no file entries) falls through to the per-commit stats
# lookup below, preserving the original behavior for those commits.
if self._changed_paths_index is not None:
relevant = self._changed_paths_index.get(commit.hexsha)
if relevant is not None:
return relevant

# Extract git root from commit
git_root = (
Path(commit.repo.working_tree_dir or commit.repo.working_dir)
Expand All @@ -419,6 +437,21 @@ def _has_relevant_changed_files(self, commit: Commit) -> bool:

rel_cwd = cwd.relative_to(git_root) if git_root in cwd.parents else Path(".")

sandboxed_selection_filters, sandboxed_ignore_filters = self._sandboxed_filters(
git_root, rel_cwd
)

# Check if the changed files of the commit that match the path filters
return self._changed_paths_match(
(str(git_root / rel_git_path) for rel_git_path in commit.stats.files),
sandboxed_selection_filters,
sandboxed_ignore_filters,
)

def _sandboxed_filters(
self, git_root: Path, rel_cwd: Path
) -> tuple[list[str], list[str]]:
"""Resolve the configured path filters to absolute paths within the repo."""
sandboxed_selection_filters: list[str] = [
str(file_filter)
for file_filter in (
Expand All @@ -445,23 +478,93 @@ def _has_relevant_changed_files(self, commit: Commit) -> bool:
if git_root in file_filter.parents
]

# Check if the changed files of the commit that match the path filters
for full_path in iter(
str(git_root / rel_git_path) for rel_git_path in commit.stats.files
):
return sandboxed_selection_filters, sandboxed_ignore_filters

@staticmethod
def _changed_paths_match(
full_paths: Iterable[str],
selection_filters: Sequence[str],
ignore_filters: Sequence[str],
) -> bool:
"""Return True if any path matches a selection filter and no ignore filter."""
for full_path in full_paths:
# Check if the filepath matches any of the file selection filters
if not any(
fnmatch(full_path, select_filter)
for select_filter in sandboxed_selection_filters
for select_filter in selection_filters
):
continue

# Pass filter matches, so now evaluate if it is supposed to be ignored
if not any(
fnmatch(full_path, ignore_filter)
for ignore_filter in sandboxed_ignore_filters
for ignore_filter in ignore_filters
):
# No ignore filter matched, so it must be a relevant file
return True

return False

def prepare_changed_paths(self, repo: "Repo") -> None:
"""
Precompute per-commit path-filter relevance with a single batched git pass.

The per-commit fallback in :meth:`_has_relevant_changed_files` reads
``Commit.stats``, which spawns one ``git diff`` subprocess per commit and
dominates the runtime of a full-history walk in large repositories such
as monorepos. This method instead collects the changed file list of
every commit in one ``git log --name-only`` invocation and stores only
the filter-match result for each commit.

Commits missing from the index (merge commits, empty commits, or commits
created after the batch ran) transparently fall back to the per-commit
stats lookup. On any failure the index stays disabled and the original
behavior is used, so this can never fail a release.
"""
git_root = (
Path(repo.working_tree_dir or repo.working_dir).absolute().resolve()
)

cwd = Path.cwd().absolute().resolve()

rel_cwd = cwd.relative_to(git_root) if git_root in cwd.parents else Path(".")

selection_filters, ignore_filters = self._sandboxed_filters(git_root, rel_cwd)

try:
batch_output = repo.git.log(
"HEAD",
"--topo-order",
"--no-renames",
"--name-only",
"--format=%x1e%H",
)
except Exception: # noqa: BLE001
self._logger.warning(
"failed to collect the changed files in a single git log pass, "
"falling back to one subprocess per commit instead",
exc_info=True,
)
return

index: dict[str, bool] = {}
for record in batch_output.split("\x1e")[1:]:
lines = record.split("\n")
changed_paths = [line for line in lines[1:] if line]
if not changed_paths:
# Merge and empty commits produce no file entries; leave
# them out of the index so the per-commit stats lookup,
# which can diff a merge against its first parent, is used.
continue

index[lines[0]] = self._changed_paths_match(
(str(git_root / path) for path in changed_paths),
selection_filters,
ignore_filters,
)

self._changed_paths_index = index
self._logger.debug(
"precomputed changed-file relevance for %d commits in a single git pass",
len(index),
)
Loading