1 | module.exports = installHooks;
|
2 |
|
3 | var fs = require('fs');
|
4 | var cwd = process.cwd();
|
5 | var resolve = require('path').resolve;
|
6 | var projectRoot = resolve(cwd.replace(/node_modules\/.*/, ''));
|
7 | var hooksDir = resolve(projectRoot, '.git/hooks');
|
8 | var template = require('./hook.template');
|
9 |
|
10 | var hooks = [
|
11 | 'post-update',
|
12 | 'pre-applypatch',
|
13 | 'pre-commit',
|
14 | 'pre-push',
|
15 | 'pre-rebase',
|
16 | 'update'
|
17 | ];
|
18 |
|
19 | function installHooks () {
|
20 | if (isGitProject()) {
|
21 | ensureHooksDirExists();
|
22 | hooks.forEach(install);
|
23 | }
|
24 | else { warnAboutGit(); }
|
25 | }
|
26 |
|
27 | function isGitProject () {
|
28 | return fs.existsSync(resolve(projectRoot, '.git'));
|
29 | }
|
30 |
|
31 | function 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 |
|
37 | function 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 |
|
44 | function needsBackup (file) {
|
45 | return fs.existsSync(file) && !generatedByGHooks(file);
|
46 | }
|
47 |
|
48 | function generatedByGHooks (file) {
|
49 | return !!fs.readFileSync(file, 'UTF-8').match(template.generatedMessage);
|
50 | }
|
51 |
|
52 | function backup (file) {
|
53 | fs.renameSync(file, file + '.bkp');
|
54 | }
|
55 |
|
56 | function hookFile (name) {
|
57 | return resolve(hooksDir, name);
|
58 | }
|
59 |
|
60 | function ensureHooksDirExists () {
|
61 | if (!fs.existsSync(hooksDir)) { fs.mkdirSync(hooksDir); }
|
62 | }
|