UNPKG

1.57 kBJavaScriptView Raw
1module.exports = installHooks;
2
3var fs = require('fs');
4var cwd = process.cwd();
5var resolve = require('path').resolve;
6var projectRoot = cwd.replace(/node_modules(?!.*node_modules(\/|\\|$)).*/, '');
7projectRoot = resolve(projectRoot);
8var hooksDir = resolve(projectRoot, '.git/hooks');
9var template = require('./hook.template');
10
11var hooks = [
12 'post-update',
13 'pre-applypatch',
14 'pre-commit',
15 'pre-push',
16 'pre-rebase',
17 'update'
18];
19
20function installHooks () {
21 if (isGitProject()) {
22 ensureHooksDirExists();
23 hooks.forEach(install);
24 }
25 else { warnAboutGit(); }
26}
27
28function isGitProject () {
29 return fs.existsSync(resolve(projectRoot, '.git'));
30}
31
32function warnAboutGit () { console.warn(
33 'This does not seem to be a git project.\n' +
34 'Although ghooks was installed, the actual git hooks have not.\n' +
35 'Run "git init" and then "npm run ghooks install".\n\n' +
36 'Please ignore this message if you are not using ghooks directly.'
37);}
38
39function install(hook) {
40 var file = hookFile(hook);
41 if (needsBackup(file)) { backup(file); }
42 fs.writeFileSync(file, template.content);
43 fs.chmodSync(file, '755');
44}
45
46function needsBackup (file) {
47 return fs.existsSync(file) && !generatedByGHooks(file);
48}
49
50function generatedByGHooks (file) {
51 return !!fs.readFileSync(file, 'UTF-8').match(template.generatedMessage);
52}
53
54function backup (file) {
55 fs.renameSync(file, file + '.bkp');
56}
57
58function hookFile (name) {
59 return resolve(hooksDir, name);
60}
61
62function ensureHooksDirExists () {
63 if (!fs.existsSync(hooksDir)) { fs.mkdirSync(hooksDir); }
64}