Last active
December 3, 2020 20:43
-
-
Save kentcdodds/cfc1085d6a653956ab95ea2ee85a26d5 to your computer and use it in GitHub Desktop.
I use this to automatically fix links in my react workshops. (This one's only for the testing-react-apps repo because those markdown files aren't rendered in a UI, the normal one is at https://gist.github.com/kentcdodds/436a77ff8977269e5fee39d9d89956de)
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 projectTitle = require(path.join(process.cwd(), 'package.json')).title | |
const linkRegex = /https?:\/\/ws\.kcd\.im.*?$/m | |
const titleRegex = { | |
'.js': /^\/\/ (?<title>.*)$/, | |
'.md': /^# (?<title>.*)$/, | |
} | |
// update feedback links | |
glob.sync('src/__tests__/**/*.md').forEach(filepath => { | |
const {name: filename, ext} = 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(titleRegex[ext]) | |
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 | |
} | |
if (linkRegex.test(contents)) { | |
const newContents = contents.replace(linkRegex, link) | |
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-feedback-links", | |
"version": "1.0.0", | |
"description": "I use this to automatically fix feedback links in my workshops", | |
"bin": "./fix-feedback-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