【问题标题】:How to make a git pre-commit hook that checks the commit message?如何制作一个检查提交消息的 git 预提交钩子?
【发布时间】:2018-01-07 00:50:58
【问题描述】:

我有一个 git commit 钩子脚本,它检查提交消息,如果消息不包含“更新”一词,脚本应该拒绝提交。

#!/bin/bash
read -p "Enter a commit message: " message

if [[ ${message} != *"updated"* ]];then
  echo "Your commit message must contain the word 'updated'"
  else
  git commit -m "$message"
  fi

如果我尝试使用命令将一些文件推送到本地仓库中,如何让这个钩子自动执行

git commit -m "updated:something"

我的想法是让它不像“运行这个脚本来提交”,而是当你打开控制台并尝试提交并输入提交消息时,脚本会自动检查你的提交消息并传递它或拒绝它。

【问题讨论】:

标签: bash git githooks git-commit


【解决方案1】:

commit-msg 为例。

#!/bin/bash

MSG="$1"

if ! grep -qE "updated" "$MSG";then
    cat "$MSG"
    echo "Your commit message must contain the word 'updated'"
    exit 1
fi

chmod 755 commit-msg 并将其复制为.git/hooks/commit-msg

【讨论】:

  • 你能解释一下最后一行吗? chmod 755 commit-msg 并将其复制为 .git/hooks/commit-msg。你的意思是 chmod +x ./commit-msg ? 755是做什么的?
  • 现在我复制你的代码并将其添加到文件中然后我尝试提交我有一个错误:错误:无法运行.git/hooks/pre-commit:没有这样的文件或目录
  • @Andrej 755a+x 的替代品,尽管它们并不完全相同。最后一行chmod ... 不是钩子commit-msg 的一部分。将代码复制到文件中并将文件命名为commit-msg,使其可执行并将其复制到当前存储库的.git/hooks/。当git commit 完成时,钩子commit-msg 被调用并检查提交消息。如果不包含“updated”,则提交失败。
  • 我觉得这个应该用chmod +x .git/hooks/commit-msg
  • 或者,您可以使用[[ $(cat $1) =~ updated ]] || exit 1
猜你喜欢
  • 2013-12-15
  • 2018-07-22
  • 1970-01-01
  • 2021-03-01
  • 2013-10-16
  • 1970-01-01
  • 2020-03-09
  • 2019-07-12
相关资源
最近更新 更多