shfshanyue / Daily-Question

互联网大厂内推及大厂面经整理,并且每天一道面试题推送。每天五分钟,半年大厂中

Home Page:https://q.shanyue.tech

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

【Q716】git hooks 原理是什么

shfshanyue opened this issue · comments

git 允许在各种操作之前添加一些 hook 脚本,如未正常运行则 git 操作不通过。最出名的还是以下两个

  • precommit
  • prepush

hook 脚本置于目录 ~/.git/hooks 中,以可执行文件的形式存在。

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

另外 git hooks 可使用 core.hooksPath 自定义脚本位置。

# 可通过命令行配置 core.hooksPath
$ git config 'core.hooksPath' .husky

# 也可通过写入文件配置 core.hooksPath
$ cat .git/config
[core]
  ignorecase = true
  precomposeunicode = true
  hooksPath = .husky

在前端工程化中,husky 即通过自定义 core.hooksPath 并将 npm scripts 写入其中的方式来实现此功能。

~/.husky 目录下手动创建 hook 脚本

# 手动创建 pre-commit hook
$ vim .husky/pre-commit

pre-commit 中进行代码风格校验

#!/bin/sh

npm run lint
npm run test