hatch icon indicating copy to clipboard operation
hatch copied to clipboard

CustomBuildHook executes twice

Open Chasarr opened this issue 5 months ago • 6 comments

Hi!

Running hatch build essentially seems to run two commands behind the scenes - hatch build -t sdist and hatch build -t wheel. Let's say my build system requires building binaries before building and uploading the package. The current system would mean that uv build would perform this time-consuming compilation twice.

Is there any way of making hatch only run this once?

Chasarr avatar Jun 30 '25 14:06 Chasarr

Show config

ofek avatar Jun 30 '25 14:06 ofek

Just a bare minimum example capable of producing a .whl and tar.gz with hatch build

# pyproject.toml
[project]
name = "hatch-test"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
authors = [
    { name = "John Doe", email = "[email protected]" }
]
requires-python = ">=3.12"
dependencies = []

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[tool.hatch.build.hooks.custom]
# hatch_build.py
from hatchling.builders.hooks.plugin.interface import BuildHookInterface
from pathlib import Path
from typing import Any, override


class CustomBuildHook(BuildHookInterface):
    @override
    def initialize(self, version: str, build_data: dict[str, Any]) -> None:
        print(f"Executing from {Path.cwd()}")
# src/hatch_test/__init__.py
print("Hello world!")

Chasarr avatar Jun 30 '25 15:06 Chasarr

Image

Which causes "Executing from blabla" to appear twice, since it's getting re-executed for both sdist generation and .whl generation

Chasarr avatar Jun 30 '25 15:06 Chasarr

[tool.hatch.build.targets.sdist.hooks.custom]

ofek avatar Jun 30 '25 16:06 ofek

Yes, but then it does not work for users running hatch build -t wheel. Would you say that hatch -t wheel is not intended for usage without running hatch build -t sdist beforehand?

Chasarr avatar Jun 30 '25 17:06 Chasarr

You could have it conditional based on an environment variable: https://hatch.pypa.io/latest/config/build/#conditional-execution

ofek avatar Jul 02 '25 21:07 ofek