download-previous-build.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import fs from 'fs';
  2. import fsp from 'fs/promises';
  3. import path from 'path';
  4. import { Readable } from 'stream';
  5. import { pipeline } from 'stream/promises';
  6. import { readFileByLine } from './lib/fetch-text-by-line';
  7. import { isCI } from 'ci-info';
  8. import { task } from './lib/trace-runner';
  9. import { defaultRequestInit, fetchWithRetry } from './lib/fetch-retry';
  10. import tarStream from 'tar-stream';
  11. import zlib from 'zlib';
  12. const IS_READING_BUILD_OUTPUT = 1 << 2;
  13. const ALL_FILES_EXISTS = 1 << 3;
  14. export const downloadPreviousBuild = task(import.meta.path, async () => {
  15. const buildOutputList: string[] = [];
  16. let flag = 1 | ALL_FILES_EXISTS;
  17. for await (const line of readFileByLine(path.resolve(import.meta.dir, '../.gitignore'))) {
  18. if (line === '# $ build output') {
  19. flag = flag | IS_READING_BUILD_OUTPUT;
  20. continue;
  21. }
  22. if (!(flag & IS_READING_BUILD_OUTPUT)) {
  23. continue;
  24. }
  25. buildOutputList.push(line);
  26. if (!isCI) {
  27. // Bun.file().exists() doesn't check directory
  28. if (!fs.existsSync(path.join(import.meta.dir, '..', line))) {
  29. flag = flag & ~ALL_FILES_EXISTS;
  30. }
  31. }
  32. }
  33. if (isCI) {
  34. flag = flag & ~ALL_FILES_EXISTS;
  35. }
  36. if (flag & ALL_FILES_EXISTS) {
  37. console.log('All files exists, skip download.');
  38. return;
  39. }
  40. const filesList = buildOutputList.map(f => path.join('ruleset.skk.moe-master', f));
  41. const resp = await fetchWithRetry('https://codeload.github.com/sukkalab/ruleset.skk.moe/tar.gz/master', defaultRequestInit);
  42. if (!resp.body) {
  43. throw new Error('Download previous build failed! No body found');
  44. }
  45. const extract = tarStream.extract();
  46. const gunzip = zlib.createGunzip();
  47. pipeline(
  48. resp.body as any,
  49. gunzip,
  50. extract
  51. );
  52. const pathPrefix = `ruleset.skk.moe-master${path.sep}`;
  53. for await (const entry of extract) {
  54. if (entry.header.type !== 'file') {
  55. entry.resume(); // Drain the entry
  56. continue;
  57. }
  58. // filter entry
  59. if (!filesList.some(f => entry.header.name.startsWith(f))) {
  60. entry.resume(); // Drain the entry
  61. continue;
  62. }
  63. const relativeEntryPath = entry.header.name.replace(pathPrefix, '');
  64. const targetPath = path.join(import.meta.dir, '..', relativeEntryPath);
  65. await fsp.mkdir(path.dirname(targetPath), { recursive: true });
  66. await pipeline(
  67. entry as any,
  68. fs.createWriteStream(targetPath)
  69. );
  70. }
  71. });
  72. if (import.meta.main) {
  73. downloadPreviousBuild();
  74. }