clean.js 1.7 KB

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