### Clone and Set Up Development Environment Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/README.md Clone the repository and install dependencies to start development. Use 'bun run dev' to run in development mode. ```bash git clone https://github.com/guhcostan/mac-cleaner-cli.git cd mac-cleaner-cli bun install bun run dev # Run in dev mode bun run test # Run tests bun run lint # Run linter bun run build # Build for production ``` -------------------------------- ### Install Dependencies and Run Scripts Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/CONTRIBUTING.md Commands to clone the repository, install dependencies using Bun, and run development, test, lint, and build scripts. ```bash git clone https://github.com//mac-cleaner-cli.git cd mac-cleaner-cli bun install bun run dev bun run test bun run lint bun run build ``` -------------------------------- ### Uninstall Output Example Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/cli-commands.md This is an example of the output you might see after a successful uninstallation, including the number of apps uninstalled, space freed, and any errors encountered. ```bash Uninstallation Complete ────────────────────── Apps uninstalled: 3 Space freed: 2.5 GB Errors: ✗ SomeApp: Failed to remove (permission denied) ``` -------------------------------- ### Initialize configuration file Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/configuration.md Initializes the configuration file with default settings and example paths. This function creates the configuration file if it does not exist. ```typescript export async function initConfig(): Promise ``` -------------------------------- ### Command Integration Example (scanCommand) Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-commands.md Example of integrating the 'scan' command within the CLI program, including options and error handling. ```typescript // src/index.ts calling scanCommand program .command('scan') .description('Scan for cleanable files') .option('-c, --category ', 'Scan a specific category', parseCategoryId) .option('-v, --verbose', 'Show the largest items in each category') .option('--json', 'Output results as JSON') .option('--no-progress', 'Disable progress bar') .action(async (options) => { try { await scanCommand({ category: options.category, verbose: options.verbose, json: options.json, noProgress: !options.progress, }); } catch (error) { handleCleanExit(error); } }); ``` -------------------------------- ### Example Usage of Interactive Command Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-commands.md Demonstrates how to import and use the interactive command with specific options. This example enables the 'includeRisky' option and sets 'absolutePaths' to false. ```typescript import { interactiveCommand } from './commands'; const result = await interactiveCommand({ includeRisky: true, absolutePaths: false, filePicker: false, }); ``` -------------------------------- ### Install Mac Cleaner CLI Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/docs/index.html Use this command to install the Mac Cleaner CLI tool globally on your system. Ensure you have Node.js and npm installed. ```bash npm install -g mac-cleaner-cli ``` -------------------------------- ### Example Usage of runAllScans Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-scanner.md Demonstrates how to call `runAllScans` with parallel options and a progress callback, then logs the final summary. ```typescript import { runAllScans } from 'mac-cleaner-cli/scanners'; const summary = await runAllScans({ parallel: true, concurrency: 4, onProgress: (completed, total, scanner) => { console.log(`${completed}/${total}: ${scanner.category.name}`); }, }); console.log(`Total: ${summary.totalSize} bytes, ${summary.totalItems} items`); ``` -------------------------------- ### Usage Example for flushDnsCache Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/maintenance-api.md Demonstrates how to import and use the `flushDnsCache` function, including handling success and sudo requirement scenarios. ```typescript import { flushDnsCache } from 'mac-cleaner-cli/maintenance'; const result = await flushDnsCache(); if (result.success) { console.log('DNS cache cleared'); } else if (result.requiresSudo) { console.log('Please run with sudo'); } ``` -------------------------------- ### Example Configuration File Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/configuration.md This JSON object demonstrates the structure and available keys for the configuration file. It includes settings for cleaning old downloads, large files, backup preferences, parallel scanning, and additional paths. ```json { "downloadsDaysOld": 30, "largeFilesMinSize": 524288000, "backupEnabled": false, "backupRetentionDays": 7, "parallelScans": true, "concurrency": 4, "filePicker": false, "extraPaths": { "nodeModules": ["~/Projects", "~/Developer"], "projects": ["~/Projects", "~/Developer", "~/Code"] } } ``` -------------------------------- ### Run mailtrap-local-cli Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/IDEAS.md Starts an SMTP server and a web UI for local email testing without Docker. Useful for development environments. ```bash npx mailtrap-local-cli # → SMTP server: localhost:1025 # → Web UI: localhost:8025 # # Send emails to any address, they'll appear in the UI ``` -------------------------------- ### Example Usage of Uninstall Command Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-commands.md Demonstrates how to import and use the uninstall command with specific options. Use `dryRun: true` to see what would be uninstalled without actually removing files. ```typescript import { uninstallCommand } from './commands'; await uninstallCommand({ yes: false, dryRun: true, }); ``` -------------------------------- ### Install Mac Cleaner CLI Globally Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/README.md Install the tool globally for frequent use. After installation, you can run the command directly from your terminal. ```bash npm install -g mac-cleaner-cli mac-cleaner-cli ``` -------------------------------- ### Get Help and Usage Information Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/docs/index.html Run the command with the --help flag to display all available commands, options, and usage instructions for the Mac Cleaner CLI. ```bash mac-cleaner-cli --help ``` -------------------------------- ### Start Webhook Development Server Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/IDEAS.md Launches a local development server that provides a public URL for receiving webhooks. It forwards incoming requests to a specified localhost port and logs request details. ```bash npx webhook-dev-cli # → Webhook URL: https://abc123.webhook.dev # → Forwarding to: localhost:3000/webhooks # # Incoming webhooks: # POST /stripe → 200 OK (45ms) # POST /github → 500 Error (12ms) [click to see body] ``` -------------------------------- ### Scanner Test File Example Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-scanner.md Each scanner has a corresponding test file. Tests utilize vitest and mock filesystem operations. ```typescript src/scanners/system-cache.test.ts src/scanners/trash.test.ts ... ``` -------------------------------- ### Scan Command Example Usage Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-commands.md Demonstrates how to import and use the scanCommand function internally with specific options for browser cache scanning. ```typescript import { scanCommand } from './commands'; const summary = await scanCommand({ category: 'browser-cache', verbose: true, json: false, }); ``` -------------------------------- ### Initialize Default Configuration File Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-utilities.md Creates a default configuration file at '~/.maccleanerrc', including example settings for extra paths. Returns the path to the created file. ```typescript const path = await initConfig(); console.log(`Created config at ${path}`); ``` -------------------------------- ### Serve Feature Flags Dashboard and API Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/IDEAS.md Starts the feature flag dashboard and API server. Access the dashboard at localhost:3000 and the API at localhost:3001/api/flags. ```bash npx toggle-cli serve ``` -------------------------------- ### Create Feature Branch Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/CONTRIBUTING.md Start new development by creating a dedicated branch from the main branch. ```bash git checkout -b feat/my-feature ``` -------------------------------- ### DNS Cache Flush Success Example Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/maintenance-api.md An example of a successful DNS cache flush operation, indicating success and a confirmation message. ```typescript { success: true, message: 'DNS cache flushed successfully' } ``` -------------------------------- ### Run Mac Cleaner CLI without installation Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/docs/index.html Execute the Mac Cleaner CLI directly using npx without a global or local installation. Requires Node.js 20 or newer. ```bash $ `npx mac-cleaner-cli` Copy ``` -------------------------------- ### CleanCommand Usage Example Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-commands.md Demonstrates how to use the cleanCommand function non-interactively to clean specific categories of files, bypassing confirmation prompts. ```typescript import { cleanCommand } from './commands'; // Non-interactive: clean specific categories const result = await cleanCommand({ categories: ['trash', 'browser-cache'], yes: true, unsafe: false, }); ``` -------------------------------- ### DNS Cache Flush Requires Sudo Example Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/maintenance-api.md An example where flushing the DNS cache fails due to insufficient privileges, indicating the need for sudo. ```typescript { success: false, message: 'DNS cache flush requires administrator privileges', error: 'Run with sudo: sudo mac-cleaner-cli maintenance --dns', requiresSudo: true } ``` -------------------------------- ### Run Mac Cleaner CLI Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/docs/index.html Execute the Mac Cleaner CLI tool to start the cleaning process. This command initiates the interactive cleaning interface. ```bash mac-cleaner-cli ``` -------------------------------- ### Run Mac Cleaner CLI Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/README.md Execute the CLI tool directly using npx. No installation is required. This command initiates a scan, displays found files, allows interactive selection, and cleans chosen items. ```bash npx mac-cleaner-cli ``` -------------------------------- ### Get Default Configuration Object Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-utilities.md Retrieves a copy of the application's built-in default configuration settings. ```typescript const defaults = getDefaultConfig(); ``` -------------------------------- ### Cron Job for Cleaning Trash Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/cli-commands.md This example shows how to schedule a cron job to non-interactively clean only the trash category daily at 2 AM. ```bash 0 2 * * * mac-cleaner-cli clean --categories trash --yes ``` -------------------------------- ### Runtime Dependencies for Mac Cleaner CLI Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/overview.md Lists the runtime dependencies required for the Mac Cleaner CLI. These are installed via npm or yarn. ```json { "@inquirer/checkbox": "^5.0.2", "@inquirer/confirm": "^6.0.2", "chalk": "^5.3.0", "commander": "^15.0.0", "ora": "^9.0.0" } ``` -------------------------------- ### Scriptable JSON Scan for Total Size Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/cli-commands.md Scans for cleanable files and outputs the results in JSON format. This example pipes the output to 'jq' to calculate and display the sum of total sizes across all categories, ideal for scripting. ```bash # Machine-readable output for scripting mac-cleaner-cli scan --json | jq '.categories | map(.totalSize) | add' ``` -------------------------------- ### Get Immediate Directory Items Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-utilities.md Retrieves a list of only the immediate children (files and directories) within a specified directory, without descending into subdirectories. Useful for a quick overview of a directory's contents. ```typescript const items = await getDirectoryItems('~/Downloads'); console.log(`${items.length} files/folders in Downloads`); ``` -------------------------------- ### Initialize and Show Configuration Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/cli-commands.md Use `--init` to create a default configuration file. Use `--show` to display the current configuration, including file overrides. ```bash mac-cleaner-cli config --init ``` ```bash mac-cleaner-cli config --show ``` ```bash # Edit and verify nano ~/.maccleanerrc mac-cleaner-cli config --show ``` -------------------------------- ### Sample Mac Cleaner CLI Configuration with All Options Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/README.md A sample configuration file demonstrating all available options for the Mac Cleaner CLI. This allows for fine-grained control over cleaning behavior and path exclusions. ```json { "defaultCategories": ["trash", "browser-cache"], "excludeCategories": ["large-files"], "downloadsDaysOld": 30, "largeFilesMinSize": 524288000, "backupEnabled": false, "backupRetentionDays": 7, "parallelScans": true, "concurrency": 4, "filePicker": true, "extraPaths": { "nodeModules": ["~/Projects", "~/Developer"], "projects": ["~/Projects", "~/Developer", "~/Code"] } } ``` -------------------------------- ### initConfig Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-utilities.md Creates a default configuration file at `~/.maccleanerrc`. ```APIDOC ## initConfig(): Promise ### Description Create default configuration file. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method N/A (Function Signature) ### Endpoint N/A (Function Signature) ### Returns `Promise` — path to created file ### Creates: `~/.maccleanerrc` with example extraPaths ### Example: ```typescript const path = await initConfig(); console.log(`Created config at ${path}`); ``` ``` -------------------------------- ### Initialize Configuration Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/configuration.md Use this command to create a new configuration file at `~/.maccleanerrc` with default values. The command will not overwrite an existing configuration file. ```bash mac-cleaner-cli config --init ``` -------------------------------- ### CI/CD: Pre-deployment Cleanup Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/cli-commands.md Perform a dry run of cleaning development cache before deployment to preview what would be removed. Use the --yes flag to confirm actions without interactive prompts. ```bash # Pre-deployment cleanup mac-cleaner-cli clean --categories dev-cache --yes --dry-run ``` -------------------------------- ### Run Lint, Test, and Build Commands Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/CONTRIBUTING.md Before submitting changes, ensure that all linting, testing, and build processes pass without errors or regressions. ```bash bun run lint # must pass bun run test # must pass, no regressions bun run build # must compile ``` -------------------------------- ### List and Clean Backups Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/cli-commands.md Use `--list` to view existing backups. Use `--clean` to delete backups older than the configured retention period. ```bash mac-cleaner-cli backup --list ``` ```bash mac-cleaner-cli backup --clean ``` -------------------------------- ### List Available Database Snapshots Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/IDEAS.md Lists all previously saved database snapshots, including their names, sizes, and when they were created. Useful for managing backups. ```bash npx db-snapshot-cli list # before-migration (2.3 MB) - 2 hours ago # clean-state (1.1 MB) - 3 days ago ``` -------------------------------- ### Clean Browser Caches Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/docs/index.html This command targets and cleans the cache data from various web browsers installed on your system. This can free up significant disk space. ```bash mac-cleaner-cli clean-browser ``` -------------------------------- ### Scan for reclaimable space (JSON output) Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/docs/index.html Use this command to get a machine-readable JSON output of the total reclaimable space. This is useful for scripting and integrations. ```bash # See what's reclaimable, as JSON $ mac-cleaner-cli scan --json | jq .totalSize 19758418935 ``` -------------------------------- ### Save Database Snapshot Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/IDEAS.md Creates a compressed snapshot of a local development database and saves it with a given name. Supports various database types like PostgreSQL, MySQL, SQLite, and MongoDB. ```bash npx db-snapshot-cli save "before-migration" # → Saved: postgres://localhost/myapp → before-migration.sql.gz ``` -------------------------------- ### Launch Interactive Mode Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/cli-commands.md Launches the interactive scanning and cleaning workflow. Use options to modify behavior. ```bash mac-cleaner-cli [options] ``` -------------------------------- ### Handle Symlinks Safely with lstat Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/security.md Use `lstat` instead of `stat` to get information about the symlink itself, preventing unintended following of symlinks. This ensures only the symlink is removed, not its target. ```typescript const stats = await lstat(path); // Use lstat, not stat if (stats.isSymbolicLink()) { // Only remove the symlink await unlink(path); } else { // Remove regular file or directory await rm(path, { recursive: true, force: true }); } ``` -------------------------------- ### Load Application Configuration Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-utilities.md Loads the application configuration, searching in a specified path, user's home directory, or using built-in defaults. Configuration files must be valid JSON and under 100 KB. Invalid values are replaced with defaults. ```typescript import { loadConfig } from 'mac-cleaner-cli/utils'; const config = await loadConfig(); console.log(`Downloads older than ${config.downloadsDaysOld} days`); ``` -------------------------------- ### Initialize Feature Flag CLI Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/IDEAS.md Initializes a new feature flag configuration and dashboard. Use this command to set up a new project with feature flagging capabilities. ```bash npx toggle-cli init ``` -------------------------------- ### Recursively Get Directory Size Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-utilities.md Calculates the total size of a directory and all its contents recursively. This function skips symlinks and gracefully handles permission errors by returning 0 for inaccessible subdirectories. ```typescript const size = await getDirectorySize('~/Library/Caches'); ``` -------------------------------- ### Display Current Configuration Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/configuration.md This command prints the currently active configuration, which is a merge of default settings and any overrides from the configuration file. It displays the output as pretty-printed JSON. ```bash mac-cleaner-cli config --show ``` -------------------------------- ### Uninstall Applications Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/cli-commands.md Use this command to uninstall applications and their associated files. It scans for .app bundles, displays their total size, allows interactive selection, and then removes them along with related files. Confirmation is required unless the --yes flag is used. ```bash mac-cleaner-cli uninstall [options] ``` ```bash # Uninstall apps interactively mac-cleaner-cli uninstall ``` ```bash # Uninstall without confirmation mac-cleaner-cli uninstall --yes ``` ```bash # Preview before uninstalling mac-cleaner-cli uninstall --dry-run ``` -------------------------------- ### Get Size of File or Directory Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-utilities.md Asynchronously retrieves the size of a file in bytes or the total size of a directory's contents. It handles symlinks by returning their size and swallows permission errors by returning 0. ```typescript const bytes = await getSize('~/Downloads'); console.log(`Downloads folder: ${bytes} bytes`); ``` -------------------------------- ### Scripting and Automation with mac-cleaner-cli Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/README.md Utilize non-interactive commands for scripting and automation. Use 'scan' for previewing, '--json' for machine-readable output, and 'clean' with '--yes' for automated cleaning. '--dry-run' allows a preview before cleaning specific categories. ```bash npx mac-cleaner-cli scan ``` ```bash npx mac-cleaner-cli scan --json ``` ```bash npx mac-cleaner-cli scan --json --verbose ``` ```bash npx mac-cleaner-cli clean --categories trash,browser-cache,homebrew --yes ``` ```bash npx mac-cleaner-cli clean --categories dev-cache --dry-run ``` ```bash npx mac-cleaner-cli clean --all --yes ``` -------------------------------- ### CLI Commands Reference Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/README.md Reference for all available CLI commands, including their options, flags, behavior, and output formats. ```APIDOC ## CLI Commands Reference This section details all commands available in the mac-cleaner-cli. ### Commands - `scan`: Initiates a scan for cleanable items. - `clean`: Removes identified cleanable items. - `interactive`: Provides an interactive mode for scanning and cleaning. - `uninstall`: Uninstalls the application and its components. - `maintenance`: Performs system maintenance tasks. - `categories`: Lists available cleaning categories. - `config`: Manages configuration settings. - `backup`: Manages backup operations. ### Options and Flags Each command supports various options and flags to customize its behavior. Refer to the individual command documentation for specifics. ### Output Formats Commands can output results in human-readable format, JSON, or other specified formats. ### Exit Codes Defines the exit codes for commands, indicating success or specific error conditions. ### Usage Examples Provides examples for scripting, CI/CD integration, and general usage. ``` -------------------------------- ### Get Items with Filtering Options Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-utilities.md Retrieves a list of files and directories within a given path, with options for recursive searching, minimum age, minimum size, and maximum depth. Useful for identifying cleanable items based on specific criteria. ```typescript // Find large files modified more than 30 days ago const items = await getItems('~', { recursive: true, minAge: 30, minSize: 100 * 1024 * 1024, maxDepth: 5, }); ``` -------------------------------- ### Basic Usage of mac-cleaner-cli Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/README.md Run the cleaner in interactive mode to scan, select, and clean files. Use the --risky flag to include potentially more sensitive categories. ```bash npx mac-cleaner-cli ``` ```bash npx mac-cleaner-cli --risky ``` ```bash npx mac-cleaner-cli --risky -f ``` -------------------------------- ### File Operation Security: spawn vs exec Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/security.md Demonstrates the secure use of `spawn()` with array arguments for file operations to prevent command injection, contrasting it with the vulnerable `exec()` method. ```typescript // GOOD: spawn with array arguments spawn('/usr/bin/open', [url], { detached: true, stdio: 'ignore' }) // BAD: exec with string interpolation exec(`open "${url}"`) // Vulnerable to injection ``` -------------------------------- ### Dry Run Cleaning Preview Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/cli-commands.md This command previews what would be cleaned in the specified categories without actually deleting any files. Useful for verifying selections. ```bash mac-cleaner-cli clean --categories dev-cache --dry-run ``` -------------------------------- ### List All Cache Files Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/docs/index.html This command lists all cache files that can be cleaned by the tool. It helps in identifying potential space savings without performing the actual cleaning. ```bash mac-cleaner-cli list ``` -------------------------------- ### Load configuration file asynchronously Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/configuration.md Asynchronously loads the configuration from a specified path. The configuration is cached after the first load for performance. ```typescript export async function loadConfig(configPath?: string): Promise ``` -------------------------------- ### 30-day downloads cleanup configuration Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/configuration.md Set the number of days to retain downloads before cleanup. This configuration is useful for managing disk space by automatically removing old downloads. ```json { "downloadsDaysOld": 30 } ``` -------------------------------- ### Enforce Configuration File Size Limit Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/security.md Limits configuration files to 100 KB to mitigate denial-of-service attacks. Files exceeding this limit will be skipped, and a warning will be logged. ```typescript if (content.length > 100 * 1024) { // 100 KB max console.warn('Config file too large, using defaults'); continue; } ``` -------------------------------- ### Encrypt and Push Environment Variables Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/IDEAS.md Encrypts a local .env file using a provided password and saves it as an encrypted file. This allows the encrypted file to be safely committed to version control. ```bash npx env-sync-cli push .env --password "team-2024" # → Encrypted and saved to: .env.encrypted # → Safe to commit to git! ``` -------------------------------- ### Show Absolute Paths Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/cli-commands.md Displays full, absolute paths for items instead of truncated notations in the output. ```bash # Show absolute paths (not truncated) mac-cleaner-cli -A ``` -------------------------------- ### Other mac-cleaner-cli Commands Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/README.md Access additional commands to list available cleaning categories, initialize or show configuration settings, and manage backups. ```bash npx mac-cleaner-cli categories ``` ```bash npx mac-cleaner-cli config --init ``` ```bash npx mac-cleaner-cli config --show ``` ```bash npx mac-cleaner-cli backup --list ``` ```bash npx mac-cleaner-cli backup --clean ``` -------------------------------- ### loadConfig Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-utilities.md Loads configuration from a file, falling back to defaults if necessary. Supports custom paths and has a defined search order. ```APIDOC ## loadConfig(configPath?: string): Promise ### Description Load configuration from file or use defaults. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method N/A (Function Signature) ### Endpoint N/A (Function Signature) ### Parameters #### Path Parameters - **configPath** (string, optional) - Optional - Custom config file path ### Returns `Promise` ### Search Order: 1. Custom path (if provided) 2. `~/.maccleanerrc` 3. `~/.config/mac-cleaner-cli/config.json` 4. Built-in defaults ### Validation: - File must be valid JSON and ≤ 100 KB - All fields are validated and invalid values use defaults - Config is cached after first load ### Example: ```typescript import { loadConfig } from 'mac-cleaner-cli/utils'; const config = await loadConfig(); console.log(`Downloads older than ${config.downloadsDaysOld} days`); ``` ``` -------------------------------- ### Uninstall Command Options Interface Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-commands.md Defines the options available for the uninstall command, including yes, dryRun, and noProgress. ```typescript interface UninstallCommandOptions { yes?: boolean; dryRun?: boolean; noProgress?: boolean; } ``` -------------------------------- ### Iterating and Displaying Maintenance Task Results Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/maintenance-api.md Demonstrates how to execute maintenance tasks sequentially and display their success or failure status using a spinner and chalk for colored output. ```typescript for (const task of tasks) { const spinner = ora(task.name).start(); const result = await task.fn(); if (result.success) { spinner.succeed(chalk.green(result.message)); } else { spinner.fail(chalk.red(`${result.message}: ${result.error}`)); } } ``` -------------------------------- ### FULL_DISK_ACCESS_HINT Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-utilities.md Provides a pre-formatted string message to be displayed as a hint when full disk access is missing. ```APIDOC ## FULL_DISK_ACCESS_HINT: string ### Description Pre-formatted hint message for display. ``` -------------------------------- ### configExists Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-utilities.md Checks if any configuration file exists at the standard locations. ```APIDOC ## configExists(): Promise ### Description Check if any configuration file exists. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method N/A (Function Signature) ### Endpoint N/A (Function Signature) ### Returns `Promise` — true if `~/.maccleanerrc` or `~/.config/mac-cleaner-cli/config.json` exists ``` -------------------------------- ### LaunchAgentsScanner Filters Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-scanner.md Explains the LaunchAgentsScanner, which identifies orphaned launch agents by checking ~/Library/LaunchAgents and /Library/LaunchAgents. It filters agents that point to non-existent executables and parses .plist files to extract executable paths. ```typescript class LaunchAgentsScanner extends BaseScanner { category: Category; scan(options?: ScannerOptions): Promise; clean(items: CleanableItem[], dryRun?: boolean): Promise; } ``` -------------------------------- ### Sync Environment Variables via GitHub Gist Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/IDEAS.md Pushes the current environment variables to a GitHub Gist for synchronization across different machines or team members. Requires authentication with GitHub. ```bash npx env-sync-cli push --gist ``` -------------------------------- ### uninstallCommand Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-commands.md Uninstalls applications along with all their related files. It performs a scan, calculates sizes, allows user selection, finds related files, confirms the uninstallation, and displays a summary. ```APIDOC ## uninstallCommand ### Description Uninstall applications with all their related files. This command scans for application bundles, calculates their size including related files, allows interactive selection, and then proceeds with removal after confirmation (unless the --yes flag is used). ### Method `async function uninstallCommand(options: UninstallCommandOptions): Promise` ### Parameters #### Options - **yes** (boolean) - Optional - Skip confirmation prompt. - **dryRun** (boolean) - Optional - Show what would be uninstalled without actually uninstalling. - **noProgress** (boolean) - Optional - Hide progress bar. ### Request Example ```typescript import { uninstallCommand } from './commands'; await uninstallCommand({ yes: false, dryRun: true, }); ``` ### Returns `Promise` ### Behavior Details 1. **Scan**: Finds all .app bundles in /Applications and ~/Applications. 2. **Size**: Calculates app size plus related files. 3. **Select**: Interactive checkbox to choose apps. 4. **Find Related**: Searches for app preferences, caches, support files. 5. **Bundle ID Detection**: Reads CFBundleIdentifier from Info.plist. 6. **Confirm**: Shows all items to be removed (unless --yes). 7. **Uninstall**: Removes app and related paths with progress. 8. **Result**: Shows summary and any errors. ### Related Paths Searched - ~/Library/Application Support/{APP_NAME} - ~/Library/Preferences/{BUNDLE_ID}.plist - ~/Library/Preferences/{APP_NAME}.plist - ~/Library/Caches/{APP_NAME} - ~/Library/Caches/{BUNDLE_ID} - ~/Library/Logs/{APP_NAME} - ~/Library/Saved Application State/{BUNDLE_ID}.savedState - ~/Library/WebKit/{APP_NAME} - ~/Library/HTTPStorages/{BUNDLE_ID} - ~/Library/Containers/{BUNDLE_ID} - ~/Library/Group Containers/*.{APP_NAME} ### Security Considerations - All path operations use `safeRemove()` with `validatePathSafety` checks. - Bundle ID is validated to match reverse domain notation. - Glob patterns are properly escaped to prevent injection. ``` -------------------------------- ### exists(path: string): Promise Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-utilities.md Asynchronously checks if a file or directory exists at the specified path. ```APIDOC ## exists(path: string): Promise ### Description Check if a file or directory exists. ### Parameters #### Path Parameters - **path** (string) - Required - Path to check ### Returns `Promise` — true if exists, false otherwise ### Example: ```typescript if (await exists('~/.config/app')) { console.log('Config directory exists'); } ``` ``` -------------------------------- ### Utility Functions Reference Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/README.md Reference for utility functions used across the project for file system operations, size formatting, and more. ```APIDOC ## Utility Functions Reference This section details the utility functions available for common operations. ### File System Utilities - `isProtectedPath(path)`: Checks if a given path is protected. - `getSize(path)`: Returns the size of a file or directory. - `removeItem(path)`: Removes a file or directory. ### Size Formatting and Parsing Functions for converting sizes between different units and formats. ### Configuration Utilities Utilities for managing and accessing configuration settings. ### Progress Bar Utilities Components for displaying progress during long-running operations. ### Backup and Disk Access Utilities Functions related to backup operations and accessing disk information. ``` -------------------------------- ### Interactive Mode with Risky Categories Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/cli-commands.md Enables the interactive mode and includes risky categories like downloads and backups. ```bash # Interactive mode with risky categories enabled mac-cleaner-cli --risky ``` -------------------------------- ### LargeFilesScanner Configuration Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-scanner.md Explains the LargeFilesScanner, which recursively scans the home directory for files exceeding a configurable minimum size (default 500 MB). Caution is advised as reviewing each file before deletion is recommended. ```typescript class LargeFilesScanner extends BaseScanner { category: Category; scan(options?: ScannerOptions): Promise; clean(items: CleanableItem[], dryRun?: boolean): Promise; } ``` -------------------------------- ### Watch for Uptime Changes with Notifications Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/IDEAS.md Runs the uptime monitor in the background and sends notifications for status changes. Supports integration with services like Slack. ```bash npx uptime-cli watch --notify slack ``` -------------------------------- ### interactiveCommand Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-commands.md Initiates a full interactive cleaning workflow: scan, display, select, confirm, and clean. It allows for various options to customize the cleaning process. ```APIDOC ## interactiveCommand ### Description Initiates a full interactive cleaning workflow: scan, display, select, confirm, and clean. It allows for various options to customize the cleaning process. ### Parameters #### Options - **includeRisky** (boolean) - Optional - Show risky categories (--risky flag) - **noProgress** (boolean) - Optional - Hide progress bars (--no-progress flag) - **absolutePaths** (boolean) - Optional - Show full paths instead of truncated (-A flag) - **filePicker** (boolean) - Optional - Enable file picker for all categories (-f flag) ### Returns `Promise` - Returns a CleanSummary object upon successful cleaning, or null if nothing was cleaned or the process was cancelled. ### Workflow 1. **Scan**: All categories are scanned with progress indication. 2. **Filter**: Risky categories are hidden unless `includeRisky` is true. 3. **Display**: Results are shown, grouped by category. 4. **Select**: A file picker UI is presented for interactive checkbox selection. Categories with `supportsFileSelection=true` or when `filePicker=true` allow per-item selection. 5. **Confirm**: A summary is presented, followed by a "Proceed?" prompt. 6. **Clean**: Selected items are deleted with progress indication. 7. **Result**: A summary detailing success and error breakdowns is displayed. 8. **Donation**: An optional prompt to support the project may appear. ### Example Usage ```typescript import { interactiveCommand } from './commands'; const result = await interactiveCommand({ includeRisky: true, absolutePaths: false, filePicker: false, }); ``` ``` -------------------------------- ### Mac Cleaner CLI Project Structure Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/CONTRIBUTING.md Overview of the directory structure for the Mac Cleaner CLI project, detailing the purpose of key directories and files. ```tree src/ ├── index.ts # CLI entry point (commander setup) ├── types.ts # Shared types and CATEGORIES registry ├── commands/ # CLI command handlers │ ├── interactive.ts # Main interactive clean flow │ ├── clean.ts # Clean execution logic │ ├── scan.ts # Scan command │ ├── uninstall.ts # App uninstaller │ └── maintenance.ts # Maintenance tasks ├── scanners/ # One file per cleanable category │ ├── base-scanner.ts # Abstract base class │ ├── system-cache.ts │ ├── browser-cache.ts │ └── ... ├── pickers/ # Interactive file selection UI ├── maintenance/ # DNS flush, purgeable space └── utils/ # Shared utilities (fs, size, config, etc.) ``` -------------------------------- ### DownloadsScanner Configuration Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-scanner.md Specifies the DownloadsScanner, which targets the ~/Downloads directory. It includes a filter for files older than a configurable number of days. ```typescript class DownloadsScanner extends BaseScanner { category: Category; scan(options?: ScannerOptions): Promise; clean(items: CleanableItem[], dryRun?: boolean): Promise; } ``` -------------------------------- ### listCategories Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-commands.md Displays all available scan categories with their descriptions, safety icons, IDs, and safety notes. This command prints output directly to standard output. ```APIDOC ## listCategories ### Description Display all available categories with descriptions. ### Returns void (prints to stdout) ### Output Groups categories by CategoryGroup, shows safety icons, IDs, descriptions, and safety notes. ``` -------------------------------- ### Check for Existing Configuration File Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-utilities.md Asynchronously checks if a user-specific configuration file exists at standard locations (~/.maccleanerrc or ~/.config/mac-cleaner-cli/config.json). ```typescript configExists() ``` -------------------------------- ### Uninstalling Applications with mac-cleaner-cli Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/README.md Completely remove applications along with their associated preferences, caches, and support files using the 'uninstall' command. ```bash npx mac-cleaner-cli uninstall ``` -------------------------------- ### File Dependencies Diagram Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/INDEX.md Visual representation of file dependencies within the Mac Cleaner CLI project. This helps understand the relationships between different modules and their usage. ```text README.md (overview & navigation) ├─ references → overview.md ├─ references → types.md ├─ references → configuration.md ├─ references → cli-commands.md ├─ references → api-scanner.md ├─ references → api-utilities.md ├─ references → api-commands.md ├─ references → maintenance-api.md └─ references → security.md cli-commands.md ├─ uses types from → types.md └─ mentions security → security.md api-scanner.md ├─ uses types from → types.md └─ mentions security → security.md api-utilities.md ├─ uses types from → types.md └─ mentions security → security.md configuration.md ├─ uses types from → types.md └─ uses utilities → api-utilities.md overview.md └─ describes → all other files ``` -------------------------------- ### CI/CD: Docker Image Cleanup Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/cli-commands.md Clean Docker-related cache and images as part of a CI/CD pipeline. The --yes flag bypasses confirmation prompts, suitable for automated environments. ```bash # Docker image cleanup mac-cleaner-cli clean --categories docker --yes ``` -------------------------------- ### Add Site to Uptime Monitor Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/IDEAS.md Adds a website or API endpoint to the uptime monitoring service. This command registers a URL to be checked for availability. ```bash npx uptime-cli add https://mysite.com ``` ```bash npx uptime-cli add https://api.mysite.com ``` -------------------------------- ### Mac Cleaner CLI Main Commands Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/README.md Lists the primary commands available for the Mac Cleaner CLI. Use these to perform interactive mode, scanning, cleaning, uninstallation, system maintenance, category listing, configuration, and backup management. ```bash mac-cleaner-cli # Interactive mode mac-cleaner-cli scan # Scan only mac-cleaner-cli clean # Non-interactive clean mac-cleaner-cli uninstall # App uninstaller mac-cleaner-cli maintenance # System tasks mac-cleaner-cli categories # List all categories mac-cleaner-cli config # Config management mac-cleaner-cli backup # Backup management ``` -------------------------------- ### Copy command to clipboard Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/docs/index.html A JavaScript function to copy the 'npx mac-cleaner-cli' command to the user's clipboard, providing visual feedback. ```javascript function copyCmd(btn) { navigator.clipboard.writeText('npx mac-cleaner-cli').then(() => { const prev = btn.textContent; btn.textContent = 'Copied!'; setTimeout(() => { btn.textContent = prev; }, 1500); }); } ``` -------------------------------- ### Run Mac Cleaner CLI Interactively Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/docs/index.html Execute the Mac Cleaner CLI to scan your system and interactively select files for cleaning. The tool provides a visual representation of disk space usage per category. ```bash npx mac-cleaner-cli 🧹 ``` -------------------------------- ### Automated Cleaning with Mac Cleaner CLI Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/docs/index.html Perform automated cleaning using the `clean --yes` command. This is suitable for scripts and cron jobs where no user interaction is desired. Use with caution. ```bash mac-cleaner-cli clean --yes ``` -------------------------------- ### getDefaultConfig Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/_autodocs/api-utilities.md Retrieves a copy of the application's built-in default configuration. ```APIDOC ## getDefaultConfig(): Config ### Description Get a copy of the built-in default configuration. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method N/A (Function Signature) ### Endpoint N/A (Function Signature) ### Returns `Config` ### Example: ```typescript const defaults = getDefaultConfig(); ``` ``` -------------------------------- ### Restore Database from Snapshot Source: https://github.com/guhcostan/mac-cleaner-cli/blob/main/IDEAS.md Restores a local development database to a previous state using a named snapshot. This is useful for resetting the database before testing or migrations. ```bash npx db-snapshot-cli restore "before-migration" # → Restored! ```