Skip to content

Instantly share code, notes, and snippets.

@zachsa
Created August 8, 2023 10:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zachsa/e9e0751b7cd3f2b18289afa83fcbbff3 to your computer and use it in GitHub Desktop.
Save zachsa/e9e0751b7cd3f2b18289afa83fcbbff3 to your computer and use it in GitHub Desktop.
update-env script
#!/usr/bin/env node
/**
* Usage:
*
* ./update-env.mjs \
* --KEY=value \
* --KEY2=value \
* --key3="Values with spaces need quotes" \
* --K "The assignment operator after a flag is optional"
* etc
*
* or optionally specify a .env path:
* ./update-env.mjs \
* --__ENV_PATH=/path/to/some/file \
* --KEY=value \
* etc
*/
import { existsSync, readFileSync, writeFileSync } from 'fs'
import { join, dirname } from 'path'
import { fileURLToPath } from 'url'
const __dirname = dirname(fileURLToPath(import.meta.url))
function updateEnv(varName, value, envPath) {
if (!existsSync(envPath)) {
writeFileSync(envPath, '')
}
const content = readFileSync(envPath, 'utf8')
const lines = content.split('\n')
let found = false
for (let i = 0; i < lines.length; i++) {
if (lines[i].startsWith(`${varName}=`)) {
lines[i] = `${varName}=${value}`
found = true
break
}
}
if (!found) {
lines.push(`${varName}=${value}`)
}
writeFileSync(
envPath,
lines.filter(line => line.trim() !== '').join('\n') + '\n'
)
}
const args = process.argv.slice(2)
const configs = {}
for (let i = 0; i < args.length; i++) {
if (args[i].startsWith('--')) {
const keySegment = args[i].slice(2)
if (keySegment.includes('=')) {
const [key, value] = keySegment.split('=')
configs[key] = value
} else if (i + 1 < args.length && !args[i + 1].startsWith('--')) {
const key = keySegment
const value = args[++i]
configs[key] = value
} else {
configs[keySegment] = 'true'
}
}
}
if (!Object.keys(configs).length) {
console.log(
'Usage: configure-env.mjs --<CONFIG_NAME>=<CONFIG_VALUE>, --<CONFIG_NAME> <CONFIG_VALUE>, or --<CONFIG_NAME>'
)
process.exit(1)
}
let envPath = join(__dirname, '..', '.env')
if (configs.__ENV_PATH) {
envPath = configs.__ENV_PATH
delete configs.__ENV_PATH
}
for (const [configName, configValue] of Object.entries(configs)) {
updateEnv(configName, configValue, envPath)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment