Skip to content

Commit

Permalink
fix: no backslash
Browse files Browse the repository at this point in the history
  • Loading branch information
stevenjoezhang committed Apr 9, 2024
1 parent 48d3cbc commit 04abf71
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 13 deletions.
20 changes: 8 additions & 12 deletions lib/plugins/tag/include_code.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { basename, extname, join, posix } from 'path';
import { basename, extname, join } from 'path';
import { url_for } from 'hexo-util';
import type Hexo from '../../hexo';

const rCaptionTitleFile = /(.*)?(?:\s+|^)(\/*\S+)/;
Expand All @@ -13,11 +14,6 @@ const rTo = /\s*to:(\d+)/i;
* {% include_code [title] [lang:language] path/to/file %}
*/

const escapeBackslash = path => {
// Replace backslashes on Windows
return path.replace(/\\/g, '/');
};

export = (ctx: Hexo) => function includeCodeTag(args: string[]) {
let codeDir = ctx.config.code_dir;
let arg = args.join(' ');
Expand Down Expand Up @@ -51,21 +47,21 @@ export = (ctx: Hexo) => function includeCodeTag(args: string[]) {
// If the language is not defined, use file extension instead
lang = lang || extname(path).substring(1);

const src = escapeBackslash(join(codeDir, path));

// If the title is not defined, use file name instead
const title = match[1] || basename(path);
const caption = `<span>${title}</span><a href="${posix.join(ctx.config.root, codeDir, path)}">view raw</a>`;
const source = join(codeDir, path);

// Prevent path traversal: https://github.com/hexojs/hexo/issues/5250
const Page = ctx.model('Page');
const doc = Page.findOne({ source: src });
const doc = Page.findOne({ source });
if (!doc) return;

let code = doc.content;
const lines = code.split('\n');
code = lines.slice(from, to).join('\n').trim();

// If the title is not defined, use file name instead
const title = match[1] || basename(path);
const caption = `<span>${title}</span><a href="${url_for.call(ctx, doc.path)}">view raw</a>`;

if (ctx.extend.highlight.query(ctx.config.syntax_highlighter)) {
const options = {
lang,
Expand Down
2 changes: 1 addition & 1 deletion test/scripts/tags/include_code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ describe('include_code', () => {
const defaultCfg = JSON.parse(JSON.stringify(hexo.config));

const fixture = [
'if (tired && night){',
'if (tired && night) {',
' sleep();',
'}'
].join('\n');
Expand Down

0 comments on commit 04abf71

Please sign in to comment.