如何将预提交预安装到钩子中 docker

How to pre-install pre commit into hooks into docker

据我了解文档,每当我将这些行添加到配置时:

repos:
-   repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v2.1.0
    hooks:
    -   id: trailing-whitespace

它预先提交从这个 repo 下载钩子代码并执行它。是否有可能以某种方式将所有挂钩预安装到 Docker 图像中。所以当我调用 pre-commit run 时没有使用网络?

我发现文档的 this 部分描述了预提交如何缓存所有存储库。它们存储在 ~/.cache/pre-commit 中,这可以通过更新 PRE_COMMIT_HOME 环境变量来配置。

但是,缓存仅在我执行 pre-commit run 时有效。但是我想预先安装所有 w/o 运行 的支票。可能吗?

您正在寻找 pre-commit install-hooks 命令

至少你需要这样的东西来缓存预提交环境:

COPY .pre-commit-config.yaml .
RUN git init . && pre-commit install-hooks

免责声明:我创建了预提交

@anthony-sottile 提供的片段很有魅力。它有助于利用 docker 缓存。这是 django world 的一个工作变体。

ARG PYTHON_VERSION=3.9-buster

# define an alias for the specfic python version used in this file.
FROM python:${PYTHON_VERSION} as python

# Python build stage
FROM python as python-build-stage

ARG BUILD_ENVIRONMENT=test

# Install apt packages
RUN apt-get update && apt-get install --no-install-recommends -y \
  # dependencies for building Python packages
  build-essential \
  # psycopg2 dependencies
  libpq-dev

# Requirements are installed here to ensure they will be cached.
COPY ./requirements .

# Create Python Dependency and Sub-Dependency Wheels.
RUN pip wheel --wheel-dir /usr/src/app/wheels  \
  -r ${BUILD_ENVIRONMENT}.txt


# Python 'run' stage
FROM python as python-run-stage

ARG BUILD_ENVIRONMENT=test
ARG APP_HOME=/app

ENV PYTHONUNBUFFERED 1
ENV PYTHONDONTWRITEBYTECODE 1
ENV BUILD_ENV ${BUILD_ENVIRONMENT}

WORKDIR ${APP_HOME}

# Install required system dependencies
RUN apt-get update && apt-get install --no-install-recommends -y \
  # psycopg2 dependencies
  libpq-dev \
  # Translations dependencies
  gettext \
  # cleaning up unused files
  && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \
  && rm -rf /var/lib/apt/lists/*

# All absolute dir copies ignore workdir instruction. All relative dir copies are wrt to the workdir instruction
# copy python dependency wheels from python-build-stage
COPY --from=python-build-stage /usr/src/app/wheels  /wheels/

# use wheels to install python dependencies
RUN pip install --no-cache-dir --no-index --find-links=/wheels/ /wheels/* \
    && rm -rf /wheels/

COPY ./compose/test/django/entrypoint /entrypoint
RUN chmod +x /entrypoint

COPY .pre-commit-config.yaml .
RUN git init . && pre-commit install-hooks

# copy application code to WORKDIR
COPY . ${APP_HOME}

ENTRYPOINT ["/entrypoint"]

然后您可以以类似的方式启动预提交检查:

docker-compose -p project_name -f test.yml run --rm django pre-commit run --all-files