跳转到内容

Hatch 构建与 Wheel 打包

Hatch 构建与 Wheel 打包

学习目标

理解 Nanobot 如何使用 Hatch 构建系统,通过自定义 build hook 将 WebUI 构建产物嵌入 Python wheel。

项目实践

pyproject.toml 配置

[build-system]
requires = ["hatchling", "hatch-vcs"]
build-backend = "hatchling.build"
[project]
name = "nanobot-ai"
dynamic = ["version"]
requires-python = ">=3.11"
[tool.hatch.build]
include = ["nanobot/**", "nanobot/web/dist/**"]
[tool.hatch.build.hooks.custom]
path = "hatch_build.py"

自定义 Build Hook

hatch_build.py 定义了一个自定义构建钩子,在 wheel 构建时将 webui/dist/ 的内容复制到 nanobot/web/dist/

from hatchling.builders.hooks.plugin.interface import BuildHookInterface
class CustomBuildHook(BuildHookInterface):
def initialize(self, version, build_data):
# 检查 webui/dist 是否存在
# 将 webui/dist/* 复制到 nanobot/web/dist/*
pass

这确保了安装 wheel 后 WebUI 文件自动可用,用户无需额外构建前端。

Entry Points

[project.scripts]
nanobot = "nanobot.cli:main"

CLI 入口点指向 nanobot.cli 模块的 main 函数,安装后直接运行 nanobot 命令。

版本管理

使用 hatch-vcs 从 git tag 自动生成版本号:

[tool.hatch.version]
source = "vcs"

发布时通过 git tag 创建版本号(如 v0.2.0)。

设计取舍

为什么用 Hatch 而非 setuptools

原因:Hatch 提供了更现代的构建体验:

  • 原生支持 pyproject.toml 配置
  • 内置 VCS 版本生成
  • 插件化的 build hooks
  • 更好的依赖管理

替代方案:setuptools。Hatch 的优势是配置更简洁、构建钩子更灵活。

参考来源