如何自动清除最新的 git-commit 消息中的特殊关键字,例如 p.e. “[build]”旨在触发 CI 管道?

问题描述 投票:0回答:1

在某些 CI 设置中,可能会使用特殊关键字来触发管道中的特定行为。例如,当且仅当分支推送中的最新 git 提交消息包含诸如 [build] 之类的关键字时,CI 管道才可能构建功能分支。

即使这有效,提交消息也会被污染。所以我想知道是否可以制作某种本地 git-commit / git-push 挂钩来自动清理最新的 git-commit 消息(如果它包含 [build] 关键字)。

bash git continuous-integration githooks
1个回答
0
投票

这是我想出的解决方案。根据我的测试,似乎工作正常。将此脚本放置为“.git/hooks/pre-push”,并确保也“chmod +x .git/hooks/pre-push”。

它检测最新的 git-commit 消息是否包含关键字 [build],如果包含,则推送它,等待几秒钟(*),它修改最新的 git-commit 消息以清理它,然后小心地强制排斥分支。即使多个开发人员正在处理功能分支,功能分支也能与此技术很好地配合 - 在 3 秒的敏感时间内,其他人不太可能调整分支。

  • 在 Azure 管道中,构建会立即触发,因此即使 2 秒也足够了 - 但 YMMV 所以请随意更改您想要等待的秒数,以确保构建在管道中触发。

请注意,技术旨在应用于功能分支 - 而不是基石分支,尤其是“master”、“main”甚至“develop”。

#!/bin/bash

declare current_branch=$(git symbolic-ref HEAD)
if [[ "$current_branch" == "refs/head/main" || "$current_branch" == "refs/head/master" || "$current_branch" == "refs/head/develop" ]]; then
    exit 0 # better not fiddle with the commit history of these branches
fi

declare latest_commit_message=$(git log --format=%B -n 1 HEAD)
if [[ "${latest_commit_message}" == *"[build]"* ]]; then
    # commit message contains [build] keyword - will push it and clean it up a few seconds later via ammend + force repush
    
    cat <<EOL >./ammend_commit_a_few_seconds_later.sh
sleep 3

declare commit_message_to_clean_up=\$(git log --format=%B -n 1 HEAD) # get the latest commit message

git commit --amend --message "\$(echo "\${commit_message_to_clean_up}" | sed -E 's/\s*\\[build\\]\s*/ /')" # amend the latest commit message to replace [build] with a single whitespace

git push origin "\$(git rev-parse --abbrev-ref HEAD)" --force-with-lease # force-push the branch

echo "Branch pushed and commit message amended."

rm ./ammend_commit_a_few_seconds_later.sh
EOL

    chmod +x ./ammend_commit_a_few_seconds_later.sh

    ./ammend_commit_a_few_seconds_later.sh &
fi

exit 0
© www.soinside.com 2019 - 2024. All rights reserved.