# Copyright Kevin Deldycke <[email protected]> and contributors.
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
"""Extract metadata from repository and Python projects to be used by GitHub workflows.
This module solves a fundamental limitation of GitHub Actions: a workflow run is
triggered by a singular event, which might encapsulate **multiple commits**. GitHub only
exposes `github.event.head_commit` (the most recent commit), but workflows often need
to process all commits in the push event.
This is critical for releases, where two commits are pushed together:
1. `[changelog] Release vX.Y.Z`: the release commit to be tagged and published
2. `[changelog] Post-release bump vX.Y.Z → vX.Y.Z`: the next dev cycle's bump
Since `github.event.head_commit` only sees the post-release bump, this module extracts
the full commit range from the push event and identifies release commits that need
special handling (tagging, PyPI publishing, GitHub release creation).
```{rubric} Output shapes
```
Every key is [printed to the environment file](https://docs.github.com/en/free-pro-team@latest/actions/reference/workflow-commands-for-github-actions#environment-files)
as one `key=value` line. Values take three shapes:
```{code-block} text
is_python_project=true
doc_files="changelog.md" "readme.md" "docs/license.md"
new_commits_matrix={"commit": ["346ce66…", "6f27db4…"], "include": [{"commit": "346ce66…", "short_sha": "346ce66"}]}
```
A scalar prints bare. A list prints as space-joined, individually quoted items,
not a JSON array: workflow `if:` conditions test membership with a padded
`contains()` against that string. A matrix prints as inlined JSON for
`fromJSON()` to parse into a job matrix. See
{func}`~repomatic.metadata.output.format_github_value` for the encoding, and
{class}`~repomatic.metadata.output.Dialect` for the other output formats.
The full key inventory is generated from this module rather than listed here, so
it cannot go stale: run `repomatic show-metadata --list-keys`, or read the rendered
table in [the workflows documentation](https://repomatic.net/workflows).
""" # noqa: E501
from __future__ import annotations
import logging
import re
import shlex
from functools import cached_property, partial
from typing import NamedTuple
from click_extra import ColumnSpec, field_docstrings
from ..config import Config
from ..deps.pins import min_release_age_days
from ..file_inventory import FileInventory
from ..github.workflow_files import iter_steps
from ..mailmap import MAILMAP_PATH
from ..pyproject import get_current_version
from ..release.binary import (
FLAT_BUILD_TARGETS,
)
from ..tooling.registry import TOOL_REGISTRY
from .env import EnvironmentMetadata
from .git import GitMetadata
from .matrix import MatrixMetadata
from .output import Dialect
from .project import ProjectMetadata
TYPE_CHECKING = False
if TYPE_CHECKING:
import pathlib
from collections.abc import Callable, Iterator, Mapping
from pathlib import Path
from typing import Any, Final, Self
FILE_GROUP_KEYS: Final[frozenset[str]] = frozenset((
"doc_files",
"gitignore_exists",
"image_files",
"json_files",
"markdown_files",
"pyproject_files",
"python_files",
"shfmt_files",
"workflow_files",
"yaml_files",
"zsh_files",
))
"""Metadata keys read off {attr}`Metadata.files`, the attribute of the same name.
The inventory answers them with no CI context, no git history and no
`pyproject.toml`, so {meth}`Metadata.dump_factories` reads them there directly.
"""
METADATA_CONFIG_FIELDS: Final[tuple[str, ...]] = (
"binaries_sync",
"manpages_script",
"release_assets",
"site_deploy",
"sphinx_builder",
"sphinx_fail_on_warning",
)
"""`Config` fields a workflow reads through the metadata output, sorted.
Every other field stays out of the output: the subcommand that needs one reads
it from `[tool.repomatic]` directly. A new field joins this list only when a
workflow condition or step reads it, like the `binaries.sync` toggle a separate
`pr-sync` step depends on.
"""
_METADATA_KEY_DESCRIPTIONS: Final[dict[str, str]] = {
"is_bot": "Workflow was triggered by a bot or automated process.",
"is_awesome": "Repository is an awesome list: its name starts with `awesome-`.",
"yaml_changed": "Current event's commit range touches at least one YAML file.",
"shfmt_changed": (
"Current event's commit range touches at least one file of `shfmt_files`."
),
"zsh_changed": "Current event's commit range touches at least one Zsh file.",
"workflows_changed": (
"Current event's commit range touches at least one GitHub workflow file."
),
"mailmap_exists": "Whether a .mailmap file exists in the repository.",
"gitignore_exists": "Whether a .gitignore file exists in the repository.",
"python_files": "List of Python files in the repository.",
"json_files": "List of JSON files in the repository.",
"yaml_files": "List of YAML files in the repository.",
"pyproject_files": "List of pyproject.toml files in the repository.",
"workflow_files": "List of GitHub workflow files.",
"doc_files": "List of documentation files.",
"markdown_files": "List of Markdown files.",
"image_files": "List of image files.",
"shfmt_files": "List of shell files formattable by shfmt.",
"zsh_files": "List of Zsh files.",
"is_python_project": "Repository is a Python project with pyproject.toml.",
"is_python_package": (
"Repository builds a distributable Python package, not a uv virtual project."
),
"changelog_has_entries": (
"The changelog section of the current version holds at least one entry."
),
"package_name": "Package name as published on PyPI.",
"manpages_asset_name": (
"Filename stem of the man-page tarball attached to a release."
),
"cli_scripts": "CLI script entry points from pyproject.toml.",
"main_cli_script": "First CLI script entry point from pyproject.toml.",
"import_name": "Top-level package the `python -m` invocation runs.",
"project_description": "Project description from pyproject.toml.",
"mypy_params": "Generated mypy command-line parameters.",
"current_version": "Current version from pyproject.toml.",
"released_version": "Version of the release commit, if any.",
"is_sphinx": "Sphinx configuration file is present.",
"builds_sphinx": "Python project with a Sphinx configuration to build.",
"active_autodoc": "Active Sphinx autodoc extensions detected.",
"uses_myst": "MyST-Parser is active in Sphinx configuration.",
"new_commits_matrix": "Matrix of new commits with long and short SHA values.",
"release_commits_matrix": (
"Matrix of release commits with long and short SHA values."
),
"is_release_push": "Event lands release commits on the release branch.",
"release_commit": (
"Newest release commit of the event, else the event's own commit."
),
"build_targets": "List of Nuitka build targets for all platforms.",
"nuitka_matrix": (
"Matrix for Nuitka compilation workflows, empty when the build is skipped."
),
"runner_arch": "Architecture of each runner image in the full test matrix.",
"test_matrix": "Full test matrix for non-PR events.",
"test_matrix_pr": "Reduced test matrix for pull requests.",
"latest_stable_python": "Newest released Python version of the full test matrix.",
"npm_min_release_age_days": "npm min-release-age cooldown, in whole days.",
"tool_versions": "Pinned version of each `repomatic run` tool, by name.",
"cloudflare_project": (
"Cloudflare Pages project of the site: `site.cloudflare-project`, else"
" the repository name."
),
}
"""One-liner descriptions for each metadata key produced by {meth}`Metadata.dump`."""
METADATA_KEYS_HEADER_DEFS: tuple[ColumnSpec, ...] = (
ColumnSpec("key", "Key"),
ColumnSpec("description", "Description"),
)
"""Column definitions for the metadata keys reference table."""
METADATA_VALUE_OPTIONS: frozenset[str] = frozenset((
"--format",
"-o",
"--output",
"--output-format",
"--sort-by",
))
"""Options on the `show-metadata` command consuming the token that follows them.
Needed by {func}`unknown_metadata_keys` to tell a positional key from an
option's value while reading a workflow's `run:` line. `--format` is the
spelling of releases before `8.0.0`, kept so that a workflow pinned to one of
them still parses.
Listed here rather than derived, and pinned against the real command by
repomatic's own test suite, so an option added later cannot quietly turn its
value into a token the lint reports as an unknown key.
"""
METADATA_SUBCOMMAND: Final[str] = "show-metadata"
"""The subcommand that prints the metadata keys a workflow asks for."""
REMOVED_METADATA_ALIAS: Final[str] = "metadata"
"""The alias of {data}`METADATA_SUBCOMMAND` that `8.0.0` removed.
A workflow still calling it fails at its first job, so the readers below
recognize it in order to report it.
"""
RENAMED_METADATA_OPTIONS: Final[dict[str, str]] = {"--format": "--output-format"}
"""Options of {data}`METADATA_SUBCOMMAND` that `8.0.0` renamed, mapped to the new name.
The command rejects the old spelling with a `UsageError`, so a workflow still
passing one fails at its first job, like a call of the removed alias. Header-only
sync never reads the job body holding the call, so the readers below recognize
the old spelling in order to report it.
"""
_METADATA_KEY_TOKEN: Final = re.compile(r"^[a-z][a-z0-9_]*$")
"""Shape of a metadata key, used to tell one from a neighbouring shell token.
Every key is a Python identifier, so a token carrying a hyphen (`github-json`),
a dollar (`$GITHUB_OUTPUT`) or a dot is something else on the command line and
is passed over rather than reported as unknown.
"""
_SHELL_OPERATORS: Final[frozenset[str]] = frozenset((
"&&",
"||",
";",
"|",
">",
">>",
"<",
"&",
))
"""Tokens that end the invocation and start unrelated words.
`repomatic show-metadata a b && echo done` must not report `echo` and `done` as
metadata keys.
"""
def _metadata_invocations(
command: str, package: str
) -> Iterator[tuple[str, list[str]]]:
"""Yield each call of the metadata subcommand in a `run:` script.
Handles both spellings in use, the upstream
`uv run -- repomatic show-metadata …` and the downstream
`uvx 'repomatic==1.2.3' show-metadata …`, by looking for the subcommand
after any token naming the package. The removed {data}`REMOVED_METADATA_ALIAS`
spelling is recognized too, so a caller can report it.
:param command: The step's `run:` script, folded or literal.
:param package: Upstream package name (like `repomatic`).
:return: `(subcommand, arguments)` per call, the arguments stopping at the
first shell operator.
"""
# A literal block scalar holds a whole script: read it a line at a time so
# a later command's words cannot be mistaken for this one's arguments.
# Backslash continuations are rejoined first, being one command still.
for line in command.replace("\\\n", " ").splitlines():
try:
tokens = shlex.split(line, comments=True)
except ValueError:
# An unbalanced quote is a line this cannot read. A shell would
# reject it too, so leave it to the shell to complain.
continue
seen_package = False
for index, token in enumerate(tokens):
if seen_package and token in (METADATA_SUBCOMMAND, REMOVED_METADATA_ALIAS):
arguments: list[str] = []
for argument in tokens[index + 1 :]:
if argument in _SHELL_OPERATORS:
break
arguments.append(argument)
yield token, arguments
break
if token == package or token.startswith(f"{package}=="):
seen_package = True
def _positional_keys(arguments: list[str]) -> list[str]:
"""Read the positional keys out of a metadata call's arguments.
Reads them the way Click would: options are dropped along with the value
each one consumes, and what remains are the positional key arguments.
"""
keys: list[str] = []
skip_next = False
for token in arguments:
if skip_next:
skip_next = False
continue
if token.startswith("-"):
# `--format=json` carries its value inline, consuming nothing.
skip_next = "=" not in token and token in METADATA_VALUE_OPTIONS
continue
if _METADATA_KEY_TOKEN.match(token):
keys.append(token)
return keys
# Silence overly verbose debug messages from py-walk logger.
logging.getLogger("py_walk").setLevel(logging.WARNING)