Initial commit
This commit is contained in:
66
tools/add_link_to_article.js
Normal file
66
tools/add_link_to_article.js
Normal file
@@ -0,0 +1,66 @@
|
||||
#!/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}`);
|
||||
})();
|
||||
Reference in New Issue
Block a user