download-previous-build.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. // mode: 'same-origin'
  36. });
  37. if (resp.status !== 200) {
  38. console.warn('Download previous build failed! Status:', resp.status);
  39. if (resp.status === 404) {
  40. return;
  41. }
  42. }
  43. if (!resp.body) {
  44. throw new Error('Download previous build failed! No body found');
  45. }
  46. const pathPrefix = 'ruleset.skk.moe-master/';
  47. const gunzip = zlib.createGunzip();
  48. const extract = tarExtract(
  49. publicDir,
  50. {
  51. ignore: tarOnIgnore,
  52. map(header) {
  53. header.name = header.name.replace(pathPrefix, '');
  54. return header;
  55. }
  56. }
  57. );
  58. return pipeline(
  59. resp.body,
  60. gunzip,
  61. extract
  62. );
  63. });
  64. });
  65. function tarOnIgnore(_: string, header?: TarEntryHeaders) {
  66. if (header) {
  67. if (header.type !== 'file' && header.type !== 'directory') {
  68. return true;
  69. }
  70. const extname = path.extname(header.name);
  71. if (extname === '.ts') {
  72. return true;
  73. }
  74. }
  75. return false;
  76. }