Skip to content

Commit

Permalink
perf(post): refactor swig escape regexp
Browse files Browse the repository at this point in the history
  • Loading branch information
SukkaW committed Jul 19, 2020
1 parent dcdff54 commit 0470503
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 13 deletions.
8 changes: 4 additions & 4 deletions lib/extend/tag.js
Expand Up @@ -4,7 +4,7 @@ const { stripIndent } = require('hexo-util');
const { cyan } = require('chalk');
const { Environment } = require('nunjucks');
const Promise = require('bluebird');
const rSwigRawFullBlock = /{% *raw *%}[\s\S]+{% *endraw *%}/;
const rSwigRawFullBlock = /{% *raw *%}/;
const escapeSwigTag = str => str.replace(/{/g, '{').replace(/}/g, '}');

class NunjucksTag {
Expand Down Expand Up @@ -228,11 +228,11 @@ class Tag {
options = {};
}

str = str.replace(/<code[^<>]*>([\s\S]+?)<\/code>/gm, (str, code) => {
str = str.replace(/<code[^<>]*>[\s\S]+?<\/code>/g, str => {
// https://hexo.io/docs/tag-plugins#Raw
// https://mozilla.github.io/nunjucks/templating.html#raw
// Only escape code block when there is no raw tag included
if (rSwigRawFullBlock.test(code)) return str;
return escapeSwigTag(str);
return rSwigRawFullBlock.test(str) ? str : escapeSwigTag(str);
});

return Promise.fromCallback(cb => { this.env.renderString(str, options, cb); })
Expand Down
17 changes: 8 additions & 9 deletions lib/hexo/post.js
Expand Up @@ -13,10 +13,10 @@ const yfm = require('hexo-front-matter');
const preservedKeys = ['title', 'slug', 'path', 'layout', 'date', 'content'];

const rPlaceholder = /(?:<|&lt;)!--\uFFFC(\d+)--(?:>|&gt;)/g;
const rSwigVar = /\{\{[\s\S]*?\}\}/g;
const rSwigComment = /\{#[\s\S]*?#\}/g;
const rSwigBlock = /\{%[\s\S]*?%\}/g;
const rSwigFullBlock = /\{% *(.+?)(?: *| +.*?)%\}[\s\S]+?\{% *end\1 *%\}/g;
const rSwigVar = /{{[\s\S]+?}}/g;
const rSwigComment = /{#[\s\S]+?#}/g;
const rSwigBlock = /{%[\s\S]+?%}/g;
const rSwigFullBlock = /{% *(\S+?)(?: *| +.+?)%}[\s\S]+?{% *end\1 *%}/g;

const _escapeContent = (cache, str) => {
const placeholder = '\uFFFC';
Expand Down Expand Up @@ -45,11 +45,10 @@ class PostRenderCache {

escapeAllSwigTags(str) {
const escape = _str => _escapeContent(this.cache, _str);
return str
.replace(rSwigFullBlock, escape)
.replace(rSwigBlock, escape)
.replace(rSwigComment, '')
.replace(rSwigVar, escape);
return str.replace(rSwigComment, '') // Remove swig comment first to reduce string size being matched next
.replace(rSwigVar, escape) // Escape swig var since it is a simple regexp
.replace(rSwigFullBlock, escape) // swig full block must escaped before swig block to avoid confliction
.replace(rSwigBlock, escape);
}
}

Expand Down

0 comments on commit 0470503

Please sign in to comment.