在 gitlab CI 中为默认分支设置 git 配置以防止提示消息

set git configuration in gitlab CI for default branch to prevent hint message

在我的 gitlab CI 中,我总是收到此提示消息。是的,我看到我必须设置 git config --global init.defaultBranch main,但是我在 CI gitlab 配置的阶段/作业中添加的所有内容都在 获取之后执行。

test:
  stage: test
  image:
    name: registry.domain.com/project/ci:1.0.0
  before_script:
    - git config --global init.defaultBranch main
  script:
    - echo "something"

正如我所说,这是行不通的。在抓取的时候,before_script没有执行。

Using Kubernetes namespace: gitlab
Using Kubernetes executor with image 
registry.domain.com/project/ci:1.0.0 ...
Using attach strategy to execute scripts...
...
Getting source from Git repository
00:01
Fetching changes with git depth set to 50...
hint: Using 'master' as the name for the initial branch. This default branch name
hint: is subject to change. To configure the initial branch name to use in all
hint: of your new repositories, which will suppress this warning, call:
hint: 
hint:   git config --global init.defaultBranch <name>
hint: 
hint: Names commonly chosen instead of 'master' are 'main', 'trunk' and
hint: 'development'. The just-created branch can be renamed via this command:
hint: 
hint:   git branch -m <name>
Initialized empty Git repository in /builds/Cf_z92LS/0/project/repo/.git/
Created fresh repository.

更新

用于 CI 管道的自定义 docker 图像是这样创建的:

FROM alpine:3.14.2

RUN apk --update add bash curl git
RUN git config --global init.defaultBranch main

但我仍然收到这些消息。

运行 CI 中的 git config --list 告诉我,配置值设置正确:

init.defaultbranch=main
fetch.recursesubmodules=false
core.repositoryformatversion=0
core.filemode=true
core.bare=false
core.logallrefupdates=true

据我所知,禁用此消息的唯一方法是在用户 运行 和 gitlab-runner 的 .gitconfig 中全局设置配置。

如果您使用 shell-runner,这可以在底层 VM 上完成,或者在使用 docker-runner[=14= 时,可以在使用的 docker-image 中完成]

更新

虽然上面写着 global,但 git 设置是基于用户的。您必须将其设置为执行 gitlab-runner 的同一用户。 根据配置,这可能是 gitlab-runner 或 shell-runners 上的自定义用户或 root 使用 docker-executor 时。

运行 脚本的顺序和上下文可能会造成混淆。根据他们所做的,不同阶段的上下文可能不同,因为在执行期间可以创建和删除许多中间容器。像这样尝试一下:

test:
  stage: test
  image:
    name: registry.domain.com/project/ci:1.0.0
  before_script:
  script:
    - git config --global init.defaultBranch main
    - echo "something"