index.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. 'use strict';
  2. var path = require('path');
  3. var globby = require('globby');
  4. var isPathCwd = require('is-path-cwd');
  5. var isPathInCwd = require('is-path-in-cwd');
  6. var objectAssign = require('object-assign');
  7. var Promise = require('pinkie-promise');
  8. var pify = require('pify');
  9. var rimraf = require('rimraf');
  10. var rimrafP = pify(rimraf, Promise);
  11. function safeCheck(file) {
  12. if (isPathCwd(file)) {
  13. throw new Error('Cannot delete the current working directory. Can be overriden with the `force` option.');
  14. }
  15. if (!isPathInCwd(file)) {
  16. throw new Error('Cannot delete files/folders outside the current working directory. Can be overriden with the `force` option.');
  17. }
  18. }
  19. module.exports = function (patterns, opts) {
  20. opts = objectAssign({}, opts);
  21. var force = opts.force;
  22. delete opts.force;
  23. var dryRun = opts.dryRun;
  24. delete opts.dryRun;
  25. return globby(patterns, opts).then(function (files) {
  26. return Promise.all(files.map(function (file) {
  27. if (!force) {
  28. safeCheck(file);
  29. }
  30. file = path.resolve(opts.cwd || '', file);
  31. if (dryRun) {
  32. return Promise.resolve(file);
  33. }
  34. return rimrafP(file).then(function () {
  35. return file;
  36. });
  37. }));
  38. });
  39. };
  40. module.exports.sync = function (patterns, opts) {
  41. opts = objectAssign({}, opts);
  42. var force = opts.force;
  43. delete opts.force;
  44. var dryRun = opts.dryRun;
  45. delete opts.dryRun;
  46. return globby.sync(patterns, opts).map(function (file) {
  47. if (!force) {
  48. safeCheck(file);
  49. }
  50. file = path.resolve(opts.cwd || '', file);
  51. if (!dryRun) {
  52. rimraf.sync(file);
  53. }
  54. return file;
  55. });
  56. };