2.7.6 与 pre-commit 配合使用

原文链接: https://docs.astral.sh/uv/guides/integration/pre-commit/

2.7.6 与 pre-commit 配合使用

官方 pre-commit 钩子位于 astral-sh/uv-pre-commit。

要把 uv 与 pre-commit 配合使用,请把下面示例之一加入 .pre-commit-config.yaml 的 repos 列表。

要确保即使 pyproject.toml 被修改后 uv.lock 文件仍然是最新的:

1
2
3
4
5
6
7
# .pre-commit-config.yaml
repos:
  - repo: https://github.com/astral-sh/uv-pre-commit
    # uv 版本。
    rev: 0.12.19
    hooks:
      - id: uv-lock

要让 requirements.txt 文件与 uv.lock 文件保持同步:

1
2
3
4
5
6
7
# .pre-commit-config.yaml
repos:
  - repo: https://github.com/astral-sh/uv-pre-commit
    # uv 版本。
    rev: 0.12.19
    hooks:
      - id: uv-export

要编译 requirements 文件:

1
2
3
4
5
6
7
8
9
# .pre-commit-config.yaml
repos:
  - repo: https://github.com/astral-sh/uv-pre-commit
    # uv 版本。
    rev: 0.12.19
    hooks:
      # 编译 requirements
      - id: pip-compile
        args: [requirements.in, -o, requirements.txt]

要编译其他 requirements 文件,请修改 args 和 files:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# .pre-commit-config.yaml
repos:
  - repo: https://github.com/astral-sh/uv-pre-commit
    # uv 版本。
    rev: 0.12.19
    hooks:
      # 编译 requirements
      - id: pip-compile
        args: [requirements-dev.in, -o, requirements-dev.txt]
        files: ^requirements-dev\.(in|txt)$

要同时对多个文件运行该钩子,请添加更多条目:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# .pre-commit-config.yaml
repos:
  - repo: https://github.com/astral-sh/uv-pre-commit
    # uv 版本。
    rev: 0.12.19
    hooks:
      # 编译 requirements
      - id: pip-compile
        name: pip-compile requirements.in
        args: [requirements.in, -o, requirements.txt]
      - id: pip-compile
        name: pip-compile requirements-dev.in
        args: [requirements-dev.in, -o, requirements-dev.txt]
        files: ^requirements-dev\.(in|txt)$
最后修改 September 25, 2026: 更新 (221c74c33)