Implement watch events

This commit is contained in:
Kyle Robinson Young 2013-02-21 21:59:40 -08:00
parent ad67808cc9
commit 8006886e52
4 changed files with 78 additions and 2 deletions

View File

@ -78,8 +78,17 @@ module.exports = function(grunt) {
// On changed/added/deleted
this.on('all', function(status, filepath) {
filepath = path.relative(process.cwd(), filepath);
taskrun.changedFiles[filepath] = status;
taskrun[options.nospawn ? 'nospawn' : 'spawn'](i, target.tasks, options, done);
// Emit watch events if anyone is listening
if (grunt.event.listeners('watch').length > 0) {
grunt.event.emit('watch', status, filepath);
}
// Run tasks if any have been specified
if (target.tasks) {
taskrun.changedFiles[filepath] = status;
taskrun[options.nospawn ? 'nospawn' : 'spawn'](i, target.tasks, options, done);
}
});
// On watcher error

18
test/fixtures/events/Gruntfile.js vendored Normal file
View File

@ -0,0 +1,18 @@
module.exports = function(grunt) {
'use strict';
grunt.initConfig({
watch: {
files: ['lib/*.js']
}
});
// Load this watch task
grunt.loadTasks('../../../tasks');
// trigger on watch events
grunt.event.on('watch', function(action, filepath) {
grunt.log.writeln(filepath + ' was indeed ' + action);
if (action === 'deleted') { grunt.util.exit(0); }
});
};

1
test/fixtures/events/lib/one.js vendored Normal file
View File

@ -0,0 +1 @@
var one = true;

48
test/tasks/events_test.js Normal file
View File

@ -0,0 +1,48 @@
'use strict';
var grunt = require('grunt');
var path = require('path');
var fs = require('fs');
var helper = require('./helper');
var fixtures = helper.fixtures;
function cleanUp() {
helper.cleanUp([
'events/node_modules',
'events/lib/added.js'
]);
}
exports.events = {
setUp: function(done) {
cleanUp();
fs.symlinkSync(path.join(__dirname, '../../node_modules'), path.join(fixtures, 'events', 'node_modules'));
done();
},
tearDown: function(done) {
cleanUp();
done();
},
events: function(test) {
test.expect(3);
var cwd = path.resolve(fixtures, 'events');
var assertWatch = helper.assertTask('watch', {cwd: cwd});
assertWatch([function() {
var write = 'var one = true;';
grunt.file.write(path.join(cwd, 'lib', 'added.js'), write);
setTimeout(function() {
grunt.file.write(path.join(cwd, 'lib', 'one.js'), write);
}, 250);
setTimeout(function() {
grunt.file.delete(path.join(cwd, 'lib', 'added.js'));
}, 500);
}], function(result) {
helper.verboseLog(result);
test.ok(result.indexOf('lib/added.js was indeed added') !== -1, 'event emitted when file added');
test.ok(result.indexOf('lib/one.js was indeed changed') !== -1, 'event emitted when file changed');
test.ok(result.indexOf('lib/added.js was indeed deleted') !== -1, 'event emitted when file deleted');
test.done();
});
},
};