Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【20170328】在 pre-commit 的钩子中运行 npm script #85

Closed
zhongxia245 opened this issue Mar 28, 2017 · 0 comments
Closed

【20170328】在 pre-commit 的钩子中运行 npm script #85

zhongxia245 opened this issue Mar 28, 2017 · 0 comments
Labels

Comments

@zhongxia245
Copy link
Owner

时间:2017-03-28 10:28:01

零、总结

在提交代码之前,如何自动执行代码校验,通过才可提交?

  1. 在 .git/hooks目录下写shell脚本,添加校验
  2. 使用 npm 的 pre-commit 包,然后添加校验

一、前言

多人协作开发的时候,每个人都有自己喜欢的IDE,写代码的风格也各不相同,那么如何约束 代码的规范呢?

可以使用 ESLint 来进行对代码的验证,提交之前验证一下,通过就 git commit

如果每一次都手动验证, 那就挺浪费时间的,那么有啥办法可以解决没?

网上查了下,发现有 node的模块 pre-commit 可以解决这个问题, 能够在 git commit 之前去执行一些操作。

二、git 如何 添加 钩子

钩子的理解很简单,可以理解成回调,比如提交代码,钩子就有 提交前提交后 这种钩子

2.1 直接在 git 仓库下添加钩子

  1. 进入 .git/hooks 目录
cd .git/hooks
  1. 查看都可以有哪些钩子
ll

在这里面写 shell 脚本,然后去做一些需要做的操作。

如果不懂 shell 怎么破, 那么就使用 npm 中的 pre-commit , 只需要在 package.json 里面配置下即可。

三、如何使用pre-commit

npm install --save-dev pre-commit

3.1 package.json

安装好 pre-commit 之后,在 package.json 里面添加 一个字段, pre-commit,如下配置。 增加一些 commit 之前需要执行的校验。

{
  "scripts": {
    "lint": "eslint ./ --cache --ignore-pattern .gitignore"
  },
  "pre-commit": [ "lint" ],
  "devDependencies": {
    "eslint": "^2.12.0",
    "pre-commit": "^1.1.3"
  }
} 

验证没有通过的话,也可以强制提交。

# 没必要记,因为提交验证失败的时候,会提示的
git commit -am 'add some code' --no-verify

3.2 pre-commit 信息

可以在 pre-commit 的脚本执行前呢, 添加一些提示信息,告知目前发生了什么事情的描述,避免不知道发生了啥错误。

{
  "scripts": {
    "lint": "eslint ./ --cache --ignore-pattern .gitignore",
    "precommit-msg": "echo 'Pre-commit checks...' && exit 0"
  },
  "pre-commit": [ "precommit-msg", "lint" ],
  "devDependencies": {
    "eslint": "^2.12.0",
    "pre-commit": "^1.1.3"
  }
} 

四、pre-commit 其他应用

  1. 代码验证(ESLint)
  2. 单元测试 (Mocha,ava, jasmine)
  3. 覆盖度测试 (nyc, istanbul)

五、参考文章

  1. 《如何用 pre-commit 来检测代码》

  2. 《[译文] 在 pre-commit 的钩子中运行 npm script》

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant