index.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. 'use strict';
  2. var path = require('path');
  3. var globby = require('globby');
  4. var eachAsync = require('each-async');
  5. var isPathCwd = require('is-path-cwd');
  6. var isPathInCwd = require('is-path-in-cwd');
  7. var rimraf = require('rimraf');
  8. var objectAssign = require('object-assign');
  9. function safeCheck(file) {
  10. if (isPathCwd(file)) {
  11. throw new Error('Cannot delete the current working directory. Can be overriden with the `force` option.');
  12. }
  13. if (!isPathInCwd(file)) {
  14. throw new Error('Cannot delete files/folders outside the current working directory. Can be overriden with the `force` option.');
  15. }
  16. }
  17. module.exports = function (patterns, opts, cb) {
  18. if (typeof opts !== 'object') {
  19. cb = opts;
  20. opts = {};
  21. }
  22. opts = objectAssign({}, opts);
  23. cb = cb || function () {};
  24. var force = opts.force;
  25. delete opts.force;
  26. var deletedFiles = [];
  27. globby(patterns, opts, function (err, files) {
  28. if (err) {
  29. cb(err);
  30. return;
  31. }
  32. eachAsync(files, function (el, i, next) {
  33. if (!force) {
  34. safeCheck(el);
  35. }
  36. el = path.resolve(opts.cwd || '', el);
  37. deletedFiles.push(el);
  38. rimraf(el, next);
  39. }, function (err) {
  40. if (err) {
  41. cb(err);
  42. return;
  43. }
  44. cb(null, deletedFiles);
  45. });
  46. });
  47. };
  48. module.exports.sync = function (patterns, opts) {
  49. opts = objectAssign({}, opts);
  50. var force = opts.force;
  51. delete opts.force;
  52. var deletedFiles = [];
  53. globby.sync(patterns, opts).forEach(function (el) {
  54. if (!force) {
  55. safeCheck(el);
  56. }
  57. el = path.resolve(opts.cwd || '', el);
  58. deletedFiles.push(el);
  59. rimraf.sync(el);
  60. });
  61. return deletedFiles;
  62. };