发布于 2026-01-06 6 阅读
0

Git Hooks 入门:什么是 Git Hooks?示例 Hooks;我们的 Hook;将其设为默认值

Git Hooks 入门

什么是 Git 钩子?

样品钩

我们的钩子

设为默认值

在本教程中,我不会着重讲解它们git hooks是什么,而是会通过一个简单的例子来展示如何使用它们。

什么是 Git 钩子?

来自Git 文档

Hooks are programs you can place in a hooks directory to trigger actions at 
certain points in git’s execution. Hooks that don’t have the executable bit set 
are ignored.

换句话说:

  • 钩子程序是在事件发生时运行的程序。
  • 有一个目录,其中包含所有钩子。

所有活动都列在这里。

在本教程中,我想重点讲解Pre-Commit活动。

样品钩

我们的文件夹中.git/hooks包含了所有默认钩子示例:

$ ls .git/hooks
applypatch-msg.sample      post-update.sample     pre-push.sample     prepare-commit-msg.sample
commit-msg.sample          pre-applypatch.sample  pre-rebase.sample   update.sample
fsmonitor-watchman.sample  pre-commit.sample      pre-receive.sample

我们的钩子

在本入门教程中,我将向您展示如何创建一个简单的脚本git hook来阻止git commit命令跳转到master分支。

现在让我们创建一个pre-commit没有文件扩展名的新文件。

$ touch .git/hooks/pre-commit

由于该git程序运行在 Linux 系统下(对于 Windows 系统则使用 MinGW),因此第一行必须是Shebang。

对于 Linux 系统:

#!/bin/bash

对于 Windows 系统,它应该是你的 Git Bash 安装目录,例如:

#!C:/Program\ Files/Git/usr/bin/sh.exe

接下来我们需要执行git branch命令来打印分支,但我们想知道当前是否在当前分支上,master方法是grep

git branch | grep "* master"

现在我们if用信息进行扭曲:

if git branch | grep "* master" > /dev/null 2>&1
then
    cat <<\EOF
# Message
EOF
fi

要禁用提交,我们需要提供一个不为 0 的退出代码:

exit 1

我们的钩子pre-commit看起来是这样的:

if git branch | grep "* master" > /dev/null 2>&1
then
    cat <<\EOF
Commits are not allowed on branch Master!
EOF
    exit 1
fi

我们来试试:

$ git commit -m "Commit message"
Commits are not allowed on branch Master!

设为默认值

大多数人的问题是什么?就是我们懒惰,我们只想做一次就完事。

我们可以使用这个工具,你可以在这里git template directory找到更多信息。 这个模板目录的作用是,当你使用命令时,它会复制该目录下所有文件名不以点号开头的文件。 现在让我们定义一下

git init

template dir

$ export GIT_TEMPLATE_DIR=PATH
$ cd PATH
$ mkdir hooks

然后,尽情PATH\hooks发挥你的创意,享受创作的乐趣吧 :)

喜欢这篇文章吗?请通过Patreon
支持我 ,并订阅我的YouTube 频道。

文章来源:https://dev.to/eranelbaz/git-hooks-101-62l