download-previous-build.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. const { fetch } = require('undici');
  2. const tar = require('tar');
  3. const fs = require('fs');
  4. const fse = require('fs-extra');
  5. const { join, resolve } = require('path');
  6. const { tmpdir } = require('os');
  7. const { Readable } = require('stream');
  8. const { pipeline } = require('stream/promises');
  9. const { readFileByLine } = require('./lib/fetch-remote-text-by-line');
  10. const fileExists = (path) => {
  11. return fs.promises.access(path, fs.constants.F_OK)
  12. .then(() => true)
  13. .catch(() => false);
  14. };
  15. (async () => {
  16. const filesList = [];
  17. let allFileExists = true;
  18. for await (const line of readFileByLine(resolve(__dirname, '../.gitignore'))) {
  19. if (
  20. (
  21. line.startsWith('List/')
  22. || line.startsWith('Modules/')
  23. ) && !line.endsWith('/')
  24. ) {
  25. allFileExists = await fileExists(join(__dirname, '..', line));
  26. filesList.push(line);
  27. if (!allFileExists) {
  28. console.log(`File not exists: ${line}`);
  29. }
  30. }
  31. }
  32. if (allFileExists) {
  33. console.log('All files exists, skip download.');
  34. return;
  35. }
  36. console.log('Download previous build.');
  37. const extractedPath = join(tmpdir(), `sukka-surge-last-build-extracted-${Date.now()}`);
  38. const [resp] = await Promise.all([
  39. fetch('https://codeload.github.com/sukkaw/surge/tar.gz/gh-pages'),
  40. fse.ensureDir(extractedPath)
  41. ]);
  42. await pipeline(
  43. Readable.fromWeb(resp.body),
  44. tar.x({
  45. cwd: extractedPath,
  46. filter(p) {
  47. const dir = p.split('/')[1];
  48. return dir === 'List' || dir === 'Modules';
  49. }
  50. })
  51. );
  52. await Promise.all(filesList.map(async p => {
  53. const src = join(extractedPath, 'Surge-gh-pages', p);
  54. if (await fileExists(src)) {
  55. return fse.copy(
  56. src,
  57. join(__dirname, '..', p),
  58. { overwrite: true }
  59. );
  60. }
  61. }));
  62. await fs.promises.unlink(extractedPath).catch(() => { });
  63. })();