From deb49cad70a08a81846375b7b352c9be9de5ee9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9sar=20D=2E=20Rodas?= Date: Mon, 10 Feb 2014 00:01:23 -0300 Subject: [PATCH] Sort files by length Before replacing the filenames, sort them by their length (descending). It is useful when we have foo-mobile.js, bar-mobile.js and mobile.js. Without the sorting it was acting unpredictably (sometimes replacing mobile..js to foo-mobile..js) --- tasks/hashresHelper.js | 35 +++++++++++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/tasks/hashresHelper.js b/tasks/hashresHelper.js index cfb0393..6a6d2ba 100644 --- a/tasks/hashresHelper.js +++ b/tasks/hashresHelper.js @@ -12,6 +12,22 @@ var fs = require('fs'), path = require('path'), utils = require('./hashresUtils'); +function preg_quote (str, delimiter) { + // http://kevin.vanzonneveld.net + // + original by: booeyOH + // + improved by: Ates Goral (http://magnetiq.com) + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // + bugfixed by: Onno Marsman + // + improved by: Brett Zamir (http://brett-zamir.me) + // * example 1: preg_quote("$40"); + // * returns 1: '\$40' + // * example 2: preg_quote("*RRRING* Hello?"); + // * returns 2: '\*RRRING\* Hello\?' + // * example 3: preg_quote("\\.+*?[^]$(){}=!<>|:"); + // * returns 3: '\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:' + return (str + '').replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + (delimiter || '') + '-]', 'g'), '\\$&'); +} + exports.hashAndSub = function(grunt, options) { var src = options.src, @@ -50,13 +66,24 @@ exports.hashAndSub = function(grunt, options) { grunt.log.write(src + ' ').ok(renamed); }); + // sort files by length + // It is very useful when we have bar.js and foo-bar.js + // @crodas + var files = []; + for (var name in nameToHashedName) { + files.push([name, nameToHashedName[name]]); + } + files.sort(function(a, b) { + return b[0].length - a[0].length; + }); + // Substituting references to the given files with the hashed ones. grunt.file.expand(f.dest).forEach(function(f) { var destContents = fs.readFileSync(f, encoding); - for (var name in nameToHashedName) { - grunt.log.debug('Substituting ' + name + ' by ' + nameToHashedName[name]); - destContents = destContents.replace(new RegExp(name, "g"), nameToHashedName[name]); - } + files.forEach(function(value) { + grunt.log.debug('Substituting ' + value[0] + ' by ' + value[1]); + destContents = destContents.replace(new RegExp(preg_quote(value[0]), "g"), value[1]); + }); grunt.log.debug('Saving the updated contents of the outination file'); fs.writeFileSync(f, destContents, encoding); });