download-previous-build.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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, traceAsync } 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. Readable.fromWeb(resp.body as any).pipe(zlib.createGunzip()).pipe(extract);
  47. const pathPrefix = `ruleset.skk.moe-master${path.sep}`;
  48. for await (const entry of extract) {
  49. if (entry.header.type !== 'file') {
  50. entry.resume(); // Drain the entry
  51. continue;
  52. }
  53. // filter entry
  54. if (!filesList.some(f => entry.header.name.startsWith(f))) {
  55. entry.resume(); // Drain the entry
  56. continue;
  57. }
  58. const relativeEntryPath = entry.header.name.replace(pathPrefix, '');
  59. const targetPath = path.join(import.meta.dir, '..', relativeEntryPath);
  60. await fsp.mkdir(path.dirname(targetPath), { recursive: true });
  61. await pipeline(
  62. entry,
  63. fs.createWriteStream(targetPath)
  64. );
  65. }
  66. });
  67. if (import.meta.main) {
  68. downloadPreviousBuild();
  69. }