git hooks 简介与使用

2021-04-25  本文已影响0人  Separes

1 简介

git hooks,即git 钩子,定义为能在特定的重要动作发生时触发自定义脚本。
git 的hook分为两种,客户端hooks和服务端hooks。
客户端钩子由诸如提交和合并这样的操作所调用,而服务器端钩子作用于诸如接收被推送的提交这样的联网操作。

官方文档:

https://git-scm.com/docs/githooks

2 说明

git hooks在git项目中的位置在 /.git/hooks 目录下,初始化时由以下sample组成:

applypatch-msg.sample*
commit-msg.sample*
post-update.sample*
pre-applypatch.sample*
pre-commit.sample*
prepare-commit-msg.sample*
pre-push.sample*
pre-rebase.sample*
pre-receive.sample*
update.sample*

完整说明详见官方文档:

https://git-scm.com/docs/githooks

3 demo(git commit代码检查)

This hook is invoked by git-commit[1], and can be bypassed with the --no-verify option. It takes no parameters, and is invoked before obtaining the proposed commit log message and making a commit. Exiting with a non-zero status from this script causes the git commit command to abort before creating a commit.
The default pre-commit hook, when enabled, catches introduction of lines with trailing whitespaces and aborts the commit when such a line is found.
All the git commit hooks are invoked with the environment variable GIT_EDITOR=: if the command will not bring up an editor to modify the commit message.
The default pre-commit hook, when enabled—and with the hooks.allownonascii config option unset or set to false—prevents the use of non-ASCII filenames.

package main

import "fmt"

var str =  "hello world!!"

func main()  {
    fmt.Println(str)
}
cp .git/hooks/pre-commit.sample .git/hooks/pre-commit && vi .git/hooks/pre-commit
#!/bin/bash

echo  "code check running..."

for FILE in `git diff --name-only --cached`; do

    grep 'hello' $FILE 2>&1 >/dev/null
    if [ $? -eq 0 ]; then
        echo $FILE '包含hello,退出commit'
        exit 1
    fi
    
done

git commit 报错

4 小结

上一篇下一篇

猜你喜欢

热点阅读