download-previous-build.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import path from 'node:path';
  2. import { pipeline } from 'node:stream/promises';
  3. import { task } from './trace';
  4. import { defaultRequestInit, fetchWithRetry } from './lib/fetch-retry';
  5. import { extract as tarExtract } from 'tar-fs';
  6. import zlib from 'node:zlib';
  7. import { Readable } from 'node:stream';
  8. const GITHUB_CODELOAD_URL = 'https://codeload.github.com/sukkalab/ruleset.skk.moe/tar.gz/master';
  9. const GITLAB_CODELOAD_URL = 'https://gitlab.com/SukkaW/ruleset.skk.moe/-/archive/master/ruleset.skk.moe-master.tar.gz';
  10. export const downloadPreviousBuild = task(require.main === module, __filename)(async (span) => {
  11. const tarGzUrl = await span.traceChildAsync('get tar.gz url', async () => {
  12. const resp = await fetchWithRetry(GITHUB_CODELOAD_URL, {
  13. ...defaultRequestInit,
  14. method: 'HEAD',
  15. retry: {
  16. retryOnNon2xx: false
  17. }
  18. });
  19. if (resp.status !== 200) {
  20. console.warn('Download previous build from GitHub failed! Status:', resp.status);
  21. console.warn('Switch to GitLab');
  22. return GITLAB_CODELOAD_URL;
  23. }
  24. return GITHUB_CODELOAD_URL;
  25. });
  26. const publicDir = path.resolve(__dirname, '..', 'public');
  27. return span.traceChildAsync('download & extract previoud build', async () => {
  28. const resp = await fetchWithRetry(tarGzUrl, {
  29. headers: {
  30. 'User-Agent': 'curl/8.9.1',
  31. // https://github.com/unjs/giget/issues/97
  32. // https://gitlab.com/gitlab-org/gitlab/-/commit/50c11f278d18fe1f3fb12eb595067216bb58ade2
  33. 'sec-fetch-mode': 'same-origin'
  34. },
  35. // https://github.com/unjs/giget/issues/97
  36. // https://gitlab.com/gitlab-org/gitlab/-/commit/50c11f278d18fe1f3fb12eb595067216bb58ade2
  37. mode: 'same-origin',
  38. retry: {
  39. retryOnNon2xx: false
  40. }
  41. });
  42. if (resp.status !== 200) {
  43. console.warn('Download previous build failed! Status:', resp.status);
  44. if (resp.status === 404) {
  45. return;
  46. }
  47. }
  48. if (!resp.body) {
  49. throw new Error('Download previous build failed! No body found');
  50. }
  51. const pathPrefix = 'ruleset.skk.moe-master/';
  52. const gunzip = zlib.createGunzip();
  53. const extract = tarExtract(
  54. publicDir,
  55. {
  56. ignore(_, header) {
  57. return header?.type !== 'file' && header?.type !== 'directory';
  58. },
  59. map(header) {
  60. header.name = header.name.replace(pathPrefix, '');
  61. return header;
  62. }
  63. }
  64. );
  65. return pipeline(
  66. Readable.fromWeb(resp.body),
  67. gunzip,
  68. extract
  69. );
  70. });
  71. });