2
0

package.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  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(), read()].filter((x) => x).join(' ');
  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 appimage', 'npx electron-builder --linux appimage --x64 --publish never'],
  256. ['linux snap', 'npx electron-builder --linux snap --x64 --publish never'],
  257. ]);
  258. const targets = table.has(key) ? [table.get(key)] : Array.from(table.values());
  259. for (const target of targets) {
  260. /* eslint-disable no-await-in-loop */
  261. await exec(target);
  262. /* eslint-enable no-await-in-loop */
  263. }
  264. break;
  265. }
  266. case 'python': {
  267. writeLine('build python');
  268. await exec('python package.py build version');
  269. await exec('python -m pip install --user build wheel --quiet');
  270. await exec('python -m build --wheel --outdir dist/pypi dist/pypi');
  271. if (read('install')) {
  272. await exec('python -m pip install --force-reinstall dist/pypi/*.whl');
  273. }
  274. break;
  275. }
  276. default: {
  277. writeLine('build');
  278. await rm('dist');
  279. await install();
  280. await build('web');
  281. await build('electron');
  282. await build('python');
  283. break;
  284. }
  285. }
  286. };
  287. const publish = async (target) => {
  288. const GITHUB_TOKEN = process.env.GITHUB_TOKEN;
  289. const GITHUB_USER = process.env.GITHUB_USER;
  290. switch (target || read()) {
  291. case 'web': {
  292. writeLine('publish web');
  293. await build('web');
  294. await rm('dist', 'gh-pages');
  295. const url = `https://x-access-token:${GITHUB_TOKEN}@github.com/${GITHUB_USER}/netron.git`;
  296. await exec(`git clone --depth=1 ${url} --branch gh-pages ./dist/gh-pages 2>&1 > /dev/null`);
  297. writeLine('cp dist/web dist/gh-pages');
  298. const source_dir = dirname('dist', 'web');
  299. const target_dir = dirname('dist', 'gh-pages');
  300. await unlink(target_dir, (file) => file !== '.git');
  301. await copy(source_dir, target_dir);
  302. await exec('git -C dist/gh-pages add --all');
  303. await exec('git -C dist/gh-pages commit --amend --no-edit');
  304. await exec('git -C dist/gh-pages push --force origin gh-pages');
  305. break;
  306. }
  307. case 'electron': {
  308. writeLine('publish electron');
  309. await install();
  310. await exec('npx electron-builder install-app-deps');
  311. await exec('npx electron-builder --mac --universal --publish always');
  312. await exec('npx electron-builder --win --x64 --arm64 --publish always');
  313. await exec('npx electron-builder --linux appimage --x64 --publish always');
  314. await exec('npx electron-builder --linux snap --x64 --publish always');
  315. break;
  316. }
  317. case 'python': {
  318. writeLine('publish python');
  319. await build('python');
  320. await exec('python -m pip install --user twine');
  321. await exec('python -m twine upload --non-interactive --skip-existing --verbose dist/pypi/*.whl');
  322. break;
  323. }
  324. case 'cask': {
  325. writeLine('publish cask');
  326. await fork('Homebrew', 'homebrew-cask');
  327. const repository = `https://github.com/${configuration.repository}`;
  328. const url = `${repository}/releases/download/v#{version}/${configuration.productName}-#{version}-mac.zip`;
  329. const sha256 = await hash(url.replace(/#{version}/g, configuration.version), 'sha256');
  330. writeLine('update manifest');
  331. const dir = await mkdir('dist', 'homebrew-cask', 'Casks', 'n');
  332. const file = path.join(dir, 'netron.rb');
  333. await fs.writeFile(file, [
  334. `cask "${configuration.name}" do`,
  335. ` version "${configuration.version}"`,
  336. ` sha256 "${sha256.toLowerCase()}"`,
  337. '',
  338. ` url "${url}"`,
  339. ` name "${configuration.productName}"`,
  340. ` desc "${configuration.description.replace('Visualizer', 'Visualiser')}"`,
  341. ` homepage "${repository}"`,
  342. '',
  343. ' auto_updates true',
  344. '',
  345. ` app "${configuration.productName}.app"`,
  346. '',
  347. ' zap trash: [',
  348. ` "~/Library/Application Support/${configuration.productName}",`,
  349. ` "~/Library/Preferences/${configuration.build.appId}.plist",`,
  350. ` "~/Library/Saved Application State/${configuration.build.appId}.savedState",`,
  351. ' ]',
  352. 'end',
  353. ''
  354. ].join('\n'));
  355. writeLine('git push homebrew-cask');
  356. await exec('git -C dist/homebrew-cask add --all');
  357. await exec(`git -C dist/homebrew-cask commit -m "${configuration.name} ${configuration.version}"`);
  358. await pullrequest('Homebrew', 'homebrew-cask', process.env.GITHUB_TOKEN, {
  359. title: `${configuration.name} ${configuration.version}`,
  360. body: 'Update version and sha256',
  361. head: `${process.env.GITHUB_USER}:master`,
  362. base: 'master'
  363. });
  364. await rm('dist', 'homebrew-cask');
  365. break;
  366. }
  367. case 'winget': {
  368. writeLine('publish winget');
  369. await fork('microsoft', 'winget-pkgs');
  370. const name = configuration.name;
  371. const version = configuration.version;
  372. const product = configuration.productName;
  373. const publisher = configuration.author.name;
  374. const identifier = `${publisher.replace(' ', '')}.${product}`;
  375. const copyright = `Copyright (c) ${publisher}`;
  376. const repository = `https://github.com/${configuration.repository}`;
  377. const url = `${repository}/releases/download/v${version}/${product}-Setup-${version}.exe`;
  378. const content = await fs.readFile(configuration.build.extends, 'utf-8');
  379. const builder = JSON.parse(content);
  380. const extensions = builder.fileAssociations.map((entry) => `- ${entry.ext}`).sort().join('\n');
  381. const sha256 = await hash(url, 'sha256');
  382. const paths = ['dist', 'winget-pkgs', 'manifests', publisher[0].toLowerCase(), publisher.replace(' ', ''), product, version];
  383. await mkdir(...paths);
  384. writeLine('update manifest');
  385. const manifestFile = dirname(...paths, identifier);
  386. await fs.writeFile(`${manifestFile}.yaml`, [
  387. '# yaml-language-server: $schema=https://aka.ms/winget-manifest.version.1.6.0.schema.json',
  388. `PackageIdentifier: ${identifier}`,
  389. `PackageVersion: ${version}`,
  390. 'DefaultLocale: en-US',
  391. 'ManifestType: version',
  392. 'ManifestVersion: 1.6.0',
  393. ''
  394. ].join('\n'));
  395. await fs.writeFile(`${manifestFile}.installer.yaml`, [
  396. '# yaml-language-server: $schema=https://aka.ms/winget-manifest.installer.1.6.0.schema.json',
  397. `PackageIdentifier: ${identifier}`,
  398. `PackageVersion: ${version}`,
  399. 'Platform:',
  400. '- Windows.Desktop',
  401. 'InstallModes:',
  402. '- silent',
  403. '- silentWithProgress',
  404. 'Installers:',
  405. '- Architecture: x86',
  406. ' Scope: user',
  407. ' InstallerType: nullsoft',
  408. ` InstallerUrl: ${url}`,
  409. ` InstallerSha256: ${sha256.toUpperCase()}`,
  410. ' InstallerLocale: en-US',
  411. ' InstallerSwitches:',
  412. ' Custom: /NORESTART',
  413. ' UpgradeBehavior: install',
  414. '- Architecture: arm64',
  415. ' Scope: user',
  416. ' InstallerType: nullsoft',
  417. ` InstallerUrl: ${url}`,
  418. ` InstallerSha256: ${sha256.toUpperCase()}`,
  419. ' InstallerLocale: en-US',
  420. ' InstallerSwitches:',
  421. ' Custom: /NORESTART',
  422. ' UpgradeBehavior: install',
  423. 'FileExtensions:',
  424. extensions,
  425. 'ManifestType: installer',
  426. 'ManifestVersion: 1.6.0',
  427. ''
  428. ].join('\n'));
  429. await fs.writeFile(`${manifestFile}.locale.en-US.yaml`, [
  430. '# yaml-language-server: $schema=https://aka.ms/winget-manifest.defaultLocale.1.6.0.schema.json',
  431. `PackageIdentifier: ${identifier}`,
  432. `PackageVersion: ${version}`,
  433. `PackageName: ${product}`,
  434. 'PackageLocale: en-US',
  435. `PackageUrl: ${repository}`,
  436. `Publisher: ${publisher}`,
  437. `PublisherUrl: ${repository}`,
  438. `PublisherSupportUrl: ${repository}/issues`,
  439. `Author: ${publisher}`,
  440. `License: ${configuration.license}`,
  441. `Copyright: ${copyright}`,
  442. `CopyrightUrl: ${repository}/blob/main/LICENSE`,
  443. `ShortDescription: ${configuration.description}`,
  444. `Description: ${configuration.description}`,
  445. `Moniker: ${name}`,
  446. 'Tags:',
  447. '- machine-learning',
  448. '- deep-learning',
  449. '- neural-network',
  450. 'ManifestType: defaultLocale',
  451. 'ManifestVersion: 1.6.0',
  452. ''
  453. ].join('\n'));
  454. writeLine('git push winget-pkgs');
  455. await exec('git -C dist/winget-pkgs add --all');
  456. await exec(`git -C dist/winget-pkgs commit -m "Update ${configuration.name} to ${configuration.version}"`);
  457. await pullrequest('microsoft', 'winget-pkgs', process.env.WINGET_TOKEN, {
  458. title: `Update ${configuration.productName} to ${configuration.version}`,
  459. body: '',
  460. head: `${process.env.GITHUB_USER}:master`,
  461. base: 'master'
  462. });
  463. await rm('dist', 'winget-pkgs');
  464. break;
  465. }
  466. default: {
  467. writeLine('publish');
  468. await rm('dist');
  469. await install();
  470. await publish('web');
  471. await publish('electron');
  472. await publish('python');
  473. await publish('cask');
  474. await publish('winget');
  475. break;
  476. }
  477. }
  478. };
  479. const lint = async () => {
  480. await install();
  481. writeLine('eslint');
  482. await exec('npx eslint --cache --cache-location ./dist/lint/.eslintcache');
  483. writeLine('ruff');
  484. await exec('python -m ruff check . --quiet');
  485. };
  486. const validate = async () => {
  487. writeLine('lint');
  488. await lint();
  489. writeLine('test');
  490. await exec('node test/models.js tag:validation');
  491. };
  492. const update = async () => {
  493. const filter = new Set(process.argv.length > 3 ? process.argv.slice(3) : []);
  494. if (filter.size === 0) {
  495. const dependencies = { ...configuration.dependencies, ...configuration.devDependencies };
  496. for (const name of Object.keys(dependencies)) {
  497. writeLine(name);
  498. /* eslint-disable no-await-in-loop */
  499. await exec(`npm install --quiet --no-progress --silent --save-exact ${name}@latest`);
  500. /* eslint-enable no-await-in-loop */
  501. }
  502. await install();
  503. }
  504. let targets = [
  505. 'armnn',
  506. 'bigdl',
  507. 'caffe', 'circle', 'cntk', 'coreml',
  508. 'dlc', 'dnn',
  509. 'executorch',
  510. 'gguf',
  511. 'kann', 'keras',
  512. 'mlir', 'mnn', 'mslite', 'megengine',
  513. 'nnabla',
  514. 'onnx', 'om',
  515. 'paddle', 'pytorch',
  516. 'rknn',
  517. 'sentencepiece', 'sklearn',
  518. 'tf',
  519. 'uff',
  520. 'xmodel'
  521. ];
  522. let commands = [
  523. 'sync',
  524. 'install',
  525. 'schema',
  526. 'metadata'
  527. ];
  528. if (filter.size > 0 && targets.some((target) => filter.has(target))) {
  529. targets = targets.filter((target) => filter.has(target));
  530. }
  531. if (filter.size > 0 && commands.some((target) => filter.has(target))) {
  532. commands = commands.filter((command) => filter.has(command));
  533. }
  534. commands = commands.join(' ');
  535. for (const target of targets) {
  536. /* eslint-disable no-await-in-loop */
  537. await exec(`tools/${target} ${commands}`);
  538. /* eslint-enable no-await-in-loop */
  539. }
  540. };
  541. const pull = async () => {
  542. await exec('git fetch --prune origin "refs/tags/*:refs/tags/*"');
  543. const before = await exec('git rev-parse HEAD', 'utf-8');
  544. try {
  545. await exec('git pull --prune --rebase --autostash');
  546. } catch (error) {
  547. writeLine(error.message);
  548. }
  549. const after = await exec('git rev-parse HEAD', 'utf-8');
  550. if (before.trim() !== after.trim()) {
  551. const output = await exec(`git diff --name-only ${before.trim()} ${after.trim()}`, 'utf-8');
  552. const files = new Set(output.split('\n'));
  553. if (files.has('package.json')) {
  554. await clean();
  555. await install();
  556. }
  557. }
  558. };
  559. const coverage = async () => {
  560. await rm('dist', 'nyc');
  561. await mkdir('dist', 'nyc');
  562. await exec('cp package.json dist/nyc');
  563. await exec('cp -R source dist/nyc');
  564. await exec('nyc instrument --compact false source dist/nyc/source');
  565. await exec('nyc --instrument npx electron ./dist/nyc');
  566. };
  567. const forge = async() => {
  568. const command = read();
  569. switch (command) {
  570. case 'install': {
  571. const packages = [
  572. '@electron-forge/cli',
  573. '@electron-forge/core',
  574. '@electron-forge/maker-snap',
  575. '@electron-forge/maker-dmg',
  576. '@electron-forge/maker-zip'
  577. ];
  578. await exec(`npm install ${packages.join(' ')} --no-save`);
  579. break;
  580. }
  581. case 'update': {
  582. const cwd = path.join(dirname(), '..', 'forge');
  583. const node_modules = path.join(cwd, 'node_modules');
  584. const links = path.join(cwd, '.links');
  585. const exists = await access(node_modules);
  586. if (!exists) {
  587. await exec('yarn', null, cwd);
  588. }
  589. await exec('yarn build', null, cwd);
  590. await exec('yarn link:prepare', null, cwd);
  591. await exec(`yarn link @electron-forge/core --link-folder=${links}`);
  592. break;
  593. }
  594. case 'build': {
  595. await exec('npx electron-forge make');
  596. break;
  597. }
  598. default: {
  599. throw new Error(`Unsupported forge command ${command}.`);
  600. }
  601. }
  602. };
  603. const analyze = async () => {
  604. const exists = await access('third_party/tools/codeql');
  605. if (!exists) {
  606. await exec('git clone --depth=1 https://github.com/github/codeql.git third_party/tools/codeql');
  607. }
  608. await rm('dist', 'codeql');
  609. await mkdir('dist', 'codeql', 'netron');
  610. await exec('cp -r publish source test tools dist/codeql/netron/');
  611. await exec('codeql database create dist/codeql/database --source-root dist/codeql/netron --language=javascript --threads=3');
  612. 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');
  613. await exec('cat dist/codeql/results.csv');
  614. };
  615. const version = async () => {
  616. await pull();
  617. const file = dirname('package.json');
  618. let content = await fs.readFile(file, 'utf-8');
  619. content = content.replace(/(\s*"version":\s")(\d\.\d\.\d)(",)/m, (match, p1, p2, p3) => {
  620. const version = Array.from((parseInt(p2.split('.').join(''), 10) + 1).toString()).join('.');
  621. return p1 + version + p3;
  622. });
  623. content = content.replace(/(\s*"date":\s")(.*)(",)/m, (match, p1, p2, p3) => {
  624. const date = new Date().toISOString().split('.').shift().split('T').join(' ');
  625. return p1 + date + p3;
  626. });
  627. await fs.writeFile(file, content, 'utf-8');
  628. await exec('npm install --package-lock-only');
  629. await load();
  630. await exec('git add package.json');
  631. await exec('git add package-lock.json');
  632. await exec(`git commit -m "Update to ${configuration.version}"`);
  633. await exec(`git tag v${configuration.version}`);
  634. await exec('git push');
  635. await exec('git push --tags');
  636. };
  637. const main = async () => {
  638. await load();
  639. try {
  640. const task = read();
  641. switch (task) {
  642. case 'start': await start(); break;
  643. case 'clean': await clean(); break;
  644. case 'purge': await purge(); break;
  645. case 'install': await install(); break;
  646. case 'build': await build(); break;
  647. case 'publish': await publish(); break;
  648. case 'version': await version(); break;
  649. case 'lint': await lint(); break;
  650. case 'validate': await validate(); break;
  651. case 'update': await update(); break;
  652. case 'pull': await pull(); break;
  653. case 'analyze': await analyze(); break;
  654. case 'coverage': await coverage(); break;
  655. case 'forge': await forge(); break;
  656. default: throw new Error(`Unsupported task '${task}'.`);
  657. }
  658. } catch (error) {
  659. if (process.stdout.write) {
  660. process.stdout.write(error.message + os.EOL);
  661. }
  662. process.exit(1);
  663. }
  664. };
  665. await main();