SmartPub

pub package License: BSD-3-Clause Alpha Release

Smart dependency management for Flutter and Dart projects

⚠️ Alpha Release: This is an early preview version. Features may change and some functionality is still being refined. Please report any issues on GitHub.

SmartPub is a powerful CLI tool that analyzes your pubspec.yaml file to identify unused dependencies, miscategorized packages, and duplicates. It helps keep your project clean and optimized by providing safe cleanup with automatic backup and restore capabilities.

✨ Features

  • πŸ” Dependency Analysis - Scans your entire project to identify which packages are actually used
  • 🧹 Unused Package Detection - Finds dependencies declared but never imported in your code
  • πŸ“‚ Miscategorization Detection - Identifies packages in wrong sections (e.g., test packages in dependencies)
  • πŸ”„ Duplicate Resolution - Detects packages declared in multiple sections
  • πŸ›‘οΈ Safe Operations - Creates automatic backups before making any changes
  • 🀝 Interactive Mode - Review and approve each change individually
  • πŸ”„ Dry-Run Mode - Preview changes without modifying files
  • πŸ€– CI/CD Integration - Machine-readable output with proper exit codes
  • ⚑ Automatic Fixes - One-command cleanup of all dependency issues
  • πŸ”™ Backup & Restore - Easy restoration if something goes wrong

πŸ“¦ Installation

Alpha Notice: This is an alpha release. Use --pre flag to install pre-release versions.

Add SmartPub to your project:

dart pub global activate smartpub --pre

Or add it to your pubspec.yaml:

dev_dependencies:
  smartpub: ^0.1.0-alpha.1

Then run:

dart pub get

πŸš€ Quick Start

Basic Analysis

Analyze your project's dependencies without making changes:

smartpub

Example Output:

βœ… Analysis complete

πŸ“Š Dependency Analysis Summary:
  Used packages: 8
  Unused packages: 2
  Miscategorized packages: 1
  Duplicate packages: 0

❌ Unused Dependencies (2):
  dependencies:
    - old_package ^1.0.0
  dev_dependencies:
    - unused_test_helper ^2.0.0

⚠️  Miscategorized Dependencies (1):
  - test_package ^1.5.0: dependencies β†’ dev_dependencies (used only in tests)

πŸ’‘ Run with --fix to automatically resolve these issues

Preview Changes

See what would be changed without modifying files:

smartpub --dry-run

Apply Fixes

Automatically fix all issues (creates backup first):

smartpub --fix

πŸ“– Usage Examples

Interactive Mode

Review and approve each change:

smartpub --interactive --fix

CI/CD Integration

Check for issues in automated pipelines:

smartpub --ci

Exit codes:

  • 0: No issues found or operation successful
  • 1: Issues found (in CI mode) or error occurred

Specific Project Directory

Analyze a project in a different directory:

smartpub --project-path /path/to/flutter/project

Restore from Backup

If something goes wrong, restore your original pubspec.yaml:

smartpub --restore

πŸ”§ Detailed CLI Reference

Available Flags and Options

Flag Short Description Default
--help -h Show help message and exit false
--fix Automatically fix dependency issues by removing unused dependencies and moving miscategorized packages false
--interactive -i Prompt for confirmation before making each change. Can be combined with --dry-run to preview changes first false
--dry-run Analyze dependencies and show what changes would be made without actually modifying any files false
--ci Run in CI/CD mode with machine-readable output, no colors, and appropriate exit codes (0=clean, 1=issues) false
--no-color Disable colored output (automatically enabled in CI mode) false
--restore Restore pubspec.yaml from the backup file (pubspec.yaml.bak) false
--project-path Path to the Dart/Flutter project directory . (current directory)

Real-World Usage Scenarios

1. Development Workflow - Daily Cleanup

# Check what needs cleaning without making changes
smartpub --dry-run

Expected Output:

πŸ” Analyzing dependencies in /path/to/project...

πŸ“Š Analysis Results:
  Used packages: 12
  Unused packages: 3
  Miscategorized packages: 1
  Duplicate packages: 0

❌ Unused Dependencies (3):
  dependencies:
    - old_animation_lib ^2.1.0 (never imported)
    - deprecated_utils ^1.0.0 (never imported)
  dev_dependencies:
    - unused_test_helper ^3.2.0 (never imported)

⚠️  Miscategorized Dependencies (1):
  - mockito ^5.4.0: dependencies β†’ dev_dependencies (only used in test files)

πŸ’‘ Run with --fix to automatically resolve these issues
   Backup will be created at pubspec.yaml.bak

2. Safe Automatic Cleanup

# Fix all issues with automatic backup
smartpub --fix

Expected Output:

πŸ” Analyzing dependencies in /path/to/project...
πŸ’Ύ Creating backup: pubspec.yaml.bak

πŸ”§ Applying fixes:
  ❌ Removing unused dependency: old_animation_lib ^2.1.0
  ❌ Removing unused dependency: deprecated_utils ^1.0.0  
  ❌ Removing unused dependency: unused_test_helper ^3.2.0
  πŸ”„ Moving mockito ^5.4.0: dependencies β†’ dev_dependencies

βœ… Successfully updated pubspec.yaml
πŸ“Š Final state: 9 used packages, 0 unused, 0 miscategorized

πŸ’‘ If something went wrong, restore with: smartpub --restore

3. Interactive Review Process

# Review each change before applying
smartpub --interactive --fix

Expected Output:

πŸ” Analyzing dependencies in /path/to/project...

Found 4 issues to fix. Review each change:

❌ Remove unused dependency 'old_animation_lib ^2.1.0' from dependencies?
   This package is declared but never imported in your code.
   [y/N/a/q] (y=yes, N=no, a=yes to all, q=quit): y

❌ Remove unused dependency 'deprecated_utils ^1.0.0' from dependencies?
   This package is declared but never imported in your code.
   [y/N/a/q]: y

πŸ”„ Move 'mockito ^5.4.0' from dependencies to dev_dependencies?
   This package is only used in test files.
   [y/N/a/q]: y

πŸ’Ύ Creating backup: pubspec.yaml.bak
πŸ”§ Applying 3 approved changes...
βœ… Successfully updated pubspec.yaml

4. CI/CD Pipeline Integration

# Check for dependency issues in automated builds
smartpub --ci

Expected Output (Clean Project):

ANALYSIS_STATUS: CLEAN
USED_PACKAGES: 8
UNUSED_PACKAGES: 0
MISCATEGORIZED_PACKAGES: 0
DUPLICATE_PACKAGES: 0
EXIT_CODE: 0

Expected Output (Issues Found):

ANALYSIS_STATUS: ISSUES_FOUND
USED_PACKAGES: 5
UNUSED_PACKAGES: 2
MISCATEGORIZED_PACKAGES: 1
DUPLICATE_PACKAGES: 0
UNUSED_LIST: old_package,unused_helper
MISCATEGORIZED_LIST: test_package:dependencies->dev_dependencies
EXIT_CODE: 1

5. Project Analysis in Different Directory

# Analyze a Flutter project in a different location
smartpub --project-path ~/flutter_projects/my_app --dry-run

Expected Output:

πŸ” Analyzing dependencies in /Users/dev/flutter_projects/my_app...

πŸ“Š Analysis Results:
  Used packages: 15
  Unused packages: 0
  Miscategorized packages: 0
  Duplicate packages: 0

βœ… All dependencies are properly used and categorized!
πŸŽ‰ Your pubspec.yaml is clean and optimized.

Flag Combinations and Effects

Development Combinations

# Preview changes interactively (safest approach)
smartpub --interactive --dry-run

# Fix issues interactively without colors (for screen readers)
smartpub --interactive --fix --no-color

# Quick analysis of specific project
smartpub --project-path ../other-project --dry-run

CI/CD Combinations

# Standard CI check (fails build if issues found)
smartpub --ci

# CI check with custom project path
smartpub --ci --project-path packages/core

# Silent CI check (no output unless issues found)
smartpub --ci --no-color > /dev/null || echo "Dependency issues detected"

Maintenance Combinations

# Clean up without interaction, no colors (for scripts)
smartpub --fix --no-color

# Restore from backup if something went wrong
smartpub --restore

# Check if backup exists before fixing
ls pubspec.yaml.bak 2>/dev/null && echo "Backup exists" || smartpub --fix

Exit Codes Reference

SmartPub uses standard exit codes to indicate operation results:

Exit Code Meaning When It Occurs
0 Success No issues found, or operation completed successfully
1 Issues Found / Error Issues detected (in CI mode), invalid arguments, or runtime error

Exit Code Examples

Success Scenarios (Exit Code 0):

# Clean project analysis
smartpub --ci
echo $?  # Output: 0

# Successful fix operation
smartpub --fix
echo $?  # Output: 0

# Successful restore operation
smartpub --restore
echo $?  # Output: 0

Issue/Error Scenarios (Exit Code 1):

# Issues found in CI mode
smartpub --ci  # Project has unused dependencies
echo $?  # Output: 1

# Invalid arguments
smartpub --unknown-flag
echo $?  # Output: 1

# File not found
smartpub --project-path /nonexistent/path
echo $?  # Output: 1

CI/CD Integration Examples

GitHub Actions

name: Dependency Check
on: [push, pull_request]

jobs:
  dependency-check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: dart-lang/setup-dart@v1
      
      - name: Install dependencies
        run: dart pub get
        
      - name: Check dependency cleanliness
        run: dart pub global activate smartpub && smartpub --ci
        
      - name: Comment on PR if issues found
        if: failure()
        run: echo "::error::Unused or miscategorized dependencies found. Run 'smartpub --fix' locally."

GitLab CI

dependency_audit:
  stage: test
  script:
    - dart pub global activate smartpub
    - smartpub --ci
  allow_failure: false
  only:
    - merge_requests
    - main

Jenkins Pipeline

pipeline {
    agent any
    stages {
        stage('Dependency Check') {
            steps {
                sh 'dart pub global activate smartpub'
                sh 'smartpub --ci'
            }
            post {
                failure {
                    echo 'Dependency issues found. Please run smartpub --fix locally.'
                }
            }
        }
    }
}

Pre-commit Hook

#!/bin/sh
# .git/hooks/pre-commit

echo "Checking dependencies..."
if ! smartpub --ci; then
    echo "❌ Dependency issues found!"
    echo "πŸ’‘ Run 'smartpub --fix' to resolve automatically"
    echo "   or 'smartpub --interactive --fix' to review changes"
    exit 1
fi
echo "βœ… Dependencies are clean"

Advanced Usage Patterns

Batch Processing Multiple Projects

# Check multiple Flutter packages
for dir in packages/*/; do
    echo "Checking $dir..."
    smartpub --project-path "$dir" --ci || echo "Issues in $dir"
done

# Generate report for all packages
echo "Package,Used,Unused,Miscategorized" > dependency_report.csv
for dir in packages/*/; do
    result=$(smartpub --project-path "$dir" --ci 2>/dev/null)
    used=$(echo "$result" | grep "USED_PACKAGES:" | cut -d: -f2)
    unused=$(echo "$result" | grep "UNUSED_PACKAGES:" | cut -d: -f2)
    misc=$(echo "$result" | grep "MISCATEGORIZED_PACKAGES:" | cut -d: -f2)
    echo "$(basename $dir),$used,$unused,$misc" >> dependency_report.csv
done

Integration with Package Scripts

# pubspec.yaml - Add custom scripts for common operations
scripts:
  deps:check: smartpub --ci
  deps:fix: smartpub --fix
  deps:preview: smartpub --dry-run
  deps:interactive: smartpub --interactive --fix
  deps:restore: smartpub --restore
  
  # Combined operations
  deps:clean: smartpub --fix && dart pub get
  deps:audit: smartpub --dry-run && dart pub outdated

Automated Cleanup in Development

# Add to your shell profile (~/.bashrc, ~/.zshrc) for automatic cleanup
alias pubclean='smartpub --fix && dart pub get'
alias pubcheck='smartpub --dry-run'
alias pubaudit='smartpub --ci && dart pub outdated'

# Function for interactive project setup
setup_project() {
    cd "$1" || return 1
    dart pub get
    smartpub --interactive --fix
    dart analyze
    dart test
}

Monorepo Management

# Script for managing dependencies across a monorepo
#!/bin/bash
# check_all_packages.sh

ROOT_DIR=$(pwd)
ISSUES_FOUND=0

find . -name "pubspec.yaml" -not -path "./.*" | while read pubspec; do
    dir=$(dirname "$pubspec")
    echo "Checking $dir..."
    
    cd "$ROOT_DIR/$dir"
    if ! smartpub --ci; then
        echo "❌ Issues found in $dir"
        ISSUES_FOUND=1
    else
        echo "βœ… $dir is clean"
    fi
    cd "$ROOT_DIR"
done

exit $ISSUES_FOUND

Custom Workflow Integration

# Pre-push hook to ensure clean dependencies
#!/bin/sh
# .git/hooks/pre-push

echo "πŸ” Checking dependencies before push..."

if ! smartpub --ci; then
    echo ""
    echo "❌ Dependency issues detected!"
    echo ""
    echo "Options:"
    echo "  1. Fix automatically: smartpub --fix"
    echo "  2. Review changes: smartpub --interactive --fix"
    echo "  3. See what's wrong: smartpub --dry-run"
    echo ""
    read -p "Fix automatically now? [y/N]: " -n 1 -r
    echo
    
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        smartpub --fix
        echo "βœ… Dependencies fixed. Please review and commit changes."
        exit 1  # Still exit 1 to prevent push until changes are committed
    else
        echo "Push cancelled. Please fix dependencies first."
        exit 1
    fi
fi

echo "βœ… Dependencies are clean. Proceeding with push."

Environment-Specific Configurations

Development Environment

# .env or shell configuration for development
export SMARTPUB_DEFAULT_MODE="interactive"
export SMARTPUB_AUTO_BACKUP="true"

# Development aliases
alias pcheck='smartpub --dry-run'
alias pfix='smartpub --interactive --fix'
alias prestore='smartpub --restore'

CI/CD Environment Variables

# GitHub Actions
env:
  SMARTPUB_CI_MODE: "true"
  SMARTPUB_NO_COLOR: "true"

# GitLab CI
variables:
  SMARTPUB_FAIL_ON_ISSUES: "true"
  SMARTPUB_OUTPUT_FORMAT: "machine"

Docker Integration

# Dockerfile for CI with SmartPub
FROM dart:stable

# Install SmartPub globally
RUN dart pub global activate smartpub

# Copy project
COPY . /app
WORKDIR /app

# Install dependencies and check them
RUN dart pub get && \
    smartpub --ci

# Continue with build...

πŸ› οΈ How It Works

  1. Project Scanning - Analyzes all Dart files in your project
  2. Import Detection - Identifies which packages are actually imported
  3. Usage Classification - Determines if packages are used in runtime code, tests, or not at all
  4. Issue Identification - Compares actual usage with pubspec.yaml declarations
  5. Safe Cleanup - Provides options to fix issues with backup protection

πŸ”’ Safety Features

  • Automatic Backups - Creates pubspec.yaml.bak before any modifications
  • Dry-Run Mode - Preview all changes before applying them
  • Interactive Confirmation - Review each change individually
  • Easy Restoration - Simple command to restore from backup
  • Non-Destructive Analysis - Default mode never modifies files

🀝 Contributing

We welcome contributions! Please see our Contributing Guidelines for details.

Development Setup

  1. Clone the repository
  2. Run dart pub get
  3. Run tests with dart test

πŸ“„ License

This project is licensed under the BSD 3-Clause - see the LICENSE file for details.

πŸ”§ Troubleshooting

For comprehensive troubleshooting information, see our detailed Troubleshooting Guide.

Quick Solutions for Common Issues

"No pubspec.yaml found"

# Ensure you're in a Dart/Flutter project root
ls pubspec.yaml

# Or specify the correct project path
smartpub --project-path /path/to/your/flutter/project

"Permission denied"

# Check and fix file permissions
ls -la pubspec.yaml
chmod 644 pubspec.yaml

"Conflicting flags"

# Use flags independently, not together
smartpub --restore    # βœ… Correct
smartpub --dry-run    # βœ… Correct
# smartpub --restore --fix  # ❌ Invalid

CI/CD Exit Code Issues

# Test locally with CI mode
smartpub --ci
echo "Exit code: $?"

For more detailed solutions, debugging techniques, and diagnostic steps, see TROUBLESHOOTING.md.

πŸ§ͺ Alpha Feedback & Testing

We need your help! This alpha release is designed to gather community feedback and identify issues before the stable release.

How to Help

  • Test the tool on your projects and report any issues
  • Share feedback on the CLI interface and user experience
  • Suggest improvements for better dependency management
  • Report bugs with detailed reproduction steps

Alpha Limitations

  • Some edge cases in dependency analysis may not be handled perfectly
  • Performance optimizations are still in progress
  • CLI output formatting may change in future versions
  • Error messages and help text are being refined

πŸ› Issues & Support

Getting Help

Quick Support

  • Documentation: Check README.md and TROUBLESHOOTING.md first
  • Search: Look through existing GitHub issues and discussions

πŸ“ˆ Roadmap

Alpha to Beta (v0.1.x)

  • Improve dependency analysis accuracy based on community feedback
  • Enhance error handling and recovery mechanisms
  • Optimize performance for large projects
  • Refine CLI output and user experience
  • Add more comprehensive test coverage

Beta to Stable (v1.0.0)

  • Support for custom dependency categories
  • Integration with popular IDEs
  • Advanced dependency optimization suggestions
  • Dependency update recommendations
  • Custom rule configuration
  • Plugin system for extensibility

Made with ❀️ for the Flutter and Dart community

Libraries

smartpub
SmartPub - Smart dependency management for Dart/Flutter projects