Skip to content

Instantly share code, notes, and snippets.

@kentcdodds
Last active April 19, 2023 04:59
Show Gist options
  • Save kentcdodds/2d44448a8997b9964b1be44cd294d1f5 to your computer and use it in GitHub Desktop.
Save kentcdodds/2d44448a8997b9964b1be44cd294d1f5 to your computer and use it in GitHub Desktop.
I use this to automatically fill in email addresses in feedback forms throughout workshop material
#!/usr/bin/env node
const path = require('path')
const inquirer = require('inquirer')
const replace = require('replace-in-file')
const isCI = require('is-ci')
const spawn = require('cross-spawn')
const fileGlob = process.argv[2] || 'src/**/*.*'
const files = path.isAbsolute(fileGlob)
? fileGlob
: path.join(process.cwd(), fileGlob)
if (isCI) {
console.log(`Not running autofill feedback as we're on CI`)
} else if (process.env.EMAIL) {
const email = process.env.EMAIL
console.log(`Autofilling email address to process.env.EMAIL: "${email}"`)
replaceEmail(email)
} else {
const tryAgain = `If you'd like to try again, run this command:\n\n npx "https://gist.github.com/kentcdodds/2d44448a8997b9964b1be44cd294d1f5"\n`
const prompt = inquirer.prompt([
{
name: 'email',
message: `What's your email address?`,
validate(val) {
if (val && !val.includes('@')) {
return 'email requires an @ sign...'
}
return true
},
},
])
const timeoutId = setTimeout(() => {
console.log(`\n\nPrompt timed out. No worries. ${tryAgain}`)
prompt.ui.close()
}, 60000)
prompt.then(({email} = {}) => {
clearTimeout(timeoutId)
if (!email) {
console.log(
`Not autofilling email because none was provided. No worries. ${tryAgain}`,
)
return
}
replaceEmail(email)
})
}
function replaceEmail(email) {
const options = {
files: [files],
from: /&em=(?!.*@)/,
to: `&em=${encodeURIComponent(email)}`,
}
replace(options)
.then(results => {
const changedFiles = results.filter(file => file.hasChanged)
console.log(
`Updated ${changedFiles.length} files with the email ${email}`,
)
if (changedFiles.length) {
console.log(
'Committing changes for you so your jest watch mode works nicely',
)
spawn.sync('git', ['commit', '-am', 'email autofill', '--no-verify'], {
stdio: 'inherit',
})
}
})
.catch(error => {
console.error('Failed to update files')
console.error(error.stack)
})
}
{
"name": "autofill-feedback-email",
"version": "1.0.0",
"description": "I use this to automatically fill in email addresses in feedback forms throughout workshop material",
"bin": "./autofill-feedback-email.js",
"dependencies": {
"inquirer": "7.0.4",
"replace-in-file": "5.0.2",
"is-ci": "2.0.0",
"cross-spawn": "7.0.1"
}
}
@kentcdodds
Copy link
Author

Based on this I think I'll go with EMAIL :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment