From 069ac3827411c1f26d97caca962a175db9a2d7cc Mon Sep 17 00:00:00 2001 From: Uiolee <22849383+uiolee@users.noreply.github.com> Date: Fri, 17 May 2024 17:07:53 +0800 Subject: [PATCH] feat: add option to use slug as title of post (#5470) Signed-off-by: Uiolee <22849383+uiolee@users.noreply.github.com> Co-authored-by: Sukka --- lib/hexo/default_config.ts | 2 ++ lib/plugins/processor/post.ts | 10 ++++++++-- test/scripts/processors/post.ts | 26 ++++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/lib/hexo/default_config.ts b/lib/hexo/default_config.ts index 6d1ede870c..390b8f32f5 100644 --- a/lib/hexo/default_config.ts +++ b/lib/hexo/default_config.ts @@ -58,6 +58,8 @@ export = { exclude_languages: [], strip_indent: true }, + use_filename_as_post_title: false, + // Category & Tag default_category: 'uncategorized', category_map: {}, diff --git a/lib/plugins/processor/post.ts b/lib/plugins/processor/post.ts index 2baee39021..969fad87a1 100644 --- a/lib/plugins/processor/post.ts +++ b/lib/plugins/processor/post.ts @@ -71,8 +71,8 @@ function processPost(ctx: Hexo, file: _File) { const { path } = file.params; const doc = Post.findOne({source: file.path}); const { config } = ctx; - const { timezone: timezoneCfg } = config; - const updated_option = config.updated_option; + const { timezone: timezoneCfg, updated_option, use_slug_as_post_title } = config; + let categories, tags; if (file.type === 'skip' && doc) { @@ -110,6 +110,12 @@ function processPost(ctx: Hexo, file: _File) { if (!preservedKeys[key]) data[key] = info[key]; } + // use `slug` as `title` of post when `title` is not specified. + // https://github.com/hexojs/hexo/issues/5372 + if (use_slug_as_post_title && !('title' in data)) { + data.title = info.title; + } + if (data.date) { data.date = toDate(data.date); } else if (info && info.year && (info.month || info.i_month) && (info.day || info.i_day)) { diff --git a/test/scripts/processors/post.ts b/test/scripts/processors/post.ts index c19f2f2c9c..9fa83192e2 100644 --- a/test/scripts/processors/post.ts +++ b/test/scripts/processors/post.ts @@ -805,6 +805,32 @@ describe('post', () => { ]); }); + // use `slug` as `title` of post when `title` is not specified. + // https://github.com/hexojs/hexo/issues/5372 + it('post - without title - use filename', async () => { + hexo.config.use_slug_as_post_title = true; + + const body = ''; + + const file = newFile({ + path: 'bar.md', + published: true, + type: 'create', + renderable: true + }); + + await writeFile(file.source, body); + await process(file); + const post = Post.findOne({ source: file.path }); + + post.title.should.eql('bar'); + + return Promise.all([ + post.remove(), + unlink(file.source) + ]); + }); + it('post - category is an alias for categories', async () => { const body = [ 'title: "Hello world"',