Skip to content

Instantly share code, notes, and snippets.

@jansanchez
Last active August 29, 2015 14:13
Show Gist options
  • Save jansanchez/d216e8c0de659a63b876 to your computer and use it in GitHub Desktop.
Save jansanchez/d216e8c0de659a63b876 to your computer and use it in GitHub Desktop.
#!/usr/bin/env node
/*
* Hook en Node.js para detectar cambios en archivos estaticos, obtener el id corto del ultimo commit
* y ejecutar una tarea en grunt.
*
* @author Jan Sanchez
*/
var fs = require('fs'),
exec = require('child_process').exec,
extensions = ['css', 'js', 'png', 'jpg', 'gif'],
hasStatic = false,
commitFile = "src/last_commit";
console.log(' + Ejecutando Hook...');
function execute(command, callback) {
exec(command, function(error, stdout, stderr) {
callback(stdout);
});
};
module.exports.getLastCommit = function(callback) {
var commit = {};
execute("git rev-list --max-count=1 HEAD", function(last) {
commit.last = last.replace("\n", "");
execute("git rev-list --max-count=1 HEAD~1", function(penultimate) {
commit.penultimate = penultimate.replace("\n", "");
var diff = "git diff " + commit.last + " " + commit.penultimate + " --name-only";
execute(diff, function(files) {
files = files.replace(/\n/gi, ',');
files = files.substr(0, files.length - 1);
commit.files = files.split(',');
callback(commit);
});
});
});
};
module.exports.getLastCommit(function(obj) {
//console.log(obj.files);
for (var i = 0; i < obj.files.length; i++) {
if (/\.js$|\.css$|\.jpg$|\.png$|\.gif$/.test(obj.files[i])) {
hasStatic = true;
break;
}
};
if (hasStatic) {
console.log(" - extensiones estaticas detectadas.");
exec('grunt produccion', {
cwd: '/home/jan/htdocs/flux/frontend/grunt'
}, function(err, stdout, stderr) {
console.log(stdout);
var exitCode = 0;
if (err) {
console.log(stderr);
exitCode = -1;
} else {
console.log(' - fin de minificacion de estaticos.');
execute("git log -1 --format=%h", function(idCommit) {
idCommit = idCommit.replace(/\n/gi, '');
//console.log(idCommit);
fs.writeFile(commitFile, idCommit, function(err) {
if (err) {
console.log(err);
} else {
var msg = 'update "' + commitFile + '" to ' + idCommit;
execute("git add .; git commit -m \"" + msg + "\" ", function() {
console.log(" - " + msg);
});
}
});
});
}
//process.exit(exitCode);
});
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment