Last active
August 9, 2024 08:43
-
-
Save sulco/092b7ca2d87519722d4f891593f792ce to your computer and use it in GitHub Desktop.
Sluggify — add `slug` to each part, chapter and lesson of a TutorialKit project
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Notes: | |
- This might change A LOT — remember to commit your current TutorialKit state before using this script. | |
- To run it, put the file in your `src/content/tutorial` folder and from there run `node sluggify.js` | |
*/ | |
import { promises as fs } from 'fs'; | |
import path from 'path'; | |
import { fileURLToPath } from 'url'; | |
const __filename = fileURLToPath(import.meta.url); | |
const __dirname = path.dirname(__filename); | |
async function traverseFolders(directory) { | |
try { | |
const entries = await fs.readdir(directory, { withFileTypes: true }); | |
const folders = entries.filter(entry => entry.isDirectory()); | |
for (const folder of folders) { | |
const folderName = folder.name; | |
const match = folderName.match(/^\d+-(.*)/); | |
if (match) { | |
const namePart = match[1]; | |
console.log(`Processing folder: ${namePart}`); | |
const subDirectory = path.join(directory, folderName); | |
const possibleFiles = ['content.md', 'content.mdx', 'meta.md']; | |
let contentPath; | |
for (const file of possibleFiles) { | |
const filePath = path.join(subDirectory, file); | |
if (await fileExists(filePath)) { | |
contentPath = filePath; | |
break; | |
} | |
} | |
if (contentPath) { | |
await updateContentFile(contentPath, namePart); | |
} else { | |
console.log(`No content or meta file found in ${folderName}`); | |
} | |
} | |
await traverseFolders(path.join(directory, folderName)); | |
} | |
} catch (err) { | |
console.error('Error:', err); | |
} | |
} | |
async function fileExists(filePath) { | |
try { | |
await fs.access(filePath); | |
return true; | |
} catch { | |
return false; | |
} | |
} | |
async function updateContentFile(filePath, slug) { | |
try { | |
let content = await fs.readFile(filePath, 'utf8'); | |
if (!content.includes(`slug: ${slug}`)) { | |
const lines = content.split('\n'); | |
lines.splice(1, 0, `slug: ${slug}`); | |
content = lines.join('\n'); | |
await fs.writeFile(filePath, content, 'utf8'); | |
console.log(`Updated ${path.basename(filePath)} in ${path.dirname(filePath)}`); | |
} else { | |
console.log(`Slug already exists in ${path.basename(filePath)}`); | |
} | |
} catch (err) { | |
console.error(`Error updating ${filePath}:`, err); | |
} | |
} | |
const startDirectory = process.cwd(); | |
traverseFolders(startDirectory); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment