1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | 'use strict';
|
10 |
|
11 | var githooks = require('../lib/githooks'),
|
12 | path = require('path');
|
13 |
|
14 | var defaults = {
|
15 |
|
16 | dest: '.git/hooks',
|
17 | template: path.resolve(__dirname, '../templates/node.js.hb'),
|
18 | hashbang: '#!/usr/bin/env node',
|
19 | preventExit: false,
|
20 | startMarker: '// GRUNT-GITHOOKS START',
|
21 | endMarker: '// GRUNT-GITHOOKS END'
|
22 | };
|
23 |
|
24 | var task = module.exports = function(grunt) {
|
25 |
|
26 |
|
27 |
|
28 |
|
29 | grunt.registerMultiTask('githooks', 'Binds grunt tasks to git hooks', function() {
|
30 |
|
31 | var options = this.options(task.defaults);
|
32 |
|
33 | grunt.file.mkdir(options.dest);
|
34 |
|
35 | for (var key in this.data) {
|
36 |
|
37 | if (task.isGitHookDefinition(key)) {
|
38 |
|
39 | task.createHook(key, this.data[key], options, grunt);
|
40 | }
|
41 | }
|
42 | });
|
43 | };
|
44 |
|
45 |
|
46 | task.createHook = function (hookName, taskNames, options, grunt) {
|
47 |
|
48 | options = task.cloneOptions(options);
|
49 |
|
50 | if(typeof taskNames === 'object') {
|
51 | task.mergeHookSpecificOptions(options, taskNames);
|
52 | taskNames = taskNames.taskNames;
|
53 | }
|
54 |
|
55 | grunt.log.subhead('Binding `' + taskNames + '` to `' + hookName + '` Git hook.');
|
56 | task.validateHookName(hookName, grunt);
|
57 |
|
58 | try {
|
59 |
|
60 | var hook = new task.internals.Hook(hookName, taskNames, options);
|
61 | hook.create();
|
62 | grunt.log.ok();
|
63 | } catch (error) {
|
64 | task.logError(error, hookName, grunt);
|
65 | }
|
66 | };
|
67 |
|
68 | task.cloneOptions = function (options) {
|
69 |
|
70 | var result = {};
|
71 |
|
72 | for (var key in options) {
|
73 | result[key] = options[key];
|
74 | }
|
75 |
|
76 | return result;
|
77 | };
|
78 |
|
79 | task.mergeHookSpecificOptions = function (options, hookOptions) {
|
80 |
|
81 | for (var key in hookOptions) {
|
82 | if (key !== 'taskNames') {
|
83 | options[key] = hookOptions[key];
|
84 | }
|
85 | }
|
86 | };
|
87 |
|
88 | task.isGitHookDefinition = function(key) {
|
89 |
|
90 | return key !== 'options';
|
91 | };
|
92 |
|
93 | task.validateHookName = function (hookName, grunt) {
|
94 |
|
95 | if (!task.internals.Hook.isNameOfAGitHook(hookName)) {
|
96 | grunt.log.errorlns('`' + hookName + '` is not the name of a Git hook. Script will be created but won\'t be triggered by Git actions.');
|
97 | }
|
98 | };
|
99 |
|
100 | task.logError = function (error, hookName, grunt) {
|
101 | var gruntError = error;
|
102 | if(error.message && error.message === 'ERR_INVALID_SCRIPT_LANGUAGE'){
|
103 | gruntError = 'A hook already exist for `' + hookName + '` but doesn\'t seem to be written in the same language as the binding script.';
|
104 | }
|
105 | grunt.fail.warn(gruntError);
|
106 | };
|
107 |
|
108 | task.defaults = defaults;
|
109 | task.internals = githooks; |
\ | No newline at end of file |