diff --git a/Gruntfile.js b/Gruntfile.js index 0986aa2..cc7a0c4 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -45,6 +45,15 @@ module.exports = function (grunt) { src: ['*'], dest: 'test/tmp/expand' }, + withDropCwd: { + options: { + dropCwd: true + }, + expand: true, + cwd: 'test/fixtures', + src: ['file.png'], + dest: 'test/tmp/withDropCwd' + }, withSummaryAttributeName: { options: { summary: 'foo' @@ -89,5 +98,8 @@ module.exports = function (grunt) { var src = path.normalize('test/fixtures/file.png'); var expected = path.normalize('test/tmp/file.26365248.png'); assert.equal(grunt.filerev.summary[src], expected); + src = path.normalize('file.png'); + expected = path.normalize('tmp/withDropCwd/file.26365248.png'); + assert.equal(grunt.filerev.summary[src], expected); }); }; diff --git a/tasks/filerev.js b/tasks/filerev.js index b57b795..f1f18e9 100644 --- a/tasks/filerev.js +++ b/tasks/filerev.js @@ -9,10 +9,12 @@ module.exports = function (grunt) { grunt.registerMultiTask('filerev', 'File revisioning based on content hashing', function () { var options = this.options({ algorithm: 'md5', - length: 8 + length: 8, + dropCwd: false }); var target = this.target; var filerev = grunt.filerev || {summary: {}}; + var cwd = this.data.cwd || ''; eachAsync(this.files, function (el, i, next) { var move = true; @@ -74,10 +76,10 @@ module.exports = function (grunt) { } } - filerev.summary[path.normalize(file)] = path.join(dirname, newName); + filerev.summary[dropCwd(path.normalize(file))] = dropCwd(path.join(dirname, newName)); grunt.verbose.writeln(chalk.green('✔ ') + file + chalk.gray(' changed to ') + newName); if (sourceMap) { - filerev.summary[path.normalize(file + '.map')] = path.join(dirname, newName + '.map'); + filerev.summary[dropCwd(path.normalize(file + '.map'))] = dropCwd(path.join(dirname, newName + '.map')); grunt.verbose.writeln(chalk.green('✔ ') + file + '.map' + chalk.gray(' changed to ') + newName + '.map'); } @@ -90,6 +92,22 @@ module.exports = function (grunt) { next(); }, this.async()); + // Drop cwd from path if relative option is set to true + function dropCwd (file) { + if (options.dropCwd === true && cwd) { + var filePath = file.split(path.sep), + cwdPath = path.normalize(cwd).split(path.sep), + pos = 0; + for (var i = 0; i < cwdPath.length; i++) { + if (filePath[i] === cwdPath[i]) { + pos = i + 1; + } + } + file = filePath.slice(pos).join(path.sep); + } + return file; + } + grunt.filerev = filerev; }); };