0.0.4 • Published 3 years ago
go-daxi v0.0.4
yorkie 代码解析
达成目标- 统一风格+强制更改后再提交
知识点掌握
- eslint - 可以通过预先设置好的规范, 检测出不符合代码风格的代码
- git hooks - git 操作指令前的钩子函数(例如 commit)
使用
- node环境下
- 安装 私有包 - goalKeeper
- 编辑器安装插件 eslint(建议 - 即使不装插件,在git 提交时也会告知错误,只是容易原地爆炸)
已有限制
- eslint校验规则
- commit message 格式
它什么时候控制了我的git
- 安装时,触发了install.js
"install": "node bin/install.js"
install.js
- 先确认之前是否已执行过,若执行过会有环境变量,立即跳出
if (isCI && !process.env.HUSKY_IGNORE_CI && !process.env.YORKIE_IGNORE_CI) { console.log('CI detected, skipping Git hooks installation') process.exit(0) }
- 未执行过,执行installFrom函数,
const installFrom = require('../src/install'); const depDir = path.join(__dirname, '..') installFrom(depDir)
src/install.js
- 找到Hooks文件夹
const findHooksDir = require('./utils/find-hooks-dir')
if (dir) { let gitDir = path.join(dir, '.git') if (!fs.existsSync(gitDir)) { return } }
return path.resolve(dir, gitDir, 'hooks') // 返回了绝对路径
写入脚本
因为.git目录中的.simple结尾的文件是不执行的。
if (hooksDir) { hooks.map(function(hookName) { return { hookName: hookName, action: createHook(depDir, projectDir, hooksDir, hookName, runnerPath) // createHook写入了脚本,除了hooks名和文件名,其他都是相同的。 } }) }
createHook()里调用getHookScript方法并返回脚本内容
const hookScript = getHookScript(hookName, relativePath, runnerPath) if (!fs.existsSync(hooksDir)) fs.mkdirSync(hooksDir)
if (!fs.existsSync(filename)) { write(filename, hookScript) return CREATE }
以上为止,我们的git hooks的脚本已经初始化完成了。也就是每当我们有git指令的时候,都会触发钩子函数
执行钩子
# Run hook node "./node_modules/yorkie/src/runner.js" pre-commit || { echo echo "pre-commit hook failed (add --no-verify to bypass)" exit 1 }
- runner.js --搜寻package.json里的gitHooks指令的对应钩子函数(例如 pre-commit)
const cwd = process.cwd() const pkg = fs.readFileSync(path.join(cwd, 'package.json')) const hooks = JSON.parse(pkg).gitHooks
- 以上为止,之后的控制权交到了我们自己的sh和js中。
- 找到Hooks文件夹
- 安装时,触发了install.js