如何使用 GitHub 操作将 `.git` 目录复制到容器中?

How can I copy `.git` directory to the container with GitHub actions?

我有一个 GitHub 动作 CI 可以在这个应用程序的最新版本中构建我的应用程序 .git 目录是构建它所必需的问题是 GitHub 操作不要在 CI 的 docker 构建步骤中删除它。

这是我的 CI 模板:

on:
  push:
  pull_request:

jobs:
  build:
    runs-on: ubuntu-20.04
    if: github.ref == 'refs/heads/3.3.5-MV'
    steps:
      - uses: actions/checkout@v2
      -
        name: Set up QEMU
        uses: docker/setup-qemu-action@v1
      -
        name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v1
      -
        name: Login to DockerHub
        uses: docker/login-action@v1
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}
      -
        name: Build and push
        id: docker_build
        uses: docker/build-push-action@v2
        with:
          file: ./Dockerfile
          tags: foo/bar:latest
          push: true
      -
        name: Image digest
        run: echo ${{ steps.docker_build.outputs.digest }}

Dockerfile

FROM ubuntu:focal
ENV TZ=Europe/Paris
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
RUN apt update && apt upgrade -y && apt install -y [all my dependencies]

WORKDIR /usr/src/app

COPY . .

WORKDIR /usr/src/app/build

#default path on docker image /usr/local
RUN cmake ../ -DCMAKE_INSTALL_PREFIX=/usr/local/ -DTOOLS=0 

RUN make -j $(nproc) install

WORKDIR /usr/local/bin

问题出在 docker/build-push-action@v2 action,默认情况下会忽略使用 actions/checkout@v2 操作创建的结帐:

By default, this action uses the Git context so you don't need to use the actions/checkout action to check out the repository because this will be done directly by BuildKit.

The git reference will be based on the event that triggered your workflow and will result in the following context: https://github.com/<owner>/<repo>.git#<ref>.

当您将 git 构建上下文传递给 docker build 时,它不会 包括 .git 目录。

如果您通读 docker/build-push-action@v2 操作的文档,您会发现您可以覆盖此行为:

However, you can use the Path context using the context input alongside the actions/checkout action to remove this restriction.

您需要修改您的工作流程,使其包含明确的 context: .,像这样:

        name: Build and push
        id: docker_build
        uses: docker/build-push-action@v2
        with:
          context: .
          file: ./Dockerfile
          tags: foo/bar:latest
          push: true

我整理了一个示例存储库来演示此 here; you can see the verification in this build run