From 5ecc2f0247f9d648dc1795b9633a3c37cc86bb52 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Aleksander=20=C5=81ukasz?= Date: Tue, 15 Jul 2014 12:18:53 +0200 Subject: [PATCH 1/1] git pre-commit hook that lints js code Installation: $ npm install $ grunt githooks --- Gruntfile.js | 19 ++++++++++++++++--- package.json | 3 ++- pre-commit.template.js | 22 ++++++++++++++++++++++ 3 files changed, 40 insertions(+), 4 deletions(-) create mode 100644 pre-commit.template.js diff --git a/Gruntfile.js b/Gruntfile.js index 05c4483..8417c15 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -2,9 +2,9 @@ module.exports = function(grunt) { 'use strict'; - var build_output_dir = grunt.option('output-dir') || 'build', - less_files = {}; + less_files = {}, + jshint_targets = grunt.option('jshint-targets'); less_files[build_output_dir + '/rng.css'] = 'src/editor/styles/main.less'; @@ -39,7 +39,7 @@ module.exports = function(grunt) { }, }, jshint: { - all: ['Gruntfile.js', 'src/**/*.js'], + all: jshint_targets ? jshint_targets.split(',') : ['Gruntfile.js', 'src/**/*.js'], options: { jshintrc: '.jshintrc' } @@ -50,6 +50,18 @@ module.exports = function(grunt) { {src: ['libs/bootstrap/img/**'], dest: build_output_dir+'/'}, ] } + }, + githooks: { + all: { + options: { + dest: grunt.option('git-hooks-dir') || '.git/hooks', + }, + 'pre-commit': { + taskNames: ['lint'], + args: '--no-color', + template: 'pre-commit.template.js' + } + } } }); @@ -57,6 +69,7 @@ module.exports = function(grunt) { grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-copy'); + grunt.loadNpmTasks('grunt-githooks'); grunt.registerTask('build', ['requirejs', 'less:production', 'copy:resources']); grunt.registerTask('lint', ['jshint']); diff --git a/package.json b/package.json index a72c0f6..1517354 100644 --- a/package.json +++ b/package.json @@ -6,6 +6,7 @@ "grunt-contrib-requirejs": "~0.4.1", "grunt-contrib-less": "~0.8.3", "grunt-contrib-jshint": "~0.7.2", - "grunt-contrib-copy": "~0.4.1" + "grunt-contrib-copy": "~0.4.1", + "grunt-githooks": "~0.3.1" } } diff --git a/pre-commit.template.js b/pre-commit.template.js new file mode 100644 index 0000000..2f0363b --- /dev/null +++ b/pre-commit.template.js @@ -0,0 +1,22 @@ +/* jshint node: true */ +'use strict'; + +var exec = require('child_process').exec; +var fs = require('fs'); + +exec('git diff --cached --name-status', function (err, stdout) { + void(err); + var toLint = []; + stdout.split('\n').forEach(function(line) { + var filePath = line.split('\t')[1]; + if(filePath && filePath.substr(-3) === '.js' && fs.existsSync(filePath)) { + toLint.push(filePath); + } + }); + if(toLint.length) { + exec('grunt {{task}} {{args}} --jshint-targets=' + toLint.join(','), function (err, stdout) { + console.log(stdout); + process.exit(err ? -1 : 0); + }); + } +}); -- 2.20.1