Last active
April 19, 2021 17:05
-
-
Save kentcdodds/436a77ff8977269e5fee39d9d89956de to your computer and use it in GitHub Desktop.
I use this to automatically fix links in my react workshops
This file contains hidden or 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
#!/usr/bin/env node | |
const path = require('path') | |
const fs = require('fs') | |
const glob = require('glob') | |
const pkg = require(path.join(process.cwd(), 'package.json')) | |
const {title: projectTitle, homepage: projectHomepage} = pkg | |
// update production deploy links | |
glob.sync('src/**/*.md').forEach(filepath => { | |
const parsed = path.parse(filepath) | |
const {name} = parsed | |
let exerciseExt | |
const exerciseHtmlPath = path.format({...parsed, base: `${name}.html`}) | |
const exerciseJsPath = path.format({...parsed, base: `${name}.js`}) | |
const exerciseTsPath = path.format({...parsed, base: `${name}.ts`}) | |
const exerciseTsxPath = path.format({...parsed, base: `${name}.tsx`}) | |
if (fs.existsSync(exerciseHtmlPath)) { | |
exerciseExt = '.html' | |
} else if (fs.existsSync(exerciseJsPath)) { | |
exerciseExt = '.js' | |
} else if (fs.existsSync(exerciseTsPath)) { | |
exerciseExt = '.ts' | |
} else if (fs.existsSync(exerciseTsxPath)) { | |
exerciseExt = '.tsx' | |
} else { | |
throw new Error(`Unsupported exercise type for "${name}"`) | |
} | |
const fullFilepath = path.join(process.cwd(), filepath) | |
const contents = fs.readFileSync(fullFilepath, { | |
encoding: 'utf-8', | |
}) | |
const lines = contents.split('\n') | |
const exerciseProdDeployLines = ` | |
Production deploys: | |
- [Exercise](${projectHomepage}isolated/exercise/${name}${exerciseExt}) | |
- [Final](${projectHomepage}isolated/final/${name}${exerciseExt}) | |
` | |
.trim() | |
.split('\n') | |
const getExtraDeployLines = extraNumber => [ | |
`[Production deploy](${projectHomepage}isolated/final/${name}.extra-${extraNumber}${exerciseExt})`, | |
] | |
const newLines = [] | |
for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) { | |
const line = lines[lineIndex] | |
newLines.push(line) | |
const extraCreditMatch = line.match(/### (?<number>\d+)\. π― /) | |
if (/## Exercise$/.test(line)) { | |
newLines.push('', ...exerciseProdDeployLines) | |
if (lines[lineIndex + 2].startsWith('Production deploys:')) { | |
// already existed, skip indexes | |
lineIndex = lineIndex + exerciseProdDeployLines.length + 1 | |
} | |
} else if (extraCreditMatch) { | |
const number = extraCreditMatch.groups.number | |
const extraDeployLines = getExtraDeployLines(number) | |
newLines.push('', ...extraDeployLines) | |
if (lines[lineIndex + 2].startsWith('[Production deploy]')) { | |
// already existed, skip indexes | |
lineIndex = lineIndex + extraDeployLines.length + 1 | |
} | |
} | |
} | |
fs.writeFileSync(fullFilepath, newLines.join('\n')) | |
}) | |
// update notes | |
glob.sync('src/**/*.md').forEach(filepath => { | |
const fullFilepath = path.join(process.cwd(), filepath) | |
const contents = fs.readFileSync(fullFilepath, { | |
encoding: 'utf-8', | |
}) | |
const notesText = ` | |
## π Your Notes | |
Elaborate on your learnings here in \`${filepath}\` | |
`.trim() | |
if (contents.includes(notesText)) return | |
const lines = contents.split('\n') | |
const notesLines = notesText.trim().split('\n') | |
notesLines.push('') // add a newline | |
const notesLineIndex = lines.findIndex(line => line === '## π Your Notes') | |
const replaceLines = notesLineIndex !== -1 | |
lines.splice(2, replaceLines ? notesLines.length : 0, ...notesLines) | |
fs.writeFileSync(fullFilepath, lines.join('\n')) | |
}) | |
// update feedback links | |
glob.sync('src/**/*.md').forEach(filepath => { | |
const {name: filename} = path.parse(filepath) | |
const fullFilepath = path.join(process.cwd(), filepath) | |
const contents = fs.readFileSync(fullFilepath, { | |
encoding: 'utf-8', | |
}) | |
const firstLine = contents.split('\n')[0] | |
const titleMatch = firstLine.match(/# (?<title>.*)$/) | |
if (!titleMatch) { | |
throw new Error(`Title is invalid for "${filepath}"`) | |
} | |
const title = titleMatch.groups.title.trim() | |
const workshop = encodeURIComponent(projectTitle) | |
const exercise = encodeURIComponent(`${filename}: ${title}`) | |
const link = `(https://ws.kcd.im/?ws=${workshop}&e=${exercise}&em=)` | |
if (contents.includes(link)) { | |
return | |
} | |
const feedbackLinkRegex = /\(https?:\/\/ws\.kcd\.im.*?\)/ | |
if (!feedbackLinkRegex.test(contents)) { | |
throw new Error(`Exercise "${filepath}" is missing workshop feedback link`) | |
} | |
const newContents = contents.replace(feedbackLinkRegex, link) | |
fs.writeFileSync(fullFilepath, newContents) | |
}) | |
// update links to isolated examples | |
glob | |
.sync('src/+(examples|final|exercise)/**/*.+(js|html|ts|tsx)', { | |
ignore: ['**/__tests__/**', '**/*.test.*/**'], | |
}) | |
.forEach(filepath => { | |
const {ext} = path.parse(filepath) | |
const fullFilepath = path.join(process.cwd(), filepath) | |
const contents = fs.readFileSync(fullFilepath, { | |
encoding: 'utf-8', | |
}) | |
const linkBase = 'http://localhost:3000/isolated' | |
const isHtml = ext === '.html' | |
const link = `${linkBase}${filepath.replace(/^src/, '')}` | |
const linkLine = isHtml ? `<!-- ${link} -->` : `// ${link}` | |
const commentStart = isHtml ? '<!--' : '//' | |
const lines = contents | |
.split('\n') | |
// filter out any existing link line (might be old) | |
.filter(line => !line.trim().startsWith(`${commentStart} ${linkBase}`)) | |
const linkLineIndex = lines.findIndex( | |
line => !line.trim().startsWith(commentStart), | |
) | |
lines.splice(linkLineIndex, 0, linkLine) | |
// add empty line after the link if there isn't one already | |
if (lines[linkLineIndex + 1].trim() !== '') { | |
lines.splice(linkLineIndex + 1, 0, '') | |
} | |
const newContents = lines.join('\n') | |
fs.writeFileSync(fullFilepath, newContents) | |
}) |
This file contains hidden or 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
{ | |
"name": "fix-links", | |
"version": "1.0.0", | |
"description": "I use this to automatically fix feedback links in my workshops", | |
"bin": "./fix-links.js", | |
"dependencies": { | |
"glob": "7.1.6" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment