0
点赞
收藏
分享

微信扫一扫

git使用husky添加git hook提交事件


注意:husky 的版本大于6.x版本,需要采用新的方式。不兼容之前的写法。

安装

npm install

在packgae.json中添加prepare脚本

  • prepare脚本会在npm install(不带参数)之后自动执行。也就是说当我们执行npm install安装完项目依赖后会执行 husky install命令,该命令会创建.husky/目录并指定该目录为git hooks所在的目录

{
"scripts": {
"prepare": "husky install"
}
}

添加git hooks,运行一下命令创建git hooks

npx husky add .husky/pre-commit “npm run package_version_auto_add”

{
"name": "app01",
"version": "1.1.3",
"description": "",
"main": "index.js",
"scripts": {
"prepare": "husky install",
"package_version_auto_add": "node package_version_auto_add.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"husky": "^7.0.4"
}
}

提交前自动升级package.json的版本号

const execSync = require('child_process').execSync
const path = require('path')
const fs = require('fs')

console.log('------------ 开发自动升级package.json版本号 ------------');

const projectPath = path.join(__dirname, './')

const packageJsonStr = fs.readFileSync('./package.json').toString()

try {
const packageJson = JSON.parse(packageJsonStr)
//
const arr = packageJson.version.split('.')
if (arr[2] < 9) {
arr[2] = +arr[2] + 1
} else if (arr[1] < 9) {
arr[1] = +arr[1] + 1
arr[2] = 0
} else {
arr[0] = +arr[0] + 1
arr[1] = 0
arr[2] = 0
}
const newVersion = arr.join('.')
packageJson.version = newVersion

console.log(packageJson);

fs.writeFileSync('./package.json', JSON.stringify(packageJson, null, '\t'))

// add new package.json
execSync(`git add package.json`)
} catch (e) {
console.error('处理package.json失败,请重试', e.message);
process.exit(1)
}

参考

​​https://www.npmjs.com/package/husky​​​​https://typicode.github.io/husky/#/​​​​https://zhuanlan.zhihu.com/p/366786798​​


举报

相关推荐

0 条评论