UNPKG

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