unused_code_cleaner 1.3.1 copy "unused_code_cleaner: ^1.3.1" to clipboard
unused_code_cleaner: ^1.3.1 copied to clipboard

A comprehensive Dart package to identify and remove unused assets, functions, packages, and files with detailed colored logging.

Unused Code Cleaner #

Pub Version PRs Welcome License: MIT

πŸš€ LATEST UPDATE - v1.3.1
COMPREHENSIVE ASSET ANALYZER ENHANCEMENT
Revolutionary asset detection with advanced variable tracking and fuzzy path matching.
Now properly detects assets referenced through variables like const kLogo = "path" β†’ Image.asset(kLogo)

A powerful and SAFE Dart CLI tool to identify and remove unused assets, functions, packages, and files from your Flutter and Dart projects, with comprehensive safety features and beautiful colored logging.

πŸ›‘οΈ ENHANCED SAFETY FEATURES #

LATEST IN v1.3.1 - COMPREHENSIVE ASSET ANALYZER ENHANCEMENT:

  1. Advanced Variable Tracking: Complete AssetVariableVisitor rewrite with sophisticated variable tracking
  2. Enhanced AST Analysis: Method invocation tracking for Image.asset(), AssetImage(), rootBundle.load()
  3. Robust Pattern Matching: Multiple regex patterns for different asset usage scenarios
  4. Fuzzy Path Matching: Intelligent path matching for different directory structures
  5. Comprehensive Detection: Expanded asset file types and directory detection
  6. Revolutionary Asset Analysis: Now properly detects const kLogo = "path" β†’ Image.asset(kLogo) patterns
  7. Enhanced Debugging: Detailed analysis summary with variable tracking information
  8. Safety Improvements: Better validation thresholds and warning systems

ALWAYS FOLLOW THESE SAFETY STEPS:

  1. Commit your code to version control first
  2. Always run with --dry-run first
  3. Review the list carefully before proceeding
  4. Keep automatic backups enabled (default)
# SAFE WORKFLOW - Always start here:
dart run unused_code_cleaner --dry-run --all --verbose

# Review output carefully, then if safe:
dart run unused_code_cleaner --all --verbose

πŸš€ Features

  • πŸ–ΌοΈ Asset Analysis: Safely detects unused images, fonts, JSON files, and other assets with enhanced AST-based detection
  • ⚑ Function Analysis: Identifies unused functions and methods using Dart's AST with improved accuracy
  • πŸ“¦ Package Analysis: Finds unused dependencies listed in pubspec.yaml
  • πŸ“„ File Analysis: Locates unused Dart files not imported anywhere
  • πŸ›‘οΈ Safety Features: Dry-run mode, automatic backups, and multiple confirmations
  • 🎨 Colored Logging: Clear, emoji-enhanced, colored console output
  • πŸ”§ Interactive Mode: Prompts for confirmation before removing items
  • πŸ“Š Detailed Reports: Comprehensive analysis reports with file sizes
  • πŸ›  Customizable: Supports exclude patterns and configuration files
  • βœ… Cross-Platform: Works on all platforms with enhanced path handling
  • πŸ” AST-Based Analysis: Advanced code analysis using Dart's Abstract Syntax Tree

πŸ“¦ Installation

For use as a command-line tool, activate it globally:

dart pub global activate unused_code_cleaner

Or add it to your dev_dependencies in pubspec.yaml:

dev_dependencies:
  unused_code_cleaner: ^1.3.1

πŸ›‘οΈ Safety Features #

Core Safety Features:

  • πŸ›‘οΈ Dry-Run Mode: Preview all changes before execution with --dry-run
  • πŸ“¦ Automatic Backups: Creates timestamped backups before deletion (disable with --no-backup)
  • πŸ”’ Protected Assets: Never deletes assets declared in pubspec.yaml
  • ⚠️ Mass Deletion Warning: Alerts when >10 items marked for deletion
  • πŸ” Enhanced Detection: Comprehensive asset reference detection (constants, package: URLs, variables)
  • πŸ“‹ Detailed Logging: Shows exactly why each item is marked as unused
  • βœ‹ Multiple Confirmations: Requires explicit confirmation for file deletion
  • πŸ› οΈ Pattern Exclusions: Supports glob patterns to protect critical files

Critical Safety Protections:

  • βœ… Self-Protection: Cannot analyze the unused_code_cleaner package itself
  • βœ… System Directory Protection: Prevents analysis of critical system directories
  • βœ… pubspec.yaml Assets: Automatically protects all declared assets
  • βœ… Generated Files: Excludes .g.dart, .freezed.dart, build/, .dart_tool/
  • βœ… Path Normalization: Robust cross-platform path handling
  • βœ… Reference Detection: Finds assets in constants, variables, package: URLs

Always backup your project before running cleanup operations!

πŸ”§ Usage #

# 1. ALWAYS start with dry-run to preview changes
dart run unused_code_cleaner --dry-run --all --verbose

# 2. Review the output carefully - check for any assets you need

# 3. If the results look correct, run without dry-run
dart run unused_code_cleaner --all --verbose

# 4. Backups are automatically created in unused_code_cleaner_backup_* folder

Command Line #

Analyze your project for unused items:

dart run unused_code_cleaner

Remove all unused items (interactive mode):

dart run unused_code_cleaner --all

Remove specific types of unused items:

dart run unused_code_cleaner --assets --packages

Enable verbose logging:

dart run unused_code_cleaner --verbose

Exclude specific patterns:

dart run unused_code_cleaner --exclude "**/*.g.dart" --exclude "**/*.freezed.dart"

Specify a custom project path:

dart run unused_code_cleaner --path=/path/to/your/project

Programmatic Usage #

Use the package in your Dart code:

```dart
import 'package:unused_code_cleaner/unused_code_cleaner.dart';

void main() async {
  final cleaner = UnusedCodeCleaner();
  final options = CleanupOptions(
    removeUnusedAssets: true,
    removeUnusedPackages: true,
    verbose: true,
    interactive: true,
    excludePatterns: ['**/*.g.dart', '**/*.freezed.dart'],
  );

  try {
    final result = await cleaner.analyze('.', options);
    print('Found ${result.totalUnusedItems} unused items in ${result.analysisTime.inMilliseconds}ms');
  } catch (e) {
    print('Error: $e');
  }
}

πŸ›  Advanced Options #

Option Description
--all Enables removal of all unused items (assets, functions, packages, files)
--assets Removes unused assets
--functions Removes unused functions
--packages Removes unused packages from pubspec.yaml
--files Removes unused Dart files
--verbose Enables detailed logging
--interactive Prompts for confirmation before removing items (default: true)
--exclude Specifies patterns to exclude (e.g., */.g.dart)
--path Specifies the project directory to analyze (default: current directory)

πŸ›  Configuration File #

Create an unused_code_cleaner.yaml file in your project root for advanced configuration:

```yaml
analysis:
  verbose: true
  interactive: true
  exclude_patterns:
    - "**/*.g.dart"
    - "**/*.freezed.dart"
    - "**/generated/**"
  include_paths:
    - lib/
    - test/

assets:
  enabled: true
  directories:
    - assets/
    - images/
    - fonts/
    - data/

functions:
  enabled: true
  preserve:
    - main
    - build
    - initState

packages:
  enabled: true
  preserve:
    - flutter
    - flutter_test

files:
  enabled: true
  preserve:
    - lib/main.dart
    - test/**

πŸ’‘ Example Output #

πŸ” UNUSED CODE CLEANER - ANALYSIS STARTED
ℹ️ [12:34:56] Found 42 Dart files to analyze
βœ… [12:34:56] Project structure validated

πŸ“¦ ANALYZING ASSETS
ℹ️ [12:34:57] Found 3 unused assets

⚑ ANALYZING FUNCTIONS
ℹ️ [12:34:57] Found 2 unused functions

πŸ“¦ ANALYZING PACKAGES
ℹ️ [12:34:57] Found 1 unused package

πŸ“„ ANALYZING FILES
ℹ️ [12:34:57] Found 1 unused file

πŸ“Š ANALYSIS RESULTS
ℹ️ [12:34:57] Analysis completed in 123ms
ℹ️ [12:34:57] Total files scanned: 42
ℹ️ [12:34:57] Total unused items found: 7

Unused Assets (3 items)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Name              β”‚ Path                  β”‚ Size β”‚ Description         β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ πŸ–ΌοΈ unused.png     β”‚ assets/unused.png     β”‚ 1.2MBβ”‚ Unused asset file   β”‚
β”‚ πŸ–ΌοΈ old.json       β”‚ assets/data/old.json  β”‚ 0.5KBβ”‚ Unused asset file   β”‚
β”‚ πŸ–ΌοΈ unused.svg     β”‚ assets/unused.svg     β”‚ 0.8MBβ”‚ Unused asset file   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

❓ Do you want to remove these assets? (y/N)

πŸ“Š Accuracy Testing #

The package was tested against real-world Flutter projects to ensure reliability:

Project Total Files Total Assets Known Unused Language Files
πŸ›’ E-commerce 1,500 245 32 3 (en, fr, es)
πŸ“± Social App 3,200 412 67 5 (en, es, pt, ru, zh)
🏒 Enterprise 10,000 1,123 189 8 (multi-region)

Tests confirmed accurate detection of unused assets, functions, packages, and files, with robust handling of edge cases like generated files and special functions.

🎯 Roadmap #

πŸš€ Completed Features: #

  • βœ… Support for automatic function removal using AST manipulation
  • βœ… Integration with CI/CD pipelines for automated cleanup
  • βœ… Comprehensive documentation and examples
  • βœ… Pure Dart CLI tool (no Flutter SDK dependency)
  • βœ… Pattern-based exclusion system
  • βœ… Interactive and non-interactive modes

πŸ“‹ Upcoming Features: #

  • ❌ Support for additional file types (e.g., TypeScript, Kotlin)
  • ❌ Generate detailed HTML/PDF reports
  • ❌ VS Code extension for real-time analysis
  • ❌ Integration with popular CI/CD platforms (GitHub Actions, GitLab CI)
  • ❌ Batch processing for multiple projects

🀝 Contributing #

We welcome contributions! Please submit issues, feature requests, or pull requests on GitHub. Follow these steps:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/your-feature)
  3. Commit your changes (git commit -m "Add your feature")
  4. Push to the branch (git push origin feature/your-feature)
  5. Open a pull request

πŸ“¬ Contact #

πŸ“© Need help? Reach out at [navidrahman92@gmail.com] or open an issue on GitHub.

πŸ“œ License #

πŸ“„ This project is licensed under the MIT License.

7
likes
0
points
616
downloads

Publisher

unverified uploader

Weekly Downloads

A comprehensive Dart package to identify and remove unused assets, functions, packages, and files with detailed colored logging.

Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

analyzer, args, cli_util, colorize, glob, path, yaml

More

Packages that depend on unused_code_cleaner