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