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
31 changes: 27 additions & 4 deletions docs/concepts/resolver-architecture.rst
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ For each requirement rule, it tries in order:
New results are merged into the session cache and filtered by the
current requirement.

Previous source URLs must be Git URLs when the selected resolver requires
Git checkouts. Incompatible entries raise an error; bootstrap without
``--previous-bootstrap-file`` after changing source providers.

Two cases need separate handling:

- **Direct-reference URL requirements**, including Git URLs, are rejected.
Expand Down Expand Up @@ -79,8 +83,15 @@ their common ``find_matches()`` method.
- ``GitHubTagProvider`` and ``GitLabTagProvider`` query repository tags
and parse versions from tag names. GitLab also reports timestamps for
age filtering.
- ``VersionMapProvider`` uses an existing version-to-URL mapping, such
as results from an earlier resolution or a URL template.
- With ``clone_url``, ``VersionMapProvider`` maps versions to full Git commit IDs
or ``refs/...`` paths, such as ``abad1deaabad1deaabad1deaabad1deaabad1dea`` or
Comment thread
jlarkin09 marked this conversation as resolved.
Resolved
``refs/tags/v1.2``. Candidate URLs combine the repository URL and ref as
``git+https://host.example/repo.git@refs/tags/v1.2``, which the Git
downloader uses to clone and check out the selected ref. Without
``clone_url``, mapped values pass through unchanged for plugin hooks.

.. versionchanged:: 0.104.0
``VersionMapProvider`` accepts a separate ``clone_url`` for mapped Git refs.

Selecting a Provider
--------------------
Expand All @@ -96,6 +107,17 @@ index URLs are ignored. Without ``source:``, Fromager uses the legacy
resolver settings and the package's ``get_resolver_provider`` override
when present.

.. versionadded:: 0.104.0
The ``versionmap-git`` profile accepts a ``versionmap`` of version
strings to Git refs and a separate HTTPS or SSH ``clone_url``.

``versionmap-git`` selects the highest mapped version matching the
requirement and constraints, then clones the repository at its mapped ref.
The resolved URL includes the ref for build-order replay. Use full commit IDs
for reproducible replay; named refs can move between builds. The ``build_sdist``
setting defaults to ``pep517`` and also accepts ``tarball`` and ``hook``.
See :class:`~fromager.packagesettings.VersionMapGitResolver` for an example.

Hook Profiles
~~~~~~~~~~~~~

Expand Down Expand Up @@ -337,7 +359,8 @@ Per-Package Configuration
-------------------------

Package settings files (YAML) configure the resolver for each package
independently: resolver type (PyPI, GitHub tags, GitLab tags, hook-based,
or blocked), index URL, cooldown, tag pattern, and override plugins.
independently: resolver type (PyPI, GitHub tags, GitLab tags, mapped Git
refs, hook-based, or blocked), index URL, cooldown, tag pattern, and
override plugins.

See :doc:`package-settings` for how settings are loaded and merged.
2 changes: 1 addition & 1 deletion docs/proposals/new-resolver-config.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ variants:
clone_url: https://git.example/viking/viking.git
build_sdist: pep517
versionmap:
'1.0': abad1dea
'1.0': abad1deaabad1deaabad1deaabad1deaabad1dea
'1.1': refs/tags/1.1
camelot:
source:
Expand Down
7 changes: 7 additions & 0 deletions docs/reference/config-reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,13 @@ Source Resolver
:inherited-members: AbstractPyPIResolver, CooldownMixin
:members: download_kinds, supports_override_hooks, resolves_prebuilt_wheel

.. versionchanged:: 0.104.0
``pypi-git`` requires a host in ``clone_url`` and rejects URLs containing
queries or fragments.

.. autopydantic_model:: VersionMapGitResolver
:members: download_kinds, supports_override_hooks, resolves_prebuilt_wheel

.. autopydantic_model:: GitHubTagDownloadResolver
:inherited-members: AbstractGitSourceResolver, CooldownMixin
:members: download_kinds, supports_override_hooks, resolves_prebuilt_wheel
Expand Down
17 changes: 16 additions & 1 deletion src/fromager/bootstrap_requirement_resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@
from packaging.version import Version
from resolvelib.resolvers import ResolverException

from . import resolver, sources, wheels
from . import gitutils, resolver, sources, wheels
from .dependency_graph import DependencyGraph
from .packagesettings import DownloadKind
from .requirements_file import RequirementType

if typing.TYPE_CHECKING:
Expand Down Expand Up @@ -178,6 +179,20 @@ def _resolve_and_extend(
source_resolver is not None and source_resolver.resolves_prebuilt_wheel
)
if cached_resolution:
if (
not pre_built
and source_resolver is not None
and source_resolver.download_kinds == {DownloadKind.git_checkout}
):
for url, _ in cached_resolution:
try:
gitutils.parse_vcs_url(url)
except ValueError as err:
raise ValueError(
f"{req.name}: previous bootstrap source URL is incompatible "
f"with {source_resolver.provider!r}; bootstrap without "
"--previous-bootstrap-file after changing source providers"
) from err
logger.debug(
f"resolved from previous bootstrap: {len(cached_resolution)} version(s)"
)
Expand Down
1 change: 1 addition & 0 deletions src/fromager/downloads.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,5 +243,6 @@ def download_git_source(
output_dir=destination_dir,
repo_url=repo_url,
ref=ref,
remote_name="origin",
)
return destination_dir
42 changes: 40 additions & 2 deletions src/fromager/gitutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,21 @@
GIT_HEAD: typing.Final = "HEAD"


def is_full_git_ref(ref: str) -> bool:
"""Return whether *ref* is a literal full Git ref name under ``refs/``."""
return (
ref.startswith("refs/")
and not ref.endswith(".")
and ".." not in ref
and "@{" not in ref
and not any(ord(c) < 33 or ord(c) == 127 or c in "~^:?*[\\" for c in ref)
and all(
part and not part.startswith(".") and not part.endswith(".lock")
for part in ref.split("/")
)
)


def git_checkout_dir(
*, work_dir: pathlib.Path, distribution_name: str, version: Version
) -> pathlib.Path:
Expand Down Expand Up @@ -101,6 +116,7 @@ def git_clone_fast(
output_dir: pathlib.Path,
repo_url: str,
ref: str = GIT_HEAD,
remote_name: str | None = None,
) -> None:
"""Efficient, blobless git clone with all submodules

Expand All @@ -111,9 +127,14 @@ def git_clone_fast(

The *ref* parameter can be any tree-ish reference like a commit, tag, or
branch. To force a tag, use ``refs/tags/v1.0`` to fetch the ``v1.0`` tag.
The *remote_name* parameter overrides Git's configured default remote name.

Like in :command:`pip`, submodules are automatically cloned recursively.

.. versionchanged:: 0.104.0
Fetch missing full refs before checkout, including nondefault branches
and custom refs such as ``refs/pull/123/head``.

.. note::

:command:`git` and ``libcurl`` do not support :envvar:`NETRC`. Use
Expand All @@ -136,11 +157,28 @@ def git_clone_fast(
"clone",
"--filter=blob:none",
"--no-checkout",
repo_url,
str(output_dir),
]
if remote_name is not None:
cmd.extend(["--origin", remote_name])
cmd.extend([repo_url, str(output_dir)])
external_commands.run(cmd, network_isolation=False)

if is_full_git_ref(ref):
local_refs = external_commands.run(
["git", "for-each-ref", "--format=%(refname)", ref],
cwd=str(output_dir),
).splitlines()
if ref not in local_refs:
if remote_name is None:
remote_name = external_commands.run(
["git", "remote"], cwd=str(output_dir)
).strip()
external_commands.run(
["git", "fetch", remote_name, f"{ref}:{ref}"],
cwd=str(output_dir),
network_isolation=False,
)

# check out reference / tag
logger.debug("check out ref")
cmd = [
Expand Down
2 changes: 2 additions & 0 deletions src/fromager/packagesettings/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
PyPIPrebuiltResolver,
PyPISDistResolver,
SourceResolver,
VersionMapGitResolver,
pep440_tag_matcher,
)
from ._settings import Settings, SettingsFile
Expand Down Expand Up @@ -93,6 +94,7 @@
"Variant",
"VariantChangelog",
"VariantInfo",
"VersionMapGitResolver",
"WheelSettings",
"default_update_extra_environ",
"get_extra_environ",
Expand Down
121 changes: 113 additions & 8 deletions src/fromager/packagesettings/_resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,35 @@

import pydantic
from packaging.utils import canonicalize_name
from packaging.version import Version

from .. import downloads, gitutils, overrides, resolver
from ..versionmap import VersionMap
from ._typedefs import MODEL_CONFIG

if typing.TYPE_CHECKING:
from packaging.requirements import Requirement
from packaging.version import Version

from .. import context, requirements_file

logger = logging.getLogger(__name__)

_VERSION_QUOTED = "%7Bversion%7D"
_PYPI_INDEX_URL = pydantic.HttpUrl("https://pypi.org/simple/")
_GIT_REF_PATTERN = re.compile(r"[0-9a-f]{40}|[0-9a-f]{64}|refs/[^\s@?#:]+")


def _validate_git_clone_url(value: pydantic.AnyUrl) -> pydantic.AnyUrl:
Comment thread
jlarkin09 marked this conversation as resolved.
Resolved
"""Require an HTTPS or SSH repository URL with a host and path."""
if value.scheme not in {"https", "ssh"}:
raise ValueError("invalid scheme in clone_url; use https or ssh")
if not value.host:
raise ValueError("clone_url has an empty host")
if not value.path:
raise ValueError("clone_url has an empty path")
if value.query is not None or value.fragment is not None:
raise ValueError("clone_url must not contain a query or fragment")
return value


class BuildSDist(enum.StrEnum):
Expand Down Expand Up @@ -117,8 +132,8 @@ def download(
*download_url* must contain everything the download needs, such as
the git ref in ``git+https://host/repo.git@refs/tags/v1.0``. It is
passed to download hooks unchanged and is not validated, so it can be
a ref instead of a URL, such as a commit SHA from a
``VersionMapProvider``.
a ref instead of a URL when a custom resolver and download hook
use that convention.
"""
raise NotImplementedError

Expand Down Expand Up @@ -466,11 +481,8 @@ class PyPIGitResolver(AbstractPyPIResolver):
@pydantic.field_validator("clone_url", mode="after")
@classmethod
def validate_clone_url(cls, value: pydantic.AnyUrl) -> pydantic.AnyUrl:
if value.scheme not in {"https", "ssh"}:
raise ValueError(f"invalid scheme in url {value}")
if not value.path:
raise ValueError(f"url {value} has an empty path")
return value
"""Validate the repository's clone URL."""
return _validate_git_clone_url(value)

def resolver_provider(
self,
Expand Down Expand Up @@ -502,6 +514,98 @@ def download(
)


class VersionMapGitResolver(AbstractResolver):
"""Resolve mapped versions and clone the repository at their Git refs.

``versionmap`` associates PEP 440 versions with full commit IDs or
``refs/...`` paths. ``clone_url`` identifies the repository. Build the sdist using
``build_sdist``, which defaults to PEP 517.

Example::

provider: versionmap-git
clone_url: https://git.example/project/repo.git
build_sdist: pep517
versionmap:
'1.0': abad1deaabad1deaabad1deaabad1deaabad1dea
'1.1': refs/tags/1.1

.. versionadded:: 0.104.0
"""

provider: typing.Literal["versionmap-git"]

download_kinds: typing.ClassVar[DownloadKindSet] = frozenset(
{DownloadKind.git_checkout}
)

clone_url: pydantic.AnyUrl
"""HTTPS or SSH repository URL without passwords, queries, or fragments.

HTTPS authentication must use Git credential helpers; SSH usernames are allowed.
"""

versionmap: dict[str, str] = pydantic.Field(min_length=1)
"""Nonempty mapping of distinct PEP 440 versions to full IDs or ref paths."""

build_sdist: BuildSDist = BuildSDist.pep517
"""Source distribution build method."""

@pydantic.field_validator("clone_url", mode="after")
@classmethod
def validate_clone_url(cls, value: pydantic.AnyUrl) -> pydantic.AnyUrl:
"""Validate the repository's clone URL."""
value = _validate_git_clone_url(value)
if value.password or (value.scheme == "https" and value.username):
raise ValueError("clone_url must not contain credentials")
return value

@pydantic.field_validator("versionmap", mode="after")
@classmethod
def validate_versionmap(cls, value: dict[str, str]) -> dict[str, str]:
"""Validate versions and refs before constructing checkout URLs."""
versions: set[Version] = set()
for version, ref in value.items():
normalized = Version(version)
if normalized in versions:
raise ValueError(f"duplicate version {version!r} after normalization")
versions.add(normalized)
if not _GIT_REF_PATTERN.fullmatch(ref) or (
ref.startswith("refs/") and not gitutils.is_full_git_ref(ref)
):
raise ValueError(f"invalid Git ref for version {version!r}: {ref!r}")
return value
Comment thread
jlarkin09 marked this conversation as resolved.
Resolved

def resolver_provider(
self,
ctx: context.WorkContext,
req: Requirement,
req_type: requirements_file.RequirementType | None,
) -> resolver.VersionMapProvider:
"""Return a provider using the mapped refs and current constraints."""
return resolver.VersionMapProvider(
version_map=VersionMap(
{Version(version): ref for version, ref in self.versionmap.items()}
),
package_name=req.name,
clone_url=str(self.clone_url),
Comment thread
jlarkin09 marked this conversation as resolved.
Resolved
constraints=ctx.constraints,
req_type=req_type,
)

def download(
self,
ctx: context.WorkContext,
req: Requirement,
version: Version,
download_url: str,
) -> DownloadedSource:
"""Clone the repository at the ref recorded in the resolved URL."""
return self._download(
ctx, req, version, download_url, DownloadKind.git_checkout
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
)


_PEP440_TAG_PATTERN = re.compile(r"^(v?\d.*)$")


Expand Down Expand Up @@ -1114,6 +1218,7 @@ def download(
| PyPIPrebuiltResolver
| PyPIDownloadResolver
| PyPIGitResolver
| VersionMapGitResolver
| GitHubTagCloneResolver
| GitHubTagDownloadResolver
| GitLabTagCloneResolver
Expand Down
2 changes: 2 additions & 0 deletions src/fromager/packagesettings/_typedefs.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
use_attribute_docstrings=True,
# preserve URLs as-is without trailing slash normalization
url_preserve_empty_path=True,
# settings inputs may contain credentials
hide_input_in_errors=True,
)


Expand Down
Loading
Loading