clean.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * grunt-contrib-clean
  3. * http://gruntjs.com/
  4. *
  5. * Copyright (c) 2013 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. grunt.log.write((options['no-write'] ? 'Not actually cleaning ' : 'Cleaning ') + filepath + '...');
  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 false;
  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 false;
  26. }
  27. }
  28. try {
  29. // Actually delete. Or not.
  30. if (!options['no-write']) {
  31. rimraf.sync(filepath);
  32. }
  33. grunt.log.ok();
  34. } catch (e) {
  35. grunt.log.error();
  36. grunt.fail.warn('Unable to delete "' + filepath + '" file (' + e.message + ').', e);
  37. }
  38. }
  39. grunt.registerMultiTask('clean', 'Clean files and folders.', function() {
  40. // Merge task-specific and/or target-specific options with these defaults.
  41. var options = this.options({
  42. force: grunt.option('force') === true,
  43. 'no-write': grunt.option('no-write') === true,
  44. });
  45. grunt.verbose.writeflags(options, 'Options');
  46. // Clean specified files / dirs.
  47. this.filesSrc.forEach(function(filepath) {
  48. clean(filepath, options);
  49. });
  50. });
  51. };