2021-02-23 21:28:23 +01:00
|
|
|
#!/usr/bin/env node
|
|
|
|
|
|
2022-02-22 12:29:26 +01:00
|
|
|
'use strict'
|
|
|
|
|
|
2021-02-23 21:28:23 +01:00
|
|
|
const fs = require('fs')
|
|
|
|
|
|
|
|
|
|
const mapKeys = (object, iteratee) => {
|
|
|
|
|
const result = {}
|
|
|
|
|
for (const key of Object.keys(object)) {
|
|
|
|
|
result[iteratee(key, object)] = object[key]
|
|
|
|
|
}
|
|
|
|
|
return result
|
|
|
|
|
}
|
|
|
|
|
|
2021-02-24 08:54:19 +01:00
|
|
|
const args = process.argv.slice(2)
|
|
|
|
|
if (args.length === 0) {
|
2021-02-23 21:28:23 +01:00
|
|
|
const { description, name, version } = require('./package.json')
|
|
|
|
|
const bin = 'toggle-scripts'
|
|
|
|
|
process.stdout.write(`Usage: ${bin} options...
|
|
|
|
|
|
|
|
|
|
${description}
|
|
|
|
|
|
|
|
|
|
Options
|
2021-02-23 21:54:26 +01:00
|
|
|
+<script> Enable the script <script>, ie remove the prefix \`_\`
|
|
|
|
|
-<script> Disable the script <script>, ie prefix it with \`_\`
|
2021-02-23 21:28:23 +01:00
|
|
|
|
|
|
|
|
Examples
|
|
|
|
|
${bin} +postinstall +preuninstall
|
|
|
|
|
${bin} -postinstall -preuninstall
|
|
|
|
|
|
|
|
|
|
${name} v${version}
|
|
|
|
|
`)
|
|
|
|
|
process.exit()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const plan = { __proto__: null }
|
2021-02-24 08:54:19 +01:00
|
|
|
for (const arg of args) {
|
2021-02-23 21:28:23 +01:00
|
|
|
const action = arg[0]
|
|
|
|
|
const script = arg.slice(1)
|
|
|
|
|
|
|
|
|
|
if (action === '+') {
|
|
|
|
|
plan['_' + script] = script
|
|
|
|
|
} else if (action === '-') {
|
|
|
|
|
plan[script] = '_' + script
|
|
|
|
|
} else {
|
|
|
|
|
throw new Error('invalid param: ' + arg)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-02-24 08:54:19 +01:00
|
|
|
const pkgPath = process.env.npm_package_json || './package.json'
|
2021-02-23 21:28:23 +01:00
|
|
|
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'))
|
|
|
|
|
pkg.scripts = mapKeys(pkg.scripts, (name, scripts) => {
|
|
|
|
|
const newName = plan[name]
|
|
|
|
|
if (newName === undefined) {
|
|
|
|
|
return name
|
|
|
|
|
}
|
|
|
|
|
if (newName in scripts) {
|
|
|
|
|
throw new Error('script already defined: ' + name)
|
|
|
|
|
}
|
|
|
|
|
return newName
|
|
|
|
|
})
|
|
|
|
|
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n')
|