download-previous-build.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. await traceAsync(
  42. 'Download and extract previous build',
  43. async () => {
  44. const resp = await fetchWithRetry('https://codeload.github.com/sukkalab/ruleset.skk.moe/tar.gz/master', defaultRequestInit);
  45. if (!resp.body) {
  46. throw new Error('Download previous build failed! No body found');
  47. }
  48. const extract = tarStream.extract();
  49. Readable.fromWeb(resp.body).pipe(zlib.createGunzip()).pipe(extract);
  50. for await (const entry of extract) {
  51. if (entry.header.type !== 'file') {
  52. entry.resume(); // Drain the entry
  53. continue;
  54. }
  55. // filter entry
  56. if (!filesList.some(f => entry.header.name.startsWith(f))) {
  57. entry.resume(); // Drain the entry
  58. continue;
  59. }
  60. const relativeEntryPath = entry.header.name.replace(`ruleset.skk.moe-master${path.sep}`, '');
  61. const targetPath = path.join(import.meta.dir, '..', relativeEntryPath);
  62. await fsp.mkdir(path.dirname(targetPath), { recursive: true });
  63. await pipeline(
  64. entry,
  65. fs.createWriteStream(targetPath)
  66. );
  67. }
  68. }
  69. );
  70. });
  71. if (import.meta.main) {
  72. downloadPreviousBuild();
  73. }