index.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. const fs = require('fs')
  2. const path = require('path')
  3. // Update package.json
  4. function updatePkg(dir, fn) {
  5. // Pkg path
  6. const file = path.join(dir, 'package.json')
  7. // Read pkg
  8. let data = fs.readFileSync(file, 'utf-8')
  9. const pkg = JSON.parse(data)
  10. // Update pkg object
  11. fn(pkg)
  12. // Stringify pkg
  13. const regex = /^[ ]+|\t+/m
  14. const res = regex.exec(data)
  15. const indent = res ? res[0] : null
  16. data = JSON.stringify(pkg, null, indent)
  17. // Write pkg
  18. fs.writeFileSync(file, `${data}\n`)
  19. }
  20. // Update pkg.scripts names
  21. function updateScripts(pkg, fn) {
  22. pkg.scripts = Object.fromEntries(
  23. Object.entries(pkg.scripts).map(([key, value]) => [fn(key), value])
  24. )
  25. }
  26. function enable(name) {
  27. if (['_install', '_postinstall'].includes(name)) {
  28. return name.substring(1)
  29. }
  30. return name
  31. }
  32. function disable(name) {
  33. if (['install', 'postinstall'].includes(name)) {
  34. return `_${name}`
  35. }
  36. return name
  37. }
  38. function enableAndSave(dir = process.cwd()) {
  39. updatePkg(dir, (pkg) => updateScripts(pkg, enable))
  40. }
  41. function disableAndSave(dir = process.cwd()) {
  42. updatePkg(dir, (pkg) => updateScripts(pkg, disable))
  43. }
  44. module.exports = {
  45. enableAndSave,
  46. disableAndSave,
  47. }