or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

index.mddocs/

Grunt Contrib Clean

Grunt Contrib Clean is a Grunt plugin that provides safe and flexible file and folder deletion functionality for build processes and project maintenance. It offers comprehensive protection features, multiple configuration formats, and detailed logging for reliable cleanup operations in Grunt workflows.

Package Information

  • Package Name: grunt-contrib-clean
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install grunt-contrib-clean --save-dev

Core Imports

The plugin is designed to be used as a Grunt task plugin. There are no direct exports to import - instead, the plugin registers tasks with the Grunt instance.

In a Gruntfile:

// Load the plugin to register the 'clean' task
grunt.loadNpmTasks('grunt-contrib-clean');

// Alternative: if using load-grunt-tasks
require('load-grunt-tasks')(grunt);

Module Structure:

// The main module exports a single registration function
const cleanPlugin = require('grunt-contrib-clean');
// This exports: function(grunt) { /* registers 'clean' task */ }

The plugin automatically registers the clean multi-task when loaded, making it available for configuration and execution.

Basic Usage

// Simple array of paths to clean
clean: ['path/to/dir/one', 'path/to/dir/two']

// Configure the task in your Gruntfile
grunt.initConfig({
  clean: {
    build: ['tmp/', 'dist/js/'],
    release: ['dist/']
  }
});

// Run the task
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.registerTask('cleanup', ['clean:build']);

Architecture

Grunt Contrib Clean is built around Grunt's multi-task system and follows the standard Grunt plugin architecture:

  • Plugin Registration: The main module exports a function that receives the Grunt instance and registers the clean multi-task
  • Task Processing: Uses Grunt's built-in file processing system (this.filesSrc) to handle glob patterns and file lists
  • Async Operations: Implements asynchronous file deletion using the async library for serial processing
  • Safety Layer: Implements multiple protection mechanisms before delegating to rimraf for actual deletion
  • Error Handling: Integrates with Grunt's logging and error reporting system for consistent user feedback

Key dependencies:

  • rimraf: Cross-platform recursive file/directory deletion
  • async: Provides eachSeries for processing files sequentially to avoid overwhelming the filesystem

Capabilities

Main Module Export

The plugin exports a single function that registers the clean task with Grunt.

/**
 * Main module export - function that registers the clean task
 * @param {Object} grunt - Grunt instance
 */
module.exports = function(grunt) {
  // Registers the 'clean' multi-task
};

Clean Task Registration

The plugin registers a multi-task called 'clean' that removes files and directories specified in the configuration.

// Task registration (handled automatically by grunt.loadNpmTasks)
grunt.registerMultiTask('clean', 'Clean files and folders.', function() {
  // Task implementation
});

Configuration Formats

Short Format

Simple array of file/directory paths for straightforward cleanup.

// Gruntfile configuration
clean: string[]

Usage Examples:

// Clean specific directories
clean: ['tmp/', 'dist/css/', 'dist/js/']

// Clean with glob patterns
clean: ['build/**/*', 'temp/*.tmp']

Medium Format (Named Targets)

Object with named targets, each containing an array of paths to clean.

// Gruntfile configuration
clean: {
  [targetName: string]: string[]
}

Usage Examples:

clean: {
  build: ['tmp/', 'dist/js/'],
  release: ['dist/', 'reports/'],
  css: ['dist/css/*.css', '!dist/css/vendor.css']
}

Long Format (Per-Target Options)

Object with named targets containing detailed configuration including per-target options.

// Gruntfile configuration  
clean: {
  [targetName: string]: {
    src: string[];
    options?: CleanOptions;
  }
}

Usage Examples:

clean: {
  build: {
    src: ['tmp/'],
    options: {
      'no-write': true  // Dry run
    }
  },
  dangerous: {
    src: ['../outside-project/'],
    options: {
      force: true  // Allow deletion outside CWD
    }
  }
}

Global Options

Options that can be applied to all clean targets or specified per-target.

interface CleanOptions {
  /** Override protection against deleting files outside current working directory */
  force?: boolean;
  /** Dry-run mode - logs what would be deleted without actually deleting */
  'no-write'?: boolean;
}

Force Option

Overrides the default protection against deleting files outside the current working directory.

// Global options for all targets
clean: {
  options: {
    force: boolean  // Default: false or grunt.option('force')
  },
  // targets...
}

Usage Examples:

// Enable force globally (dangerous!)
clean: {
  options: {
    force: true
  },
  project: ['../other-project/build/']
}

// Enable force per-target
clean: {
  local: ['tmp/'],
  external: {
    src: ['../shared-cache/'],
    options: { force: true }
  }
}

No-Write Option

Enables dry-run mode where the task logs what would be deleted without actually performing deletions.

// Global or per-target option
'no-write': boolean  // Default: false or grunt.option('no-write')

Usage Examples:

// Global dry-run
clean: {
  options: {
    'no-write': true
  },
  build: ['tmp/', 'dist/']
}

// Per-target dry-run
clean: {
  build: ['tmp/'],
  test: {
    src: ['dist/'],
    options: { 'no-write': true }
  }
}

Globbing Pattern Support

Supports standard glob patterns for flexible file selection.

// Glob pattern examples
clean: {
  // Delete entire folder
  folder: ['path/to/dir/'],
  folder_alt: ['path/to/dir/**'],
  
  // Delete folder contents but keep folder
  contents: ['path/to/dir/*'],
  
  // Delete only subfolders
  subfolders: ['path/to/dir/*/'],
  
  // Delete specific file types
  css: ['path/to/dir/*.css'],
  all_css: ['path/to/dir/**/*.css'],
  
  // Exclude patterns (use ! prefix)
  js_except_min: ['path/to/dir/*.js', '!path/to/dir/*.min.js']
}

Safety Features

The plugin includes multiple safety mechanisms to prevent accidental data loss.

Current Working Directory Protection

Prevents deletion of the current working directory unless explicitly overridden.

// These operations are blocked by default:
clean: ['./', process.cwd()]

// Override with force option:
clean: {
  options: { force: true },
  dangerous: ['./']
}

Outside CWD Protection

Prevents deletion of files outside the current working directory unless explicitly overridden.

// These operations are blocked by default:
clean: ['../other-project/', '/absolute/path/']

// Override with force option:
clean: {
  options: { force: true },
  external: ['../shared-build/']
}

File Existence Checking

Automatically checks if files exist before attempting deletion to avoid errors.

Command Line Interface

The clean task supports various command line execution patterns and options.

// Command execution patterns
grunt clean                    // Run all clean targets
grunt clean:targetName        // Run specific target
grunt clean --option-name     // Run with command line options

Usage Examples:

# Run all configured clean targets
grunt clean

# Run specific clean target
grunt clean:build
grunt clean:release

# Combine with other tasks
grunt build clean:build test

Command Line Options

Options can be passed via command line flags to override configuration.

// Command line option integration
grunt clean --no-write        // Enable dry-run mode
grunt clean --force          // Enable force mode  
grunt clean --verbose        // Enable verbose logging

Usage Examples:

# Dry-run mode - show what would be deleted
grunt clean --no-write

# Force mode - allow deletion outside CWD (dangerous!)
grunt clean --force

# Verbose logging - show detailed operation info
grunt clean --verbose

# Combine options
grunt clean:build --no-write --verbose

Error Handling

The plugin provides comprehensive error handling with detailed error messages and graceful failure modes.

// Error handling patterns and responses
interface ErrorHandling {
  fileNotExists: "skip_silently";     // No error, continues processing
  permissionDenied: "fail_with_error"; // grunt.fail.warn() with details
  cwdProtection: "fail_with_warning";  // grunt.fail.warn() with safety message
  outsideCwdProtection: "fail_with_warning"; // grunt.fail.warn() with safety message
  rimrafError: "fail_with_details";    // grunt.fail.warn() with underlying error
}

Error Categories:

  1. Silent Handling: File/directory doesn't exist - operation continues
  2. Safety Warnings: CWD or outside-CWD protection triggered - task fails with warning
  3. Permission Errors: Insufficient permissions - task fails with detailed error message
  4. Deletion Errors: Underlying filesystem errors - task fails with rimraf error details

Example Error Messages:

// Safety protection errors
"Cannot delete the current working directory."
"Cannot delete files outside the current working directory."

// Deletion errors  
'Unable to delete "path/to/file" file (EACCES: permission denied).'

Error Recovery:

  • Errors in one file don't stop processing of remaining files
  • Each file is processed independently via async.eachSeries
  • Task fails only after attempting all files when errors occur

Logging and Output

Provides detailed logging information about cleanup operations.

// Logging features:
// - Verbose mode shows each file being cleaned
// - Dry-run mode shows what would be cleaned
// - Success messages show total paths cleaned
// - Error messages include file paths and error details

Example Output:

Running "clean:build" (clean) task
Cleaning tmp/file1.js...
Cleaning tmp/file2.js...
Cleaning dist/old.css...
>> 3 paths cleaned.

Done.

Types

Internal Clean Function

Internal function that handles individual file/directory deletion with safety checks.

/**
 * Internal function that handles individual file/directory deletion
 * @param {string} filepath - Path to file or directory to delete
 * @param {CleanOptions} options - Configuration options (force, no-write)
 * @param {Function} done - Callback function called when operation completes
 */
function clean(filepath, options, done) {
  // Safety checks:
  // - Check if file exists (skip if doesn't exist)
  // - Prevent CWD deletion unless force=true
  // - Prevent outside-CWD deletion unless force=true
  // 
  // Deletion:
  // - Log operation (verbose mode)
  // - Skip actual deletion if no-write=true
  // - Use rimraf for actual deletion
  // - Call done() callback with any errors
}

Implementation Details:

  • Returns early via done() if file doesn't exist (no error)
  • Validates against CWD deletion unless options.force is true
  • Validates against outside-CWD deletion unless options.force is true
  • Logs operations in dry-run mode when options['no-write'] is true
  • Uses rimraf library for cross-platform recursive deletion
  • Calls done(error) callback with any deletion errors

Task Configuration Types

// Short format
type CleanConfigShort = string[];

// Medium format
type CleanConfigMedium = {
  [targetName: string]: string[];
};

// Long format
type CleanConfigLong = {
  options?: CleanOptions;
  [targetName: string]: {
    src: string[];
    options?: CleanOptions;
  };
};

// Combined configuration type
type CleanConfig = CleanConfigShort | CleanConfigMedium | CleanConfigLong;

Options Interface

interface CleanOptions {
  /** 
   * Override protection against deleting files outside current working directory
   * Default: false or grunt.option('force')
   */
  force?: boolean;
  
  /** 
   * Dry-run mode - logs what would be deleted without actually deleting
   * Default: false or grunt.option('no-write')
   */
  'no-write'?: boolean;
}