突然何?
Hexoの話です。
ブログのお引越しをして早数年…
放置しすぎでごめんなさい、という話も程々に、ちょいちょいブログ更新も再開しようということで、Hexoのカスタマイズも進めていこうということになりました。
え?ブログはオワコンだって?知らんわそんなこと。
ブログのパーマリンクは、これまで使ってきたブログアプリの設定を継承して、/:year/:month/:id/っていう設定にしているんですが、これだと毎回記事を書く時Front Matterに、idを設定しないといけないわけです。
お分かりと思いますが、:idの値は一意でないといけないので、毎回、次のid何だっけ?っと調べるのも面倒だし、何よりミスる可能性もあるわけなんです。
なので、自動的にidを生成してくれたらいいのにな、と思いまして、じゃあプラグインを作ればいいじゃない(マリー)となりました。
とりまAIに相談。
サクッとコードを書いてくれた。
'use strict';
const fs = require('node:fs/promises');
const path = require('node:path');
const postsDir = path.join(hexo.source_dir, '_posts');
const draftsDir = path.join(hexo.source_dir, '_drafts');
// ディレクトリ内の記事ファイルを再帰的に取得
async function getFiles(dir) {
const entries = await fs.readdir(dir, { withFileTypes: true });
const files = [];
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
files.push(...await getFiles(fullPath));
} else if (entry.isFile()) {
files.push(fullPath);
}
}
return files;
}
// Front MatterからIDを取得
function getId(content) {
const match = content.match(
/^---\s*\r?\n([\s\S]*?)\r?\n---/
);
if (!match) return null;
const idMatch = match[1].match(/^id:\s*["']?(\d+)["']?\s*$/m);
if (!idMatch) return null;
const id = Number(idMatch[1]);
return Number.isSafeInteger(id) ? id : null;
}
// _posts内の最大IDから次のIDを取得
async function getNextId() {
let maxId = 0;
const files = await getFiles(postsDir);
for (const file of files) {
const content = await fs.readFile(file, 'utf8');
const id = getId(content);
if (id !== null) {
maxId = Math.max(maxId, id);
}
}
return maxId + 1;
}
// 下書きファイルをslugから検索
async function findDraft(slug) {
const files = await getFiles(draftsDir);
const matches = files.filter(file =>
path.basename(file, path.extname(file)) === String(slug)
);
if (matches.length !== 1) {
throw new Error(
`下書きを特定できません: ${slug} (${matches.length}件)`
);
}
return matches[0];
}
// Front MatterにIDを設定
async function setPostId(file, id) {
let content = await fs.readFile(file, 'utf8');
const match = content.match(
/^(---\s*\r?\n)([\s\S]*?)(\r?\n---)/
);
if (!match) {
throw new Error(`Front Matterが見つかりません: ${file}`);
}
let frontMatter = match[2];
if (/^id\s*:/m.test(frontMatter)) {
frontMatter = frontMatter.replace(
/^id\s*:.*$/m,
`id: ${id}`
);
} else {
frontMatter += `\nid: ${id}`;
}
content =
match[1] +
frontMatter +
match[3] +
content.slice(match[0].length);
await fs.writeFile(file, content, 'utf8');
}
// Hexo標準のpublish処理を拡張
const originalPublish = hexo.post.publish;
hexo.post.publish = async function(data, replace) {
// 次のIDを取得
const nextId = await getNextId();
// 公開対象の下書きを取得
const draftFile = await findDraft(data.slug);
// 公開前にIDを書き込む
await setPostId(draftFile, nextId);
hexo.log.info(`公開記事にID ${nextId} を設定します`);
// Hexo標準の公開処理を実行
const result = await originalPublish.call(this, data, replace);
hexo.log.info(`記事を公開しました。ID: ${nextId}`);
return result;
};
これをauto-post-id.jsとしてscripts以下に設置して完成。
AIありがたすぎる。
近ごろAIの進歩が目覚ましく、弊害としてセキュリティの脆弱性を突く効率も爆上がりってなわけで、ここのところ騒がれているセキュリティ問題について、Webサイトを運営する側としては他人事じゃないですよ。
静的サイトジェネレータに移行しといて良かったぁー!