From e00c0444da05cdbce99feb4bc79c604ec6521f24 Mon Sep 17 00:00:00 2001 From: alexfitiskin Date: Sun, 11 Aug 2013 01:51:01 +0400 Subject: [PATCH] Add support to parse and save multiple files. fixes ehynds/grunt-image-embed#19 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit If `dest` param is a directory — each input file will be saved into separate file in `dest` directory (with same name). Add `cwd` param to add base path for input files. --- tasks/grunt-image-embed.js | 52 +++++++++++++++++++++++++++++++------- 1 file changed, 43 insertions(+), 9 deletions(-) diff --git a/tasks/grunt-image-embed.js b/tasks/grunt-image-embed.js index 889fafa..0421cb7 100644 --- a/tasks/grunt-image-embed.js +++ b/tasks/grunt-image-embed.js @@ -6,10 +6,13 @@ * Licensed under the MIT license. */ +// External libs +var path = require('path'); + // Internal libs var grunt_encode = require("./lib/encode"); -module.exports = function(grunt) { +module.exports = function (grunt) { "use strict"; // Grunt lib init @@ -18,25 +21,56 @@ module.exports = function(grunt) { // Grunt utils var async = grunt.util.async; - grunt.registerMultiTask("imageEmbed", "Embed images as base64 data URIs inside your stylesheets", function() { + grunt.registerMultiTask("imageEmbed", "Embed images as base64 data URIs inside your stylesheets", function () { var opts = this.options(); var done = this.async(); // Process each src file - this.files.forEach(function(file) { + this.files.forEach(function (file) { + var cwd = file.cwd; var dest = file.dest; - var tasks; + var destIsFile = !!path.extname(dest); + + var src = file.src.filter(function(src) { + if (cwd) { + src = path.join(cwd, src); + } + + if (grunt.file.isFile(src)) { + return true; + } else { + grunt.log.warn('Source file "' + src + '" not found.'); + return false; + } + }); - tasks = file.src.map(function(srcFile) { - return function(callback) { + if (src.length > 1 && destIsFile) { + grunt.log.warn('Source file cannot be more than one when dest is a file.'); + } + + + var tasks = file.src.map(function (srcFile) { + return function (callback) { + if (cwd) { + srcFile = path.join(cwd, srcFile); + } encode.stylesheet(srcFile, opts, callback); }; }); // Once all files have been processed write them out. - async.parallel(tasks, function(err, output) { - grunt.file.write(dest, output); - grunt.log.writeln('File "' + dest + '" created.'); + async.parallel(tasks, function (err, output) { + if (destIsFile) { + grunt.file.write(dest, content); + grunt.log.writeln('File "' + dest + '" created.'); + } else { + output.forEach(function (content, index) { + var outputPath = path.join(dest, src[index]); + grunt.file.write(outputPath, content); + grunt.log.writeln('File "' + outputPath + '" created.'); + }); + } + done(); }); });