download-previous-build.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import path from 'node:path';
  2. import fs from 'node:fs';
  3. import { pipeline } from 'node:stream/promises';
  4. import picocolors from 'picocolors';
  5. import { task } from './trace';
  6. import { extract as tarExtract } from 'tar-fs';
  7. import type { Headers as TarEntryHeaders } from 'tar-fs';
  8. import zlib from 'node:zlib';
  9. import { $fetch } from './lib/make-fetch-happen';
  10. const GITHUB_CODELOAD_URL = 'https://codeload.github.com/sukkalab/ruleset.skk.moe/tar.gz/master';
  11. const GITLAB_CODELOAD_URL = 'https://gitlab.com/SukkaW/ruleset.skk.moe/-/archive/master/ruleset.skk.moe-master.tar.gz';
  12. export const downloadPreviousBuild = task(require.main === module, __filename)(async (span) => {
  13. const publicDir = path.resolve(__dirname, '..', 'public');
  14. if (fs.existsSync(publicDir)) {
  15. console.log(picocolors.blue('Public directory exists, skip downloading previous build'));
  16. return;
  17. }
  18. const tarGzUrl = await span.traceChildAsync('get tar.gz url', async () => {
  19. const resp = await $fetch(GITHUB_CODELOAD_URL, { method: 'HEAD' });
  20. if (resp.status !== 200) {
  21. console.warn('Download previous build from GitHub failed! Status:', resp.status);
  22. console.warn('Switch to GitLab');
  23. return GITLAB_CODELOAD_URL;
  24. }
  25. return GITHUB_CODELOAD_URL;
  26. });
  27. return span.traceChildAsync('download & extract previoud build', async () => {
  28. const resp = await $fetch(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. });
  36. if (resp.status !== 200) {
  37. console.warn('Download previous build failed! Status:', resp.status);
  38. if (resp.status === 404) {
  39. return;
  40. }
  41. }
  42. if (!resp.body) {
  43. throw new Error('Download previous build failed! No body found');
  44. }
  45. const pathPrefix = 'ruleset.skk.moe-master/';
  46. const gunzip = zlib.createGunzip();
  47. const extract = tarExtract(
  48. publicDir,
  49. {
  50. ignore: tarOnIgnore,
  51. map(header) {
  52. header.name = header.name.replace(pathPrefix, '');
  53. return header;
  54. }
  55. }
  56. );
  57. return pipeline(
  58. resp.body,
  59. gunzip,
  60. extract
  61. );
  62. });
  63. });
  64. function tarOnIgnore(_: string, header?: TarEntryHeaders) {
  65. if (header) {
  66. if (header.type !== 'file' && header.type !== 'directory') {
  67. return true;
  68. }
  69. const extname = path.extname(header.name);
  70. if (extname === '.ts') {
  71. return true;
  72. }
  73. }
  74. return false;
  75. }