1
Files
2025/tools/add_link_to_article.js
2025-03-28 12:57:37 +01:00

67 lines
2.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
const fs = require("fs");
const path = require("path");
const yaml = require("js-yaml");
const { scrapePage } = require("./lib/puppeteer");
if (process.argv.length < 4) {
console.error("Usage: add_link_to_article.js <URL> <path_to_article>");
process.exit(1);
}
const url = process.argv[2];
const articlePath = process.argv[3];
const indexPath = path.join(articlePath, "index.md");
// Vérifier si le fichier `index.md` existe
if (!fs.existsSync(indexPath)) {
console.error(`❌ The article at ${indexPath} does not exist.`);
process.exit(1);
}
// Charger le frontmatter YAML depuis `index.md`
const fileContent = fs.readFileSync(indexPath, "utf8");
const frontmatterMatch = fileContent.match(/^---\n([\s\S]+?)\n---/);
if (!frontmatterMatch) {
console.error("❌ No valid frontmatter found in the article.");
process.exit(1);
}
let frontmatter = yaml.load(frontmatterMatch[1]);
if (!frontmatter.links) frontmatter.links = [];
// Vérifier si le lien existe déjà
if (frontmatter.links.some(link => link.url === url)) {
console.log(`⚠ The link "${url}" is already in the article.`);
process.exit(0);
}
// Scraper la page pour récupérer le titre et la langue
(async () => {
console.log(`🔍 Retrieving metadata for ${url}...`);
const metadata = await scrapePage(url, "/dev/null"); // Ignore la capture décran pour ce script
if (!metadata.title) {
console.error("❌ Failed to retrieve page title. Skipping.");
process.exit(1);
}
frontmatter.links.push({
name: metadata.title,
lang: metadata.lang || "unknown",
url: url,
official: false
});
// Reconstruire le frontmatter YAML
const newFrontmatter = yaml.dump(frontmatter);
const newContent = `---\n${newFrontmatter}---\n${fileContent.replace(frontmatterMatch[0], "").trim()}`;
// Écrire le fichier
fs.writeFileSync(indexPath, newContent, "utf8");
console.log(`✔ Link successfully added to ${indexPath}`);
})();