-
-
Notifications
You must be signed in to change notification settings - Fork 999
/
hooks.ts
102 lines (83 loc) 路 2.21 KB
/
hooks.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import fs = require('fs')
import path = require('path')
import { isGhooks, isPreCommit, isHusky, isYorkie } from './is'
import { getBanner } from './getBanner'
export const huskyIdentifier = '# husky'
export function getHookScript(): string {
return `#!/bin/sh
${huskyIdentifier}
${getBanner()}
. "$(dirname "$0")/husky.sh"
`
}
const hookList = [
'applypatch-msg',
'pre-applypatch',
'post-applypatch',
'pre-commit',
'pre-merge-commit',
'prepare-commit-msg',
'commit-msg',
'post-commit',
'pre-rebase',
'post-checkout',
'post-merge',
'pre-push',
'post-update',
'push-to-checkout',
'pre-auto-gc',
'post-rewrite',
'sendemail-validate',
]
function getHooks(gitHooksDir: string): string[] {
return hookList.map((hookName: string): string =>
path.join(gitHooksDir, hookName)
)
}
function writeHook(filename: string, script: string): void {
fs.writeFileSync(filename, script, 'utf-8')
fs.chmodSync(filename, 0o0755)
}
function createHook(filename: string): void {
const name = path.basename(filename)
const hookScript = getHookScript()
// Check if hook exist
if (fs.existsSync(filename)) {
const hook = fs.readFileSync(filename, 'utf-8')
// Migrate
if (isGhooks(hook)) {
console.log(`migrating existing ghooks script: ${name}`)
return writeHook(filename, hookScript)
}
// Migrate
if (isPreCommit(hook)) {
console.log(`migrating existing pre-commit script: ${name}`)
return writeHook(filename, hookScript)
}
// Update
if (isHusky(hook) || isYorkie(hook)) {
return writeHook(filename, hookScript)
}
// Skip
console.log(`skipping existing user hook: ${name}`)
return
}
// Create hook if it doesn't exist
writeHook(filename, hookScript)
}
export function createHooks(gitHooksDir: string): void {
getHooks(gitHooksDir).forEach(createHook)
}
function canRemove(filename: string): boolean {
if (fs.existsSync(filename)) {
const data = fs.readFileSync(filename, 'utf-8')
return isHusky(data)
}
return false
}
function removeHook(filename: string): void {
fs.unlinkSync(filename)
}
export function removeHooks(gitHooksDir: string): void {
getHooks(gitHooksDir).filter(canRemove).forEach(removeHook)
}