Skip to content

Commit

Permalink
fix: Failed to create post with special character title (#5149)
Browse files Browse the repository at this point in the history
  • Loading branch information
D-Sketon committed Feb 6, 2023
1 parent 4f2dde4 commit d5f3f82
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/hexo/post.js
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,9 @@ const prepareFrontMatter = (data, jsonMode) => {
} else if (moment.isDate(item)) {
data[key] = moment.utc(item).format('YYYY-MM-DD HH:mm:ss');
} else if (typeof item === 'string') {
if (jsonMode || item.includes(':') || item.startsWith('#') || item.startsWith('!!')) data[key] = `"${item}"`;
if (jsonMode || item.includes(':') || item.startsWith('#') || item.startsWith('!!')
|| item.includes('{') || item.includes('}') || item.includes('[') || item.includes(']')
|| item.includes('\'') || item.includes('"')) data[key] = `"${item.replace(/"/g, '\\"')}"`;
}
}

Expand Down
84 changes: 84 additions & 0 deletions test/scripts/console/new.js
Original file line number Diff line number Diff line change
Expand Up @@ -247,4 +247,88 @@ describe('new', () => {

await unlink(path);
});

it('special character - 1', async () => {
const date = moment(now);
const path = join(hexo.source_dir, '_posts', 'Hello-World.md');
const body = [
'title: \'[Hello] World\'',
'foo: bar',
'date: ' + date.format('YYYY-MM-DD HH:mm:ss'),
'tags:',
'---'
].join('\n') + '\n';

await n({
_: ['[Hello] World'],
foo: 'bar'
});
const content = await readFile(path);
content.should.eql(body);

await unlink(path);
});

it('special character - 2', async () => {
const date = moment(now);
const path = join(hexo.source_dir, '_posts', 'Hello-World.md');
const body = [
'title: \'{Hello} World\'',
'foo: bar',
'date: ' + date.format('YYYY-MM-DD HH:mm:ss'),
'tags:',
'---'
].join('\n') + '\n';

await n({
_: ['{Hello} World'],
foo: 'bar'
});
const content = await readFile(path);
content.should.eql(body);

await unlink(path);
});

it('special character - 3', async () => {
const date = moment(now);
const path = join(hexo.source_dir, '_posts', 'Hello-World.md');
const body = [
'title: \'\'\'Hello\'\' World\'',
'foo: bar',
'date: ' + date.format('YYYY-MM-DD HH:mm:ss'),
'tags:',
'---'
].join('\n') + '\n';

await n({
_: ['\'Hello\' World'],
foo: 'bar'
});
const content = await readFile(path);
content.should.eql(body);

await unlink(path);
});

it('special character - 4', async () => {
const date = moment(now);
const path = join(hexo.source_dir, '_posts', 'Hello-World.md');
const body = [
'title: \'"Hello" World\'',
'foo: bar',
'date: ' + date.format('YYYY-MM-DD HH:mm:ss'),
'tags:',
'---'
].join('\n') + '\n';

await n({
_: ['"Hello" World'],
foo: 'bar'
});
const content = await readFile(path);
content.should.eql(body);

await unlink(path);
});
});

0 comments on commit d5f3f82

Please sign in to comment.