1
0
mirror of https://github.com/tw93/Mole.git synced 2026-02-04 19:09:43 +00:00

Reconstruct the clean split logic

This commit is contained in:
Tw93
2025-11-28 22:39:11 +09:00
parent 58da36afdd
commit a47f7d0d32
12 changed files with 2138 additions and 1069 deletions

File diff suppressed because it is too large Load Diff

256
lib/clean_apps.sh Normal file
View File

@@ -0,0 +1,256 @@
#!/bin/bash
# Application Data Cleanup Module
set -euo pipefail
# Clean .DS_Store (Finder metadata), home uses maxdepth 5, excludes slow paths, max 500 files
# Args: $1=target_dir, $2=label
clean_ds_store_tree() {
local target="$1"
local label="$2"
[[ -d "$target" ]] || return 0
local file_count=0
local total_bytes=0
local spinner_active="false"
if [[ -t 1 ]]; then
MOLE_SPINNER_PREFIX=" "
start_inline_spinner "Cleaning Finder metadata..."
spinner_active="true"
fi
# Build exclusion paths for find (skip common slow/large directories)
local -a exclude_paths=(
-path "*/Library/Application Support/MobileSync" -prune -o
-path "*/Library/Developer" -prune -o
-path "*/.Trash" -prune -o
-path "*/node_modules" -prune -o
-path "*/.git" -prune -o
-path "*/Library/Caches" -prune -o
)
# Build find command to avoid unbound array expansion with set -u
local -a find_cmd=("find" "$target")
if [[ "$target" == "$HOME" ]]; then
find_cmd+=("-maxdepth" "5")
fi
find_cmd+=("${exclude_paths[@]}" "-type" "f" "-name" ".DS_Store" "-print0")
# Find .DS_Store files with exclusions and depth limit
while IFS= read -r -d '' ds_file; do
local size
size=$(get_file_size "$ds_file")
total_bytes=$((total_bytes + size))
((file_count++))
if [[ "$DRY_RUN" != "true" ]]; then
rm -f "$ds_file" 2> /dev/null || true
fi
# Stop after 500 files to avoid hanging
if [[ $file_count -ge 500 ]]; then
break
fi
done < <("${find_cmd[@]}" 2> /dev/null)
if [[ "$spinner_active" == "true" ]]; then
stop_inline_spinner
echo -ne "\r\033[K"
fi
if [[ $file_count -gt 0 ]]; then
local size_human
size_human=$(bytes_to_human "$total_bytes")
if [[ "$DRY_RUN" == "true" ]]; then
echo -e " ${YELLOW}${NC} $label ${YELLOW}($file_count files, $size_human dry)${NC}"
else
echo -e " ${GREEN}${ICON_SUCCESS}${NC} $label ${GREEN}($file_count files, $size_human)${NC}"
fi
local size_kb=$(((total_bytes + 1023) / 1024))
((files_cleaned += file_count))
((total_size_cleaned += size_kb))
((total_items++))
note_activity
fi
}
# Clean data for uninstalled apps (caches/logs/states older than 60 days)
# Protects system apps, major vendors, scans /Applications+running processes
# Max 100 items/pattern, 2s du timeout. Env: ORPHAN_AGE_THRESHOLD, DRY_RUN
clean_orphaned_app_data() {
# Quick permission check - if we can't access Library folders, skip
if ! ls "$HOME/Library/Caches" > /dev/null 2>&1; then
echo -e " ${YELLOW}${ICON_WARNING}${NC} Skipped: No permission to access Library folders"
return 0
fi
# Build list of installed/active apps
local installed_bundles=$(create_temp_file)
MOLE_SPINNER_PREFIX=" " start_inline_spinner "Scanning installed apps..."
# Scan all Applications directories
local -a app_dirs=(
"/Applications"
"/System/Applications"
"$HOME/Applications"
)
for app_dir in "${app_dirs[@]}"; do
[[ -d "$app_dir" ]] || continue
find "$app_dir" -name "*.app" -maxdepth 3 -type d 2> /dev/null | while IFS= read -r app_path; do
local bundle_id
bundle_id=$(defaults read "$app_path/Contents/Info.plist" CFBundleIdentifier 2> /dev/null || echo "")
[[ -n "$bundle_id" ]] && echo "$bundle_id"
done >> "$installed_bundles"
done
# Get running applications and LaunchAgents with timeout protection
local running_apps=$(run_with_timeout 5 osascript -e 'tell application "System Events" to get bundle identifier of every application process' 2> /dev/null || echo "")
echo "$running_apps" | tr ',' '\n' | sed -e 's/^ *//;s/ *$//' -e '/^$/d' >> "$installed_bundles"
run_with_timeout 5 find ~/Library/LaunchAgents /Library/LaunchAgents \
-name "*.plist" -type f 2> /dev/null | while IFS= read -r plist; do
basename "$plist" .plist
done >> "$installed_bundles" 2> /dev/null || true
# Deduplicate
sort -u "$installed_bundles" -o "$installed_bundles"
local app_count=$(wc -l < "$installed_bundles" 2> /dev/null | tr -d ' ')
stop_inline_spinner
echo -e " ${GREEN}${ICON_SUCCESS}${NC} Found $app_count active/installed apps"
# Track statistics
local orphaned_count=0
local total_orphaned_kb=0
# Check if bundle is orphaned - conservative approach
is_orphaned() {
local bundle_id="$1"
local directory_path="$2"
# Skip system-critical and protected apps
if should_protect_data "$bundle_id"; then
return 1
fi
# Check if app exists in our scan
if grep -q "^$bundle_id$" "$installed_bundles" 2> /dev/null; then
return 1
fi
# Extra check for system bundles
case "$bundle_id" in
com.apple.* | loginwindow | dock | systempreferences | finder | safari)
return 1
;;
esac
# Skip major vendors
case "$bundle_id" in
com.adobe.* | com.microsoft.* | com.google.* | org.mozilla.* | com.jetbrains.* | com.docker.*)
return 1
;;
esac
# Check file age - only clean if 60+ days inactive
# Use modification time (mtime) instead of access time (atime)
# because macOS disables atime updates by default for performance
if [[ -e "$directory_path" ]]; then
local last_modified_epoch=$(get_file_mtime "$directory_path")
local current_epoch=$(date +%s)
local days_since_modified=$(((current_epoch - last_modified_epoch) / 86400))
if [[ $days_since_modified -lt ${ORPHAN_AGE_THRESHOLD:-60} ]]; then
return 1
fi
fi
return 0
}
# Unified orphaned resource scanner (caches, logs, states, webkit, HTTP, cookies)
MOLE_SPINNER_PREFIX=" " start_inline_spinner "Scanning orphaned app resources..."
# Define resource types to scan
# CRITICAL: NEVER add LaunchAgents or LaunchDaemons (breaks login items/startup apps)
local -a resource_types=(
"$HOME/Library/Caches|Caches|com.*:org.*:net.*:io.*"
"$HOME/Library/Logs|Logs|com.*:org.*:net.*:io.*"
"$HOME/Library/Saved Application State|States|*.savedState"
"$HOME/Library/WebKit|WebKit|com.*:org.*:net.*:io.*"
"$HOME/Library/HTTPStorages|HTTP|com.*:org.*:net.*:io.*"
"$HOME/Library/Cookies|Cookies|*.binarycookies"
)
orphaned_count=0
for resource_type in "${resource_types[@]}"; do
IFS='|' read -r base_path label patterns <<< "$resource_type"
# Check both existence and permission to avoid hanging
if [[ ! -d "$base_path" ]]; then
continue
fi
# Quick permission check - if we can't ls the directory, skip it
if ! ls "$base_path" > /dev/null 2>&1; then
continue
fi
# Build file pattern array
local -a file_patterns=()
IFS=':' read -ra pattern_arr <<< "$patterns"
for pat in "${pattern_arr[@]}"; do
file_patterns+=("$base_path/$pat")
done
# Scan and clean orphaned items
for item_path in "${file_patterns[@]}"; do
# Use shell glob (no ls needed)
# Limit iterations to prevent hanging on directories with too many files
local iteration_count=0
local max_iterations=100
for match in $item_path; do
[[ -e "$match" ]] || continue
# Safety: limit iterations to prevent infinite loops on massive directories
((iteration_count++))
if [[ $iteration_count -gt $max_iterations ]]; then
break
fi
# Extract bundle ID from filename
local bundle_id=$(basename "$match")
bundle_id="${bundle_id%.savedState}"
bundle_id="${bundle_id%.binarycookies}"
if is_orphaned "$bundle_id" "$match"; then
# Use timeout to prevent du from hanging on large/problematic directories
local size_kb
size_kb=$(run_with_timeout 2 du -sk "$match" 2> /dev/null | awk '{print $1}' || echo "0")
if [[ -z "$size_kb" || "$size_kb" == "0" ]]; then
continue
fi
safe_clean "$match" "Orphaned $label: $bundle_id"
((orphaned_count++))
((total_orphaned_kb += size_kb))
fi
done
done
done
stop_inline_spinner
if [[ $orphaned_count -gt 0 ]]; then
local orphaned_mb=$(echo "$total_orphaned_kb" | awk '{printf "%.1f", $1/1024}')
echo " ${GREEN}${ICON_SUCCESS}${NC} Cleaned $orphaned_count items (~${orphaned_mb}MB)"
note_activity
fi
rm -f "$installed_bundles"
}

207
lib/clean_brew.sh Normal file
View File

@@ -0,0 +1,207 @@
#!/bin/bash
# Homebrew Cleanup Module
set -euo pipefail
# Clean orphaned cask records (apps manually deleted but cask record remains)
# Uses 2-day cache to avoid expensive brew info calls
# Cache format: cask_name|AppName.app
clean_orphaned_casks() {
command -v brew > /dev/null 2>&1 || return 0
if [[ -t 1 ]]; then
MOLE_SPINNER_PREFIX=" " start_inline_spinner "Scanning orphaned casks..."
fi
local cache_dir="$HOME/.cache/mole"
local cask_cache="$cache_dir/cask_apps.cache"
local use_cache=false
# Check if cache is valid (less than 2 days old)
if [[ -f "$cask_cache" ]]; then
local cache_age=$(($(date +%s) - $(get_file_mtime "$cask_cache")))
if [[ $cache_age -lt 172800 ]]; then
use_cache=true
fi
fi
local orphaned_casks=()
if [[ "$use_cache" == "true" ]]; then
# Use cached cask → app mapping to avoid expensive brew info calls
while IFS='|' read -r cask app_name; do
[[ ! -e "/Applications/$app_name" ]] && orphaned_casks+=("$cask")
done < "$cask_cache"
else
# Rebuild cache: query all installed casks and extract app names
mkdir -p "$cache_dir"
true > "$cask_cache"
while IFS= read -r cask; do
# Get app path from cask info (expensive call, hence caching)
local cask_info
cask_info=$(brew info --cask "$cask" 2> /dev/null || true)
# Extract app name from "AppName.app (App)" format in cask info output
local app_name
app_name=$(echo "$cask_info" | grep -E '\.app \(App\)' | head -1 | sed -E 's/^[[:space:]]*//' | sed -E 's/ \(App\).*//' || true)
# Skip if no app artifact (might be a utility package like fonts)
[[ -z "$app_name" ]] && continue
# Save to cache for future runs
echo "$cask|$app_name" >> "$cask_cache"
# Check if app exists in /Applications
[[ ! -e "/Applications/$app_name" ]] && orphaned_casks+=("$cask")
done < <(brew list --cask 2> /dev/null || true)
fi
# Remove orphaned casks if found and sudo session is still valid
if [[ ${#orphaned_casks[@]} -gt 0 ]]; then
# Check if sudo session is still valid (without prompting)
if sudo -n true 2> /dev/null; then
if [[ -t 1 ]]; then
stop_inline_spinner
MOLE_SPINNER_PREFIX=" " start_inline_spinner "Cleaning orphaned casks..."
fi
local removed_casks=0
for cask in "${orphaned_casks[@]}"; do
if brew uninstall --cask "$cask" --force > /dev/null 2>&1; then
((removed_casks++))
fi
done
if [[ -t 1 ]]; then stop_inline_spinner; fi
[[ $removed_casks -gt 0 ]] && log_success "Orphaned Homebrew casks ($removed_casks apps)"
else
# Sudo session expired - inform user to run brew manually
if [[ -t 1 ]]; then stop_inline_spinner; fi
echo -e " ${YELLOW}${ICON_WARNING}${NC} Found ${#orphaned_casks[@]} orphaned casks (sudo expired, run ${GRAY}brew list --cask${NC} to check)"
fi
else
if [[ -t 1 ]]; then stop_inline_spinner; fi
fi
}
# Clean Homebrew caches and remove orphaned dependencies
# Skips if run within 2 days, runs cleanup/autoremove in parallel with 120s timeout
# Env: MO_BREW_TIMEOUT, DRY_RUN
clean_homebrew() {
command -v brew > /dev/null 2>&1 || return 0
# Dry run mode - just indicate what would happen
if [[ "${DRY_RUN:-false}" == "true" ]]; then
echo -e " ${YELLOW}${NC} Homebrew (would cleanup and autoremove)"
return 0
fi
# Smart caching: check if brew cleanup was run recently (within 2 days)
local brew_cache_file="${HOME}/.cache/mole/brew_last_cleanup"
local cache_valid_days=2
local should_skip=false
if [[ -f "$brew_cache_file" ]]; then
local last_cleanup
last_cleanup=$(cat "$brew_cache_file" 2> /dev/null || echo "0")
local current_time
current_time=$(date +%s)
local time_diff=$((current_time - last_cleanup))
local days_diff=$((time_diff / 86400))
if [[ $days_diff -lt $cache_valid_days ]]; then
should_skip=true
echo -e " ${GREEN}${ICON_SUCCESS}${NC} Homebrew (cleaned ${days_diff}d ago, skipped)"
fi
fi
[[ "$should_skip" == "true" ]] && return 0
if [[ -t 1 ]]; then
MOLE_SPINNER_PREFIX=" " start_inline_spinner "Homebrew cleanup and autoremove..."
fi
local timeout_seconds=${MO_BREW_TIMEOUT:-120}
# Run brew cleanup and autoremove in parallel for performance
local brew_tmp_file autoremove_tmp_file
brew_tmp_file=$(create_temp_file)
autoremove_tmp_file=$(create_temp_file)
(brew cleanup > "$brew_tmp_file" 2>&1) &
local brew_pid=$!
(brew autoremove > "$autoremove_tmp_file" 2>&1) &
local autoremove_pid=$!
local elapsed=0
local brew_done=false
local autoremove_done=false
# Wait for both to complete or timeout
while [[ "$brew_done" == "false" ]] || [[ "$autoremove_done" == "false" ]]; do
if [[ $elapsed -ge $timeout_seconds ]]; then
kill -TERM $brew_pid $autoremove_pid 2> /dev/null || true
break
fi
kill -0 $brew_pid 2> /dev/null || brew_done=true
kill -0 $autoremove_pid 2> /dev/null || autoremove_done=true
sleep 1
((elapsed++))
done
# Wait for processes to finish
local brew_success=false
if wait $brew_pid 2> /dev/null; then
brew_success=true
fi
local autoremove_success=false
if wait $autoremove_pid 2> /dev/null; then
autoremove_success=true
fi
if [[ -t 1 ]]; then stop_inline_spinner; fi
# Process cleanup output and extract metrics
if [[ "$brew_success" == "true" && -f "$brew_tmp_file" ]]; then
local brew_output
brew_output=$(cat "$brew_tmp_file" 2> /dev/null || echo "")
local removed_count freed_space
removed_count=$(printf '%s\n' "$brew_output" | grep -c "Removing:" 2> /dev/null || true)
freed_space=$(printf '%s\n' "$brew_output" | grep -o "[0-9.]*[KMGT]B freed" 2> /dev/null | tail -1 || true)
if [[ $removed_count -gt 0 ]] || [[ -n "$freed_space" ]]; then
if [[ -n "$freed_space" ]]; then
echo -e " ${GREEN}${ICON_SUCCESS}${NC} Homebrew cleanup ${GREEN}($freed_space)${NC}"
else
echo -e " ${GREEN}${ICON_SUCCESS}${NC} Homebrew cleanup (${removed_count} items)"
fi
fi
elif [[ $elapsed -ge $timeout_seconds ]]; then
echo -e " ${YELLOW}${ICON_WARNING}${NC} Homebrew cleanup timed out (run ${GRAY}brew cleanup${NC} manually)"
fi
# Process autoremove output - only show if packages were removed
if [[ "$autoremove_success" == "true" && -f "$autoremove_tmp_file" ]]; then
local autoremove_output
autoremove_output=$(cat "$autoremove_tmp_file" 2> /dev/null || echo "")
local removed_packages
removed_packages=$(printf '%s\n' "$autoremove_output" | grep -c "^Uninstalling" 2> /dev/null || true)
if [[ $removed_packages -gt 0 ]]; then
echo -e " ${GREEN}${ICON_SUCCESS}${NC} Removed orphaned dependencies (${removed_packages} packages)"
fi
elif [[ $elapsed -ge $timeout_seconds ]]; then
echo -e " ${YELLOW}${ICON_WARNING}${NC} Autoremove timed out (run ${GRAY}brew autoremove${NC} manually)"
fi
# Update cache timestamp on successful completion
if [[ "$brew_success" == "true" || "$autoremove_success" == "true" ]]; then
mkdir -p "$(dirname "$brew_cache_file")"
date +%s > "$brew_cache_file"
fi
}

200
lib/clean_caches.sh Normal file
View File

@@ -0,0 +1,200 @@
#!/bin/bash
# Cache Cleanup Module
set -euo pipefail
# Trigger all TCC permission dialogs upfront to avoid random interruptions
# Only runs once (uses ~/.cache/mole/permissions_granted flag)
check_tcc_permissions() {
# Only check in interactive mode
[[ -t 1 ]] || return 0
local permission_flag="$HOME/.cache/mole/permissions_granted"
# Skip if permissions were already granted
[[ -f "$permission_flag" ]] && return 0
# Key protected directories that require TCC approval
local -a tcc_dirs=(
"$HOME/Library/Caches"
"$HOME/Library/Logs"
"$HOME/Library/Application Support"
"$HOME/Library/Containers"
"$HOME/.cache"
)
# Quick permission test - if first directory is accessible, likely others are too
# Use simple ls test instead of find to avoid triggering permission dialogs prematurely
local needs_permission_check=false
if ! ls "$HOME/Library/Caches" > /dev/null 2>&1; then
needs_permission_check=true
fi
if [[ "$needs_permission_check" == "true" ]]; then
echo ""
echo -e "${BLUE}First-time setup${NC}"
echo -e "${GRAY}macOS will request permissions to access Library folders.${NC}"
echo -e "${GRAY}You may see ${GREEN}${#tcc_dirs[@]} permission dialogs${NC}${GRAY} - please approve them all.${NC}"
echo ""
echo -ne "${PURPLE}${ICON_ARROW}${NC} Press ${GREEN}Enter${NC} to continue: "
read -r
MOLE_SPINNER_PREFIX="" start_inline_spinner "Requesting permissions..."
# Trigger all TCC prompts upfront by accessing each directory
# Using find -maxdepth 1 ensures we touch the directory without deep scanning
for dir in "${tcc_dirs[@]}"; do
[[ -d "$dir" ]] && find "$dir" -maxdepth 1 -type d > /dev/null 2>&1
done
stop_inline_spinner
echo ""
fi
# Mark permissions as granted (won't prompt again)
mkdir -p "$(dirname "$permission_flag")" 2> /dev/null || true
touch "$permission_flag" 2> /dev/null || true
}
# Clean browser Service Worker cache, protecting web editing tools (capcut, photopea, pixlr)
# Args: $1=browser_name, $2=cache_path
clean_service_worker_cache() {
local browser_name="$1"
local cache_path="$2"
[[ ! -d "$cache_path" ]] && return 0
local cleaned_size=0
local protected_count=0
# Find all cache directories and calculate sizes
while IFS= read -r cache_dir; do
[[ ! -d "$cache_dir" ]] && continue
# Extract domain from path using regex
# Pattern matches: letters/numbers, hyphens, then dot, then TLD
# Example: "abc123_https_example.com_0" → "example.com"
local domain=$(basename "$cache_dir" | grep -oE '[a-zA-Z0-9][-a-zA-Z0-9]*\.[a-zA-Z]{2,}' | head -1 || echo "")
local size=$(du -sk "$cache_dir" 2> /dev/null | awk '{print $1}')
# Check if domain is protected
local is_protected=false
for protected_domain in "${PROTECTED_SW_DOMAINS[@]}"; do
if [[ "$domain" == *"$protected_domain"* ]]; then
is_protected=true
protected_count=$((protected_count + 1))
break
fi
done
# Clean if not protected
if [[ "$is_protected" == "false" ]]; then
if [[ "$DRY_RUN" != "true" ]]; then
rm -rf "$cache_dir" 2> /dev/null || true
fi
cleaned_size=$((cleaned_size + size))
fi
done < <(find "$cache_path" -type d -depth 2 2> /dev/null)
if [[ $cleaned_size -gt 0 ]]; then
local cleaned_mb=$((cleaned_size / 1024))
if [[ "$DRY_RUN" != "true" ]]; then
echo -e " ${GREEN}${ICON_SUCCESS}${NC} $browser_name Service Worker cache (${cleaned_mb}MB cleaned, $protected_count protected)"
else
echo -e " ${YELLOW}${NC} $browser_name Service Worker cache (would clean ${cleaned_mb}MB, $protected_count protected)"
fi
note_activity
fi
}
# Clean Next.js (.next/cache) and Python (__pycache__) build caches
# Uses maxdepth 3, excludes Library/.Trash/node_modules, 10s timeout per scan
clean_project_caches() {
# Clean Next.js caches
if [[ -t 1 ]]; then
MOLE_SPINNER_PREFIX=" "
start_inline_spinner "Searching Next.js caches..."
fi
# Use timeout to prevent hanging on problematic directories
local nextjs_tmp_file
nextjs_tmp_file=$(create_temp_file)
(
find "$HOME" -P -mount -type d -name ".next" -maxdepth 3 \
-not -path "*/Library/*" \
-not -path "*/.Trash/*" \
-not -path "*/node_modules/*" \
-not -path "*/.*" \
2> /dev/null || true
) > "$nextjs_tmp_file" 2>&1 &
local find_pid=$!
local find_timeout=10
local elapsed=0
# Wait for find to complete or timeout
while kill -0 $find_pid 2> /dev/null && [[ $elapsed -lt $find_timeout ]]; do
sleep 1
((elapsed++))
done
# Kill if still running after timeout
if kill -0 $find_pid 2> /dev/null; then
kill -TERM $find_pid 2> /dev/null || true
wait $find_pid 2> /dev/null || true
else
wait $find_pid 2> /dev/null || true
fi
# Clean found Next.js caches
while IFS= read -r next_dir; do
[[ -d "$next_dir/cache" ]] && safe_clean "$next_dir/cache"/* "Next.js build cache" || true
done < "$nextjs_tmp_file"
if [[ -t 1 ]]; then
stop_inline_spinner
fi
# Clean Python bytecode caches
if [[ -t 1 ]]; then
MOLE_SPINNER_PREFIX=" "
start_inline_spinner "Searching Python caches..."
fi
# Use timeout to prevent hanging on problematic directories
local pycache_tmp_file
pycache_tmp_file=$(create_temp_file)
(
find "$HOME" -P -mount -type d -name "__pycache__" -maxdepth 3 \
-not -path "*/Library/*" \
-not -path "*/.Trash/*" \
-not -path "*/node_modules/*" \
-not -path "*/.*" \
2> /dev/null || true
) > "$pycache_tmp_file" 2>&1 &
local find_pid=$!
local find_timeout=10
local elapsed=0
# Wait for find to complete or timeout
while kill -0 $find_pid 2> /dev/null && [[ $elapsed -lt $find_timeout ]]; do
sleep 1
((elapsed++))
done
# Kill if still running after timeout
if kill -0 $find_pid 2> /dev/null; then
kill -TERM $find_pid 2> /dev/null || true
wait $find_pid 2> /dev/null || true
else
wait $find_pid 2> /dev/null || true
fi
# Clean found Python caches
while IFS= read -r pycache; do
[[ -d "$pycache" ]] && safe_clean "$pycache"/* "Python bytecode cache" || true
done < "$pycache_tmp_file"
if [[ -t 1 ]]; then
stop_inline_spinner
fi
}

258
lib/clean_dev.sh Normal file
View File

@@ -0,0 +1,258 @@
#!/bin/bash
# Developer Tools Cleanup Module
set -euo pipefail
# Clean npm cache (command + directories)
# Env: DRY_RUN
clean_dev_npm() {
if command -v npm > /dev/null 2>&1; then
if [[ "$DRY_RUN" != "true" ]]; then
clean_tool_cache "npm cache" npm cache clean --force
else
echo -e " ${YELLOW}${NC} npm cache (would clean)"
fi
note_activity
fi
safe_clean ~/.npm/_cacache/* "npm cache directory"
safe_clean ~/.npm/_logs/* "npm logs"
safe_clean ~/.tnpm/_cacache/* "tnpm cache directory"
safe_clean ~/.tnpm/_logs/* "tnpm logs"
safe_clean ~/.yarn/cache/* "Yarn cache"
safe_clean ~/.bun/install/cache/* "Bun cache"
}
# Clean Python/pip cache (command + directories)
# Env: DRY_RUN
clean_dev_python() {
if command -v pip3 > /dev/null 2>&1; then
if [[ "$DRY_RUN" != "true" ]]; then
clean_tool_cache "pip cache" bash -c 'pip3 cache purge >/dev/null 2>&1 || true'
else
echo -e " ${YELLOW}${NC} pip cache (would clean)"
fi
note_activity
fi
safe_clean ~/.cache/pip/* "pip cache directory"
safe_clean ~/Library/Caches/pip/* "pip cache (macOS)"
safe_clean ~/.pyenv/cache/* "pyenv cache"
safe_clean ~/.cache/poetry/* "Poetry cache"
safe_clean ~/.cache/uv/* "uv cache"
safe_clean ~/.cache/ruff/* "Ruff cache"
safe_clean ~/.cache/mypy/* "MyPy cache"
safe_clean ~/.pytest_cache/* "Pytest cache"
safe_clean ~/.jupyter/runtime/* "Jupyter runtime cache"
safe_clean ~/.cache/huggingface/* "Hugging Face cache"
safe_clean ~/.cache/torch/* "PyTorch cache"
safe_clean ~/.cache/tensorflow/* "TensorFlow cache"
safe_clean ~/.conda/pkgs/* "Conda packages cache"
safe_clean ~/anaconda3/pkgs/* "Anaconda packages cache"
safe_clean ~/.cache/wandb/* "Weights & Biases cache"
}
# Clean Go cache (command + directories)
# Env: DRY_RUN
clean_dev_go() {
if command -v go > /dev/null 2>&1; then
if [[ "$DRY_RUN" != "true" ]]; then
clean_tool_cache "Go cache" bash -c 'go clean -modcache >/dev/null 2>&1 || true; go clean -cache >/dev/null 2>&1 || true'
else
echo -e " ${YELLOW}${NC} Go cache (would clean)"
fi
note_activity
fi
safe_clean ~/Library/Caches/go-build/* "Go build cache"
safe_clean ~/go/pkg/mod/cache/* "Go module cache"
}
# Clean Rust/cargo cache directories
clean_dev_rust() {
safe_clean ~/.cargo/registry/cache/* "Rust cargo cache"
safe_clean ~/.cargo/git/* "Cargo git cache"
safe_clean ~/.rustup/toolchains/*/share/doc/* "Rust documentation cache"
safe_clean ~/.rustup/downloads/* "Rust downloads cache"
}
# Clean Docker cache (command + directories)
# Env: DRY_RUN
clean_dev_docker() {
if command -v docker > /dev/null 2>&1; then
if [[ "$DRY_RUN" != "true" ]]; then
clean_tool_cache "Docker build cache" docker builder prune -af
else
echo -e " ${YELLOW}${NC} Docker build cache (would clean)"
fi
note_activity
fi
safe_clean ~/.docker/buildx/cache/* "Docker BuildX cache"
}
# Clean Nix package manager
# Env: DRY_RUN
clean_dev_nix() {
if command -v nix-collect-garbage > /dev/null 2>&1; then
if [[ "$DRY_RUN" != "true" ]]; then
clean_tool_cache "Nix garbage collection" nix-collect-garbage --delete-older-than 30d
else
echo -e " ${YELLOW}${NC} Nix garbage collection (would clean)"
fi
note_activity
fi
}
# Clean cloud CLI tools cache
clean_dev_cloud() {
safe_clean ~/.kube/cache/* "Kubernetes cache"
safe_clean ~/.local/share/containers/storage/tmp/* "Container storage temp"
safe_clean ~/.aws/cli/cache/* "AWS CLI cache"
safe_clean ~/.config/gcloud/logs/* "Google Cloud logs"
safe_clean ~/.azure/logs/* "Azure CLI logs"
}
# Clean frontend build tool caches
clean_dev_frontend() {
safe_clean ~/.pnpm-store/* "pnpm store cache"
safe_clean ~/.local/share/pnpm/store/* "pnpm global store"
safe_clean ~/.cache/typescript/* "TypeScript cache"
safe_clean ~/.cache/electron/* "Electron cache"
safe_clean ~/.cache/node-gyp/* "node-gyp cache"
safe_clean ~/.node-gyp/* "node-gyp build cache"
safe_clean ~/.turbo/cache/* "Turbo cache"
safe_clean ~/.vite/cache/* "Vite cache"
safe_clean ~/.cache/vite/* "Vite global cache"
safe_clean ~/.cache/webpack/* "Webpack cache"
safe_clean ~/.parcel-cache/* "Parcel cache"
safe_clean ~/.cache/eslint/* "ESLint cache"
safe_clean ~/.cache/prettier/* "Prettier cache"
}
# Clean mobile development tools
clean_dev_mobile() {
safe_clean ~/Library/Caches/Google/AndroidStudio*/* "Android Studio cache"
safe_clean ~/Library/Caches/CocoaPods/* "CocoaPods cache"
safe_clean ~/.cache/flutter/* "Flutter cache"
safe_clean ~/.android/build-cache/* "Android build cache"
safe_clean ~/.android/cache/* "Android SDK cache"
safe_clean ~/Library/Developer/Xcode/iOS\ DeviceSupport/*/Symbols/System/Library/Caches/* "iOS device cache"
safe_clean ~/Library/Developer/Xcode/UserData/IB\ Support/* "Xcode Interface Builder cache"
safe_clean ~/.cache/swift-package-manager/* "Swift package manager cache"
}
# Clean JVM ecosystem tools
clean_dev_jvm() {
safe_clean ~/.gradle/caches/* "Gradle caches"
safe_clean ~/.gradle/daemon/* "Gradle daemon logs"
safe_clean ~/.sbt/* "SBT cache"
safe_clean ~/.ivy2/cache/* "Ivy cache"
}
# Clean other language tools
clean_dev_other_langs() {
safe_clean ~/.bundle/cache/* "Ruby Bundler cache"
safe_clean ~/.composer/cache/* "PHP Composer cache"
safe_clean ~/.nuget/packages/* "NuGet packages cache"
safe_clean ~/.pub-cache/* "Dart Pub cache"
safe_clean ~/.cache/bazel/* "Bazel cache"
safe_clean ~/.cache/zig/* "Zig cache"
safe_clean ~/Library/Caches/deno/* "Deno cache"
}
# Clean CI/CD and DevOps tools
clean_dev_cicd() {
safe_clean ~/.cache/terraform/* "Terraform cache"
safe_clean ~/.grafana/cache/* "Grafana cache"
safe_clean ~/.prometheus/data/wal/* "Prometheus WAL cache"
safe_clean ~/.jenkins/workspace/*/target/* "Jenkins workspace cache"
safe_clean ~/.cache/gitlab-runner/* "GitLab Runner cache"
safe_clean ~/.github/cache/* "GitHub Actions cache"
safe_clean ~/.circleci/cache/* "CircleCI cache"
safe_clean ~/.sonar/* "SonarQube cache"
}
# Clean database tools
clean_dev_database() {
safe_clean ~/Library/Caches/com.sequel-ace.sequel-ace/* "Sequel Ace cache"
safe_clean ~/Library/Caches/com.eggerapps.Sequel-Pro/* "Sequel Pro cache"
safe_clean ~/Library/Caches/redis-desktop-manager/* "Redis Desktop Manager cache"
safe_clean ~/Library/Caches/com.navicat.* "Navicat cache"
safe_clean ~/Library/Caches/com.dbeaver.* "DBeaver cache"
safe_clean ~/Library/Caches/com.redis.RedisInsight "Redis Insight cache"
}
# Clean API/network debugging tools
clean_dev_api_tools() {
safe_clean ~/Library/Caches/com.postmanlabs.mac/* "Postman cache"
safe_clean ~/Library/Caches/com.konghq.insomnia/* "Insomnia cache"
safe_clean ~/Library/Caches/com.tinyapp.TablePlus/* "TablePlus cache"
safe_clean ~/Library/Caches/com.getpaw.Paw/* "Paw API cache"
safe_clean ~/Library/Caches/com.charlesproxy.charles/* "Charles Proxy cache"
safe_clean ~/Library/Caches/com.proxyman.NSProxy/* "Proxyman cache"
}
# Clean misc dev tools
clean_dev_misc() {
safe_clean ~/Library/Caches/com.unity3d.*/* "Unity cache"
safe_clean ~/Library/Caches/com.jetbrains.toolbox/* "JetBrains Toolbox cache"
safe_clean ~/Library/Caches/com.mongodb.compass/* "MongoDB Compass cache"
safe_clean ~/Library/Caches/com.figma.Desktop/* "Figma cache"
safe_clean ~/Library/Caches/com.github.GitHubDesktop/* "GitHub Desktop cache"
safe_clean ~/Library/Caches/SentryCrash/* "Sentry crash reports"
safe_clean ~/Library/Caches/KSCrash/* "KSCrash reports"
safe_clean ~/Library/Caches/com.crashlytics.data/* "Crashlytics data"
}
# Clean shell and version control
clean_dev_shell() {
safe_clean ~/.gitconfig.lock "Git config lock"
safe_clean ~/.gitconfig.bak* "Git config backup"
safe_clean ~/.oh-my-zsh/cache/* "Oh My Zsh cache"
safe_clean ~/.config/fish/fish_history.bak* "Fish shell backup"
safe_clean ~/.bash_history.bak* "Bash history backup"
safe_clean ~/.zsh_history.bak* "Zsh history backup"
safe_clean ~/.cache/pre-commit/* "pre-commit cache"
}
# Clean network utilities
clean_dev_network() {
safe_clean ~/.cache/curl/* "curl cache"
safe_clean ~/.cache/wget/* "wget cache"
safe_clean ~/Library/Caches/curl/* "curl cache (macOS)"
safe_clean ~/Library/Caches/wget/* "wget cache (macOS)"
}
# Main developer tools cleanup function
# Calls all specialized cleanup functions
# Env: DRY_RUN
clean_developer_tools() {
clean_dev_npm
clean_dev_python
clean_dev_go
clean_dev_rust
clean_dev_docker
clean_dev_cloud
clean_dev_nix
clean_dev_shell
clean_dev_frontend
# Project build caches (delegated to clean_caches module)
clean_project_caches
clean_dev_mobile
clean_dev_jvm
clean_dev_other_langs
clean_dev_cicd
clean_dev_database
clean_dev_api_tools
clean_dev_network
clean_dev_misc
# Homebrew caches and cleanup (delegated to clean_brew module)
safe_clean ~/Library/Caches/Homebrew/* "Homebrew cache"
safe_clean /opt/homebrew/var/homebrew/locks/* "Homebrew lock files (M series)"
safe_clean /usr/local/var/homebrew/locks/* "Homebrew lock files (Intel)"
clean_homebrew
}

168
lib/clean_system.sh Normal file
View File

@@ -0,0 +1,168 @@
#!/bin/bash
# System-Level Cleanup Module
# Deep system cleanup (requires sudo) and Time Machine failed backups
set -euo pipefail
# Deep system cleanup (requires sudo)
# Env: DRY_RUN, TEMP_FILE_AGE_DAYS
clean_deep_system() {
# Clean system caches safely (only old files)
sudo find /Library/Caches -name "*.cache" -mtime +7 -delete 2> /dev/null || true
sudo find /Library/Caches -name "*.tmp" -mtime +7 -delete 2> /dev/null || true
sudo find /Library/Caches -type f -name "*.log" -mtime +30 -delete 2> /dev/null || true
# Clean old temp files only
local tmp_cleaned=0
local tmp_count=$(sudo find /tmp -type f -mtime +${TEMP_FILE_AGE_DAYS} 2> /dev/null | wc -l | tr -d ' ')
if [[ "$tmp_count" -gt 0 ]]; then
sudo find /tmp -type f -mtime +${TEMP_FILE_AGE_DAYS} -delete 2> /dev/null || true
tmp_cleaned=1
fi
local var_tmp_count=$(sudo find /var/tmp -type f -mtime +${TEMP_FILE_AGE_DAYS} 2> /dev/null | wc -l | tr -d ' ')
if [[ "$var_tmp_count" -gt 0 ]]; then
sudo find /var/tmp -type f -mtime +${TEMP_FILE_AGE_DAYS} -delete 2> /dev/null || true
tmp_cleaned=1
fi
[[ $tmp_cleaned -eq 1 ]] && log_success "Old system temp files (${TEMP_FILE_AGE_DAYS}+ days)"
# Clean system crash reports and diagnostics
sudo find /Library/Logs/DiagnosticReports -type f -mtime +30 -delete 2> /dev/null || true
sudo find /Library/Logs/CrashReporter -type f -mtime +30 -delete 2> /dev/null || true
log_success "Old system crash reports (30+ days)"
# Clean old system logs
sudo find /var/log -name "*.log" -type f -mtime +30 -delete 2> /dev/null || true
sudo find /var/log -name "*.gz" -type f -mtime +30 -delete 2> /dev/null || true
log_success "Old system logs (30+ days)"
sudo rm -rf /Library/Updates/* 2> /dev/null || true
log_success "System library caches and updates"
# Clean orphaned cask records (delegated to clean_brew module)
clean_orphaned_casks
}
# Clean Time Machine failed backups
# Env: DRY_RUN
# Globals: files_cleaned, total_size_cleaned, total_items (modified if not DRY_RUN)
clean_time_machine_failed_backups() {
local tm_cleaned=0
# Check all mounted volumes
if [[ ! -d "/Volumes" ]]; then
echo -e " ${GREEN}${ICON_SUCCESS}${NC} No failed Time Machine backups found"
return 0
fi
for volume in /Volumes/*; do
[[ -d "$volume" ]] || continue
# Skip system and network volumes
[[ "$volume" == "/Volumes/MacintoshHD" || "$volume" == "/" ]] && continue
local fs_type=$(df -T "$volume" 2> /dev/null | tail -1 | awk '{print $2}')
case "$fs_type" in
nfs | smbfs | afpfs | cifs | webdav) continue ;;
esac
# HFS+ style backups (Backups.backupdb)
local backupdb_dir="$volume/Backups.backupdb"
if [[ -d "$backupdb_dir" ]]; then
while IFS= read -r inprogress_file; do
[[ -d "$inprogress_file" ]] || continue
# Safety: only delete backups older than 24 hours
local file_mtime=$(get_file_mtime "$inprogress_file")
local current_time=$(date +%s)
local hours_old=$(((current_time - file_mtime) / 3600))
if [[ $hours_old -lt 24 ]]; then
continue
fi
local size_kb=$(du -sk "$inprogress_file" 2> /dev/null | awk '{print $1}' || echo "0")
if [[ "$size_kb" -gt 0 ]]; then
local backup_name=$(basename "$inprogress_file")
if [[ "$DRY_RUN" != "true" ]]; then
if command -v tmutil > /dev/null 2>&1; then
if tmutil delete "$inprogress_file" 2> /dev/null; then
local size_human=$(bytes_to_human "$((size_kb * 1024))")
echo -e " ${GREEN}${ICON_SUCCESS}${NC} Failed backup: $backup_name ${GREEN}($size_human)${NC}"
((tm_cleaned++))
((files_cleaned++))
((total_size_cleaned += size_kb))
((total_items++))
note_activity
else
echo -e " ${YELLOW}!${NC} Could not delete: $backup_name (try manually with sudo)"
fi
else
echo -e " ${YELLOW}!${NC} tmutil not available, skipping: $backup_name"
fi
else
local size_human=$(bytes_to_human "$((size_kb * 1024))")
echo -e " ${YELLOW}${NC} Failed backup: $backup_name ${YELLOW}($size_human dry)${NC}"
((tm_cleaned++))
note_activity
fi
fi
done < <(find "$backupdb_dir" -maxdepth 3 -type d \( -name "*.inProgress" -o -name "*.inprogress" \) 2> /dev/null || true)
fi
# APFS style backups (.backupbundle or .sparsebundle)
for bundle in "$volume"/*.backupbundle "$volume"/*.sparsebundle; do
[[ -e "$bundle" ]] || continue
[[ -d "$bundle" ]] || continue
# Check if bundle is mounted
local bundle_name=$(basename "$bundle")
local mounted_path=$(hdiutil info 2> /dev/null | grep -A 5 "image-path.*$bundle_name" | grep "/Volumes/" | awk '{print $1}' | head -1 || echo "")
if [[ -n "$mounted_path" && -d "$mounted_path" ]]; then
while IFS= read -r inprogress_file; do
[[ -d "$inprogress_file" ]] || continue
# Safety: only delete backups older than 24 hours
local file_mtime=$(get_file_mtime "$inprogress_file")
local current_time=$(date +%s)
local hours_old=$(((current_time - file_mtime) / 3600))
if [[ $hours_old -lt 24 ]]; then
continue
fi
local size_kb=$(du -sk "$inprogress_file" 2> /dev/null | awk '{print $1}' || echo "0")
if [[ "$size_kb" -gt 0 ]]; then
local backup_name=$(basename "$inprogress_file")
if [[ "$DRY_RUN" != "true" ]]; then
if command -v tmutil > /dev/null 2>&1; then
if tmutil delete "$inprogress_file" 2> /dev/null; then
local size_human=$(bytes_to_human "$((size_kb * 1024))")
echo -e " ${GREEN}${ICON_SUCCESS}${NC} Failed APFS backup in $bundle_name: $backup_name ${GREEN}($size_human)${NC}"
((tm_cleaned++))
((files_cleaned++))
((total_size_cleaned += size_kb))
((total_items++))
note_activity
else
echo -e " ${YELLOW}!${NC} Could not delete from bundle: $backup_name"
fi
fi
else
local size_human=$(bytes_to_human "$((size_kb * 1024))")
echo -e " ${YELLOW}${NC} Failed APFS backup in $bundle_name: $backup_name ${YELLOW}($size_human dry)${NC}"
((tm_cleaned++))
note_activity
fi
fi
done < <(find "$mounted_path" -maxdepth 3 -type d \( -name "*.inProgress" -o -name "*.inprogress" \) 2> /dev/null || true)
fi
done
done
if [[ $tm_cleaned -eq 0 ]]; then
echo -e " ${GREEN}${ICON_SUCCESS}${NC} No failed Time Machine backups found"
fi
}

229
lib/clean_user_apps.sh Normal file
View File

@@ -0,0 +1,229 @@
#!/bin/bash
# User GUI Applications Cleanup Module
# Desktop applications, communication tools, media players, games, utilities
set -euo pipefail
# Clean Xcode and iOS development tools
clean_xcode_tools() {
safe_clean ~/Library/Developer/Xcode/DerivedData/* "Xcode derived data"
safe_clean ~/Library/Developer/CoreSimulator/Caches/* "Simulator cache"
safe_clean ~/Library/Developer/CoreSimulator/Devices/*/data/tmp/* "Simulator temp files"
safe_clean ~/Library/Caches/com.apple.dt.Xcode/* "Xcode cache"
safe_clean ~/Library/Developer/Xcode/iOS\ Device\ Logs/* "iOS device logs"
safe_clean ~/Library/Developer/Xcode/watchOS\ Device\ Logs/* "watchOS device logs"
safe_clean ~/Library/Developer/Xcode/Products/* "Xcode build products"
}
# Clean code editors (VS Code, Sublime, etc.)
clean_code_editors() {
safe_clean ~/Library/Application\ Support/Code/logs/* "VS Code logs"
safe_clean ~/Library/Application\ Support/Code/Cache/* "VS Code cache"
safe_clean ~/Library/Application\ Support/Code/CachedExtensions/* "VS Code extension cache"
safe_clean ~/Library/Application\ Support/Code/CachedData/* "VS Code data cache"
safe_clean ~/Library/Caches/JetBrains/* "JetBrains cache"
safe_clean ~/Library/Caches/com.sublimetext.*/* "Sublime Text cache"
}
# Clean communication apps (Slack, Discord, Zoom, etc.)
clean_communication_apps() {
safe_clean ~/Library/Application\ Support/discord/Cache/* "Discord cache"
safe_clean ~/Library/Application\ Support/Slack/Cache/* "Slack cache"
safe_clean ~/Library/Caches/us.zoom.xos/* "Zoom cache"
safe_clean ~/Library/Caches/com.tencent.xinWeChat/* "WeChat cache"
safe_clean ~/Library/Caches/ru.keepcoder.Telegram/* "Telegram cache"
safe_clean ~/Library/Caches/com.microsoft.teams2/* "Microsoft Teams cache"
safe_clean ~/Library/Caches/net.whatsapp.WhatsApp/* "WhatsApp cache"
safe_clean ~/Library/Caches/com.skype.skype/* "Skype cache"
safe_clean ~/Library/Caches/com.tencent.meeting/* "Tencent Meeting cache"
safe_clean ~/Library/Caches/com.tencent.WeWorkMac/* "WeCom cache"
safe_clean ~/Library/Caches/com.feishu.*/* "Feishu cache"
}
# Clean DingTalk
clean_dingtalk() {
safe_clean ~/Library/Caches/dd.work.exclusive4aliding/* "DingTalk (iDingTalk) cache"
safe_clean ~/Library/Caches/com.alibaba.AliLang.osx/* "AliLang security component"
safe_clean ~/Library/Application\ Support/iDingTalk/log/* "DingTalk logs"
safe_clean ~/Library/Application\ Support/iDingTalk/holmeslogs/* "DingTalk holmes logs"
}
# Clean AI assistants
clean_ai_apps() {
safe_clean ~/Library/Caches/com.openai.chat/* "ChatGPT cache"
safe_clean ~/Library/Caches/com.anthropic.claudefordesktop/* "Claude desktop cache"
safe_clean ~/Library/Logs/Claude/* "Claude logs"
}
# Clean design and creative tools
clean_design_tools() {
safe_clean ~/Library/Caches/com.bohemiancoding.sketch3/* "Sketch cache"
safe_clean ~/Library/Application\ Support/com.bohemiancoding.sketch3/cache/* "Sketch app cache"
safe_clean ~/Library/Caches/Adobe/* "Adobe cache"
safe_clean ~/Library/Caches/com.adobe.*/* "Adobe app caches"
safe_clean ~/Library/Caches/com.figma.Desktop/* "Figma cache"
safe_clean ~/Library/Caches/com.raycast.macos/* "Raycast cache"
}
# Clean video editing tools
clean_video_tools() {
safe_clean ~/Library/Caches/net.telestream.screenflow10/* "ScreenFlow cache"
safe_clean ~/Library/Caches/com.apple.FinalCut/* "Final Cut Pro cache"
safe_clean ~/Library/Caches/com.blackmagic-design.DaVinciResolve/* "DaVinci Resolve cache"
safe_clean ~/Library/Caches/com.adobe.PremierePro.*/* "Premiere Pro cache"
}
# Clean 3D and CAD tools
clean_3d_tools() {
safe_clean ~/Library/Caches/org.blenderfoundation.blender/* "Blender cache"
safe_clean ~/Library/Caches/com.maxon.cinema4d/* "Cinema 4D cache"
safe_clean ~/Library/Caches/com.autodesk.*/* "Autodesk cache"
safe_clean ~/Library/Caches/com.sketchup.*/* "SketchUp cache"
}
# Clean productivity apps
clean_productivity_apps() {
safe_clean ~/Library/Caches/com.tw93.MiaoYan/* "MiaoYan cache"
safe_clean ~/Library/Caches/com.klee.desktop/* "Klee cache"
safe_clean ~/Library/Caches/klee_desktop/* "Klee desktop cache"
safe_clean ~/Library/Caches/com.orabrowser.app/* "Ora browser cache"
safe_clean ~/Library/Caches/com.filo.client/* "Filo cache"
safe_clean ~/Library/Caches/com.flomoapp.mac/* "Flomo cache"
}
# Clean music and media players
clean_media_players() {
safe_clean ~/Library/Caches/com.spotify.client/* "Spotify cache"
safe_clean ~/Library/Caches/com.apple.Music "Apple Music cache"
safe_clean ~/Library/Caches/com.apple.podcasts "Apple Podcasts cache"
safe_clean ~/Library/Caches/com.apple.TV/* "Apple TV cache"
safe_clean ~/Library/Caches/tv.plex.player.desktop "Plex cache"
safe_clean ~/Library/Caches/com.netease.163music "NetEase Music cache"
safe_clean ~/Library/Caches/com.tencent.QQMusic/* "QQ Music cache"
safe_clean ~/Library/Caches/com.kugou.mac/* "Kugou Music cache"
safe_clean ~/Library/Caches/com.kuwo.mac/* "Kuwo Music cache"
}
# Clean video players
clean_video_players() {
safe_clean ~/Library/Caches/com.colliderli.iina "IINA cache"
safe_clean ~/Library/Caches/org.videolan.vlc "VLC cache"
safe_clean ~/Library/Caches/io.mpv "MPV cache"
safe_clean ~/Library/Caches/com.iqiyi.player "iQIYI cache"
safe_clean ~/Library/Caches/com.tencent.tenvideo "Tencent Video cache"
safe_clean ~/Library/Caches/tv.danmaku.bili/* "Bilibili cache"
safe_clean ~/Library/Caches/com.douyu.*/* "Douyu cache"
safe_clean ~/Library/Caches/com.huya.*/* "Huya cache"
}
# Clean download managers
clean_download_managers() {
safe_clean ~/Library/Caches/net.xmac.aria2gui "Aria2 cache"
safe_clean ~/Library/Caches/org.m0k.transmission "Transmission cache"
safe_clean ~/Library/Caches/com.qbittorrent.qBittorrent "qBittorrent cache"
safe_clean ~/Library/Caches/com.downie.Downie-* "Downie cache"
safe_clean ~/Library/Caches/com.folx.*/* "Folx cache"
safe_clean ~/Library/Caches/com.charlessoft.pacifist/* "Pacifist cache"
}
# Clean gaming platforms
clean_gaming_platforms() {
safe_clean ~/Library/Caches/com.valvesoftware.steam/* "Steam cache"
safe_clean ~/Library/Application\ Support/Steam/htmlcache/* "Steam web cache"
safe_clean ~/Library/Caches/com.epicgames.EpicGamesLauncher/* "Epic Games cache"
safe_clean ~/Library/Caches/com.blizzard.Battle.net/* "Battle.net cache"
safe_clean ~/Library/Application\ Support/Battle.net/Cache/* "Battle.net app cache"
safe_clean ~/Library/Caches/com.ea.*/* "EA Origin cache"
safe_clean ~/Library/Caches/com.gog.galaxy/* "GOG Galaxy cache"
safe_clean ~/Library/Caches/com.riotgames.*/* "Riot Games cache"
}
# Clean translation and dictionary apps
clean_translation_apps() {
safe_clean ~/Library/Caches/com.youdao.YoudaoDict "Youdao Dictionary cache"
safe_clean ~/Library/Caches/com.eudic.* "Eudict cache"
safe_clean ~/Library/Caches/com.bob-build.Bob "Bob Translation cache"
}
# Clean screenshot and screen recording tools
clean_screenshot_tools() {
safe_clean ~/Library/Caches/com.cleanshot.* "CleanShot cache"
safe_clean ~/Library/Caches/com.reincubate.camo "Camo cache"
safe_clean ~/Library/Caches/com.xnipapp.xnip "Xnip cache"
}
# Clean email clients
clean_email_clients() {
safe_clean ~/Library/Caches/com.readdle.smartemail-Mac "Spark cache"
safe_clean ~/Library/Caches/com.airmail.* "Airmail cache"
}
# Clean task management apps
clean_task_apps() {
safe_clean ~/Library/Caches/com.todoist.mac.Todoist "Todoist cache"
safe_clean ~/Library/Caches/com.any.do.* "Any.do cache"
}
# Clean shell and terminal utilities
clean_shell_utils() {
safe_clean ~/.zcompdump* "Zsh completion cache"
safe_clean ~/.lesshst "less history"
safe_clean ~/.viminfo.tmp "Vim temporary files"
safe_clean ~/.wget-hsts "wget HSTS cache"
}
# Clean input method and system utilities
clean_system_utils() {
safe_clean ~/Library/Caches/com.runjuu.Input-Source-Pro/* "Input Source Pro cache"
safe_clean ~/Library/Caches/macos-wakatime.WakaTime/* "WakaTime cache"
}
# Clean note-taking apps
clean_note_apps() {
safe_clean ~/Library/Caches/notion.id/* "Notion cache"
safe_clean ~/Library/Caches/md.obsidian/* "Obsidian cache"
safe_clean ~/Library/Caches/com.logseq.*/* "Logseq cache"
safe_clean ~/Library/Caches/com.bear-writer.*/* "Bear cache"
safe_clean ~/Library/Caches/com.evernote.*/* "Evernote cache"
safe_clean ~/Library/Caches/com.yinxiang.*/* "Yinxiang Note cache"
}
# Clean launcher and automation tools
clean_launcher_apps() {
safe_clean ~/Library/Caches/com.runningwithcrayons.Alfred/* "Alfred cache"
safe_clean ~/Library/Caches/cx.c3.theunarchiver/* "The Unarchiver cache"
}
# Clean remote desktop tools
clean_remote_desktop() {
safe_clean ~/Library/Caches/com.teamviewer.*/* "TeamViewer cache"
safe_clean ~/Library/Caches/com.anydesk.*/* "AnyDesk cache"
safe_clean ~/Library/Caches/com.todesk.*/* "ToDesk cache"
safe_clean ~/Library/Caches/com.sunlogin.*/* "Sunlogin cache"
}
# Main function to clean all user GUI applications
clean_user_gui_applications() {
clean_xcode_tools
clean_code_editors
clean_communication_apps
clean_dingtalk
clean_ai_apps
clean_design_tools
clean_video_tools
clean_3d_tools
clean_productivity_apps
clean_media_players
clean_video_players
clean_download_managers
clean_gaming_platforms
clean_translation_apps
clean_screenshot_tools
clean_email_clients
clean_task_apps
clean_shell_utils
clean_system_utils
clean_note_apps
clean_launcher_apps
clean_remote_desktop
}

241
lib/clean_user_data.sh Normal file
View File

@@ -0,0 +1,241 @@
#!/bin/bash
# User Data Cleanup Module
# Essential user caches, browsers, cloud storage, office apps
set -euo pipefail
# Clean user essentials (caches, logs, trash, crash reports)
# Env: DRY_RUN
clean_user_essentials() {
safe_clean ~/Library/Caches/* "User app cache"
safe_clean ~/Library/Logs/* "User app logs"
safe_clean ~/.Trash/* "Trash"
# Empty trash on mounted volumes
if [[ -d "/Volumes" ]]; then
for volume in /Volumes/*; do
[[ -d "$volume" && -d "$volume/.Trashes" && -w "$volume" ]] || continue
# Skip network volumes
local fs_type=$(df -T "$volume" 2> /dev/null | tail -1 | awk '{print $2}')
case "$fs_type" in
nfs | smbfs | afpfs | cifs | webdav) continue ;;
esac
# Verify volume is mounted
if mount | grep -q "on $volume "; then
if [[ "$DRY_RUN" != "true" ]]; then
find "$volume/.Trashes" -mindepth 1 -maxdepth 1 -exec rm -rf {} \; 2> /dev/null || true
fi
fi
done
fi
safe_clean ~/Library/Application\ Support/CrashReporter/* "Crash reports"
safe_clean ~/Library/DiagnosticReports/* "Diagnostic reports"
safe_clean ~/Library/Caches/com.apple.QuickLook.thumbnailcache "QuickLook thumbnails"
safe_clean ~/Library/Caches/Quick\ Look/* "QuickLook cache"
safe_clean ~/Library/Caches/com.apple.iconservices* "Icon services cache"
safe_clean ~/Library/Caches/CloudKit/* "CloudKit cache"
# Clean incomplete downloads
safe_clean ~/Downloads/*.download "Incomplete downloads (Safari)"
safe_clean ~/Downloads/*.crdownload "Incomplete downloads (Chrome)"
safe_clean ~/Downloads/*.part "Incomplete downloads (partial)"
# Additional user-level caches
safe_clean ~/Library/Autosave\ Information/* "Autosave information"
safe_clean ~/Library/IdentityCaches/* "Identity caches"
safe_clean ~/Library/Suggestions/* "Suggestions cache (Siri)"
safe_clean ~/Library/Calendars/Calendar\ Cache "Calendar cache"
safe_clean ~/Library/Application\ Support/AddressBook/Sources/*/Photos.cache "Address Book photo cache"
}
# Clean Finder metadata (.DS_Store files)
# Env: PROTECT_FINDER_METADATA
clean_finder_metadata() {
if [[ "$PROTECT_FINDER_METADATA" == "true" ]]; then
note_activity
echo -e " ${YELLOW}${NC} Finder metadata protected by whitelist"
echo -e " ${YELLOW}${NC} Run ${GRAY}mo clean --whitelist${NC} to allow cleaning .DS_Store files"
else
clean_ds_store_tree "$HOME" "Home directory (.DS_Store)"
if [[ -d "/Volumes" ]]; then
for volume in /Volumes/*; do
[[ -d "$volume" && -w "$volume" ]] || continue
local fs_type=""
fs_type=$(df -T "$volume" 2> /dev/null | tail -1 | awk '{print $2}')
case "$fs_type" in
nfs | smbfs | afpfs | cifs | webdav) continue ;;
esac
clean_ds_store_tree "$volume" "$(basename "$volume") volume (.DS_Store)"
done
fi
fi
}
# Clean macOS system caches
clean_macos_system_caches() {
safe_clean ~/Library/Saved\ Application\ State/* "Saved application states"
safe_clean ~/Library/Caches/com.apple.spotlight "Spotlight cache"
safe_clean ~/Library/Caches/com.apple.photoanalysisd "Photo analysis cache"
safe_clean ~/Library/Caches/com.apple.akd "Apple ID cache"
safe_clean ~/Library/Caches/com.apple.Safari/Webpage\ Previews/* "Safari webpage previews"
safe_clean ~/Library/Application\ Support/CloudDocs/session/db/* "iCloud session cache"
safe_clean ~/Library/Caches/com.apple.Safari/fsCachedData/* "Safari cached data"
safe_clean ~/Library/Caches/com.apple.WebKit.WebContent/* "WebKit content cache"
safe_clean ~/Library/Caches/com.apple.WebKit.Networking/* "WebKit network cache"
}
# Clean sandboxed app caches
clean_sandboxed_app_caches() {
safe_clean ~/Library/Containers/com.apple.wallpaper.agent/Data/Library/Caches/* "Wallpaper agent cache"
safe_clean ~/Library/Containers/com.apple.mediaanalysisd/Data/Library/Caches/* "Media analysis cache"
safe_clean ~/Library/Containers/com.apple.AppStore/Data/Library/Caches/* "App Store cache"
safe_clean ~/Library/Containers/com.apple.configurator.xpc.InternetService/Data/tmp/* "Apple Configurator temp files"
safe_clean ~/Library/Containers/*/Data/Library/Caches/* "Sandboxed app caches"
}
# Clean browser caches (Safari, Chrome, Edge, Firefox, etc.)
clean_browsers() {
safe_clean ~/Library/Caches/com.apple.Safari/* "Safari cache"
# Chrome/Chromium
safe_clean ~/Library/Caches/Google/Chrome/* "Chrome cache"
safe_clean ~/Library/Application\ Support/Google/Chrome/*/Application\ Cache/* "Chrome app cache"
safe_clean ~/Library/Application\ Support/Google/Chrome/*/GPUCache/* "Chrome GPU cache"
safe_clean ~/Library/Caches/Chromium/* "Chromium cache"
safe_clean ~/Library/Caches/com.microsoft.edgemac/* "Edge cache"
safe_clean ~/Library/Caches/company.thebrowser.Browser/* "Arc cache"
safe_clean ~/Library/Caches/company.thebrowser.dia/* "Dia cache"
safe_clean ~/Library/Caches/BraveSoftware/Brave-Browser/* "Brave cache"
safe_clean ~/Library/Caches/Firefox/* "Firefox cache"
safe_clean ~/Library/Caches/com.operasoftware.Opera/* "Opera cache"
safe_clean ~/Library/Caches/com.vivaldi.Vivaldi/* "Vivaldi cache"
safe_clean ~/Library/Caches/Comet/* "Comet cache"
safe_clean ~/Library/Caches/com.kagi.kagimacOS/* "Orion cache"
safe_clean ~/Library/Caches/zen/* "Zen cache"
safe_clean ~/Library/Application\ Support/Firefox/Profiles/*/cache2/* "Firefox profile cache"
# Service Worker CacheStorage (all profiles)
# Limit search depth to prevent hanging on large profile directories
while IFS= read -r sw_path; do
[[ -z "$sw_path" ]] && continue
local profile_name=$(basename "$(dirname "$(dirname "$sw_path")")")
local browser_name="Chrome"
[[ "$sw_path" == *"Microsoft Edge"* ]] && browser_name="Edge"
[[ "$sw_path" == *"Brave"* ]] && browser_name="Brave"
[[ "$sw_path" == *"Arc"* ]] && browser_name="Arc"
[[ "$profile_name" != "Default" ]] && browser_name="$browser_name ($profile_name)"
clean_service_worker_cache "$browser_name" "$sw_path"
done < <(find "$HOME/Library/Application Support/Google/Chrome" \
"$HOME/Library/Application Support/Microsoft Edge" \
"$HOME/Library/Application Support/BraveSoftware/Brave-Browser" \
"$HOME/Library/Application Support/Arc/User Data" \
-maxdepth 6 -type d -name "CacheStorage" -path "*/Service Worker/*" 2> /dev/null || true)
}
# Clean cloud storage app caches
clean_cloud_storage() {
safe_clean ~/Library/Caches/com.dropbox.* "Dropbox cache"
safe_clean ~/Library/Caches/com.getdropbox.dropbox "Dropbox cache"
safe_clean ~/Library/Caches/com.google.GoogleDrive "Google Drive cache"
safe_clean ~/Library/Caches/com.baidu.netdisk "Baidu Netdisk cache"
safe_clean ~/Library/Caches/com.alibaba.teambitiondisk "Alibaba Cloud cache"
safe_clean ~/Library/Caches/com.box.desktop "Box cache"
safe_clean ~/Library/Caches/com.microsoft.OneDrive "OneDrive cache"
}
# Clean office application caches
clean_office_applications() {
safe_clean ~/Library/Caches/com.microsoft.Word "Microsoft Word cache"
safe_clean ~/Library/Caches/com.microsoft.Excel "Microsoft Excel cache"
safe_clean ~/Library/Caches/com.microsoft.Powerpoint "Microsoft PowerPoint cache"
safe_clean ~/Library/Caches/com.microsoft.Outlook/* "Microsoft Outlook cache"
safe_clean ~/Library/Caches/com.apple.iWork.* "Apple iWork cache"
safe_clean ~/Library/Caches/com.kingsoft.wpsoffice.mac "WPS Office cache"
safe_clean ~/Library/Caches/org.mozilla.thunderbird/* "Thunderbird cache"
safe_clean ~/Library/Caches/com.apple.mail/* "Apple Mail cache"
}
# Clean virtualization tools
clean_virtualization_tools() {
safe_clean ~/Library/Caches/com.vmware.fusion "VMware Fusion cache"
safe_clean ~/Library/Caches/com.parallels.* "Parallels cache"
safe_clean ~/VirtualBox\ VMs/.cache "VirtualBox cache"
safe_clean ~/.vagrant.d/tmp/* "Vagrant temporary files"
}
# Clean Application Support logs
clean_application_support_logs() {
# Check permission
if [[ ! -d "$HOME/Library/Application Support" ]] || ! ls "$HOME/Library/Application Support" > /dev/null 2>&1; then
note_activity
echo -e " ${YELLOW}${ICON_WARNING}${NC} Skipped: No permission to access Application Support"
return 0
fi
# Clean log directories with iteration limit to prevent hanging
local iteration_count=0
local max_iterations=200
for app_dir in ~/Library/Application\ Support/*; do
[[ -d "$app_dir" ]] || continue
# Safety: limit iterations
((iteration_count++))
if [[ $iteration_count -gt $max_iterations ]]; then
break
fi
app_name=$(basename "$app_dir")
# Skip system and protected apps
case "$app_name" in
com.apple.* | Adobe* | JetBrains* | 1Password | Claude | *ClashX* | *clash* | mihomo* | *Surge* | iTerm* | *iterm* | Warp* | Kitty* | Alacritty* | WezTerm* | Ghostty*)
continue
;;
esac
# Clean common log directories (only if they exist and are accessible)
if [[ -d "$app_dir/log" ]] && ls "$app_dir/log" > /dev/null 2>&1; then
safe_clean "$app_dir/log"/* "App logs: $app_name"
fi
if [[ -d "$app_dir/logs" ]] && ls "$app_dir/logs" > /dev/null 2>&1; then
safe_clean "$app_dir/logs"/* "App logs: $app_name"
fi
if [[ -d "$app_dir/activitylog" ]] && ls "$app_dir/activitylog" > /dev/null 2>&1; then
safe_clean "$app_dir/activitylog"/* "Activity logs: $app_name"
fi
done
}
# Check and show iOS device backup info
check_ios_device_backups() {
local backup_dir="$HOME/Library/Application Support/MobileSync/Backup"
if [[ -d "$backup_dir" ]] && find "$backup_dir" -mindepth 1 -maxdepth 1 | read -r _; then
local backup_kb=$(du -sk "$backup_dir" 2> /dev/null | awk '{print $1}')
if [[ -n "${backup_kb:-}" && "$backup_kb" -gt 102400 ]]; then
local backup_human=$(du -sh "$backup_dir" 2> /dev/null | awk '{print $1}')
note_activity
echo -e " Found ${GREEN}${backup_human}${NC} iOS backups"
echo -e " You can delete them manually: ${backup_dir}"
fi
fi
}
# Clean Apple Silicon specific caches
# Env: IS_M_SERIES
clean_apple_silicon_caches() {
if [[ "$IS_M_SERIES" != "true" ]]; then
return 0
fi
safe_clean /Library/Apple/usr/share/rosetta/rosetta_update_bundle "Rosetta 2 cache"
safe_clean ~/Library/Caches/com.apple.rosetta.update "Rosetta 2 user cache"
safe_clean ~/Library/Caches/com.apple.amp.mediasevicesd "Apple Silicon media service cache"
}

View File

@@ -35,7 +35,7 @@ readonly ICON_NAV_DOWN="↓" # Navigation down
readonly ICON_NAV_LEFT="←" # Navigation left
readonly ICON_NAV_RIGHT="→" # Navigation right
# Spinner character helpers (ASCII by default, overridable via env)
# Get spinner characters (ASCII by default, overridable via MO_SPINNER_CHARS env)
mo_spinner_chars() {
local chars="${MO_SPINNER_CHARS:-|/-\\}"
[[ -z "$chars" ]] && chars='|/-\\'
@@ -46,16 +46,19 @@ mo_spinner_chars() {
# Always use system BSD stat instead of potentially overridden GNU version
readonly STAT_BSD="/usr/bin/stat"
# Get file size in bytes using BSD stat
get_file_size() {
local file="$1"
$STAT_BSD -f%z "$file" 2> /dev/null || echo 0
}
# Get file modification time (epoch seconds) using BSD stat
get_file_mtime() {
local file="$1"
$STAT_BSD -f%m "$file" 2> /dev/null || echo 0
}
# Get file owner username using BSD stat
get_file_owner() {
local file="$1"
$STAT_BSD -f%Su "$file" 2> /dev/null || echo ""
@@ -200,8 +203,8 @@ log_error() {
# Call rotation check once when common.sh is sourced
rotate_log_once
# Icon output helpers
# Consistent summary blocks for command results
# Print formatted summary block with heading and details
# Args: $1=status (ignored), $2=heading, $@=details
print_summary_block() {
local heading=""
@@ -228,7 +231,7 @@ print_summary_block() {
echo "$divider"
}
# System detection
# Detect CPU architecture (Apple Silicon or Intel)
detect_architecture() {
if [[ "$(uname -m)" == "arm64" ]]; then
echo "Apple Silicon"
@@ -237,24 +240,29 @@ detect_architecture() {
fi
}
# Get free disk space on root volume (human-readable)
get_free_space() {
df -h / | awk 'NR==2 {print $4}'
}
# Common UI functions
# Clear terminal screen and move cursor to home
clear_screen() {
printf '\033[2J\033[H'
}
# Hide terminal cursor
hide_cursor() {
printf '\033[?25l'
}
# Show terminal cursor
show_cursor() {
printf '\033[?25h'
}
# Keyboard input handling (simplified)
# Read single keypress and return normalized key name
# Returns: ENTER, SPACE, UP, DOWN, LEFT, RIGHT, QUIT, DELETE, CHAR:<c>, etc.
# Env: MOLE_READ_KEY_FORCE_CHAR=1 for filter mode
read_key() {
local key rest read_status
@@ -354,7 +362,7 @@ read_key() {
esac
}
# Drain pending input (simplified single-pass)
# Drain pending keyboard/mouse input to prevent accidental triggers
drain_pending_input() {
local drained=0
# Single pass with 0.01s timeout is sufficient for mouse wheel events
@@ -364,7 +372,7 @@ drain_pending_input() {
done
}
# Shared timeout helper -------------------------------------------------------
# Initialize timeout command (gtimeout or timeout)
if [[ -z "${MO_TIMEOUT_INITIALIZED:-}" ]]; then
MO_TIMEOUT_BIN=""
for candidate in gtimeout timeout; do
@@ -376,6 +384,8 @@ if [[ -z "${MO_TIMEOUT_INITIALIZED:-}" ]]; then
export MO_TIMEOUT_INITIALIZED=1
fi
# Run command with timeout (uses gtimeout/timeout if available, fallback to kill)
# Args: $1=seconds, $@=command
run_with_timeout() {
local duration="${1:-0}"
shift || true
@@ -650,6 +660,7 @@ request_sudo_access() {
return $?
}
# Legacy sudo request (no Touch ID, password only)
request_sudo() {
echo "This operation requires administrator privileges."
echo -n "Please enter your password: "
@@ -663,7 +674,8 @@ request_sudo() {
fi
}
# Homebrew update utilities
# Update Mole via Homebrew with timeout and error handling
# Args: $1=current_version, Env: MO_BREW_UPDATE_TIMEOUT
update_via_homebrew() {
local version="${1:-unknown}"

200
tests/clean_caches.bats Normal file
View File

@@ -0,0 +1,200 @@
#!/usr/bin/env bats
setup_file() {
PROJECT_ROOT="$(cd "${BATS_TEST_DIRNAME}/.." && pwd)"
export PROJECT_ROOT
ORIGINAL_HOME="${HOME:-}"
export ORIGINAL_HOME
HOME="$(mktemp -d "${BATS_TEST_DIRNAME}/tmp-clean-caches.XXXXXX")"
export HOME
mkdir -p "$HOME"
mkdir -p "$HOME/.cache/mole"
mkdir -p "$HOME/Library/Caches"
mkdir -p "$HOME/Library/Logs"
}
teardown_file() {
rm -rf "$HOME"
if [[ -n "${ORIGINAL_HOME:-}" ]]; then
export HOME="$ORIGINAL_HOME"
fi
}
setup() {
source "$PROJECT_ROOT/lib/common.sh"
source "$PROJECT_ROOT/lib/clean_caches.sh"
# Clean permission flag for each test
rm -f "$HOME/.cache/mole/permissions_granted"
}
# Test check_tcc_permissions in non-interactive mode
@test "check_tcc_permissions skips in non-interactive mode" {
# Redirect stdin to simulate non-TTY
run bash -c "source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/clean_caches.sh'; check_tcc_permissions" < /dev/null
[ "$status" -eq 0 ]
# Should not create permission flag in non-interactive mode
[[ ! -f "$HOME/.cache/mole/permissions_granted" ]]
}
# Test check_tcc_permissions with existing permission flag
@test "check_tcc_permissions skips when permissions already granted" {
# Create permission flag
mkdir -p "$HOME/.cache/mole"
touch "$HOME/.cache/mole/permissions_granted"
# Even in TTY mode, should skip if flag exists
run bash -c "source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/clean_caches.sh'; [[ -t 1 ]] || true; check_tcc_permissions"
[ "$status" -eq 0 ]
}
# Test check_tcc_permissions directory checks
@test "check_tcc_permissions validates protected directories" {
# The function checks these directories exist:
# - ~/Library/Caches
# - ~/Library/Logs
# - ~/Library/Application Support
# - ~/Library/Containers
# - ~/.cache
# Ensure test environment has these directories
[[ -d "$HOME/Library/Caches" ]]
[[ -d "$HOME/Library/Logs" ]]
[[ -d "$HOME/.cache/mole" ]]
# Function should handle missing directories gracefully
run bash -c "source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/clean_caches.sh'; check_tcc_permissions < /dev/null"
[ "$status" -eq 0 ]
}
# Test clean_service_worker_cache with non-existent path
@test "clean_service_worker_cache returns early when path doesn't exist" {
run bash -c "source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/clean_caches.sh'; clean_service_worker_cache 'TestBrowser' '/nonexistent/path'"
[ "$status" -eq 0 ]
}
# Test clean_service_worker_cache with empty directory
@test "clean_service_worker_cache handles empty cache directory" {
local test_cache="$HOME/test_sw_cache"
mkdir -p "$test_cache"
run bash -c "source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/clean_caches.sh'; clean_service_worker_cache 'TestBrowser' '$test_cache'"
[ "$status" -eq 0 ]
rm -rf "$test_cache"
}
# Test clean_service_worker_cache domain protection
@test "clean_service_worker_cache protects specified domains" {
local test_cache="$HOME/test_sw_cache"
mkdir -p "$test_cache/abc123_https_capcut.com_0"
mkdir -p "$test_cache/def456_https_example.com_0"
# Mock PROTECTED_SW_DOMAINS
export PROTECTED_SW_DOMAINS=("capcut.com" "photopea.com")
# Dry run to check protection logic
run bash -c "
export DRY_RUN=true
export PROTECTED_SW_DOMAINS=(capcut.com photopea.com)
source '$PROJECT_ROOT/lib/common.sh'
source '$PROJECT_ROOT/lib/clean_caches.sh'
clean_service_worker_cache 'TestBrowser' '$test_cache'
"
[ "$status" -eq 0 ]
# Protected domain directory should still exist
[[ -d "$test_cache/abc123_https_capcut.com_0" ]]
rm -rf "$test_cache"
}
# Test clean_project_caches function
@test "clean_project_caches completes without errors" {
# Create test project structures
mkdir -p "$HOME/projects/test-app/.next/cache"
mkdir -p "$HOME/projects/python-app/__pycache__"
# Create some dummy cache files
touch "$HOME/projects/test-app/.next/cache/test.cache"
touch "$HOME/projects/python-app/__pycache__/module.pyc"
run bash -c "
export DRY_RUN=true
source '$PROJECT_ROOT/lib/common.sh'
source '$PROJECT_ROOT/lib/clean_caches.sh'
clean_project_caches
"
[ "$status" -eq 0 ]
rm -rf "$HOME/projects"
}
# Test clean_project_caches timeout protection
@test "clean_project_caches handles timeout gracefully" {
# Create a test directory structure
mkdir -p "$HOME/test-project/.next"
# Mock find to simulate slow operation
function find() {
sleep 2 # Simulate slow find
echo "$HOME/test-project/.next"
}
export -f find
# Should complete within reasonable time even with slow find
run timeout 15 bash -c "
source '$PROJECT_ROOT/lib/common.sh'
source '$PROJECT_ROOT/lib/clean_caches.sh'
clean_project_caches
"
# Either succeeds or times out gracefully (both acceptable)
[ "$status" -eq 0 ] || [ "$status" -eq 124 ]
rm -rf "$HOME/test-project"
}
# Test clean_project_caches exclusions
@test "clean_project_caches excludes Library and Trash directories" {
# These directories should be excluded from scan
mkdir -p "$HOME/Library/.next/cache"
mkdir -p "$HOME/.Trash/.next/cache"
mkdir -p "$HOME/projects/.next/cache"
# Only non-excluded directories should be scanned
# We can't easily test this without mocking, but we can verify no crashes
run bash -c "
export DRY_RUN=true
source '$PROJECT_ROOT/lib/common.sh'
source '$PROJECT_ROOT/lib/clean_caches.sh'
clean_project_caches
"
[ "$status" -eq 0 ]
rm -rf "$HOME/projects"
}
# Test permission flag creation
@test "check_tcc_permissions creates permission flag after check" {
# Remove flag if exists
rm -f "$HOME/.cache/mole/permissions_granted"
# Simulate accessible Library/Caches (skip TCC dialog)
function ls() {
return 0 # Simulate accessible
}
export -f ls
run bash -c "
source '$PROJECT_ROOT/lib/common.sh'
source '$PROJECT_ROOT/lib/clean_caches.sh'
check_tcc_permissions < /dev/null
"
[ "$status" -eq 0 ]
# Permission flag should be created
[[ -f "$HOME/.cache/mole/permissions_granted" ]]
}

123
tests/sudo_manager.bats Normal file
View File

@@ -0,0 +1,123 @@
#!/usr/bin/env bats
setup_file() {
PROJECT_ROOT="$(cd "${BATS_TEST_DIRNAME}/.." && pwd)"
export PROJECT_ROOT
}
setup() {
# Source common.sh first (required by sudo_manager)
source "$PROJECT_ROOT/lib/common.sh"
source "$PROJECT_ROOT/lib/sudo_manager.sh"
}
# Test sudo session detection
@test "has_sudo_session returns 1 when no sudo session" {
# Most test environments don't have active sudo
# This test verifies the function handles no-sudo gracefully
run has_sudo_session
# Either no sudo (status 1) or sudo available (status 0)
# Both are valid - we just check it doesn't crash
[ "$status" -eq 0 ] || [ "$status" -eq 1 ]
}
# Test sudo keepalive lifecycle
@test "sudo keepalive functions don't crash" {
# Test that keepalive functions can be called without errors
# We can't actually test sudo without prompting, but we can test structure
# Mock sudo to avoid actual auth
function sudo() {
return 1 # Simulate no sudo available
}
export -f sudo
# These should not crash even without real sudo
run bash -c "source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/sudo_manager.sh'; has_sudo_session"
[ "$status" -eq 1 ] # Expected: no sudo session
}
# Test keepalive PID management
@test "_start_sudo_keepalive returns a PID" {
# Mock sudo to simulate successful session
function sudo() {
case "$1" in
-n) return 0 ;; # Simulate valid sudo session
-v) return 0 ;; # Refresh succeeds
*) return 1 ;;
esac
}
export -f sudo
# Start keepalive (will run in background)
local pid
pid=$(bash -c "source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/sudo_manager.sh'; _start_sudo_keepalive")
# Should return a PID (number)
[[ "$pid" =~ ^[0-9]+$ ]]
# Clean up background process
kill "$pid" 2>/dev/null || true
wait "$pid" 2>/dev/null || true
}
# Test _stop_sudo_keepalive
@test "_stop_sudo_keepalive handles invalid PID gracefully" {
run bash -c "source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/sudo_manager.sh'; _stop_sudo_keepalive ''"
[ "$status" -eq 0 ]
run bash -c "source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/sudo_manager.sh'; _stop_sudo_keepalive '99999'"
[ "$status" -eq 0 ]
}
# Test request_sudo function structure
@test "request_sudo accepts prompt parameter" {
# Mock request_sudo_access to avoid actual prompting
function request_sudo_access() {
return 1 # Simulate denied
}
export -f request_sudo_access
run bash -c "source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/sudo_manager.sh'; request_sudo 'Test prompt'"
[ "$status" -eq 1 ] # Expected: denied
}
# Test start_sudo_session integration
@test "start_sudo_session handles success and failure paths" {
# Mock request_sudo to simulate denied access
function request_sudo() {
return 1
}
export -f request_sudo
run bash -c "source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/sudo_manager.sh'; start_sudo_session 'Test'"
[ "$status" -eq 1 ]
# Mock request_sudo to simulate granted access
function request_sudo() {
return 0
}
function _start_sudo_keepalive() {
echo "12345"
}
export -f request_sudo
export -f _start_sudo_keepalive
run bash -c "source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/sudo_manager.sh'; start_sudo_session 'Test'"
[ "$status" -eq 0 ]
}
# Test stop_sudo_session cleanup
@test "stop_sudo_session cleans up keepalive process" {
# Set a fake PID
export MOLE_SUDO_KEEPALIVE_PID="99999"
run bash -c "export MOLE_SUDO_KEEPALIVE_PID=99999; source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/sudo_manager.sh'; stop_sudo_session"
[ "$status" -eq 0 ]
}
# Test global state management
@test "sudo manager initializes global state correctly" {
result=$(bash -c "source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/sudo_manager.sh'; echo \$MOLE_SUDO_ESTABLISHED")
[[ "$result" == "false" ]] || [[ -z "$result" ]]
}

197
tests/update_manager.bats Normal file
View File

@@ -0,0 +1,197 @@
#!/usr/bin/env bats
setup_file() {
PROJECT_ROOT="$(cd "${BATS_TEST_DIRNAME}/.." && pwd)"
export PROJECT_ROOT
ORIGINAL_HOME="${HOME:-}"
export ORIGINAL_HOME
HOME="$(mktemp -d "${BATS_TEST_DIRNAME}/tmp-update-manager.XXXXXX")"
export HOME
mkdir -p "$HOME"
}
teardown_file() {
rm -rf "$HOME"
if [[ -n "${ORIGINAL_HOME:-}" ]]; then
export HOME="$ORIGINAL_HOME"
fi
}
setup() {
source "$PROJECT_ROOT/lib/common.sh"
source "$PROJECT_ROOT/lib/update_manager.sh"
}
# Test brew_has_outdated function
@test "brew_has_outdated returns 1 when brew not installed" {
function brew() {
return 127 # Command not found
}
export -f brew
run bash -c "source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/update_manager.sh'; brew_has_outdated"
[ "$status" -eq 1 ]
}
@test "brew_has_outdated checks formula by default" {
# Mock brew to simulate outdated formulas
function brew() {
if [[ "$1" == "outdated" && "$2" != "--cask" ]]; then
echo "package1"
echo "package2"
return 0
fi
return 1
}
export -f brew
run bash -c "source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/update_manager.sh'; brew_has_outdated"
[ "$status" -eq 0 ]
}
@test "brew_has_outdated checks casks when specified" {
# Mock brew to simulate outdated casks
function brew() {
if [[ "$1" == "outdated" && "$2" == "--cask" ]]; then
echo "app1"
return 0
fi
return 1
}
export -f brew
run bash -c "source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/update_manager.sh'; brew_has_outdated cask"
[ "$status" -eq 0 ]
}
# Test format_brew_update_label function
@test "format_brew_update_label returns empty when no updates" {
result=$(BREW_OUTDATED_COUNT=0 bash -c "source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/update_manager.sh'; format_brew_update_label")
[[ -z "$result" ]]
}
@test "format_brew_update_label formats with formula and cask counts" {
result=$(BREW_OUTDATED_COUNT=5 BREW_FORMULA_OUTDATED_COUNT=3 BREW_CASK_OUTDATED_COUNT=2 bash -c "source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/update_manager.sh'; format_brew_update_label")
[[ "$result" =~ "3 formula" ]]
[[ "$result" =~ "2 cask" ]]
}
@test "format_brew_update_label shows total when breakdown unavailable" {
result=$(BREW_OUTDATED_COUNT=5 bash -c "source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/update_manager.sh'; format_brew_update_label")
[[ "$result" =~ "5 updates" ]]
}
# Test ask_for_updates function
@test "ask_for_updates returns 1 when no updates available" {
run bash -c "source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/update_manager.sh'; ask_for_updates < /dev/null"
[ "$status" -eq 1 ]
}
@test "ask_for_updates detects Homebrew updates" {
# Mock environment with Homebrew updates
export BREW_OUTDATED_COUNT=5
export BREW_FORMULA_OUTDATED_COUNT=3
export BREW_CASK_OUTDATED_COUNT=2
# Use input redirection to simulate ESC (cancel)
run bash -c "printf '\x1b' | source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/update_manager.sh'; ask_for_updates"
# Should show updates and ask for confirmation
[ "$status" -eq 1 ] # ESC cancels
}
@test "ask_for_updates detects App Store updates" {
export APPSTORE_UPDATE_COUNT=3
run bash -c "printf '\x1b' | source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/update_manager.sh'; ask_for_updates"
[ "$status" -eq 1 ] # ESC cancels
}
@test "ask_for_updates detects macOS updates" {
export MACOS_UPDATE_AVAILABLE=true
run bash -c "printf '\x1b' | source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/update_manager.sh'; ask_for_updates"
[ "$status" -eq 1 ] # ESC cancels
}
@test "ask_for_updates detects Mole updates" {
export MOLE_UPDATE_AVAILABLE=true
run bash -c "printf '\x1b' | source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/update_manager.sh'; ask_for_updates"
[ "$status" -eq 1 ] # ESC cancels
}
# Test perform_updates function structure
@test "perform_updates handles brew formula updates" {
# Mock brew to avoid actual updates
function brew() {
case "$1" in
outdated)
if [[ "${2:-}" == "--cask" ]]; then
return 1 # No cask updates
else
echo "test-package"
return 0 # Has formula updates
fi
;;
upgrade)
echo "Upgrading test-package..."
return 0
;;
*)
return 1
;;
esac
}
export -f brew
export BREW_OUTDATED_COUNT=1
export BREW_FORMULA_OUTDATED_COUNT=1
export BREW_CASK_OUTDATED_COUNT=0
run bash -c "source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/update_manager.sh'; perform_updates"
[ "$status" -eq 0 ]
}
# Test update_homebrew function
@test "update_homebrew returns early when no updates" {
function brew() {
case "$1" in
outdated)
return 1 # No updates
;;
*)
return 1
;;
esac
}
export -f brew
run bash -c "source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/update_manager.sh'; update_homebrew"
[ "$status" -eq 0 ]
}
@test "update_homebrew handles network failures gracefully" {
function brew() {
case "$1" in
outdated)
if [[ "${2:-}" == "--quiet" ]]; then
echo "test-package"
return 0
fi
;;
upgrade)
return 1 # Simulate failure
;;
*)
return 1
;;
esac
}
export -f brew
run bash -c "source '$PROJECT_ROOT/lib/common.sh'; source '$PROJECT_ROOT/lib/update_manager.sh'; update_homebrew"
# Should handle failure without crashing
[ "$status" -eq 0 ] || [ "$status" -eq 1 ]
}