From 5fbe95fd1561170f8c91182d6001f9eb6ffe657e Mon Sep 17 00:00:00 2001 From: Sebastian Koszuta Date: Fri, 13 Dec 2024 13:51:17 +0100 Subject: [PATCH] Added "apply migration" step to the link checker tool --- tools/links-check/index.ts | 6 ++++++ tools/links-check/migrate.ts | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 tools/links-check/migrate.ts diff --git a/tools/links-check/index.ts b/tools/links-check/index.ts index b38d89f..98f088e 100755 --- a/tools/links-check/index.ts +++ b/tools/links-check/index.ts @@ -5,6 +5,7 @@ import * as fs from "node:fs"; import * as path from "node:path"; import ignore from "ignore"; import fg from "fast-glob"; +import { promptUserForMigration, performMigrations } from "./migrate"; main().catch((err: unknown) => { console.error(`🚨 ${err}`); @@ -95,4 +96,9 @@ async function main() { } printReport(report); + + const applyMigrations = await promptUserForMigration(); + if (applyMigrations) { + await performMigrations(report, commonPath); + } } diff --git a/tools/links-check/migrate.ts b/tools/links-check/migrate.ts new file mode 100644 index 0000000..8d58ea2 --- /dev/null +++ b/tools/links-check/migrate.ts @@ -0,0 +1,35 @@ +import type { Report } from "./report"; +import * as readline from "node:readline"; +import * as fs from "node:fs"; +import * as path from "node:path"; + +export async function promptUserForMigration(): Promise { + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + }); + + return new Promise((resolve) => { + rl.question("Would you like to apply suggested migrations? (yes/no): ", (answer) => { + rl.close(); + resolve(answer.toLowerCase() === "yes"); + }); + }); +} + +export async function performMigrations(report: Report, commonPath: string) { + for (const [filePath, links] of report.outdated) { + const absoluteFilePath = path.resolve(commonPath, filePath); + const fileContent = await fs.promises.readFile(absoluteFilePath, "utf-8"); + let updatedContent = fileContent; + + for (const link of links) { + if (link.updated && link.migrated) { + updatedContent = updatedContent.replace(link.url, link.updated); + } + } + + await fs.promises.writeFile(absoluteFilePath, updatedContent, "utf-8"); + console.info(`Updated links in file: ${absoluteFilePath}`); + } +}