用 vscode 脚本创建 hugo 文章

目录

我通常使用 VSCODE 进行开发和记录笔记,书写文章标题是中文在浏览器上显示不是特别友好,考虑了这一点,我使用了以下脚本,将文件名保留中文,文章标题转换为英文,提高文章的可读性。

为了实现这一需求,选择了 VSCode 任务,方案如下:

  1. 创建任务编写脚本,使得在 VSCode 弹出输入框,接收输入的标题和分类;
  2. 创建 python 脚本将输入的标题和分类生成对应的 Hugo 命令,并执行;
  3. 中英文翻译:利用 Google 翻译 API ,将输入的中文标题翻译成英文;
  4. 翻译后的 ${title} 如果有多个单词,单词间用 "-“连接;
  5. 调用 hugo 创建一个 post/${yyyy}/${yyyy-MM-dd}-${title}.md;
  6. 找到文件中 slug: 开头的行,替换 slug: ${translated_title}

1. 创建任务编写脚本

在当前项目下.vscode 创建 task.json 文件,并添加如下内容

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "新建文章",
            "type": "shell",
            "command": "python3.9",
            "args": ["scripts/new_post.py", "${input:title}" , "${input:categories}"],
            "problemMatcher": []
        }
    ],
    "inputs": [
        {
            "id": "title",
            "type": "promptString",
            "description": "请输出文章标题."
        },
        {
            "id": "categories",
            "type": "promptString",
            "description": "请输出文章分类."
        }
    ]
}

2. 创建 python 脚本 将输入的标题生成对应的 Hugo 命令

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import os
import argparse
from googletrans import Translator
import subprocess
from datetime import datetime


def translate_title(title):
    translator = Translator()
    translated_title = translator.translate(title, src='auto', dest='en').text
    # 如果翻译后的标题包含多个单词,将它们用连字符连接
    translated_title = translated_title.replace(' ', '-')
    return translated_title


def create_post(title, categories=None):
    translated_title = translate_title(title)
    now = datetime.now()
    yyyy = now.strftime("%Y")
    file_name = f"{yyyy}/{title}.md"
    file_path = f"content/posts/{file_name}"
    if categories:
        file_name = f"{categories}/{title}.md"
        print(f"category: {categories.split('/')}")
    if os.path.exists(file_path):
        print(f"Error: File '{file_path}' already exists.")
        exit(1)
    # 调用 hugo 创建 post
    subprocess.run(["hugo", "new", f"content/posts/{file_name}"])

    # 找到文件中的 title: 行,并在其后添加 slug: 行
    with open(f"content/posts/{file_name}", 'r+', encoding='utf-8') as file:
        lines = file.readlines()
        for idx, line in enumerate(lines):
            if line.strip().startswith("slug:"):
                lines[idx] = f"slug: {translated_title}\n"
            if line.strip().startswith("categories:"):
                if categories:
                    lines[idx] = f"category: {categories.split('/')}\n"
                break
        file.seek(0)
        file.writelines(lines)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Create a new Hugo post")
    parser.add_argument("title", type=str, help="文章标题")
    parser.add_argument(
        "categories",
        type=str,
        help="文章分类",
        nargs="?",
        default=None,
        help="文章分类,可选参数"
    )

    args = parser.parse_args()

    # 创建 post
    create_post(args.title, categories=args.categories)
1
2
3
python3.9 scripts/new_post.py 测试 工具箱/vscode
category: ['工具箱', 'vscode']
Error: File 'content/posts/2024/测试.md' already exists.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
---
title: "测试"
slug: Use-VSCODE-script-to-create-a-hugo-article
date: 2024-03-06T15:31:29+08:00
lastmod: 2024-03-06T15:31:29+08:00
author: kbsonlong
authorEmail: kbsonlong@gmail.com
draft: true
featuredImage:
category: ['工具箱', 'vscode']
tags: []
---

通过 VSCODE 创建文章

终端 - 运行任务 - 新建文章 - 输入标题和分类即可创建文章

202403061546190

202403061547371

202403061547700

202403061547493

0%