index.js 1.4 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 overriden with the `force` option.');
  13. }
  14. if (!isPathInCwd(file)) {
  15. throw new Error('Cannot delete files/folders outside the current working directory. Can be overriden with the `force` option.');
  16. }
  17. }
  18. module.exports = (patterns, opts) => {
  19. opts = Object.assign({}, opts);
  20. const force = opts.force;
  21. delete opts.force;
  22. const dryRun = opts.dryRun;
  23. delete opts.dryRun;
  24. const mapper = file => {
  25. if (!force) {
  26. safeCheck(file);
  27. }
  28. file = path.resolve(opts.cwd || '', file);
  29. if (dryRun) {
  30. return file;
  31. }
  32. return rimrafP(file, {glob: false}).then(() => file);
  33. };
  34. return globby(patterns, opts).then(files => pMap(files, mapper, opts));
  35. };
  36. module.exports.sync = (patterns, opts) => {
  37. opts = Object.assign({}, opts);
  38. const force = opts.force;
  39. delete opts.force;
  40. const dryRun = opts.dryRun;
  41. delete opts.dryRun;
  42. return globby.sync(patterns, opts).map(file => {
  43. if (!force) {
  44. safeCheck(file);
  45. }
  46. file = path.resolve(opts.cwd || '', file);
  47. if (!dryRun) {
  48. rimraf.sync(file, {glob: false});
  49. }
  50. return file;
  51. });
  52. };