UNPKG

1.46 kBJavaScriptView Raw
1'use strict'
2
3const debug = require('debug')('elint:utils:is-git-hooks')
4const co = require('co')
5const find = require('find-process')
6
7const huskyCmdReg = /node_modules(\/|\\)husky/
8
9/**
10 * 获取 ppid
11 * node v7.x 居然不支持 process.ppid(v6.x 支持)
12 *
13 * @returns {Promise<number>} ppid
14 */
15/* istanbul ignore next */
16function getPPID () {
17 const ppid = process.ppid
18
19 if (typeof ppid === 'number') {
20 return Promise.resolve(ppid)
21 }
22
23 return find('pid', process.pid)
24 .then(list => {
25 return list && list[0] && list[0].ppid
26 })
27}
28
29/**
30 * 根据 pid 判断是否由 husky 调用
31 *
32 * @param {string} ppid parent pid
33 * @returns {Promise<boolean>} 是否是 husky 调用
34 */
35function isRunByHusky (ppid) {
36 return find('pid', ppid).then(list => {
37 debug('process list: %o', list)
38
39 const cmd = list[0] && list[0].cmd
40 const pppid = list[0] && list[0].ppid
41
42 if (!cmd) {
43 return false
44 }
45
46 if (huskyCmdReg.test(cmd)) {
47 return true
48 }
49
50 // 一直迭代到最顶
51 return isRunByHusky(pppid)
52 })
53}
54
55/**
56 * 判断执行环境是否是 git hooks
57 *
58 * @returns {Promise<boolean>} 是否是 git hooks 环境
59 */
60function isGitHooks () {
61 return co(function * () {
62 const ppid = yield getPPID()
63
64 debug(`ppid: ${ppid}`)
65
66 return isRunByHusky(ppid)
67 }).catch(/* istanbul ignore next */ function (err) {
68 debug('error: %o', err)
69 return false
70 })
71}
72
73module.exports = isGitHooks