Skip to content

Build hook plugins


ビルドフックは、ビルドプロセスのさまざまな段階で実行されるコードを提供します。[build hook configurationのドキュメントを参照してください。

Known third-party

  • hatch-argparse-manpage - argparseベースのCLIのマニュアルページを生成します。
  • hatch-autorun - 最初のインポートの前に自動的に実行されるインストールにコードを注入するために使用されます。
  • hatch-build-scripts - アーティファクトを作成する任意のシェルコマンドを実行します。
  • hatch-cython - Cython拡張を構築します。
  • hatch-gettext - GNUgettextツールを使用して多言語メッセージをコンパイルします。
  • hatch-jupyter-builder - Project Jupyterエコシステムのパッケージに使用します。
  • hatch-mypyc - Mypycでコードをコンパイルします。
  • hatch-odoo - Odooアドオンを適切な名前空間にパッケージ化します。
  • scikit-build-core - CMakeを使用した拡張モジュールを構築します。

Overview

ビルドフックは、ビルドターゲットの選択されたversionごとに実行されます。

initializationステージは各ビルドの直前に発生し、finalizationステージはその直後に発生します。各ステージでは、build dataを表示または変更できます。

Build data

ビルド・データは、その内容がビルドの動作に影響を与える単純なマッピングです。存在し、認識されるフィールドは、各ビルド・ターゲットによって異なります。

次のフィールドは常に存在し、ビルドシステム自体によって認識されます。:

Field Type Description
artifacts list[str] これは追加のartifact patternsのリストであり、通常は追加されるだけです。
force_include dict[str, str] これは、余分なforced inclusion pathsのマッピングであり、競合が発生した場合にはこのマッピングが優先されます。
build_hooks tuple[str, ...] これは、構成されたビルドフックの名前の不変のシーケンスであり、実行される順序と一致します。

Attention

ユーザー向けのTOMLオプションにはハイフンが付けられているが、ビルドデータフィールドにはアンダースコアを付けて、プラグインが有効なPython識別子として使用できるようにする必要があります。

Notes

場合によっては、artifactsではなくforce_includeを使用する必要があります。たとえば、lib.sosite-packagesのルートに直接インストールし、プロジェクトがpackagesrc/fooを定義するとします。src/lib.soを作成した場合、ディレクトリトラバーサルはsrcではなくsrc/fooで始まるため、一致することはありません。その場合は、次のいずれかを実行する必要があります。:

build_data['force_include']['src/lib.so'] = 'src/lib.so'

または

build_data['force_include']['/absolute/path/to/src/lib.so'] = 'src/lib.so'

BuildHookInterface

Example usage:

from hatchling.builders.hooks.plugin.interface import BuildHookInterface


class SpecialBuildHook(BuildHookInterface):
    PLUGIN_NAME = 'special'
    ...
from hatchling.plugin import hookimpl

from .plugin import SpecialBuildHook


@hookimpl
def hatch_register_build_hook():
    return SpecialBuildHook
Source code in backend/src/hatchling/builders/hooks/plugin/interface.py
class BuildHookInterface(Generic[BuilderConfigBound]):  # no cov
    """
    Example usage:

    ```python tab="plugin.py"
    from hatchling.builders.hooks.plugin.interface import BuildHookInterface


    class SpecialBuildHook(BuildHookInterface):
        PLUGIN_NAME = 'special'
        ...
    ```

    ```python tab="hooks.py"
    from hatchling.plugin import hookimpl

    from .plugin import SpecialBuildHook


    @hookimpl
    def hatch_register_build_hook():
        return SpecialBuildHook
    ```
    """

    PLUGIN_NAME = ''
    """The name used for selection."""

    def __init__(
        self,
        root: str,
        config: dict[str, Any],
        build_config: BuilderConfigBound,
        metadata: ProjectMetadata,
        directory: str,
        target_name: str,
        app: Application | None = None,
    ) -> None:
        self.__root = root
        self.__config = config
        self.__build_config = build_config
        self.__metadata = metadata
        self.__directory = directory
        self.__target_name = target_name
        self.__app = app

    @property
    def app(self) -> Application:
        """
        An instance of [Application](../utilities.md#hatchling.bridge.app.Application).
        """
        if self.__app is None:
            from hatchling.bridge.app import Application

            self.__app = cast(Application, Application().get_safe_application())

        return self.__app

    @property
    def root(self) -> str:
        """
        The root of the project tree.
        """
        return self.__root

    @property
    def config(self) -> dict[str, Any]:
        """
        The cumulative hook configuration.

        ```toml config-example
        [tool.hatch.build.hooks.<PLUGIN_NAME>]
        [tool.hatch.build.targets.<TARGET_NAME>.hooks.<PLUGIN_NAME>]
        ```
        """
        return self.__config

    @property
    def metadata(self) -> ProjectMetadata:
        # Undocumented for now
        return self.__metadata

    @property
    def build_config(self) -> BuilderConfigBound:
        """
        An instance of [BuilderConfig](../utilities.md#hatchling.builders.config.BuilderConfig).
        """
        return self.__build_config

    @property
    def directory(self) -> str:
        """
        The build directory.
        """
        return self.__directory

    @property
    def target_name(self) -> str:
        """
        The plugin name of the build target.
        """
        return self.__target_name

    def dependencies(self) -> list[str]:  # noqa: PLR6301
        """
        A list of extra [dependencies](../../config/dependency.md) that must be installed
        prior to builds.

        !!! warning
            - For this to have any effect the hook dependency itself cannot be dynamic and
                must always be defined in `build-system.requires`.
            - As the hook must be imported to call this method, imports that require these
                dependencies must be evaluated lazily.
        """
        return []

    def clean(self, versions: list[str]) -> None:
        """
        This occurs before the build process if the `-c`/`--clean` flag was passed to
        the [`build`](../../cli/reference.md#hatch-build) command, or when invoking
        the [`clean`](../../cli/reference.md#hatch-clean) command.
        """

    def initialize(self, version: str, build_data: dict[str, Any]) -> None:
        """
        This occurs immediately before each build.

        Any modifications to the build data will be seen by the build target.
        """

    def finalize(self, version: str, build_data: dict[str, Any], artifact_path: str) -> None:
        """
        This occurs immediately after each build and will not run if the `--hooks-only` flag
        was passed to the [`build`](../../cli/reference.md#hatch-build) command.

        The build data will reflect any modifications done by the target during the build.
        """

PLUGIN_NAME = '' class-attribute instance-attribute

The name used for selection.

app: Application property

An instance of Application.

root: str property

The root of the project tree.

config: dict[str, Any] property

The cumulative hook configuration.

[tool.hatch.build.hooks.<PLUGIN_NAME>]
[tool.hatch.build.targets.<TARGET_NAME>.hooks.<PLUGIN_NAME>]
[build.hooks.<PLUGIN_NAME>]
[build.targets.<TARGET_NAME>.hooks.<PLUGIN_NAME>]

build_config: BuilderConfigBound property

An instance of BuilderConfig.

target_name: str property

The plugin name of the build target.

directory: str property

The build directory.

dependencies() -> list[str]

A list of extra dependencies that must be installed prior to builds.

Warning

  • For this to have any effect the hook dependency itself cannot be dynamic and must always be defined in build-system.requires.
  • As the hook must be imported to call this method, imports that require these dependencies must be evaluated lazily.
Source code in backend/src/hatchling/builders/hooks/plugin/interface.py
def dependencies(self) -> list[str]:  # noqa: PLR6301
    """
    A list of extra [dependencies](../../config/dependency.md) that must be installed
    prior to builds.

    !!! warning
        - For this to have any effect the hook dependency itself cannot be dynamic and
            must always be defined in `build-system.requires`.
        - As the hook must be imported to call this method, imports that require these
            dependencies must be evaluated lazily.
    """
    return []

clean(versions: list[str]) -> None

This occurs before the build process if the -c/--clean flag was passed to the build command, or when invoking the clean command.

Source code in backend/src/hatchling/builders/hooks/plugin/interface.py
def clean(self, versions: list[str]) -> None:
    """
    This occurs before the build process if the `-c`/`--clean` flag was passed to
    the [`build`](../../cli/reference.md#hatch-build) command, or when invoking
    the [`clean`](../../cli/reference.md#hatch-clean) command.
    """

initialize(version: str, build_data: dict[str, Any]) -> None

This occurs immediately before each build.

Any modifications to the build data will be seen by the build target.

Source code in backend/src/hatchling/builders/hooks/plugin/interface.py
def initialize(self, version: str, build_data: dict[str, Any]) -> None:
    """
    This occurs immediately before each build.

    Any modifications to the build data will be seen by the build target.
    """

finalize(version: str, build_data: dict[str, Any], artifact_path: str) -> None

This occurs immediately after each build and will not run if the --hooks-only flag was passed to the build command.

The build data will reflect any modifications done by the target during the build.

Source code in backend/src/hatchling/builders/hooks/plugin/interface.py
def finalize(self, version: str, build_data: dict[str, Any], artifact_path: str) -> None:
    """
    This occurs immediately after each build and will not run if the `--hooks-only` flag
    was passed to the [`build`](../../cli/reference.md#hatch-build) command.

    The build data will reflect any modifications done by the target during the build.
    """