|
| 1 | +import * as path from 'path'; |
| 2 | +import * as fs from 'fs'; |
| 3 | +import * as util from 'util'; |
| 4 | + |
| 5 | +const readdir = util.promisify(fs.readdir); |
| 6 | +const readFile = util.promisify(fs.readFile); |
| 7 | +const writeFile = util.promisify(fs.writeFile); |
| 8 | + |
| 9 | +async function replaceLinks(oldPath: string, newPath: string): Promise<void> { |
| 10 | + const oldFilename = path.basename(oldPath, '.md'); |
| 11 | + const newFilename = path.basename(newPath, '.md'); |
| 12 | + const dirPath = path.dirname(oldPath); |
| 13 | + |
| 14 | + // Get all markdown files in the root directory |
| 15 | + const files = await readdir(dirPath); |
| 16 | + |
| 17 | + const mdFiles = files.filter((file) => path.extname(file) === '.md'); |
| 18 | + |
| 19 | + // For each markdown file |
| 20 | + for (const file of mdFiles) { |
| 21 | + const filePath = path.join(dirPath, file); |
| 22 | + |
| 23 | + // Read the content of the file |
| 24 | + const content = await readFile(filePath, 'utf-8'); |
| 25 | + |
| 26 | + // Create a regex to match the old filename |
| 27 | + const regex = new RegExp(`\\[\\[${oldFilename}\\]\\]`, 'g'); |
| 28 | + |
| 29 | + // Replace the old filename with the new filename |
| 30 | + const newContent = content.replace(regex, `[[${newFilename}]]`); |
| 31 | + |
| 32 | + // Write the new content back to the file |
| 33 | + await writeFile(filePath, newContent, 'utf-8'); |
| 34 | + } |
| 35 | +} |
0 commit comments