Skip to content
This repository has been archived by the owner on Oct 25, 2022. It is now read-only.

Sort files #32

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 31 additions & 7 deletions tasks/hashresHelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -60,16 +76,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(utils.preg_quote(name)+"(\\?[0-9a-z]+)?", "g"), nameToHashedName[name]);

grunt.log.debug('Substituting ' + nameToNameSearch[name] + ' by ' + nameToHashedName[name]);
destContents = destContents.replace(new RegExp(nameToNameSearch[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);
});
Expand Down