Skip to content

Commit

Permalink
Proper use of encoding for hashing international characters.
Browse files Browse the repository at this point in the history
  • Loading branch information
michaellopez committed Mar 18, 2013
1 parent e979a06 commit 3671e36
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 3 deletions.
6 changes: 6 additions & 0 deletions Gruntfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@ module.exports = function(grunt) {
},
src: ['tmp/custom.txt']
},
international_options: {
options: {
encoding: 'utf8'
},
src: ['tmp/international.txt']
},
},

// Unit tests.
Expand Down
7 changes: 4 additions & 3 deletions tasks/rev.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,24 +14,25 @@ var fs = require('fs'),

module.exports = function(grunt) {

function md5(filepath, algorithm, encoding) {
function md5(filepath, algorithm, encoding, fileEncoding) {
var hash = crypto.createHash(algorithm);
grunt.log.verbose.write('Hashing ' + filepath + '...');
hash.update(grunt.file.read(filepath));
hash.update(grunt.file.read(filepath), fileEncoding);
return hash.digest(encoding);
}

grunt.registerMultiTask('rev', 'Prefix static asset file names with a content hash', function() {

var options = this.options({
encoding: 'utf8',
algorithm: 'md5',
length: 8
});

this.files.forEach(function(filePair) {
filePair.src.forEach(function(f) {

var hash = md5(f, options.algorithm, 'hex'),
var hash = md5(f, options.algorithm, 'hex', options.encoding),
prefix = hash.slice(0, options.length),
renamed = [prefix, path.basename(f)].join('.'),
outPath = path.resolve(path.dirname(f), renamed);
Expand Down
1 change: 1 addition & 0 deletions test/fixtures/international.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The quick brown fox jumps over the lazy dog åäöæøéßç
8 changes: 8 additions & 0 deletions test/rev_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,12 @@ exports.rev = {

test.done();
},
international_options: function(test) {
test.expect(1);

var exists = grunt.file.exists('tmp/faa07745.international.txt');
test.ok(exists, '8 character MD5 hash prefix for international content');

test.done();
}
};

0 comments on commit 3671e36

Please sign in to comment.