Skip to content

Instantly share code, notes, and snippets.

@purtuga
Last active August 29, 2015 14:10
Show Gist options
  • Save purtuga/e0c466eee74f9c411f54 to your computer and use it in GitHub Desktop.
Save purtuga/e0c466eee74f9c411f54 to your computer and use it in GitHub Desktop.
A grunt-copy task filter option function. Enables the copying of only changed files to the destination.
/**
* Returns a function that can be used with grunt's copy
* task 'filter' option. Checks if file being copied
* is newer than that destination file. A local file can be
* used as the "destination" timestampt - a useful method for
* when the destination file is really in a remote system
* (ex. linux server, or a WEBDav folder).
*
* @param {Array} target
* The grunt Copy configurtaion task that this instance
* will apply to.
* @param {String} timestampFile
* A timestamp file. Will be used instead of accessing the
* destination file when detemining if file should be copied.
*
* @return {Boolean}
* True - yes, its new
* false - no, its not new
*
* @see https://gist.github.com/purtuga/e0c466eee74f9c411f54
*
* @example
*
* grunt.initConfig({
* copy: {
* build: {
* src: "src/**,
* dest: "build/",
* expand: true,
* filter: onlyNew(['copy', 'build'])
* }
* }
* })
*
*/
function onlyNew(target, timestampFile) {
var newTimestamp,
taskCreated = false;
if (!onlyNew.isTaskCreated) {
onlyNew.isTaskCreated = true;
grunt.registerTask('onlyNewPostRun', function(f){
var file = Array.prototype.slice.call(arguments, 0).join(':');
grunt.log.writeln("onlyNewPostRun Task RUNNING for file: " + file);
fs.writeFileSync(file, 'temp file');
});
onlyNew.timestampFiles = {};
}
// Return the callback function for each file check - used in the task
return function(src) {
var dest = grunt.config(target.concat('dest')),
cwd = grunt.config(target.concat('cwd')),
dstat, stat, response;
if (!timestampFile) {
dest = cwd ?
path.join(dest, path.relative(cwd, src)) :
path.join(dest, src);
} else {
dest = timestampFile;
}
if (timestampFile && !onlyNew.timestampFiles[timestampFile]) {
onlyNew.timestampFiles[timestampFile] = true;
grunt.task.run("onlyNewPostRun:" + timestampFile);
}
grunt.verbose.writeln("Src File: " + src);
grunt.verbose.writeln("Dest File: " + dest);
try {
dstat = fs.statSync(dest);
stat = fs.statSync(src);
} catch (e) {
return true;
}
response = ( stat.isFile() && stat.mtime.getTime() > dstat.mtime.getTime() );
return response;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment