gn-asar.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. const asar = require('@electron/asar');
  2. const assert = require('node:assert');
  3. const fs = require('node:fs');
  4. const os = require('node:os');
  5. const path = require('node: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.mkdirSync(path.dirname(newLocation), { recursive: true });
  38. fs.writeFileSync(newLocation, fs.readFileSync(file));
  39. }
  40. } catch (err) {
  41. console.error('Unexpected error while generating ASAR', err);
  42. fs.promises.rm(tmpPath, { force: true, recursive: true })
  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.promises.rm(tmpPath, { force: true, recursive: true }).then(exit).catch(exit);
  55. }).then(() => fs.promises.rm(tmpPath, { force: true, recursive: true }));