Hugoの記事を新規作成するための小さなPythonスクリプトの紹介メモです。テンプレートを元にタイトル、日付、UUIDを自動埋め込みします。
UUIDでURLを一意にし、日付はJST固定で埋め込むようにしています。
既存ファイルがある場合はエラーで止まるようにしています。
スクリプト本体です。
new.py
import datetime
import os
import sys
import uuid
def create_article(output_filepath: str):
output_path = os.path.join('content', output_filepath)
if os.path.exists(output_path):
print(f'Error: Output file already exists: {output_path}', file=sys.stderr)
sys.exit(1)
title = os.path.splitext(os.path.basename(output_path))[0]
JST = datetime.timezone(datetime.timedelta(hours=9))
now = datetime.datetime.now(JST).isoformat(timespec='seconds')
unique_id = str(uuid.uuid4())
template_path = f'archetypes/template.md'
if not os.path.exists(template_path):
print(f'Template does not exist: {template_path}', file=sys.stderr)
sys.exit(1)
with open(template_path, 'r', encoding='utf-8') as f:
content = f.read()
content = content.replace('{{title}}', title)\
.replace('{{date}}', now)\
.replace('{{uuid}}', unique_id)
output_dir = os.path.dirname(output_path)
os.makedirs(output_dir, exist_ok=True)
with open(output_path, 'w', encoding='utf-8') as f:
f.write(content)
print(f'Article created: {output_path}')
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Usage: python new.py output_filepath')
sys.exit(1)
output_filepath = sys.argv[1]
create_article(output_filepath)
sys.exit(0)テンプレートは次のようにしました。
archetypes/template.md
---
title: {{title}}
summary:
tags: []
date: {{date}}
draft: true
url: p/{{uuid}}/
---使い方はシンプルで、次のように実行します。
Bash
python new.py posts/new-post.mdこれでcontent/posts/new-post.mdがテンプレートを埋め込んだ状態で生成されます。
