Skip to content

Commit

Permalink
Add utils.escape tests and fix unicode escaping
Browse files Browse the repository at this point in the history
Fixes #2955
  • Loading branch information
Jan Krems authored and boneskull committed Sep 3, 2017
1 parent 800acbc commit 9f403bf
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 5 deletions.
7 changes: 2 additions & 5 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ var statSync = require('fs').statSync;
var watchFile = require('fs').watchFile;
var lstatSync = require('fs').lstatSync;
var toISOString = require('./to-iso-string');
var he = require('he');

/**
* Ignored directories.
Expand All @@ -35,11 +36,7 @@ exports.inherits = require('util').inherits;
* @return {string}
*/
exports.escape = function (html) {
return String(html)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
return he.encode(String(html), { useNamedReferences: true });
};

/**
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,7 @@
"escape-string-regexp": "1.0.5",
"glob": "7.1.1",
"growl": "1.9.2",
"he": "1.1.1",
"json3": "3.3.2",
"lodash.create": "3.1.1",
"mkdirp": "0.5.1",
Expand Down
18 changes: 18 additions & 0 deletions test/unit/utils.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -624,4 +624,22 @@ describe('lib/utils', function () {
expect(utils.isPromise({})).to.be(false);
});
});

describe('escape', function () {
it('replaces the usual xml suspects', function () {
expect(utils.escape('<a<bc<d<')).to.be('&lt;a&lt;bc&lt;d&lt;');
expect(utils.escape('>a>bc>d>')).to.be('&gt;a&gt;bc&gt;d&gt;');
expect(utils.escape('"a"bc"d"')).to.be('&quot;a&quot;bc&quot;d&quot;');
expect(utils.escape('<>"&')).to.be('&lt;&gt;&quot;&amp;');

expect(utils.escape('&a&bc&d&')).to.be('&amp;a&amp;bc&amp;d&amp;');
expect(utils.escape('&amp;&lt;')).to.be('&amp;amp;&amp;lt;');
});

it('replaces invalid xml characters', function () {
expect(utils.escape('\x1B[32mfoo\x1B[0m')).to.be('&#x1B;[32mfoo&#x1B;[0m');
// Ensure we can handle non-trivial unicode characters as well
expect(utils.escape('💩')).to.be('&#x1F4A9;');
});
});
});

0 comments on commit 9f403bf

Please sign in to comment.