Synchronisation du contenu avec lemmy
This commit is contained in:
53
tools/lib/frontmatter.js
Normal file
53
tools/lib/frontmatter.js
Normal file
@@ -0,0 +1,53 @@
|
||||
const fs = require("node:fs");
|
||||
const yaml = require("js-yaml");
|
||||
|
||||
const FRONTMATTER_PATTERN = /^---\n([\s\S]*?)\n---\n?/;
|
||||
|
||||
/**
|
||||
* Lit le frontmatter d'un fichier Markdown et retourne son contenu brut.
|
||||
* La fonction préserve également le corps du fichier afin de permettre
|
||||
* une réécriture propre après modification.
|
||||
* @param {string} filePath Chemin absolu du fichier à analyser.
|
||||
* @returns {{ data: Record<string, any>, body: string, frontmatterText: string, raw: string }|null}
|
||||
*/
|
||||
function readFrontmatterFile(filePath) {
|
||||
const raw = fs.readFileSync(filePath, "utf8");
|
||||
const match = raw.match(FRONTMATTER_PATTERN);
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
const frontmatterText = match[1];
|
||||
const data = yaml.load(frontmatterText) || {};
|
||||
const body = raw.slice(match[0].length);
|
||||
return {
|
||||
data,
|
||||
body,
|
||||
frontmatterText,
|
||||
raw,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Réécrit complètement le fichier Markdown avec un frontmatter mis à jour.
|
||||
* @param {string} filePath Chemin absolu du fichier.
|
||||
* @param {Record<string, any>} frontmatter Objet contenant les métadonnées.
|
||||
* @param {string} body Corps Markdown déjà prêt à être réinséré.
|
||||
*/
|
||||
function writeFrontmatterFile(filePath, frontmatter, body) {
|
||||
if (
|
||||
typeof frontmatter !== "object" ||
|
||||
frontmatter === null ||
|
||||
Array.isArray(frontmatter)
|
||||
) {
|
||||
throw new Error(`Frontmatter invalide pour ${filePath}`);
|
||||
}
|
||||
const serialized = yaml.dump(frontmatter, { lineWidth: 120, sortKeys: false }).trimEnd();
|
||||
const contentBody = typeof body === "string" ? body : "";
|
||||
const rewritten = `---\n${serialized}\n---\n${contentBody}`;
|
||||
fs.writeFileSync(filePath, rewritten, "utf8");
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
readFrontmatterFile,
|
||||
writeFrontmatterFile,
|
||||
};
|
||||
Reference in New Issue
Block a user