šŸ” Code Extractor

function main_v66

Maturity: 34

A cleanup utility function that removes virtual environment directories from all SmartStat sessions while preserving project files, reporting disk space freed and cleanup statistics.

File:
/tf/active/vicechatdev/vice_ai/run_full_cleanup.py
Lines:
12 - 55
Complexity:
moderate

Purpose

This function serves as the main entry point for a comprehensive cleanup operation across all SmartStat sessions. It initializes the necessary configuration and agent executor, measures disk usage before and after cleanup, executes the cleanup of virtual environment directories across all sessions, and provides detailed reporting of the cleanup results including space freed, number of venvs cleaned, and projects preserved. This is useful for maintenance tasks to reclaim disk space by removing temporary virtual environments while keeping important project files intact.

Source Code

def main():
    # Initialize config and agent executor
    config = Config()
    agent_executor = AgentExecutor(config)
    
    print(f"\n{'='*60}")
    print(f"Running FULL cleanup on all SmartStat sessions")
    print(f"{'='*60}\n")
    
    # Get total size before
    import subprocess
    scripts_dir = Path(config.GENERATED_SCRIPTS_FOLDER)
    result = subprocess.run(['du', '-sh', str(scripts_dir)], capture_output=True, text=True)
    size_before = result.stdout.split()[0]
    print(f"Total size BEFORE cleanup: {size_before}")
    
    # Count sessions and projects
    session_count = len([d for d in scripts_dir.iterdir() if d.is_dir()])
    print(f"Total sessions: {session_count}\n")
    
    # Run cleanup on all sessions
    print("Running cleanup...")
    cleanup_result = agent_executor.cleanup_venv_directories()  # No session_id = clean all
    
    if cleanup_result['success']:
        print(f"\nāœ“ Cleanup completed successfully!")
        print(f"  - Total venvs cleaned: {cleanup_result['cleaned_count']}")
        print(f"  - Total projects preserved: {cleanup_result['preserved_count']}")
        print(f"  - Total space freed: {cleanup_result['space_freed_mb'] / 1024:.2f} GB")
    else:
        print(f"\nāœ— Cleanup failed: {cleanup_result.get('error', 'Unknown error')}")
        return 1
    
    # Get size after
    result = subprocess.run(['du', '-sh', str(scripts_dir)], capture_output=True, text=True)
    size_after = result.stdout.split()[0]
    print(f"\nTotal size AFTER cleanup: {size_after}")
    
    print(f"\n{'='*60}")
    print(f"Full cleanup completed successfully!")
    print(f"Before: {size_before} → After: {size_after}")
    print(f"{'='*60}\n")
    
    return 0

Return Value

Returns an integer exit code: 0 for successful completion, 1 if cleanup failed. This follows standard Unix convention for command-line tools where 0 indicates success and non-zero indicates failure.

Dependencies

  • pathlib
  • subprocess
  • smartstat_config
  • agent_executor

Required Imports

from pathlib import Path
from smartstat_config import Config
from agent_executor import AgentExecutor
import subprocess

Usage Example

if __name__ == '__main__':
    import sys
    from pathlib import Path
    from smartstat_config import Config
    from agent_executor import AgentExecutor
    import subprocess
    
    # Run the cleanup
    exit_code = main()
    sys.exit(exit_code)

Best Practices

  • This function should be run with appropriate permissions to delete directories within the configured scripts folder
  • The function is platform-dependent and requires Unix-like systems (Linux/macOS) due to the 'du' command usage
  • Consider backing up important data before running this cleanup operation
  • The function performs cleanup on ALL sessions without confirmation - ensure this is the intended behavior before execution
  • Monitor the output carefully to verify that the correct number of venvs are being cleaned and projects are preserved
  • The function uses subprocess to call system commands which may have security implications if paths are not properly validated
  • Exit codes should be properly handled by the calling process to determine if cleanup was successful

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function main_v65 80.2% similar

    A test function that validates the cleanup functionality of virtual environments in project directories by testing on a specific session, measuring disk space before/after cleanup, and verifying that important files are preserved.

    From: /tf/active/vicechatdev/vice_ai/test_cleanup.py
  • function main_v68 54.7% similar

    A debugging utility function that analyzes and displays execution tracking information for a specific session in a statistical analysis service.

    From: /tf/active/vicechatdev/full_smartstat/debug_execution_tracking.py
  • function file_cleanup 51.0% similar

    Removes files older than 60 seconds from the './static/files/' directory.

    From: /tf/active/vicechatdev/datacapture_integrated.py
  • function main_v60 49.7% similar

    Command-line interface function that orchestrates the cleaning of ChromaDB collections by removing duplicates and similar documents, with options to skip collections and customize the cleaning process.

    From: /tf/active/vicechatdev/chromadb-cleanup/main.py
  • class SmartStatConfig 48.9% similar

    Configuration class for SmartStat service that manages directory paths and API keys for various LLM providers integrated into Vice AI.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
← Back to Browse