gn-asar.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. const asar = require('asar')
  2. const assert = require('assert')
  3. const fs = require('fs-extra')
  4. const os = require('os')
  5. const path = require('path')
  6. const getArgGroup = (name) => {
  7. const group = []
  8. let inGroup = false
  9. for (const arg of process.argv) {
  10. // At the next flag we stop being in the current group
  11. if (arg.startsWith('--')) inGroup = false
  12. // Push all args in the group
  13. if (inGroup) group.push(arg)
  14. // If we find the start flag, start pushing
  15. if (arg === `--${name}`) inGroup = true
  16. }
  17. return group
  18. }
  19. const base = getArgGroup('base')
  20. const files = getArgGroup('files')
  21. const out = getArgGroup('out')
  22. assert(base.length === 1, 'should have a single base dir')
  23. assert(files.length >= 1, 'should have at least one input file')
  24. assert(out.length === 1, 'should have a single out path')
  25. // Ensure all files are inside the base dir
  26. for (const file of files) {
  27. if (!file.startsWith(base[0])) {
  28. console.error(`Expected all files to be inside the base dir but "${file}" was not in "${base[0]}"`)
  29. process.exit(1)
  30. }
  31. }
  32. const tmpPath = fs.mkdtempSync(path.resolve(os.tmpdir(), 'electron-gn-asar-'))
  33. try {
  34. // Copy all files to a tmp dir to avoid including scrap files in the ASAR
  35. for (const file of files) {
  36. const newLocation = path.resolve(tmpPath, path.relative(base[0], file))
  37. fs.mkdirsSync(path.dirname(newLocation))
  38. fs.writeFileSync(newLocation, fs.readFileSync(file))
  39. }
  40. } catch (err) {
  41. console.error('Unexpected error while generating ASAR', err)
  42. fs.remove(tmpPath)
  43. .then(() => process.exit(1))
  44. .catch(() => process.exit(1))
  45. return
  46. }
  47. // Create the ASAR archive
  48. asar.createPackageWithOptions(tmpPath, out[0], {})
  49. .catch(err => {
  50. const exit = () => {
  51. console.error('Unexpected error while generating ASAR', err)
  52. process.exit(1)
  53. }
  54. fs.remove(tmpPath).then(exit).catch(exit)
  55. }).then(() => fs.remove(tmpPath))