package.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  1. import * as child_process from 'child_process';
  2. import * as crypto from 'crypto';
  3. import * as fs from 'fs/promises';
  4. import * as os from 'os';
  5. import * as path from 'path';
  6. import * as url from 'url';
  7. const args = process.argv.slice(2);
  8. const read = (match) => {
  9. if (args.length > 0 && (!match || args[0] === match)) {
  10. return args.shift();
  11. }
  12. return null;
  13. };
  14. let configuration = null;
  15. const dirname = (...args) => {
  16. const file = url.fileURLToPath(import.meta.url);
  17. const dir = path.dirname(file);
  18. return path.join(dir, ...args);
  19. };
  20. const load = async () => {
  21. const file = dirname('package.json');
  22. const content = await fs.readFile(file, 'utf-8');
  23. configuration = JSON.parse(content);
  24. };
  25. const clearLine = () => {
  26. if (process.stdout.clearLine) {
  27. process.stdout.clearLine();
  28. }
  29. };
  30. const write = (message) => {
  31. if (process.stdout.write) {
  32. process.stdout.write(message);
  33. }
  34. };
  35. const writeLine = (message) => {
  36. write(message + os.EOL);
  37. };
  38. const access = async (path) => {
  39. try {
  40. await fs.access(path);
  41. return true;
  42. } catch {
  43. return false;
  44. }
  45. };
  46. const rm = async (...args) => {
  47. const dir = dirname(...args);
  48. const exists = await access(dir);
  49. if (exists) {
  50. const paths = path.join(...args);
  51. writeLine(`rm ${paths}`);
  52. const options = { recursive: true, force: true };
  53. await fs.rm(dir, options);
  54. }
  55. };
  56. const mkdir = async (...args) => {
  57. const dir = dirname(...args);
  58. const exists = await access(dir);
  59. if (!exists) {
  60. const paths = path.join(...args);
  61. writeLine(`mkdir ${paths}`);
  62. const options = { recursive: true };
  63. await fs.mkdir(dir, options);
  64. }
  65. return dir;
  66. };
  67. const copy = async (source, target, filter) => {
  68. let files = await fs.readdir(source);
  69. files = filter ? files.filter((file) => filter(file)) : files;
  70. const promises = files.map((file) => fs.copyFile(path.join(source, file), path.join(target, file)));
  71. await Promise.all(promises);
  72. };
  73. const unlink = async (dir, filter) => {
  74. let files = await fs.readdir(dir);
  75. files = filter ? files.filter((file) => filter(file)) : files;
  76. const promises = files.map((file) => fs.unlink(path.join(dir, file)));
  77. await Promise.all(promises);
  78. };
  79. const exec = async (command, encoding, cwd) => {
  80. cwd = cwd || dirname();
  81. if (encoding) {
  82. return child_process.execSync(command, { cwd, encoding });
  83. }
  84. child_process.execSync(command, { cwd, stdio: [0,1,2] });
  85. return '';
  86. };
  87. const sleep = (delay) => {
  88. return new Promise((resolve) => {
  89. setTimeout(resolve, delay);
  90. });
  91. };
  92. const request = async (url, init, status) => {
  93. const response = await fetch(url, init);
  94. if (status !== false && !response.ok) {
  95. throw new Error(`${response.status.toString()} ${response.statusText}`);
  96. }
  97. if (response.body) {
  98. const reader = response.body.getReader();
  99. let position = 0;
  100. const stream = new ReadableStream({
  101. start(controller) {
  102. const read = async () => {
  103. try {
  104. const result = await reader.read();
  105. if (result.done) {
  106. clearLine();
  107. controller.close();
  108. } else {
  109. position += result.value.length;
  110. write(` ${position} bytes\r`);
  111. controller.enqueue(result.value);
  112. read();
  113. }
  114. } catch (error) {
  115. controller.error(error);
  116. }
  117. };
  118. read();
  119. }
  120. });
  121. return new Response(stream, {
  122. status: response.status,
  123. statusText: response.statusText,
  124. headers: response.headers
  125. });
  126. }
  127. return response;
  128. };
  129. const download = async (url) => {
  130. writeLine(`download ${url}`);
  131. const response = await request(url);
  132. return response.arrayBuffer().then((buffer) => new Uint8Array(buffer));
  133. };
  134. const hash = async (url, algorithm) => {
  135. const data = await download(url);
  136. const hash = crypto.createHash(algorithm);
  137. hash.update(data);
  138. return hash.digest('hex');
  139. };
  140. const fork = async (organization, repository) => {
  141. const headers = {
  142. Authorization: `Bearer ${process.env.GITHUB_TOKEN}`
  143. };
  144. writeLine(`github delete ${repository}`);
  145. await request(`https://api.github.com/repos/${process.env.GITHUB_USER}/${repository}`, {
  146. method: 'DELETE',
  147. headers
  148. }, false);
  149. await sleep(4000);
  150. writeLine(`github fork ${repository}`);
  151. await request(`https://api.github.com/repos/${organization}/${repository}/forks`, {
  152. method: 'POST',
  153. headers,
  154. body: ''
  155. });
  156. await sleep(4000);
  157. await rm('dist', repository);
  158. writeLine(`github clone ${repository}`);
  159. await exec(`git clone --depth=2 https://x-access-token:${process.env.GITHUB_TOKEN}@github.com/${process.env.GITHUB_USER}/${repository}.git dist/${repository}`);
  160. };
  161. const pullrequest = async (organization, repository, token, body) => {
  162. writeLine(`github push ${repository}`);
  163. await exec(`git -C dist/${repository} push`);
  164. writeLine(`github pullrequest ${repository}`);
  165. const headers = {
  166. Authorization: `Bearer ${token}`
  167. };
  168. await request(`https://api.github.com/repos/${organization}/${repository}/pulls`, {
  169. method: 'POST',
  170. headers,
  171. body: JSON.stringify(body)
  172. });
  173. };
  174. const clean = async () => {
  175. await rm('dist');
  176. await rm('node_modules');
  177. await rm('package-lock.json');
  178. await rm('yarn.lock');
  179. };
  180. const install = async () => {
  181. const node_modules = dirname('node_modules');
  182. let exists = await access(node_modules);
  183. if (exists) {
  184. const dependencies = { ...configuration.dependencies, ...configuration.devDependencies };
  185. const matches = await Promise.all(Object.entries(dependencies).map(async ([name, version]) => {
  186. const file = path.join('node_modules', name, 'package.json');
  187. const exists = await access(file);
  188. if (exists) {
  189. const content = await fs.readFile(file, 'utf8');
  190. const obj = JSON.parse(content);
  191. return obj.version === version;
  192. }
  193. return false;
  194. }));
  195. exists = matches.every((match) => match);
  196. if (!exists) {
  197. await clean();
  198. }
  199. }
  200. exists = await access(node_modules);
  201. if (!exists) {
  202. await exec('npm install');
  203. }
  204. try {
  205. await exec('python --version', 'utf-8');
  206. await exec('python -m pip install --upgrade --quiet setuptools ruff');
  207. } catch {
  208. // continue regardless of error
  209. }
  210. };
  211. const start = async () => {
  212. await install();
  213. await exec('npx electron .');
  214. };
  215. const purge = async () => {
  216. await clean();
  217. await rm('third_party', 'bin');
  218. await rm('third_party', 'env');
  219. await rm('third_party', 'source');
  220. };
  221. const build = async (target) => {
  222. switch (target || read()) {
  223. case 'web': {
  224. writeLine('build web');
  225. await rm('dist', 'web');
  226. await mkdir('dist', 'web');
  227. writeLine('cp source/dir dist/dir');
  228. const source_dir = dirname('source');
  229. const dist_dir = dirname('dist', 'web');
  230. const extensions = new Set(['html', 'css', 'js', 'json', 'ico', 'png']);
  231. await copy(source_dir, dist_dir, (file) => extensions.has(file.split('.').pop()));
  232. await rm('dist', 'web', 'app.js');
  233. await rm('dist', 'web', 'node.js');
  234. await rm('dist', 'web', 'desktop.mjs');
  235. const contentFile = dirname('dist', 'web', 'index.html');
  236. let content = await fs.readFile(contentFile, 'utf-8');
  237. content = content.replace(/(<meta\s*name="version"\s*content=")(.*)(">)/m, (match, p1, p2, p3) => {
  238. return p1 + configuration.version + p3;
  239. });
  240. content = content.replace(/(<meta\s*name="date"\s*content=")(.*)(">)/m, (match, p1, p2, p3) => {
  241. return p1 + configuration.date + p3;
  242. });
  243. await fs.writeFile(contentFile, content, 'utf-8');
  244. break;
  245. }
  246. case 'electron': {
  247. const key = read();
  248. const target = key ? `electron ${key}` : 'electron';
  249. writeLine(`build ${target}`);
  250. await install();
  251. await exec('npx electron-builder install-app-deps');
  252. const table = new Map([
  253. ['mac', 'npx electron-builder --mac --universal --publish never -c.mac.identity=null'],
  254. ['windows', 'npx electron-builder --win --x64 --arm64 --publish never'],
  255. ['linux', 'npx electron-builder --linux appimage --x64 --publish never']
  256. ]);
  257. const targets = table.has(key) ? [table.get(key)] : Array.from(table.values());
  258. for (const target of targets) {
  259. /* eslint-disable no-await-in-loop */
  260. await exec(target);
  261. /* eslint-enable no-await-in-loop */
  262. }
  263. break;
  264. }
  265. case 'python': {
  266. writeLine('build python');
  267. await exec('python package.py build version');
  268. await exec('python -m pip install --user build wheel --quiet');
  269. await exec('python -m build --wheel --outdir dist/pypi dist/pypi');
  270. if (read('install')) {
  271. await exec('python -m pip install --force-reinstall dist/pypi/*.whl');
  272. }
  273. break;
  274. }
  275. default: {
  276. writeLine('build');
  277. await rm('dist');
  278. await install();
  279. await build('web');
  280. await build('electron');
  281. await build('python');
  282. break;
  283. }
  284. }
  285. };
  286. const publish = async (target) => {
  287. const GITHUB_TOKEN = process.env.GITHUB_TOKEN;
  288. const GITHUB_USER = process.env.GITHUB_USER;
  289. switch (target || read()) {
  290. case 'web': {
  291. writeLine('publish web');
  292. await build('web');
  293. await rm('dist', 'gh-pages');
  294. const url = `https://x-access-token:${GITHUB_TOKEN}@github.com/${GITHUB_USER}/netron.git`;
  295. await exec(`git clone --depth=1 ${url} --branch gh-pages ./dist/gh-pages 2>&1 > /dev/null`);
  296. writeLine('cp dist/web dist/gh-pages');
  297. const source_dir = dirname('dist', 'web');
  298. const target_dir = dirname('dist', 'gh-pages');
  299. await unlink(target_dir, (file) => file !== '.git');
  300. await copy(source_dir, target_dir);
  301. await exec('git -C dist/gh-pages add --all');
  302. await exec('git -C dist/gh-pages commit --amend --no-edit');
  303. await exec('git -C dist/gh-pages push --force origin gh-pages');
  304. break;
  305. }
  306. case 'electron': {
  307. const key = read();
  308. const target = key ? ` ${key}` : '';
  309. writeLine(`publish electron ${target}`);
  310. await install();
  311. await exec('npx electron-builder install-app-deps');
  312. const table = new Map([
  313. ['mac', 'npx electron-builder --mac --universal --publish always'],
  314. ['windows', 'npx electron-builder --win --x64 --arm64 --publish always'],
  315. ['linux', 'npx electron-builder --linux appimage --x64 --publish always']
  316. ]);
  317. const targets = table.has(key) ? [table.get(key)] : Array.from(table.values());
  318. for (const target of targets) {
  319. /* eslint-disable no-await-in-loop */
  320. await exec(target);
  321. /* eslint-enable no-await-in-loop */
  322. }
  323. break;
  324. }
  325. case 'python': {
  326. writeLine('publish python');
  327. await build('python');
  328. await exec('python -m pip install --user twine');
  329. await exec('python -m twine upload --non-interactive --skip-existing --verbose dist/pypi/*.whl');
  330. break;
  331. }
  332. case 'cask': {
  333. writeLine('publish cask');
  334. await fork('Homebrew', 'homebrew-cask');
  335. const repository = `https://github.com/${configuration.repository}`;
  336. const url = `${repository}/releases/download/v#{version}/${configuration.productName}-#{version}-mac.zip`;
  337. const sha256 = await hash(url.replace(/#{version}/g, configuration.version), 'sha256');
  338. writeLine('update manifest');
  339. const dir = await mkdir('dist', 'homebrew-cask', 'Casks', 'n');
  340. const file = path.join(dir, 'netron.rb');
  341. await fs.writeFile(file, [
  342. `cask "${configuration.name}" do`,
  343. ` version "${configuration.version}"`,
  344. ` sha256 "${sha256.toLowerCase()}"`,
  345. '',
  346. ` url "${url}"`,
  347. ` name "${configuration.productName}"`,
  348. ` desc "${configuration.description.replace('Visualizer', 'Visualiser')}"`,
  349. ` homepage "${repository}"`,
  350. '',
  351. ' auto_updates true',
  352. '',
  353. ` app "${configuration.productName}.app"`,
  354. '',
  355. ' zap trash: [',
  356. ` "~/Library/Application Support/${configuration.productName}",`,
  357. ` "~/Library/Preferences/${configuration.build.appId}.plist",`,
  358. ` "~/Library/Saved Application State/${configuration.build.appId}.savedState",`,
  359. ' ]',
  360. 'end',
  361. ''
  362. ].join('\n'));
  363. writeLine('git push homebrew-cask');
  364. await exec('git -C dist/homebrew-cask add --all');
  365. await exec(`git -C dist/homebrew-cask commit -m "${configuration.name} ${configuration.version}"`);
  366. await pullrequest('Homebrew', 'homebrew-cask', process.env.GITHUB_TOKEN, {
  367. title: `${configuration.name} ${configuration.version}`,
  368. body: 'Update version and sha256',
  369. head: `${process.env.GITHUB_USER}:master`,
  370. base: 'master'
  371. });
  372. await rm('dist', 'homebrew-cask');
  373. break;
  374. }
  375. case 'winget': {
  376. writeLine('publish winget');
  377. await fork('microsoft', 'winget-pkgs');
  378. const name = configuration.name;
  379. const version = configuration.version;
  380. const product = configuration.productName;
  381. const publisher = configuration.author.name;
  382. const identifier = `${publisher.replace(' ', '')}.${product}`;
  383. const copyright = `Copyright (c) ${publisher}`;
  384. const repository = `https://github.com/${configuration.repository}`;
  385. const url = `${repository}/releases/download/v${version}/${product}-Setup-${version}.exe`;
  386. const content = await fs.readFile(configuration.build.extends, 'utf-8');
  387. const builder = JSON.parse(content);
  388. const extensions = builder.fileAssociations.map((entry) => `- ${entry.ext}`).sort().join('\n');
  389. const sha256 = await hash(url, 'sha256');
  390. const paths = ['dist', 'winget-pkgs', 'manifests', publisher[0].toLowerCase(), publisher.replace(' ', ''), product, version];
  391. await mkdir(...paths);
  392. writeLine('update manifest');
  393. const manifestFile = dirname(...paths, identifier);
  394. await fs.writeFile(`${manifestFile}.yaml`, [
  395. '# yaml-language-server: $schema=https://aka.ms/winget-manifest.version.1.6.0.schema.json',
  396. `PackageIdentifier: ${identifier}`,
  397. `PackageVersion: ${version}`,
  398. 'DefaultLocale: en-US',
  399. 'ManifestType: version',
  400. 'ManifestVersion: 1.6.0',
  401. ''
  402. ].join('\n'));
  403. await fs.writeFile(`${manifestFile}.installer.yaml`, [
  404. '# yaml-language-server: $schema=https://aka.ms/winget-manifest.installer.1.6.0.schema.json',
  405. `PackageIdentifier: ${identifier}`,
  406. `PackageVersion: ${version}`,
  407. 'Platform:',
  408. '- Windows.Desktop',
  409. 'InstallModes:',
  410. '- silent',
  411. '- silentWithProgress',
  412. 'Installers:',
  413. '- Architecture: x86',
  414. ' Scope: user',
  415. ' InstallerType: nullsoft',
  416. ` InstallerUrl: ${url}`,
  417. ` InstallerSha256: ${sha256.toUpperCase()}`,
  418. ' InstallerLocale: en-US',
  419. ' InstallerSwitches:',
  420. ' Custom: /NORESTART',
  421. ' UpgradeBehavior: install',
  422. '- Architecture: arm64',
  423. ' Scope: user',
  424. ' InstallerType: nullsoft',
  425. ` InstallerUrl: ${url}`,
  426. ` InstallerSha256: ${sha256.toUpperCase()}`,
  427. ' InstallerLocale: en-US',
  428. ' InstallerSwitches:',
  429. ' Custom: /NORESTART',
  430. ' UpgradeBehavior: install',
  431. 'FileExtensions:',
  432. extensions,
  433. 'ManifestType: installer',
  434. 'ManifestVersion: 1.6.0',
  435. ''
  436. ].join('\n'));
  437. await fs.writeFile(`${manifestFile}.locale.en-US.yaml`, [
  438. '# yaml-language-server: $schema=https://aka.ms/winget-manifest.defaultLocale.1.6.0.schema.json',
  439. `PackageIdentifier: ${identifier}`,
  440. `PackageVersion: ${version}`,
  441. `PackageName: ${product}`,
  442. 'PackageLocale: en-US',
  443. `PackageUrl: ${repository}`,
  444. `Publisher: ${publisher}`,
  445. `PublisherUrl: ${repository}`,
  446. `PublisherSupportUrl: ${repository}/issues`,
  447. `Author: ${publisher}`,
  448. `License: ${configuration.license}`,
  449. `Copyright: ${copyright}`,
  450. `CopyrightUrl: ${repository}/blob/main/LICENSE`,
  451. `ShortDescription: ${configuration.description}`,
  452. `Description: ${configuration.description}`,
  453. `Moniker: ${name}`,
  454. 'Tags:',
  455. '- machine-learning',
  456. '- deep-learning',
  457. '- neural-network',
  458. 'ManifestType: defaultLocale',
  459. 'ManifestVersion: 1.6.0',
  460. ''
  461. ].join('\n'));
  462. writeLine('git push winget-pkgs');
  463. await exec('git -C dist/winget-pkgs add --all');
  464. await exec(`git -C dist/winget-pkgs commit -m "Update ${configuration.name} to ${configuration.version}"`);
  465. await pullrequest('microsoft', 'winget-pkgs', process.env.WINGET_TOKEN, {
  466. title: `Update ${configuration.productName} to ${configuration.version}`,
  467. body: '',
  468. head: `${process.env.GITHUB_USER}:master`,
  469. base: 'master'
  470. });
  471. await rm('dist', 'winget-pkgs');
  472. break;
  473. }
  474. default: {
  475. writeLine('publish');
  476. await rm('dist');
  477. await install();
  478. await publish('web');
  479. await publish('electron');
  480. await publish('python');
  481. await publish('cask');
  482. await publish('winget');
  483. break;
  484. }
  485. }
  486. };
  487. const lint = async () => {
  488. await install();
  489. writeLine('eslint');
  490. await exec('npx eslint --cache --cache-location ./dist/lint/.eslintcache');
  491. writeLine('ruff');
  492. await exec('python -m ruff check . --quiet');
  493. };
  494. const test = async (target) => {
  495. let models = true;
  496. while (true) {
  497. /* eslint-disable no-await-in-loop */
  498. if (target === 'desktop' || read('desktop')) {
  499. target = null;
  500. models = false;
  501. await exec('npx playwright install --with-deps');
  502. const host = process.platform === 'linux' && (process.env.GITHUB_ACTIONS || process.env.CI) ? 'xvfb-run -a ' : '';
  503. await exec(`${host}npx playwright test --config=test/playwright.config.js --project=desktop`);
  504. continue;
  505. }
  506. if (target === 'browser' || read('browser')) {
  507. target = null;
  508. models = false;
  509. if (process.platform !== 'win32') {
  510. await exec('npx playwright install --with-deps');
  511. const headed = process.env.GITHUB_ACTIONS || process.env.CI ? '' : ' --headed';
  512. await exec(`npx playwright test --config=test/playwright.config.js --project=browser${headed}`);
  513. }
  514. continue;
  515. }
  516. break;
  517. /* eslint-enable no-await-in-loop */
  518. }
  519. if (models) {
  520. target = target || args.join(' ');
  521. await exec(`node test/models.js ${target}`);
  522. }
  523. };
  524. const validate = async () => {
  525. writeLine('lint');
  526. await lint();
  527. writeLine('test');
  528. await test('tag:validation');
  529. writeLine('test desktop');
  530. await test('desktop');
  531. writeLine('test browser');
  532. await test('browser');
  533. };
  534. const update = async () => {
  535. const filter = new Set(process.argv.length > 3 ? process.argv.slice(3) : []);
  536. if (filter.size === 0) {
  537. const dependencies = { ...configuration.dependencies, ...configuration.devDependencies };
  538. for (const name of Object.keys(dependencies)) {
  539. writeLine(name);
  540. /* eslint-disable no-await-in-loop */
  541. await exec(`npm install --quiet --no-progress --silent --save-exact ${name}@latest`);
  542. /* eslint-enable no-await-in-loop */
  543. }
  544. await install();
  545. }
  546. let targets = [
  547. 'armnn',
  548. 'bigdl',
  549. 'caffe', 'circle', 'cntk', 'coreml',
  550. 'dlc', 'dnn',
  551. 'executorch',
  552. 'gguf',
  553. 'kann', 'keras',
  554. 'mlir', 'mnn', 'mslite', 'megengine',
  555. 'nnabla',
  556. 'onnx', 'om',
  557. 'paddle', 'pytorch',
  558. 'rknn',
  559. 'sentencepiece', 'sklearn',
  560. 'tf',
  561. 'uff',
  562. 'xmodel'
  563. ];
  564. let commands = [
  565. 'sync',
  566. 'install',
  567. 'schema',
  568. 'metadata'
  569. ];
  570. if (filter.size > 0 && targets.some((target) => filter.has(target))) {
  571. targets = targets.filter((target) => filter.has(target));
  572. }
  573. if (filter.size > 0 && commands.some((target) => filter.has(target))) {
  574. commands = commands.filter((command) => filter.has(command));
  575. }
  576. commands = commands.join(' ');
  577. for (const target of targets) {
  578. /* eslint-disable no-await-in-loop */
  579. await exec(`tools/${target} ${commands}`);
  580. /* eslint-enable no-await-in-loop */
  581. }
  582. };
  583. const pull = async () => {
  584. await exec('git fetch --prune origin "refs/tags/*:refs/tags/*"');
  585. const before = await exec('git rev-parse HEAD', 'utf-8');
  586. try {
  587. await exec('git pull --prune --rebase --autostash');
  588. } catch (error) {
  589. writeLine(error.message);
  590. }
  591. const after = await exec('git rev-parse HEAD', 'utf-8');
  592. if (before.trim() !== after.trim()) {
  593. const output = await exec(`git diff --name-only ${before.trim()} ${after.trim()}`, 'utf-8');
  594. const files = new Set(output.split('\n'));
  595. if (files.has('package.json')) {
  596. await clean();
  597. await install();
  598. }
  599. }
  600. };
  601. const coverage = async () => {
  602. await rm('dist', 'nyc');
  603. await mkdir('dist', 'nyc');
  604. await exec('cp package.json dist/nyc');
  605. await exec('cp -R source dist/nyc');
  606. await exec('nyc instrument --compact false source dist/nyc/source');
  607. await exec('nyc --instrument npx electron ./dist/nyc');
  608. };
  609. const forge = async() => {
  610. const command = read();
  611. switch (command) {
  612. case 'install': {
  613. const packages = [
  614. '@electron-forge/cli',
  615. '@electron-forge/core',
  616. '@electron-forge/maker-snap',
  617. '@electron-forge/maker-dmg',
  618. '@electron-forge/maker-zip'
  619. ];
  620. await exec(`npm install ${packages.join(' ')} --no-save`);
  621. break;
  622. }
  623. case 'update': {
  624. const cwd = path.join(dirname(), '..', 'forge');
  625. const node_modules = path.join(cwd, 'node_modules');
  626. const links = path.join(cwd, '.links');
  627. const exists = await access(node_modules);
  628. if (!exists) {
  629. await exec('yarn', null, cwd);
  630. }
  631. await exec('yarn build', null, cwd);
  632. await exec('yarn link:prepare', null, cwd);
  633. await exec(`yarn link @electron-forge/core --link-folder=${links}`);
  634. break;
  635. }
  636. case 'build': {
  637. await exec('npx electron-forge make');
  638. break;
  639. }
  640. default: {
  641. throw new Error(`Unsupported forge command ${command}.`);
  642. }
  643. }
  644. };
  645. const analyze = async () => {
  646. const exists = await access('third_party/tools/codeql');
  647. if (!exists) {
  648. await exec('git clone --depth=1 https://github.com/github/codeql.git third_party/tools/codeql');
  649. }
  650. await rm('dist', 'codeql');
  651. await mkdir('dist', 'codeql', 'netron');
  652. await exec('cp -r publish source test tools dist/codeql/netron/');
  653. await exec('codeql database create dist/codeql/database --source-root dist/codeql/netron --language=javascript --threads=3');
  654. await exec('codeql database analyze dist/codeql/database ./third_party/tools/codeql/javascript/ql/src/codeql-suites/javascript-security-and-quality.qls --format=csv --output=dist/codeql/results.csv --threads=3');
  655. await exec('cat dist/codeql/results.csv');
  656. };
  657. const version = async () => {
  658. await pull();
  659. const file = dirname('package.json');
  660. let content = await fs.readFile(file, 'utf-8');
  661. content = content.replace(/(\s*"version":\s")(\d\.\d\.\d)(",)/m, (match, p1, p2, p3) => {
  662. const version = Array.from((parseInt(p2.split('.').join(''), 10) + 1).toString()).join('.');
  663. return p1 + version + p3;
  664. });
  665. content = content.replace(/(\s*"date":\s")(.*)(",)/m, (match, p1, p2, p3) => {
  666. const date = new Date().toISOString().split('.').shift().split('T').join(' ');
  667. return p1 + date + p3;
  668. });
  669. await fs.writeFile(file, content, 'utf-8');
  670. await exec('npm install --package-lock-only');
  671. await load();
  672. await exec('git add package.json');
  673. await exec('git add package-lock.json');
  674. await exec(`git commit -m "Update to ${configuration.version}"`);
  675. await exec(`git tag v${configuration.version}`);
  676. await exec('git push');
  677. await exec('git push --tags');
  678. };
  679. const main = async () => {
  680. await load();
  681. try {
  682. const task = read();
  683. switch (task) {
  684. case 'start': await start(); break;
  685. case 'clean': await clean(); break;
  686. case 'purge': await purge(); break;
  687. case 'install': await install(); break;
  688. case 'build': await build(); break;
  689. case 'publish': await publish(); break;
  690. case 'version': await version(); break;
  691. case 'lint': await lint(); break;
  692. case 'test': await test(); break;
  693. case 'validate': await validate(); break;
  694. case 'update': await update(); break;
  695. case 'pull': await pull(); break;
  696. case 'analyze': await analyze(); break;
  697. case 'coverage': await coverage(); break;
  698. case 'forge': await forge(); break;
  699. default: throw new Error(`Unsupported task '${task}'.`);
  700. }
  701. } catch (error) {
  702. if (process.stdout.write) {
  703. process.stdout.write(error.message + os.EOL);
  704. }
  705. process.exit(1);
  706. }
  707. };
  708. await main();