Skip to content

Commit 3407cdc

Browse files
fix(sources): allow sdist hooks with source config
Allow packages with `source:` to select their `build_sdist` override. Validate the selected variant's hook before resolution or download, and keep `tarball` as the default while allowing explicit PEP 517 builds. Document the VCS exclusion default and build dependency prerequisite, and separate dispatch tests from archive-content tests. Closes: #1445 Co-Authored-By: Codex <noreply@openai.com> Signed-off-by: Lalatendu Mohanty <lmohanty@redhat.com>
1 parent d86e496 commit 3407cdc

13 files changed

Lines changed: 789 additions & 64 deletions

‎docs/concepts/hooks-and-overrides.rst‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,16 @@ arguments.
6666
artifact kind. Package overrides remain active. See :ref:`prepare_source_hook`
6767
for their arguments and the public Git checkout helper.
6868

69+
With ``source:`` configured, set ``build_sdist: hook`` to use the package's
70+
custom sdist builder. See :ref:`build_sdist_hook` for details.
71+
72+
.. versionchanged:: 0.104.0
73+
74+
``source.build_sdist: hook`` requires a callable package override. Fromager
75+
rejects a missing or non-callable hook before resolving or downloading the
76+
package. Hooks that delegate to ``default_build_sdist()`` exclude VCS
77+
metadata by default when ``source:`` is configured.
78+
6979
Global Hooks
7080
------------
7181

‎docs/concepts/package-settings.rst‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,11 @@ Settings Loading Flow
3535
``PackageBuildInfo`` objects are created lazily the first time a
3636
package is queried and cached for the rest of the run.
3737

38+
.. versionchanged:: 0.104.0
39+
With ``source.build_sdist: hook``, Fromager checks that the selected
40+
variant's hook exists and can be called before resolving or downloading
41+
the package. Hooks used only by other variants are not required.
42+
3843
``PackageSettings`` validates source settings when it loads each package.
3944
A package-level ``source`` cannot be combined with an explicitly set
4045
variant ``pre_built`` or ``wheel_server_url``. A variant-level ``source``

‎docs/concepts/resolver-architecture.rst‎

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -212,17 +212,32 @@ Building the Sdist
212212
Git checkouts can be prepared directly. Configured source resolvers
213213
also select the sdist build method.
214214

215-
For source builds, the configured resolver selects one of two methods:
215+
For source builds, ``source.build_sdist`` selects the build method:
216216

217217
- ``pep517`` calls the package's build backend. Git checkout resolvers
218-
default to it.
218+
default to it. Archive-based PyPI resolvers can select it explicitly.
219219
- ``tarball`` repacks the prepared source without VCS metadata such as
220-
``.git``. PyPI sdist resolvers default to it.
220+
``.git``. Archive-based PyPI resolvers default to it.
221+
- ``hook`` calls the package's custom ``build_sdist`` hook. It can generate
222+
files or choose which directory to pack. A missing or non-callable hook is
223+
rejected before resolution or download.
221224

222-
``hook-sdist`` requires an explicit ``build_sdist: pep517`` or
223-
``build_sdist: tarball`` setting. A configured method takes precedence
224-
over a ``build_sdist`` override and logs a warning when the override is
225-
ignored; packages without ``source:`` keep using the override.
225+
``hook-sdist`` requires an explicit build method. Other profiles that build
226+
from source can also select ``hook``. The ``pep517`` and ``tarball`` methods
227+
skip installed build hooks with a warning. Without ``source:``, Fromager
228+
uses the hook when present, or the default otherwise.
229+
230+
Hooks that delegate to ``default_build_sdist()`` inherit its default VCS
231+
exclusion for configured source profiles. An explicit ``exclude_vcs`` value
232+
overrides this policy. Hooks that create archives directly choose their contents.
233+
234+
See :ref:`build_sdist_hook` for the arguments, archive rules, and an example.
235+
236+
.. versionchanged:: 0.104.0
237+
238+
``source.build_sdist: hook`` enables package overrides for configured
239+
source profiles. ``default_build_sdist()`` excludes VCS metadata by default
240+
for those profiles.
226241

227242
Replaying a Build Order
228243
-----------------------

‎docs/proposals/new-resolver-config.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,11 @@ hook and `source` settings, then at least one `source` setting (top-level or
174174
variant) must use `provider: hook-sdist` or `provider: hook-prebuilt`. The
175175
rule ensures that the hooks are used.
176176

177+
Set `build_sdist: hook` under `source` to use the package's custom sdist
178+
builder with any profile that builds from source. A missing hook is an error.
179+
The `pep517` and `tarball` methods skip installed build hooks with a warning.
180+
Packages without `source` keep their existing build-hook behavior.
181+
177182
### git clone
178183

179184
Git cloning uses the more efficient `git_clone_fast` function. Like pip's

‎docs/reference/config-reference.rst‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,19 @@ Source Resolver
7676

7777
.. autoattribute:: pep517
7878
.. autoattribute:: tarball
79+
.. autoattribute:: hook
80+
81+
.. versionadded:: 0.104.0
82+
83+
Set ``build_sdist: hook`` to use the package's custom sdist builder.
84+
The hook must be installed and callable. This option is only available for
85+
source builds. See :ref:`build_sdist_hook` for details and an example.
86+
87+
.. versionchanged:: 0.104.0
88+
89+
``pypi-sdist`` and ``pypi-download`` accept an explicit
90+
``build_sdist: pep517``. Their default remains ``tarball`` because some
91+
build backends require VCS metadata that source archives do not contain.
7992

8093
.. autoclass:: DownloadedSource
8194
:members: path, kind

‎docs/reference/hooks.rst‎

Lines changed: 45 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -361,17 +361,55 @@ Source hooks
361361
.. versionchanged:: 0.103.0
362362
Passing ``DownloadKind.git_checkout`` prepares a clean Git checkout.
363363

364+
.. _build_sdist_hook:
365+
364366
.. autofromagerhook:: default_build_sdist
365367

366-
The ``build_sdist()`` function is responsible for creating a new source
367-
distribution from the prepared source tree and placing it in
368-
``ctx.sdists_build``. The dist name and version of the sdist file must
369-
match the ``Requirement`` and ``Version``.
368+
The ``build_sdist()`` hook packs prepared sources into an sdist and returns
369+
its ``Path``. The file must exist in ``ctx.sdists_builds`` and match the
370+
requested package name and version.
371+
372+
The hook receives ``ctx``, ``extra_environ``, ``req``, ``version``,
373+
``sdist_root_dir``, ``build_env``, and ``build_dir``. Build dependencies are
374+
installed when the build pipeline prepares them. The standalone
375+
``step build-sdist`` command does not install dependencies; run
376+
``step prepare-build`` first. Use the hook to generate files or pack a
377+
directory other than the wheel build directory.
378+
379+
.. versionchanged:: 0.104.0
380+
381+
With ``source:``, set ``build_sdist: hook`` to call this hook.
382+
A missing or non-callable hook is rejected before resolution or
383+
download. The ``pep517`` and ``tarball`` methods
384+
skip installed hooks with a warning. Without ``source:``, Fromager
385+
uses the hook when present, or the default otherwise.
386+
387+
For a package downloaded as a tarball:
388+
389+
.. code-block:: yaml
390+
391+
build_dir: python
392+
source:
393+
provider: pypi-download
394+
download_url: https://sources.example/project-{version}.tar.gz
395+
download_kind: tarball
396+
build_sdist: hook
397+
398+
Any profile that builds from source can use this option. The
399+
``hook-sdist`` profile still needs a resolver or download hook.
400+
401+
.. versionchanged:: 0.104.0
402+
403+
``default_build_sdist()`` now excludes VCS metadata such as ``.git``
404+
by default when the effective package or variant has ``source:``
405+
configured, including when called by a hook. Pass ``exclude_vcs=False``
406+
to retain the previous behavior.
370407

371-
The arguments are the ``WorkContext``, the ``Requirement`` being evaluated, and the
372-
`Path` to the root of the source tree.
408+
Without ``source:``, the helper retains VCS metadata by default; pass
409+
``exclude_vcs=True`` to omit it.
373410

374-
The return value is the ``Path`` to the newly created source distribution.
411+
Hooks that create archives directly choose their contents and must omit
412+
VCS metadata themselves.
375413

376414
Source helper functions
377415
~~~~~~~~~~~~~~~~~~~~~~~

‎src/fromager/packagesettings/_pbi.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
PurlConfig,
2222
VariantInfo,
2323
)
24+
from ._resolver import BuildSDist
2425
from ._templates import _resolve_template, substitute_template
2526
from ._typedefs import Annotations, PackageVersion, PatchMap, Template, Variant
2627

@@ -52,6 +53,22 @@ def __init__(self, settings: Settings, ps: PackageSettings) -> None:
5253
self._plugin_module: types.ModuleType | typing.Literal[False] | None = False
5354
self._patches: PatchMap | None = None
5455
self._annotations: Annotations | None = None
56+
self._validate_build_sdist_hook()
57+
58+
def _validate_build_sdist_hook(self) -> None:
59+
"""Check the selected variant's hook before resolution or download."""
60+
source_resolver = self.source_resolver
61+
if (
62+
source_resolver is None
63+
or source_resolver.build_sdist is not BuildSDist.hook
64+
):
65+
return
66+
hook = overrides.find_override_method(self.package, "build_sdist")
67+
if not callable(hook):
68+
raise ValueError(
69+
f"{self.package}: source.build_sdist='hook' requires a callable "
70+
"build_sdist override hook"
71+
)
5572

5673
@property
5774
def package(self) -> NormalizedName:

‎src/fromager/packagesettings/_resolver.py‎

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,15 @@
2828

2929

3030
class BuildSDist(enum.StrEnum):
31+
"""Source distribution build method."""
32+
3133
pep517 = "pep517"
3234
tarball = "tarball"
35+
hook = "hook"
36+
"""Call the package's ``build_sdist`` override hook.
37+
38+
.. versionadded:: 0.104.0
39+
"""
3340

3441

3542
class DownloadKind(enum.StrEnum):
@@ -71,10 +78,14 @@ class AbstractResolver(pydantic.BaseModel):
7178
provider: str
7279

7380
build_sdist: BuildSDist | None
74-
"""Sdist build strategy; None for resolvers that do not build from source."""
81+
"""Sdist build strategy; None for resolvers that do not build from source.
82+
83+
``hook`` requires a package ``build_sdist`` override independently of
84+
the profile's resolver and download hooks.
85+
"""
7586

7687
supports_override_hooks: typing.ClassVar[bool] = False
77-
"""Does resolver support override hooks?"""
88+
"""Does resolver support resolution and download override hooks?"""
7889

7990
download_kinds: typing.ClassVar[DownloadKindSet] = frozenset()
8091
"""Set of download kinds this resolver can return."""
@@ -248,9 +259,11 @@ class PyPISDistResolver(AbstractPyPIResolver):
248259

249260
provider: typing.Literal["pypi-sdist"]
250261

251-
# It is not safe to use PEP 517 to re-generate a source distribution.
252-
# Some PEP 517 backends require VCS to generate correct sdist.
253-
build_sdist: typing.Literal[BuildSDist.tarball] = BuildSDist.tarball
262+
# Tarball repacking is the safe default because some PEP 517 backends
263+
# require VCS metadata to generate a correct sdist.
264+
build_sdist: typing.Literal[
265+
BuildSDist.pep517, BuildSDist.tarball, BuildSDist.hook
266+
] = BuildSDist.tarball
254267
download_kinds: typing.ClassVar[DownloadKindSet] = frozenset({DownloadKind.sdist})
255268

256269
def resolver_provider(
@@ -362,7 +375,9 @@ class PyPIDownloadResolver(AbstractPyPIResolver):
362375
URL must contain '{version}' template string.
363376
"""
364377

365-
build_sdist: typing.Literal[BuildSDist.tarball] = BuildSDist.tarball
378+
build_sdist: typing.Literal[
379+
BuildSDist.pep517, BuildSDist.tarball, BuildSDist.hook
380+
] = BuildSDist.tarball
366381
download_kinds: typing.ClassVar[DownloadKindSet] = frozenset(
367382
{DownloadKind.sdist, DownloadKind.tarball}
368383
)
@@ -808,7 +823,7 @@ class AbstractHookResolver(AbstractResolver, CooldownMixin):
808823
"""Abstract base class for hook-based resolvers"""
809824

810825
supports_override_hooks: typing.ClassVar[bool] = True
811-
"""Hook resolvers support override hooks."""
826+
"""Hook resolvers support resolution and download override hooks."""
812827

813828
hookless_provider: typing.ClassVar[str]
814829
"""Profile to suggest for packages without hooks."""
@@ -953,7 +968,8 @@ class HookSDistResolver(AbstractHookResolver):
953968
``Path`` treated as an sdist.
954969
Without a download hook, the resolved URL is downloaded as an sdist.
955970
Specify ``build_sdist`` explicitly: ``tarball`` to repack an existing
956-
sdist, or ``pep517`` to build from a git checkout.
971+
sdist, ``pep517`` to build from a git checkout, or ``hook`` to call
972+
the package's ``build_sdist`` override.
957973
958974
Example::
959975

‎src/fromager/sources.py‎

Lines changed: 44 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -624,58 +624,65 @@ def build_sdist(
624624
sdist_root_dir: pathlib.Path,
625625
build_env: build_environment.BuildEnvironment,
626626
) -> pathlib.Path:
627-
"""Build a source distribution using the configured strategy or legacy hook."""
627+
"""Build a source distribution using the configured strategy or legacy hook.
628+
629+
``source.build_sdist: hook`` requires a package override. Configured
630+
``pep517`` and ``tarball`` strategies take precedence over overrides.
631+
632+
.. versionchanged:: 0.104.0
633+
Configured source profiles can select the ``build_sdist`` override.
634+
"""
628635
pbi = ctx.package_build_info(req)
629636
source_resolver = pbi.source_resolver
637+
strategy = source_resolver.build_sdist if source_resolver is not None else None
630638
build_dir = pbi.build_dir(sdist_root_dir)
631639

632640
logger.info(f"building {ctx.variant} source distribution for {req} in {build_dir}")
641+
if source_resolver is not None:
642+
build_sdist_override = overrides.find_override_method(req.name, "build_sdist")
643+
if strategy is packagesettings.BuildSDist.hook:
644+
if not callable(build_sdist_override):
645+
raise ValueError(
646+
f"{req.name}: source.build_sdist='hook' requires a callable "
647+
"build_sdist override hook"
648+
)
649+
elif build_sdist_override is not None:
650+
logger.warning(
651+
"%s: ignoring build_sdist override because source.build_sdist is %s",
652+
req.name,
653+
strategy,
654+
)
633655
extra_environ = packagesettings.get_extra_environ(
634656
ctx=ctx,
635657
req=req,
636658
version=version,
637659
sdist_root_dir=sdist_root_dir,
638660
build_env=build_env,
639661
)
640-
if source_resolver is not None:
641-
if overrides.find_override_method(req.name, "build_sdist") is not None:
642-
logger.warning(
643-
"%s: ignoring build_sdist override because source.build_sdist is %s",
644-
req.name,
645-
source_resolver.build_sdist,
646-
)
647-
if (
648-
source_resolver is not None
649-
and source_resolver.build_sdist is packagesettings.BuildSDist.pep517
650-
):
651-
sdist_file = pep517_build_sdist(
662+
if source_resolver is None or strategy is packagesettings.BuildSDist.hook:
663+
sdist_file: pathlib.Path = overrides.find_and_invoke(
664+
req.name,
665+
"build_sdist",
666+
default_build_sdist,
652667
ctx=ctx,
653668
extra_environ=extra_environ,
654669
req=req,
655670
version=version,
656671
sdist_root_dir=sdist_root_dir,
672+
build_dir=build_dir,
657673
build_env=build_env,
658674
)
659-
elif (
660-
source_resolver is not None
661-
and source_resolver.build_sdist is packagesettings.BuildSDist.tarball
662-
):
663-
sdist_file = default_build_sdist(
675+
elif strategy is packagesettings.BuildSDist.pep517:
676+
sdist_file = pep517_build_sdist(
664677
ctx=ctx,
665678
extra_environ=extra_environ,
666679
req=req,
667680
version=version,
668681
sdist_root_dir=sdist_root_dir,
669-
build_dir=build_dir,
670682
build_env=build_env,
671-
# Git checkouts keep their `.git`; keep it out of the sdist.
672-
exclude_vcs=True,
673683
)
674-
elif source_resolver is None:
675-
sdist_file = overrides.find_and_invoke(
676-
req.name,
677-
"build_sdist",
678-
default_build_sdist,
684+
elif strategy is packagesettings.BuildSDist.tarball:
685+
sdist_file = default_build_sdist(
679686
ctx=ctx,
680687
extra_environ=extra_environ,
681688
req=req,
@@ -686,8 +693,7 @@ def build_sdist(
686693
)
687694
else:
688695
raise ValueError(
689-
f"{req.name}: unsupported source.build_sdist strategy "
690-
f"{source_resolver.build_sdist!r}"
696+
f"{req.name}: unsupported source.build_sdist strategy {strategy!r}"
691697
)
692698
logger.info(f"built source distribution {sdist_file}")
693699

@@ -713,12 +719,20 @@ def default_build_sdist(
713719
build_env: build_environment.BuildEnvironment,
714720
build_dir: pathlib.Path,
715721
*,
716-
exclude_vcs: bool = False,
722+
exclude_vcs: bool | None = None,
717723
) -> pathlib.Path:
718724
"""Repack *build_dir* as an sdist.
719725
720-
With *exclude_vcs*, VCS metadata such as ``.git`` is left out.
726+
With *exclude_vcs*, VCS metadata such as ``.git`` is left out. By default,
727+
exclude it when ``source:`` is configured, and retain it otherwise.
728+
Explicit booleans override this policy.
729+
730+
.. versionchanged:: 0.104.0
731+
With ``exclude_vcs=None``, exclude VCS metadata when the effective
732+
package or variant has ``source:`` configured; retain it otherwise.
721733
"""
734+
if exclude_vcs is None:
735+
exclude_vcs = ctx.package_build_info(req).source_resolver is not None
722736
# It seems like the "correct" way to do this would be to run the
723737
# PEP 517 API in the source tree we have modified. However, quite
724738
# a few packages assume their source distribution is being built

0 commit comments

Comments
 (0)