index.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. 'use strict';
  2. const path = require('path');
  3. const globby = require('globby');
  4. const isPathCwd = require('is-path-cwd');
  5. const isPathInCwd = require('is-path-in-cwd');
  6. const pify = require('pify');
  7. const rimraf = require('rimraf');
  8. const pMap = require('p-map');
  9. const rimrafP = pify(rimraf);
  10. function safeCheck(file) {
  11. if (isPathCwd(file)) {
  12. throw new Error('Cannot delete the current working directory. Can be overridden with the `force` option.');
  13. }
  14. if (!isPathInCwd(file)) {
  15. throw new Error('Cannot delete files/folders outside the current working directory. Can be overridden with the `force` option.');
  16. }
  17. }
  18. const del = (patterns, options) => {
  19. options = Object.assign({}, options);
  20. const {force, dryRun} = options;
  21. delete options.force;
  22. delete options.dryRun;
  23. const mapper = file => {
  24. if (!force) {
  25. safeCheck(file);
  26. }
  27. file = path.resolve(options.cwd || '', file);
  28. if (dryRun) {
  29. return file;
  30. }
  31. return rimrafP(file, {glob: false}).then(() => file);
  32. };
  33. return globby(patterns, options).then(files => pMap(files, mapper, options));
  34. };
  35. module.exports = del;
  36. // TODO: Remove this for the next major release
  37. module.exports.default = del;
  38. module.exports.sync = (patterns, options) => {
  39. options = Object.assign({}, options);
  40. const {force, dryRun} = options;
  41. delete options.force;
  42. delete options.dryRun;
  43. return globby.sync(patterns, options).map(file => {
  44. if (!force) {
  45. safeCheck(file);
  46. }
  47. file = path.resolve(options.cwd || '', file);
  48. if (!dryRun) {
  49. rimraf.sync(file, {glob: false});
  50. }
  51. return file;
  52. });
  53. };