recursive-copy.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.recursiveCopy = recursiveCopy;
  6. var _path = _interopRequireDefault(require("path"));
  7. var _fs = require("fs");
  8. var _asyncSema = require("next/dist/compiled/async-sema");
  9. var _isError = _interopRequireDefault(require("./is-error"));
  10. function _interopRequireDefault(obj) {
  11. return obj && obj.__esModule ? obj : {
  12. default: obj
  13. };
  14. }
  15. const COPYFILE_EXCL = _fs.constants.COPYFILE_EXCL;
  16. async function recursiveCopy(source, dest, { concurrency =32 , overwrite =false , filter =()=>true } = {}) {
  17. const cwdPath = process.cwd();
  18. const from = _path.default.resolve(cwdPath, source);
  19. const to = _path.default.resolve(cwdPath, dest);
  20. const sema = new _asyncSema.Sema(concurrency);
  21. // deep copy the file/directory
  22. async function _copy(item, lstats) {
  23. const target = item.replace(from, to);
  24. await sema.acquire();
  25. if (!lstats) {
  26. // after lock on first run
  27. lstats = await _fs.promises.lstat(from);
  28. }
  29. // readdir & lstat do not follow symbolic links
  30. // if part is a symbolic link, follow it with stat
  31. let isFile = lstats.isFile();
  32. let isDirectory = lstats.isDirectory();
  33. if (lstats.isSymbolicLink()) {
  34. const stats = await _fs.promises.stat(item);
  35. isFile = stats.isFile();
  36. isDirectory = stats.isDirectory();
  37. }
  38. if (isDirectory) {
  39. try {
  40. await _fs.promises.mkdir(target, {
  41. recursive: true
  42. });
  43. } catch (err) {
  44. // do not throw `folder already exists` errors
  45. if ((0, _isError).default(err) && err.code !== "EEXIST") {
  46. throw err;
  47. }
  48. }
  49. sema.release();
  50. const files = await _fs.promises.readdir(item, {
  51. withFileTypes: true
  52. });
  53. await Promise.all(files.map((file)=>_copy(_path.default.join(item, file.name), file)));
  54. } else if (isFile && // before we send the path to filter
  55. // we remove the base path (from) and replace \ by / (windows)
  56. filter(item.replace(from, "").replace(/\\/g, "/"))) {
  57. await _fs.promises.copyFile(item, target, overwrite ? undefined : COPYFILE_EXCL);
  58. sema.release();
  59. } else {
  60. sema.release();
  61. }
  62. }
  63. await _copy(from);
  64. }
  65. //# sourceMappingURL=recursive-copy.js.map