clean.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * grunt-contrib-clean
  3. * https://gruntjs.com/
  4. *
  5. * Copyright (c) 2016 Tim Branyen, contributors
  6. * Licensed under the MIT license.
  7. */
  8. 'use strict';
  9. var async = require('async');
  10. var rimraf = require('rimraf');
  11. module.exports = function(grunt) {
  12. function clean(filepath, options, done) {
  13. if (!grunt.file.exists(filepath)) {
  14. return done();
  15. }
  16. // Only delete cwd or outside cwd if --force enabled. Be careful, people!
  17. if (!options.force) {
  18. if (grunt.file.isPathCwd(filepath)) {
  19. grunt.verbose.error();
  20. grunt.fail.warn('Cannot delete the current working directory.');
  21. return done();
  22. } else if (!grunt.file.isPathInCwd(filepath)) {
  23. grunt.verbose.error();
  24. grunt.fail.warn('Cannot delete files outside the current working directory.');
  25. return done();
  26. }
  27. }
  28. grunt.verbose.writeln((options['no-write'] ? 'Not actually cleaning ' : 'Cleaning ') + filepath + '...');
  29. // Actually delete. Or not.
  30. if (options['no-write']) {
  31. return done();
  32. }
  33. rimraf(filepath, function (err) {
  34. if (err) {
  35. grunt.log.error();
  36. grunt.fail.warn('Unable to delete "' + filepath + '" file (' + err.message + ').', err);
  37. }
  38. done();
  39. });
  40. }
  41. grunt.registerMultiTask('clean', 'Clean files and folders.', function() {
  42. // Merge task-specific and/or target-specific options with these defaults.
  43. var options = this.options({
  44. force: grunt.option('force') === true,
  45. 'no-write': grunt.option('no-write') === true
  46. });
  47. var done = this.async();
  48. // Clean specified files / dirs.
  49. var files = this.filesSrc;
  50. async.eachSeries(files, function (filepath, cb) {
  51. clean(filepath, options, cb);
  52. }, function (err) {
  53. grunt.log.ok(files.length + ' ' + grunt.util.pluralize(files.length, 'path/paths') + ' cleaned.');
  54. done(err);
  55. });
  56. });
  57. };