Free, open-source macOS cleaner. CleanMyMac alternative with zero telemetry. Native SwiftUI, scheduled auto-cleaning, Xcode/Homebrew/system cache cleanup. MIT licensed.
Swift cache-cleanercleanmymaccleanupdisk-cleanerdisk-spacehomebrewmac-utilitymacosmacos-appmacos-cleanermacosxnativeossosxprivacyswiftswiftuisystem-cleanerxcode-cleaner
feat(cli): add puremac terminal cleaner (#157)
Moamen Basel54a0bf31dfe8
diff --git a/README.md b/README.mdindex b2597a7..dc7b014 100644--- a/README.md+++ b/README.md@@ -68,6 +68,21 @@ xcodebuild -project PureMac.xcodeproj -scheme PureMac -configuration Release \open build/Build/Products/Release/PureMac.app```+### Command line (beta)++Prefer the terminal? `puremac` is a CLI companion that reuses the same cleaning+logic and safety rules to clear developer caches, purge project build artifacts,+and analyze disk usage.++```bash+brew install momenbasel/tap/puremac-cli+puremac clean dev --dry-run+```++++See [`cli/README.md`](cli/README.md) for the full command reference.+## How it compares| | **PureMac** | CleanMyMac | Pearcleaner | Mole | OnyX |diff --git a/cli/.gitignore b/cli/.gitignorenew file mode 100644index 0000000..30bcfa4--- /dev/null+++ b/cli/.gitignore@@ -0,0 +1 @@+.build/diff --git a/cli/Package.swift b/cli/Package.swiftnew file mode 100644index 0000000..3f1743c--- /dev/null+++ b/cli/Package.swift@@ -0,0 +1,27 @@+// swift-tools-version:5.9+import PackageDescription++let package = Package(+ name: "puremac",+ platforms: [.macOS(.v11)],+ products: [+ .executable(name: "puremac", targets: ["puremac"]),+ ],+ dependencies: [+ .package(url: "https://github.com/apple/swift-argument-parser", from: "1.3.0"),+ ],+ targets: [+ .executableTarget(+ name: "puremac",+ dependencies: [+ .product(name: "ArgumentParser", package: "swift-argument-parser"),+ ],+ path: "Sources/puremac"+ ),+ .testTarget(+ name: "puremacTests",+ dependencies: ["puremac"],+ path: "Tests/puremacTests"+ ),+ ]+)diff --git a/cli/README.md b/cli/README.mdnew file mode 100644index 0000000..9874926--- /dev/null+++ b/cli/README.md@@ -0,0 +1,88 @@+# PureMac CLI++Clean developer caches, project artifacts, and disk clutter from the terminal. A+command-line companion to the [PureMac](https://github.com/momenbasel/PureMac) app+that reuses the same cleaning logic and safety rules.++PureMac scans first and removes only what you approve. Cache and junk removal is+permanent, but cloud state (iCloud, Dropbox, OneDrive) and your config dotfiles+(`~/.ssh`, `~/.aws`, `~/.gnupg`, `~/.docker`, `~/.claude`, ...) are never touched.++++## Install++```bash+brew install momenbasel/tap/puremac-cli+```++Or build from source (requires a Swift 5.9+ toolchain):++```bash+cd cli+swift build -c release+.build/release/puremac --help+```++## Commands++| Command | What it does |+|---|---|+| `puremac clean` | Scan all categories (dev, junk, ai, trash), review, then remove |+| `puremac clean dev` | Package-manager and build-tool caches only |+| `puremac clean junk` | User logs and Xcode-generated junk only |+| `puremac clean ai` | AI-tool caches and logs only |+| `puremac clean trash` | Empty the user Trash and mounted-volume trashes |+| `puremac purge [path]` | Find removable build artifacts inside project folders |+| `puremac analyze [path]` | Show what is taking up disk space, largest first |+| `puremac optimize [ram\|purgeable]` | Free inactive RAM and release purgeable disk space |+| `puremac ignore add\|remove\|list <path>` | Protect paths from every scan |+| `puremac config` | Show or change preferences |++Flags on `clean` and `purge`:++- `--force` removes immediately, skipping the confirmation. Run without it first.+- `--dry-run` scans and reports what it would remove, deleting nothing.+- `--json` prints machine-readable output and never deletes.++## What `clean dev` covers++Homebrew, npm, Yarn, pnpm, pip, Cargo, Go, CocoaPods, VS Code, JetBrains, Maven,+Gradle, Poetry, uv, Bun, Deno, mise, Flutter/Dart, NuGet/.NET, Swift Package+Manager, Docker, and OrbStack. Only precise cache and build directories are+targeted, never a whole config directory such as `~/.cargo` or `~/.docker`.++## What `purge` finds++`node_modules`, `.next`, `.nuxt`, `.turbo`, `.svelte-kit`, `.angular`,+`.parcel-cache`, `target`, `.build`, `DerivedData`, `Pods`, `.venv`, `venv`,+`__pycache__`, `.pytest_cache`, `.mypy_cache`, `.tox`, `.ruff_cache`, `.gradle`,+and `cmake-build-*`, grouped by project. Artifacts older than seven days are+preselected; newer ones are shown but left unchecked.++## Safety++Every deletion passes one gate before it runs:++- Protected roots (`/`, `$HOME`, `~/Library`, and other containers) can be scanned+ into but never removed themselves.+- Config and credential directories are on a hard denylist.+- Cloud File Provider state (iCloud, Dropbox, OneDrive, Google Drive) is refused,+ checked against both the literal and symlink-resolved path.+- Symlinks are skipped, and no deletion follows a symlinked parent.+- Paths on your ignore list are excluded from every command.+- `clean` and `purge` print the full list of what will be removed and ask for+ confirmation before deleting anything.++Protect a path permanently:++```bash+puremac ignore add ~/Projects/important+```++## Notes++- `clean` and `junk` are user-scoped and need no `sudo`.+- `analyze` is read-only; nothing is deleted while browsing.+- An interactive full-screen browser for `analyze` is not built yet; the current+ view ranks folders by size like `du -d1 | sort`.diff --git a/cli/Sources/puremac/Commands/Analyze.swift b/cli/Sources/puremac/Commands/Analyze.swiftnew file mode 100644index 0000000..fbf172b--- /dev/null+++ b/cli/Sources/puremac/Commands/Analyze.swift@@ -0,0 +1,81 @@+import ArgumentParser+import Foundation++struct Analyze: ParsableCommand {+ static let configuration = CommandConfiguration(+ abstract: "Show what is taking up disk space, largest first.",+ discussion: """+ Sizes the immediate children of a folder and ranks them, like `du -d1 | sort`.+ puremac analyze Explore your home folder+ puremac analyze ~/Library Explore a specific folder+ Browsing never modifies files.+ """+ )++ @Argument(help: "Folder to analyze. Omit for your home folder.")+ var path: String?++ @Option(name: .shortAndLong, help: "How many levels deep to break down (default 1).")+ var depth: Int = 1++ @Flag(name: .long, help: "Emit machine-readable JSON and exit.")+ var json = false++ func run() throws {+ let target = ((path ?? Safety.home) as NSString).expandingTildeInPath+ var isDir: ObjCBool = false+ guard FileManager.default.fileExists(atPath: target, isDirectory: &isDir), isDir.boolValue else {+ throw ValidationError("Not a folder: \(target)")+ }++ let children = sizedChildren(of: target)+ let total = children.reduce(Int64(0)) { $0 + $1.size }++ if json {+ struct Row: Encodable { let path: String; let bytes: Int64 }+ let enc = JSONEncoder(); enc.outputFormatting = [.prettyPrinted, .withoutEscapingSlashes]+ let data = try enc.encode(children.map { Row(path: $0.path, bytes: $0.size) })+ print(String(decoding: data, as: UTF8.self))+ return+ }++ let vol = SystemInfo.volume(target)+ if vol.total > 0 {+ print("")+ print(Term.bold("\(ByteCount.human(vol.available)) free of \(ByteCount.human(vol.total))"))+ }+ print(Term.dim("\(Render.shorten(target)) — \(ByteCount.human(total))"))+ print("")+ printLevel(children, total: total, indent: " ", depthLeft: max(1, depth) - 1)+ }++ struct Child { let path: String; let size: Int64; let isDir: Bool }++ func sizedChildren(of dir: String) -> [Child] {+ let fm = FileManager.default+ guard let names = try? fm.contentsOfDirectory(atPath: dir) else { return [] }+ return names.compactMap { name -> Child? in+ let full = "\(dir)/\(name)"+ if let type = (try? fm.attributesOfItem(atPath: full)[.type]) as? FileAttributeType, type == .typeSymbolicLink {+ return nil+ }+ var isDir: ObjCBool = false+ fm.fileExists(atPath: full, isDirectory: &isDir)+ return Child(path: full, size: DirSizer.size(of: full), isDir: isDir.boolValue)+ }.sorted { $0.size > $1.size }+ }++ func printLevel(_ children: [Child], total: Int64, indent: String, depthLeft: Int) {+ for child in children where child.size > 0 {+ let frac = total > 0 ? Double(child.size) / Double(total) : 0+ let pct = String(format: "%5.1f%%", frac * 100)+ let size = ByteCount.human(child.size).padding(toLength: 10, withPad: " ", startingAt: 0)+ let name = URL(fileURLWithPath: child.path).lastPathComponent + (child.isDir ? "/" : "")+ print("\(indent)\(size) \(Term.dim(pct)) \(Term.bar(fraction: frac, width: 20)) \(name)")+ if depthLeft > 0 && child.isDir {+ let sub = sizedChildren(of: child.path)+ printLevel(Array(sub.prefix(10)), total: child.size, indent: indent + " ", depthLeft: depthLeft - 1)+ }+ }+ }+}diff --git a/cli/Sources/puremac/Commands/Clean.swift b/cli/Sources/puremac/Commands/Clean.swiftnew file mode 100644index 0000000..6b2f2b2--- /dev/null+++ b/cli/Sources/puremac/Commands/Clean.swift@@ -0,0 +1,107 @@+import ArgumentParser+import Foundation++struct Clean: ParsableCommand {+ static let configuration = CommandConfiguration(+ abstract: "Scan and remove developer caches, system junk, AI-tool junk, and Trash.",+ discussion: """+ With no category, scans all of: dev, junk, ai, trash.+ puremac clean Scan everything, review, confirm+ puremac clean dev Package-manager & build-tool caches only+ puremac clean junk User logs & Xcode-generated junk only+ puremac clean ai AI-tool caches & logs only+ puremac clean trash Empty user + mounted-volume Trash+ """+ )++ @Argument(help: "Category to clean: dev | junk | ai | trash. Omit to clean all.")+ var category: String?++ @Flag(name: .long, help: "Skip the confirmation prompt and remove immediately.")+ var force = false++ @Flag(name: .customLong("dry-run"), help: "Scan and report only; never delete.")+ var dryRun = false++ @Flag(name: .long, help: "Emit machine-readable JSON and exit (never deletes).")+ var json = false++ static let validIDs = ["dev", "junk", "ai", "trash"]++ func validate() throws {+ if let c = category, !Clean.validIDs.contains(c) {+ throw ValidationError("Unknown category '\(c)'. Use one of: \(Clean.validIDs.joined(separator: ", ")).")+ }+ }++ func run() throws {+ let ids = category.map { [$0] } ?? Clean.validIDs+ let ignore = IgnoreStore()+ let cats = ids.map { id in+ CategoryScanner.scan(categoryID: id, title: Clean.title(id), ignore: ignore)+ }.filter { !$0.groups.isEmpty }++ if json {+ print(JSONReport.string(cats))+ return+ }++ if cats.isEmpty {+ print(Term.green("Nothing to clean — you're already tidy."))+ return+ }++ Render.scanResults(cats)+ Render.selectionLine(cats)++ let selected = cats.flatMap { $0.selectedItems }+ if selected.isEmpty {+ print(Term.dim("No items selected by default. Nothing removed."))+ return+ }++ if dryRun {+ let out = Cleaner.remove(selected, ignore: ignore, dryRun: true)+ Render.cleanupSummary(out, dryRun: true)+ return+ }++ if !force {+ Render.deletionReview(cats)+ let total = ByteCount.human(selected.reduce(Int64(0)) { $0 + $1.sizeBytes })+ guard Term.confirm("Remove \(selected.count) items (\(total))?", default: false) else {+ print(Term.dim("Cancelled. Nothing removed."))+ return+ }+ }++ let out = Cleaner.remove(selected, ignore: ignore, dryRun: false)+ Render.cleanupSummary(out, dryRun: false)+ if !force {+ print(Term.dim("Tip: `puremac ignore add <path>` protects a path · `puremac clean --force` skips this prompt"))+ }+ if out.hadFailures { throw ExitCode.failure }+ }++ static func title(_ id: String) -> String {+ Catalog.categoryTitles.first { $0.id == id }?.title ?? id.capitalized+ }+}++enum JSONReport {+ static func string(_ cats: [CategoryScan]) -> String {+ struct Out: Encodable {+ struct Cat: Encodable { let id, title: String; let totalBytes, selectedBytes: Int64; let groups: [ToolGroup] }+ let totalBytes: Int64+ let categories: [Cat]+ }+ let out = Out(+ totalBytes: cats.reduce(0) { $0 + $1.allBytes },+ categories: cats.map { Out.Cat(id: $0.id, title: $0.title, totalBytes: $0.allBytes, selectedBytes: $0.totalBytes, groups: $0.groups) }+ )+ let enc = JSONEncoder()+ enc.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]+ enc.dateEncodingStrategy = .iso8601+ return (try? enc.encode(out)).flatMap { String(data: $0, encoding: .utf8) } ?? "{}"+ }+}diff --git a/cli/Sources/puremac/Commands/Config.swift b/cli/Sources/puremac/Commands/Config.swiftnew file mode 100644index 0000000..7939863--- /dev/null+++ b/cli/Sources/puremac/Commands/Config.swift@@ -0,0 +1,37 @@+import ArgumentParser+import Foundation++struct Config: ParsableCommand {+ static let configuration = CommandConfiguration(+ abstract: "Show or change CLI preferences.",+ discussion: """+ puremac config Show all settings and file locations+ puremac config set purge.older_than_days 14+ PureMac CLI sends no telemetry — there is nothing to opt out of.+ """+ )++ @Argument(help: "'set' to change a value, omit to show all.") var action: String?+ @Argument(help: "Key to set.") var key: String?+ @Argument(help: "Value to set.") var value: String?++ func run() throws {+ var store = ConfigStore()+ if action == "set" {+ guard let key, let value else { throw ValidationError("Usage: puremac config set <key> <value>") }+ guard ConfigStore.knownKeys.contains(key) else {+ throw ValidationError("Unknown key '\(key)'. Known: \(ConfigStore.knownKeys.joined(separator: ", "))")+ }+ store.set(key, value)+ print(Term.green("✓ \(key) = \(value)"))+ return+ }+ print(Term.bold("PureMac CLI configuration"))+ print(Term.dim(" config: ") + Render.shorten(AppPaths.configFile.path))+ print(Term.dim(" ignore: ") + Render.shorten(AppPaths.ignoreFile.path))+ print("")+ for key in ConfigStore.knownKeys {+ print(" \(key) = \(store.values[key] ?? Term.dim("(default)"))")+ }+ }+}diff --git a/cli/Sources/puremac/Commands/Ignore.swift b/cli/Sources/puremac/Commands/Ignore.swiftnew file mode 100644index 0000000..374ee0f--- /dev/null+++ b/cli/Sources/puremac/Commands/Ignore.swift@@ -0,0 +1,45 @@+import ArgumentParser+import Foundation++struct Ignore: ParsableCommand {+ static let configuration = CommandConfiguration(+ abstract: "Protect paths so clean/purge/analyze never touch them.",+ subcommands: [Add.self, Remove.self, List.self],+ defaultSubcommand: List.self+ )++ struct Add: ParsableCommand {+ static let configuration = CommandConfiguration(abstract: "Add a path to the ignore list.")+ @Argument(help: "Path to protect.") var path: String+ func run() throws {+ var store = IgnoreStore()+ let added = try store.add(path)+ let shown = Render.shorten(((path as NSString).expandingTildeInPath as NSString).standardizingPath)+ print(added ? Term.green("✓ Protected ") + shown : Term.dim("Already protected: \(shown)"))+ }+ }++ struct Remove: ParsableCommand {+ static let configuration = CommandConfiguration(abstract: "Remove a path from the ignore list.")+ @Argument(help: "Path to stop protecting.") var path: String+ func run() throws {+ var store = IgnoreStore()+ let removed = try store.remove(path)+ let shown = Render.shorten(((path as NSString).expandingTildeInPath as NSString).standardizingPath)+ print(removed ? Term.green("✓ Removed ") + shown : Term.yellow("Not in ignore list: \(shown)"))+ }+ }++ struct List: ParsableCommand {+ static let configuration = CommandConfiguration(abstract: "Show protected paths.")+ func run() throws {+ let store = IgnoreStore()+ if store.roots.isEmpty {+ print(Term.dim("No protected paths. Add one with `puremac ignore add <path>`."))+ return+ }+ print(Term.bold("Protected paths:"))+ for root in store.roots.sorted() { print(" " + Render.shorten(root)) }+ }+ }+}diff --git a/cli/Sources/puremac/Commands/Optimize.swift b/cli/Sources/puremac/Commands/Optimize.swiftnew file mode 100644index 0000000..f260940--- /dev/null+++ b/cli/Sources/puremac/Commands/Optimize.swift@@ -0,0 +1,63 @@+import ArgumentParser+import Foundation++struct Optimize: ParsableCommand {+ static let configuration = CommandConfiguration(+ abstract: "Free inactive RAM and release purgeable disk space.",+ discussion: """+ puremac optimize Run both tasks+ puremac optimize ram Ask macOS to release inactive memory+ puremac optimize purgeable Release APFS purgeable disk space+ macOS manages memory on its own; these are best-effort nudges, not magic.+ """+ )++ @Argument(help: "Task to run: ram | purgeable. Omit to run both.")+ var task: String?++ func validate() throws {+ if let t = task, t != "ram", t != "purgeable" {+ throw ValidationError("Unknown task '\(t)'. Use 'ram' or 'purgeable'.")+ }+ }++ func run() throws {+ let all = task == nil+ var ok = true+ if all || task == "ram" { ok = optimizeRAM() && ok }+ if all || task == "purgeable" { ok = optimizePurgeable() && ok }+ if !ok { throw ExitCode.failure }+ }++ @discardableResult+ private func optimizeRAM() -> Bool {+ let before = SystemInfo.memory()+ print(Term.dim("Releasing inactive memory…"))+ let r = Shell.run("/usr/sbin/purge", [])+ let after = SystemInfo.memory()+ if r.status == 0 {+ let delta = after.free - before.free+ let avail = after.free + after.inactive+ print(Term.green("✓ RAM optimized") + " · \(ByteCount.human(max(0, delta))) newly free · \(ByteCount.human(avail)) available")+ return true+ }+ print(Term.yellow("• Could not run purge") + Term.dim(" — try: sudo puremac optimize ram"))+ print(Term.dim(" macOS already reclaims inactive memory automatically under pressure."))+ return false+ }++ @discardableResult+ private func optimizePurgeable() -> Bool {+ let before = SystemInfo.volume("/").available+ print(Term.dim("Releasing purgeable disk space…"))+ let r = Shell.run("/usr/sbin/diskutil", ["apfs", "purgePurgeable", "/"])+ let after = SystemInfo.volume("/").available+ if r.status == 0 {+ let freed = max(0, after - before)+ print(Term.green("✓ Purgeable space released") + " · \(ByteCount.human(freed)) reclaimed")+ return true+ }+ print(Term.yellow("• Could not release purgeable space") + Term.dim(" — try: sudo puremac optimize purgeable"))+ return false+ }+}diff --git a/cli/Sources/puremac/Commands/Purge.swift b/cli/Sources/puremac/Commands/Purge.swiftnew file mode 100644index 0000000..53d20eb--- /dev/null+++ b/cli/Sources/puremac/Commands/Purge.swift@@ -0,0 +1,98 @@+import ArgumentParser+import Foundation++struct Purge: ParsableCommand {+ static let configuration = CommandConfiguration(+ abstract: "Find removable build artifacts inside project folders (node_modules, target, .venv, …).",+ discussion: """+ With no path, scans ~/Projects, ~/Code, ~/dev, ~/GitHub, ~/Workspace.+ Artifacts older than the age threshold are preselected; newer ones are shown unchecked.+ puremac purge Scan the default project folders+ puremac purge ~/Work/app Scan a specific folder+ """+ )++ @Argument(help: "Folder(s) to scan. Omit to scan the default project locations.")+ var paths: [String] = []++ @Option(name: .customLong("older-than"), help: "Preselect artifacts older than N days (default 7, or config).")+ var olderThanDays: Int = -1++ @Flag(name: .long, help: "Skip the confirmation prompt and remove immediately.")+ var force = false++ @Flag(name: .customLong("dry-run"), help: "Scan and report only; never delete.")+ var dryRun = false++ @Flag(name: .long, help: "Emit machine-readable JSON and exit (never deletes).")+ var json = false++ func validate() throws {+ if olderThanDays != -1 && !(0...3650).contains(olderThanDays) {+ throw ValidationError("--older-than must be between 0 and 3650 days.")+ }+ for p in paths {+ let v = Safety.isValidScanRoot(p)+ if !v.ok { throw ValidationError(v.reason ?? "invalid path") }+ }+ }++ func run() throws {+ let ignore = IgnoreStore()+ let days = resolvedDays()+ let roots = paths.isEmpty+ ? Purger.defaultRoots+ : paths.map { (($0 as NSString).expandingTildeInPath as NSString).standardizingPath }++ if !json { Term.err(Term.dim("Scanning " + roots.map { Render.shorten($0) }.joined(separator: ", ") + " …")) }+ let cat = Purger.scan(roots: roots, olderThanDays: days, ignore: ignore)++ if json { print(JSONReport.string([cat])); return }++ if cat.groups.isEmpty {+ print(Term.green("No project artifacts found."))+ return+ }++ let projectCount = cat.groups.count+ print("")+ print(Term.bold("Found \(ByteCount.human(cat.allBytes)) across \(projectCount) project\(projectCount == 1 ? "" : "s")"))+ for group in cat.groups {+ print("")+ print(" \(Term.cyan(group.tool)) \(Term.dim(ByteCount.human(group.allBytes)))")+ for item in group.items {+ let mark = item.selected ? Term.green("✓") : Term.dim("·")+ let recent = item.selected ? "" : Term.dim(" recent")+ print(" \(mark) \(Render.sizeCol(item.sizeBytes)) \(Render.shorten(item.path))\(recent)")+ }+ }+ print("")+ print(Term.dim("Artifacts newer than \(days) days are shown but left unchecked."))++ let selected = cat.selectedItems+ if selected.isEmpty { print(Term.dim("\nNothing preselected. Nothing removed.")); return }++ if dryRun {+ let out = Cleaner.remove(selected, ignore: ignore, dryRun: true)+ Render.cleanupSummary(out, dryRun: true)+ return+ }+ if !force {+ Render.deletionReview([cat])+ let total = ByteCount.human(selected.reduce(Int64(0)) { $0 + $1.sizeBytes })+ guard Term.confirm("Remove \(selected.count) artifacts (\(total))?", default: false) else {+ print(Term.dim("Cancelled. Nothing removed."))+ return+ }+ }+ let out = Cleaner.remove(selected, ignore: ignore, dryRun: false)+ Render.cleanupSummary(out, dryRun: false)+ if out.hadFailures { throw ExitCode.failure }+ }++ private func resolvedDays() -> Int {+ if olderThanDays >= 0 { return olderThanDays }+ if let v = ConfigStore().values["purge.older_than_days"], let n = Int(v), (0...3650).contains(n) { return n }+ return 7+ }+}diff --git a/cli/Sources/puremac/Core/ByteCount.swift b/cli/Sources/puremac/Core/ByteCount.swiftnew file mode 100644index 0000000..21e1174--- /dev/null+++ b/cli/Sources/puremac/Core/ByteCount.swift@@ -0,0 +1,19 @@+import Foundation++enum ByteCount {+ static func human(_ bytes: Int64) -> String {+ if bytes <= 0 { return "Zero KB" }+ let units = ["bytes", "KB", "MB", "GB", "TB", "PB"]+ var value = Double(bytes)+ var idx = 0+ while value >= 1000 && idx < units.count - 1 {+ value /= 1000+ idx += 1+ }+ if idx == 0 { return "\(Int(value)) bytes" }++ var formatted = String(format: "%.1f", value)+ if formatted.hasSuffix(".0") { formatted = String(formatted.dropLast(2)) }+ return "\(formatted) \(units[idx])"+ }+}diff --git a/cli/Sources/puremac/Core/Catalog.swift b/cli/Sources/puremac/Core/Catalog.swiftnew file mode 100644index 0000000..2a29272--- /dev/null+++ b/cli/Sources/puremac/Core/Catalog.swift@@ -0,0 +1,88 @@+import Foundation++struct Target {+ let tool: String+ let paths: [String]+ var selectedByDefault: Bool = true++ var contents: Bool = false+}++enum Catalog {+ static let home = FileManager.default.homeDirectoryForCurrentUser.path+ private static func h(_ rel: String) -> String { "\(home)/\(rel)" }++ static var dev: [Target] {+ [++ Target(tool: "Homebrew", paths: [h("Library/Caches/Homebrew")]),+ Target(tool: "npm", paths: [h(".npm/_cacache")]),+ Target(tool: "Yarn", paths: [h("Library/Caches/Yarn"), h(".cache/yarn"), h(".yarn/berry/cache")]),+ Target(tool: "pnpm", paths: [h("Library/pnpm/store"), h(".pnpm-store"), h(".cache/pnpm")]),+ Target(tool: "pip", paths: [h("Library/Caches/pip"), h(".cache/pip")]),++ Target(tool: "Cargo (Rust)", paths: [h(".cargo/registry/cache"), h(".cargo/registry/index"), h(".cargo/git/db"), h(".cargo/git/checkouts")]),+ Target(tool: "Go", paths: [h("Library/Caches/go-build"), h("go/pkg/mod/cache")]),+ Target(tool: "CocoaPods", paths: [h("Library/Caches/CocoaPods")]),+ Target(tool: "VS Code", paths: [h("Library/Application Support/Code/Cache"), h("Library/Application Support/Code/CachedData"), h("Library/Application Support/Code/CachedExtensionVSIXs"), h("Library/Application Support/Code/logs")]),+ Target(tool: "JetBrains", paths: [h("Library/Caches/JetBrains"), h("Library/Logs/JetBrains")]),++ Target(tool: "Maven (~/.m2 — may hold local installs)", paths: [h(".m2/repository")], selectedByDefault: false),+ Target(tool: "Gradle", paths: [h(".gradle/caches"), h(".gradle/daemon"), h(".gradle/wrapper/dists")]),+ Target(tool: "Poetry", paths: [h("Library/Caches/pypoetry"), h(".cache/pypoetry")]),+ Target(tool: "uv", paths: [h(".cache/uv"), h("Library/Caches/uv")]),+ Target(tool: "Bun", paths: [h(".bun/install/cache")]),+ Target(tool: "Deno", paths: [h("Library/Caches/deno"), h(".cache/deno")]),+ Target(tool: "mise", paths: [h(".cache/mise")]),+ Target(tool: "Flutter / Dart pub", paths: [h(".pub-cache")]),+ Target(tool: "NuGet / .NET (~/.nuget — may hold local packages)", paths: [h(".nuget/packages"), h(".local/share/NuGet/http-cache")], selectedByDefault: false),++ Target(tool: "Swift Package Manager", paths: [h("Library/Caches/org.swift.swiftpm")]),++ Target(tool: "Docker Desktop", paths: [h("Library/Containers/com.docker.docker/Data/cache"), h("Library/Containers/com.docker.docker/Data/log"), h("Library/Containers/com.docker.docker/Data/tmp"), h("Library/Group Containers/group.com.docker/Caches"), h(".docker/cli-plugins/.cache"), h(".docker/buildx/cache")]),+ Target(tool: "OrbStack", paths: [h(".orbstack/log"), h("Library/Caches/dev.kdrag0n.MacVirt"), h("Library/Logs/OrbStack")]),+ ]+ }++ static var junk: [Target] {+ [++ Target(tool: "User logs", paths: [h("Library/Logs")], contents: true),+ Target(tool: "Saved application state", paths: [h("Library/Saved Application State")], selectedByDefault: false),+ Target(tool: "Xcode DerivedData", paths: [h("Library/Developer/Xcode/DerivedData")]),+ Target(tool: "Xcode Archives", paths: [h("Library/Developer/Xcode/Archives")], selectedByDefault: false),+ Target(tool: "iOS DeviceSupport", paths: [h("Library/Developer/Xcode/iOS DeviceSupport")]),+ Target(tool: "watchOS DeviceSupport", paths: [h("Library/Developer/Xcode/watchOS DeviceSupport")]),+ Target(tool: "tvOS DeviceSupport", paths: [h("Library/Developer/Xcode/tvOS DeviceSupport")]),+ Target(tool: "CoreSimulator caches", paths: [h("Library/Developer/CoreSimulator/Caches")]),+ Target(tool: "Xcode app cache", paths: [h("Library/Caches/com.apple.dt.Xcode")]),+ Target(tool: "XCTestDevices", paths: [h("Library/Developer/XCTestDevices")]),+ Target(tool: "SwiftUI Previews", paths: [h("Library/Developer/Xcode/UserData/Previews")]),+ ]+ }++ static var ai: [Target] {+ [++ Target(tool: "Ollama (logs/cache)", paths: [h(".ollama/logs"), h("Library/Caches/ollama"), h("Library/Caches/com.electron.ollama")]),+ Target(tool: "LM Studio (logs)", paths: [h(".lmstudio/server-logs")]),+ Target(tool: "Cursor (cache)", paths: [h("Library/Application Support/Cursor/Cache"), h("Library/Application Support/Cursor/CachedData"), h("Library/Application Support/Cursor/logs")]),+ ]+ }++ static func targets(for id: String) -> [Target] {+ switch id {+ case "dev": return dev+ case "junk": return junk+ case "ai": return ai+ default: return []+ }+ }++ static let categoryTitles: [(id: String, title: String)] = [+ ("dev", "Dev Tools"),+ ("junk", "System Junk"),+ ("ai", "AI Junk"),+ ("trash", "Trash"),+ ]+}diff --git a/cli/Sources/puremac/Core/CategoryScanner.swift b/cli/Sources/puremac/Core/CategoryScanner.swiftnew file mode 100644index 0000000..51c8008--- /dev/null+++ b/cli/Sources/puremac/Core/CategoryScanner.swift@@ -0,0 +1,91 @@+import Foundation++enum CategoryScanner {+ static let minSize: Int64 = 1024++ static func scan(categoryID id: String, title: String, ignore: IgnoreStore) -> CategoryScan {+ FileHandle.standardError.write(Data(" scanning \(title)…\r".utf8))+ let groups = id == "trash" ? scanTrash(ignore: ignore) : scanCatalog(id: id, ignore: ignore)+ FileHandle.standardError.write(Data(" \r".utf8))+ return CategoryScan(id: id, title: title, groups: groups)+ }++ private static func scanCatalog(id: String, ignore: IgnoreStore) -> [ToolGroup] {+ let targets = Catalog.targets(for: id)+ var candidates: [(target: Int, path: String)] = []+ for (ti, target) in targets.enumerated() {+ let paths = target.contents+ ? target.paths.filter { !Safety.isSymlink($0) }.flatMap(children(of:))+ : target.paths+ for path in paths where passesPreFilter(path, ignore: ignore) {+ candidates.append((ti, path))+ }+ }+ let sizes = concurrentSizes(candidates.map { $0.path })++ var itemsByTarget = [Int: [ScanItem]](minimumCapacity: targets.count)+ for (i, c) in candidates.enumerated() where sizes[i] >= minSize {+ let item = ScanItem(path: c.path, sizeBytes: sizes[i],+ modified: DirSizer.modified(of: c.path),+ selected: targets[c.target].selectedByDefault)+ itemsByTarget[c.target, default: []].append(item)+ }+ return targets.indices.compactMap { ti in+ guard let items = itemsByTarget[ti], !items.isEmpty else { return nil }+ return ToolGroup(tool: targets[ti].tool, items: items)+ }+ }++ private static func children(of dir: String) -> [String] {+ guard let names = try? FileManager.default.contentsOfDirectory(atPath: dir) else { return [] }+ return names.map { "\(dir)/\($0)" }+ }++ private static func passesPreFilter(_ path: String, ignore: IgnoreStore) -> Bool {+ let fm = FileManager.default+ guard fm.fileExists(atPath: path) else { return false }+ if let type = (try? fm.attributesOfItem(atPath: path)[.type]) as? FileAttributeType, type == .typeSymbolicLink {+ return false+ }+ if Safety.isProviderOwned(path) { return false }+ if ignore.isIgnored(path) { return false }+ return true+ }++ static func concurrentSizes(_ paths: [String]) -> [Int64] {+ guard !paths.isEmpty else { return [] }+ var out = [Int64](repeating: 0, count: paths.count)+ out.withUnsafeMutableBufferPointer { buf in+ DispatchQueue.concurrentPerform(iterations: paths.count) { i in+ buf[i] = DirSizer.size(of: paths[i])+ }+ }+ return out+ }++ private static func scanTrash(ignore: IgnoreStore) -> [ToolGroup] {+ let fm = FileManager.default+ var roots = ["\(Safety.home)/.Trash"]+ let uid = getuid()+ if let vols = try? fm.contentsOfDirectory(atPath: "/Volumes") {+ for vol in vols { roots.append("/Volumes/\(vol)/.Trashes/\(uid)") }+ }++ var groups: [ToolGroup] = []+ for root in roots where !Safety.isSymlink(root) {+ guard let children = try? fm.contentsOfDirectory(atPath: root), !children.isEmpty else { continue }+ let paths = children.map { "\(root)/\($0)" }.filter { passesPreFilter($0, ignore: ignore) }+ let sizes = concurrentSizes(paths)+ let items = zip(paths, sizes).compactMap { (path, size) -> ScanItem? in+ size >= minSize ? ScanItem(path: path, sizeBytes: size, modified: DirSizer.modified(of: path)) : nil+ }+ if !items.isEmpty {+ let label = root.hasPrefix("/Volumes/")+ ? "Trash — \(URL(fileURLWithPath: root).deletingLastPathComponent().lastPathComponent)"+ : "Trash"+ groups.append(ToolGroup(tool: label, items: items))+ }+ }+ return groups+ }+}diff --git a/cli/Sources/puremac/Core/Cleaner.swift b/cli/Sources/puremac/Core/Cleaner.swiftnew file mode 100644index 0000000..251c2c5--- /dev/null+++ b/cli/Sources/puremac/Core/Cleaner.swift@@ -0,0 +1,58 @@+import Foundation++struct CleanOutcome {+ var removed: Int = 0+ var freedBytes: Int64 = 0+ var skipped: [(path: String, reason: String)] = []+ var failed: [(path: String, error: String)] = []+ var hadFailures: Bool { !failed.isEmpty }+}++enum Cleaner {+ static func remove(_ items: [ScanItem], ignore: IgnoreStore, dryRun: Bool) -> CleanOutcome {+ var out = CleanOutcome()+ let fm = FileManager.default+ for item in items {+ if Safety.isSymlink(item.path) || parentHasSymlink(item.path) {+ out.skipped.append((item.path, "symlink"))+ continue+ }+ let verdict = Safety.canRemove(item.path, ignore: ignore)+ guard verdict.ok else {+ out.skipped.append((item.path, verdict.reason ?? "protected"))+ continue+ }+ if dryRun {+ out.removed += 1+ out.freedBytes += item.sizeBytes+ continue+ }+ if Safety.isSymlink(item.path) || parentHasSymlink(item.path) {+ out.skipped.append((item.path, "became a symlink"))+ continue+ }+ do {+ try fm.removeItem(atPath: item.path)+ out.removed += 1+ out.freedBytes += item.sizeBytes+ } catch {+ let ns = error as NSError+ let hint = (ns.code == NSFileWriteNoPermissionError || ns.code == NSFileReadNoPermissionError)+ ? "locked or in use — close the owning app and retry" : ns.localizedDescription+ out.failed.append((item.path, hint))+ }+ }+ return out+ }++ static func parentHasSymlink(_ path: String) -> Bool {+ var url = URL(fileURLWithPath: path).deletingLastPathComponent()+ while url.path.count > 1 {+ if Safety.isSymlink(url.path) { return true }+ let parent = url.deletingLastPathComponent()+ if parent.path == url.path { break }+ url = parent+ }+ return false+ }+}diff --git a/cli/Sources/puremac/Core/Purger.swift b/cli/Sources/puremac/Core/Purger.swiftnew file mode 100644index 0000000..0cae5f7--- /dev/null+++ b/cli/Sources/puremac/Core/Purger.swift@@ -0,0 +1,68 @@+import Foundation++enum Purger {++ static let artifactNames: Set<String> = [+ "node_modules", ".next", ".nuxt", ".turbo", ".svelte-kit", ".angular", ".parcel-cache",+ "target", ".build", "DerivedData", "Pods",+ ".venv", "venv", "__pycache__", ".pytest_cache", ".mypy_cache", ".tox", ".ruff_cache",+ ".gradle",+ ]++ static let artifactPrefixes = ["cmake-build"]++ static let defaultRoots = ["Projects", "Code", "dev", "GitHub", "Workspace"]+ .map { "\(Safety.home)/\($0)" }++ static func isArtifact(_ name: String) -> Bool {+ artifactNames.contains(name) || artifactPrefixes.contains { name.hasPrefix($0) }+ }++ static func scan(roots: [String], olderThanDays: Int, ignore: IgnoreStore) -> CategoryScan {+ let fm = FileManager.default+ let cutoff = Date().addingTimeInterval(-Double(olderThanDays) * 86_400)+ var byProject: [String: [ScanItem]] = [:]+ var order: [String] = []++ for root in roots where Safety.isValidScanRoot(root).ok {+ let rootURL = URL(fileURLWithPath: root).resolvingSymlinksInPath()+ guard let en = fm.enumerator(at: rootURL,+ includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey],+ options: [.skipsPackageDescendants],+ errorHandler: { _, _ in true }) else { continue }++ for case let url as URL in en {+ let name = url.lastPathComponent+ let vals = try? url.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])+ if vals?.isSymbolicLink == true { en.skipDescendants(); continue }+ guard vals?.isDirectory == true else { continue }+ if en.level > 8 { en.skipDescendants(); continue }+ if Safety.isProviderOwned(url.path) || ignore.isIgnored(url.path) { en.skipDescendants(); continue }++ if isArtifact(name) {+ en.skipDescendants()+ let size = DirSizer.size(of: url.path)+ guard size >= CategoryScanner.minSize else { continue }+ let mod = DirSizer.modified(of: url.path)+ let old = (mod ?? .distantFuture) < cutoff+ let project = projectLabel(url, level: en.level, root: rootURL)+ let item = ScanItem(path: url.path, sizeBytes: size, modified: mod, selected: old)+ byProject[project, default: []].append(item)+ if !order.contains(project) { order.append(project) }+ }+ }+ }++ let groups = order.map { proj in+ ToolGroup(tool: proj, items: byProject[proj]!.sorted { $0.sizeBytes > $1.sizeBytes })+ }.sorted { $0.allBytes > $1.allBytes }+ return CategoryScan(id: "purge", title: "Project Artifacts", groups: groups)+ }++ private static func projectLabel(_ url: URL, level: Int, root: URL) -> String {+ guard level > 1 else { return url.lastPathComponent }+ var u = url+ for _ in 0..<(level - 1) { u = u.deletingLastPathComponent() }+ return u.lastPathComponent+ }+}diff --git a/cli/Sources/puremac/Core/Render.swift b/cli/Sources/puremac/Core/Render.swiftnew file mode 100644index 0000000..b0e8394--- /dev/null+++ b/cli/Sources/puremac/Core/Render.swift@@ -0,0 +1,97 @@+import Foundation++enum Render {+ static let rule = String(repeating: "─", count: 60)++ static func scanResults(_ cats: [CategoryScan]) {+ let grand = cats.reduce(Int64(0)) { $0 + $1.allBytes }+ print("")+ print(Term.bold("\(ByteCount.human(grand)) of removable items found"))+ for cat in cats where !cat.groups.isEmpty {+ print("")+ print(" \(Term.cyan(cat.title)) \(Term.dim(ByteCount.human(cat.allBytes)))")+ for group in cat.groups {+ for item in group.items {+ let mark = item.selected ? Term.green("✓") : Term.dim("·")+ print(" \(mark) \(sizeCol(item.sizeBytes)) \(pad(group.tool, 22)) \(Term.dim(shorten(item.path)))")+ }+ }+ }+ }++ static func selectionLine(_ cats: [CategoryScan]) {+ let items = cats.flatMap { $0.selectedItems }+ let total = items.reduce(Int64(0)) { $0 + $1.sizeBytes }+ print("")+ print(Term.bold("\(items.count) items selected (\(ByteCount.human(total)))"))+ }++ static func deletionReview(_ cats: [CategoryScan]) {+ let selected = cats.flatMap { $0.selectedItems }+ let total = selected.reduce(Int64(0)) { $0 + $1.sizeBytes }+ print("")+ print(Term.yellow(rule))+ print(" " + Term.bold("The following will be permanently deleted:"))+ print(Term.yellow(rule))+ for cat in cats {+ let catSelected = cat.selectedItems+ guard !catSelected.isEmpty else { continue }+ print(" " + Term.cyan(cat.title))+ for group in cat.groups {+ for item in group.items where item.selected {+ print(" \(sizeCol(item.sizeBytes)) \(pad(group.tool, 20)) \(shorten(item.path))")+ }+ }+ }+ print(Term.yellow(rule))+ print(" " + Term.bold("Total: \(ByteCount.human(total))") + Term.dim(" · \(selected.count) items"))+ print(Term.yellow(rule))+ }++ static func cleanupSummary(_ out: CleanOutcome, dryRun: Bool) {+ print("")+ let freed = ByteCount.human(out.freedBytes)+ if dryRun {+ print(Term.bold("Dry run — nothing was deleted."))+ print(" " + Term.bold(freed) + " reclaimable across \(out.removed) items")+ } else {+ box(title: freed, subtitle: "cleaned!")+ print(" " + Term.bold("\(out.removed)") + " items removed")+ }+ if !out.skipped.isEmpty {+ print(" " + Term.yellow("\(out.skipped.count) skipped") + Term.dim(" (protected/ignored)"))+ }+ if !out.failed.isEmpty {+ print(" " + Term.red("\(out.failed.count) failed"))+ for f in out.failed.prefix(10) { Term.err(" ! \(shorten(f.path)) — \(f.error)") }+ }+ print("")+ }++ private static func box(title: String, subtitle: String) {+ let width = max(title.count, subtitle.count) + 6+ let top = "┌" + String(repeating: "─", count: width) + "┐"+ let bot = "└" + String(repeating: "─", count: width) + "┘"+ print("")+ print(" " + Term.green(top))+ print(" " + Term.green("│") + center(title, width) + Term.green("│"))+ print(" " + Term.green("│") + center(subtitle, width) + Term.green("│"))+ print(" " + Term.green(bot))+ print("")+ }++ private static func center(_ s: String, _ width: Int) -> String {+ let pad = max(0, width - s.count)+ let left = pad / 2, right = pad - left+ return String(repeating: " ", count: left) + Term.bold(s) + String(repeating: " ", count: right)+ }++ static func sizeCol(_ bytes: Int64) -> String { pad(ByteCount.human(bytes), 10) }+ static func pad(_ s: String, _ n: Int) -> String { s.count >= n ? s : s + String(repeating: " ", count: n - s.count) }++ static func shorten(_ path: String) -> String {+ let home = FileManager.default.homeDirectoryForCurrentUser.path+ if path == home { return "~" }+ return path.hasPrefix(home + "/") ? "~" + path.dropFirst(home.count) : path+ }+}diff --git a/cli/Sources/puremac/Core/Safety.swift b/cli/Sources/puremac/Core/Safety.swiftnew file mode 100644index 0000000..c99a06f--- /dev/null+++ b/cli/Sources/puremac/Core/Safety.swift@@ -0,0 +1,83 @@+import Foundation++enum Safety {+ static let home = FileManager.default.homeDirectoryForCurrentUser.path++ static var deniedRoots: [String] {+ [+ "\(home)/Library/Mobile Documents",+ "\(home)/Library/CloudStorage",+ "\(home)/Library/Application Support/FileProvider",+ "\(home)/Library/Application Support/CloudDocs",+ "\(home)/Library/Daemon Containers",+ "\(home)/Library/Caches/CloudKit",+ "\(home)/Library/Caches/com.apple.bird",+ "\(home)/Library/Caches/com.apple.cloudkit",+ "\(home)/Library/Caches/com.apple.cloudd",+ "\(home)/Library/Caches/com.apple.FileProvider",+ ]+ }++ static var criticalRoots: Set<String> {+ [+ "/", home, "/System", "/Library", "/Applications", "/Users", "/usr", "/bin", "/sbin", "/etc", "/var", "/private",+ "\(home)/Library", "\(home)/Library/Caches", "\(home)/Library/Application Support",+ "\(home)/Library/Containers", "\(home)/Library/Preferences", "\(home)/Library/Logs",+ "\(home)/Library/Developer", "\(home)/Library/Developer/Xcode",+ "\(home)/.config", "\(home)/.cache", "\(home)/Documents", "\(home)/Desktop", "\(home)/Downloads",+ ]+ }++ static func isSymlink(_ path: String) -> Bool {+ let type = (try? FileManager.default.attributesOfItem(atPath: path)[.type]) as? FileAttributeType+ return type == .typeSymbolicLink+ }++ static func isProviderOwned(_ path: String) -> Bool {+ let candidates = [+ (path as NSString).standardizingPath,+ URL(fileURLWithPath: path).resolvingSymlinksInPath().path,+ ]+ for candidate in candidates {+ if candidate.contains("com~apple~") { return true }+ for root in deniedRoots where candidate == root || candidate.hasPrefix(root + "/") { return true }+ }+ return false+ }++ static var deniedUserRoots: [String] {+ [".ssh", ".aws", ".gnupg", ".gpg", ".kube", ".docker", ".claude", ".config", ".cargo", ".rustup",+ ".gem", ".nvm", ".pyenv", ".rbenv", ".ollama", ".lmstudio"].map { "\(home)/\($0)" }+ }++ static func isCredentialRoot(_ path: String) -> Bool {+ for root in deniedUserRoots where path == root { return true }+ return false+ }++ static func canRemove(_ path: String, ignore: IgnoreStore) -> (ok: Bool, reason: String?) {+ let std = (path as NSString).standardizingPath+ let resolved = URL(fileURLWithPath: std).resolvingSymlinksInPath().path+ if std.isEmpty || std == "/" || resolved == "/" { return (false, "root path") }+ if criticalRoots.contains(std) || criticalRoots.contains(resolved) { return (false, "protected root") }+ if isCredentialRoot(std) || isCredentialRoot(resolved) { return (false, "config/credentials dir") }+ if isProviderOwned(std) { return (false, "cloud/provider state") }+ if ignore.isIgnored(std) || ignore.isIgnored(resolved) { return (false, "ignored") }+ if !FileManager.default.fileExists(atPath: std) { return (false, "missing") }+ return (true, nil)+ }++ static func isValidScanRoot(_ path: String) -> (ok: Bool, reason: String?) {+ let expanded = (path as NSString).expandingTildeInPath+ let resolved = URL(fileURLWithPath: expanded).resolvingSymlinksInPath().path+ let std = (resolved as NSString).standardizingPath+ var systemRoots: Set<String> = ["/", "/System", "/Library", "/Applications", "/Users", "/private", "/usr", "/bin", "/sbin", "/etc", "/var", "/opt", "/cores", "/Volumes", home]+ for dir in ["Library", "Pictures", "Music", "Movies", "Public"] { systemRoots.insert("\(home)/\(dir)") }+ if systemRoots.contains(std) { return (false, "'\(path)' is a system location — scan a project folder instead") }+ var isDir: ObjCBool = false+ guard FileManager.default.fileExists(atPath: std, isDirectory: &isDir), isDir.boolValue else {+ return (false, "not a folder: \(path)")+ }+ return (true, nil)+ }+}diff --git a/cli/Sources/puremac/Core/Scanner.swift b/cli/Sources/puremac/Core/Scanner.swiftnew file mode 100644index 0000000..3f132ce--- /dev/null+++ b/cli/Sources/puremac/Core/Scanner.swift@@ -0,0 +1,67 @@+import Foundation++struct ScanItem: Codable {+ let path: String+ let sizeBytes: Int64+ let modified: Date?++ var selected: Bool = true+ var human: String { ByteCount.human(sizeBytes) }+}++struct ToolGroup: Codable {+ let tool: String+ var items: [ScanItem]+ var totalBytes: Int64 { items.filter { $0.selected }.reduce(0) { $0 + $1.sizeBytes } }+ var allBytes: Int64 { items.reduce(0) { $0 + $1.sizeBytes } }+}++struct CategoryScan: Codable {+ let id: String+ let title: String+ var groups: [ToolGroup]+ var totalBytes: Int64 { groups.reduce(0) { $0 + $1.totalBytes } }+ var allBytes: Int64 { groups.reduce(0) { $0 + $1.allBytes } }+ var selectedItems: [ScanItem] { groups.flatMap { $0.items }.filter { $0.selected } }+}++enum DirSizer {++ static func size(of path: String) -> Int64 {+ let fm = FileManager.default+ var isDir: ObjCBool = false+ guard fm.fileExists(atPath: path, isDirectory: &isDir) else { return 0 }+ if !isDir.boolValue { return fileSize(URL(fileURLWithPath: path)) }++ let r = Shell.run("/usr/bin/du", ["-sk", path])+ if r.status == 0 {+ let field = r.out.prefix { $0.isNumber }+ if let kb = Int64(field) {+ let (bytes, overflow) = kb.multipliedReportingOverflow(by: 1024)+ return overflow ? .max : bytes+ }+ }+ return foundationSize(URL(fileURLWithPath: path))+ }++ private static func foundationSize(_ url: URL) -> Int64 {+ var total: Int64 = 0+ let keys: [URLResourceKey] = [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey]+ guard let en = FileManager.default.enumerator(at: url, includingPropertiesForKeys: keys,+ options: [], errorHandler: { _, _ in true }) else { return 0 }+ for case let item as URL in en { total += fileSize(item) }+ return total+ }++ private static func fileSize(_ url: URL) -> Int64 {+ let vals = try? url.resourceValues(forKeys: [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey, .fileSizeKey])+ if let a = vals?.totalFileAllocatedSize { return Int64(a) }+ if let a = vals?.fileAllocatedSize { return Int64(a) }+ if let a = vals?.fileSize { return Int64(a) }+ return 0+ }++ static func modified(of path: String) -> Date? {+ (try? FileManager.default.attributesOfItem(atPath: path)[.modificationDate]) as? Date+ }+}diff --git a/cli/Sources/puremac/Core/Shell.swift b/cli/Sources/puremac/Core/Shell.swiftnew file mode 100644index 0000000..0ad60c4--- /dev/null+++ b/cli/Sources/puremac/Core/Shell.swift@@ -0,0 +1,32 @@+import Foundation++enum Shell {+ struct Result { let status: Int32; let out: String; let err: String }++ @discardableResult+ static func run(_ launchPath: String, _ args: [String]) -> Result {+ guard FileManager.default.isExecutableFile(atPath: launchPath) else {+ return Result(status: 127, out: "", err: "not found: \(launchPath)")+ }+ let p = Process()+ p.executableURL = URL(fileURLWithPath: launchPath)+ p.arguments = args+ let outPipe = Pipe(), errPipe = Pipe()+ p.standardOutput = outPipe+ p.standardError = errPipe+ do { try p.run() } catch {+ return Result(status: 126, out: "", err: (error as NSError).localizedDescription)+ }++ var outData = Data(), errData = Data()+ let group = DispatchGroup()+ let q = DispatchQueue(label: "puremac.shell.drain", attributes: .concurrent)+ q.async(group: group) { outData = outPipe.fileHandleForReading.readDataToEndOfFile() }+ q.async(group: group) { errData = errPipe.fileHandleForReading.readDataToEndOfFile() }+ group.wait()+ p.waitUntilExit()+ return Result(status: p.terminationStatus,+ out: String(decoding: outData, as: UTF8.self),+ err: String(decoding: errData, as: UTF8.self))+ }+}diff --git a/cli/Sources/puremac/Core/Stores.swift b/cli/Sources/puremac/Core/Stores.swiftnew file mode 100644index 0000000..73d127e--- /dev/null+++ b/cli/Sources/puremac/Core/Stores.swift@@ -0,0 +1,88 @@+import Foundation++enum AppPaths {+ static var configDir: URL {+ let base: URL+ if let xdg = ProcessInfo.processInfo.environment["XDG_CONFIG_HOME"], !xdg.isEmpty {+ base = URL(fileURLWithPath: xdg, isDirectory: true)+ } else {+ base = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".config", isDirectory: true)+ }+ return base.appendingPathComponent("puremac", isDirectory: true)+ }++ static var ignoreFile: URL { configDir.appendingPathComponent("ignore") }+ static var configFile: URL { configDir.appendingPathComponent("config.json") }++ static func ensureDir() {+ try? FileManager.default.createDirectory(at: configDir, withIntermediateDirectories: true)+ }+}++struct IgnoreStore {+ private(set) var roots: [String]++ init() {+ if let data = try? String(contentsOf: AppPaths.ignoreFile, encoding: .utf8) {+ roots = data.split(separator: "\n").map(String.init)+ .map { (($0 as NSString).expandingTildeInPath as NSString).standardizingPath }+ .filter { !$0.isEmpty }+ } else {+ roots = []+ }+ }++ func isIgnored(_ path: String) -> Bool {+ let std = (path as NSString).standardizingPath+ for root in roots where std == root || std.hasPrefix(root + "/") { return true }+ return false+ }++ mutating func add(_ path: String) throws -> Bool {+ let std = (((path as NSString).expandingTildeInPath) as NSString).standardizingPath+ guard !roots.contains(std) else { return false }+ roots.append(std)+ try save()+ return true+ }++ mutating func remove(_ path: String) throws -> Bool {+ let std = (((path as NSString).expandingTildeInPath) as NSString).standardizingPath+ guard let idx = roots.firstIndex(of: std) else { return false }+ roots.remove(at: idx)+ try save()+ return true+ }++ private func save() throws {+ AppPaths.ensureDir()+ try (roots.sorted().joined(separator: "\n") + "\n").write(to: AppPaths.ignoreFile, atomically: true, encoding: .utf8)+ }+}++struct ConfigStore {+ var values: [String: String]++ static let knownKeys = ["purge.older_than_days"]++ init() {+ if let data = try? Data(contentsOf: AppPaths.configFile),+ let obj = try? JSONSerialization.jsonObject(with: data) as? [String: String] {+ values = obj+ } else {+ values = [:]+ }+ }++ mutating func set(_ key: String, _ value: String) {+ values[key] = value+ save()+ }++ private func save() {+ AppPaths.ensureDir()+ if let data = try? JSONSerialization.data(withJSONObject: values, options: [.prettyPrinted, .sortedKeys]) {+ try? data.write(to: AppPaths.configFile)+ }+ }+}diff --git a/cli/Sources/puremac/Core/SystemInfo.swift b/cli/Sources/puremac/Core/SystemInfo.swiftnew file mode 100644index 0000000..afd6e46--- /dev/null+++ b/cli/Sources/puremac/Core/SystemInfo.swift@@ -0,0 +1,27 @@+import Foundation+import Darwin++enum SystemInfo {++ static func memory() -> (free: Int64, inactive: Int64) {+ var stats = vm_statistics64()+ var count = mach_msg_type_number_t(MemoryLayout<vm_statistics64_data_t>.size / MemoryLayout<integer_t>.size)+ let host = mach_host_self()+ let kr = withUnsafeMutablePointer(to: &stats) {+ $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) {+ host_statistics64(host, HOST_VM_INFO64, $0, &count)+ }+ }+ guard kr == KERN_SUCCESS else { return (0, 0) }+ let page = Int64(vm_kernel_page_size)+ return (Int64(stats.free_count) * page, Int64(stats.inactive_count) * page)+ }++ static func volume(_ path: String) -> (available: Int64, total: Int64) {+ let url = URL(fileURLWithPath: path)+ let vals = try? url.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey, .volumeTotalCapacityKey, .volumeAvailableCapacityKey])+ let avail = Int64(vals?.volumeAvailableCapacityForImportantUsage ?? Int64(vals?.volumeAvailableCapacity ?? 0))+ let total = Int64(vals?.volumeTotalCapacity ?? 0)+ return (avail, total)+ }+}diff --git a/cli/Sources/puremac/Core/Term.swift b/cli/Sources/puremac/Core/Term.swiftnew file mode 100644index 0000000..925ac6f--- /dev/null+++ b/cli/Sources/puremac/Core/Term.swift@@ -0,0 +1,39 @@+import Foundation++enum Term {+ static let colorEnabled: Bool = {+ if ProcessInfo.processInfo.environment["NO_COLOR"] != nil { return false }+ if ProcessInfo.processInfo.environment["TERM"] == "dumb" { return false }+ return isatty(fileno(stdout)) == 1+ }()++ static func style(_ s: String, _ codes: String) -> String {+ colorEnabled ? "\u{1B}[\(codes)m\(s)\u{1B}[0m" : s+ }++ static func bold(_ s: String) -> String { style(s, "1") }+ static func dim(_ s: String) -> String { style(s, "2") }+ static func red(_ s: String) -> String { style(s, "31") }+ static func green(_ s: String) -> String { style(s, "32") }+ static func yellow(_ s: String) -> String { style(s, "33") }+ static func blue(_ s: String) -> String { style(s, "34") }+ static func cyan(_ s: String) -> String { style(s, "36") }++ static func err(_ s: String) { FileHandle.standardError.write(Data((s + "\n").utf8)) }++ static func confirm(_ prompt: String, default def: Bool = false) -> Bool {+ guard isatty(fileno(stdin)) == 1 else { return def }+ let hint = def ? "[Y/n]" : "[y/N]"+ print("\(prompt) \(hint) ", terminator: "")+ guard let line = readLine() else { return def }+ let answer = line.trimmingCharacters(in: .whitespaces).lowercased()+ if answer.isEmpty { return def }+ return answer == "y" || answer == "yes"+ }++ static func bar(fraction: Double, width: Int = 24) -> String {+ let clamped = max(0, min(1, fraction))+ let filled = Int((Double(width) * clamped).rounded())+ return String(repeating: "█", count: filled) + String(repeating: "░", count: width - filled)+ }+}diff --git a/cli/Sources/puremac/PureMac.swift b/cli/Sources/puremac/PureMac.swiftnew file mode 100644index 0000000..96e9172--- /dev/null+++ b/cli/Sources/puremac/PureMac.swift@@ -0,0 +1,19 @@+import ArgumentParser+import Foundation++let puremacVersion = "1.0.0"++@main+struct PureMac: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "puremac",+ abstract: "Clean developer caches, project artifacts, and disk clutter — from the terminal.",+ discussion: """+ PureMac scans first and removes only what you approve. Cache/junk removal is+ permanent; cloud (iCloud/Dropbox/…) state and your config dotfiles are never touched.+ """,+ version: puremacVersion,+ subcommands: [Clean.self, Purge.self, Analyze.self, Optimize.self, Ignore.self, Config.self],+ defaultSubcommand: Clean.self+ )+}diff --git a/cli/Tests/puremacTests/puremacTests.swift b/cli/Tests/puremacTests/puremacTests.swiftnew file mode 100644index 0000000..cd243d3--- /dev/null+++ b/cli/Tests/puremacTests/puremacTests.swift@@ -0,0 +1,85 @@+import XCTest+@testable import puremac++final class PureMacTests: XCTestCase {+ let home = FileManager.default.homeDirectoryForCurrentUser.path++ func testByteCountFormatting() {+ XCTAssertEqual(ByteCount.human(0), "Zero KB")+ XCTAssertEqual(ByteCount.human(1_000), "1 KB")+ XCTAssertEqual(ByteCount.human(631_000), "631 KB")+ XCTAssertEqual(ByteCount.human(23_790_000_000), "23.8 GB")+ XCTAssertEqual(ByteCount.human(358_700_000), "358.7 MB")+ }++ func testArtifactMatching() {+ XCTAssertTrue(Purger.isArtifact("node_modules"))+ XCTAssertTrue(Purger.isArtifact(".venv"))+ XCTAssertTrue(Purger.isArtifact("cmake-build-debug"))+ XCTAssertFalse(Purger.isArtifact("src"))+ XCTAssertFalse(Purger.isArtifact("vendor"))+ }++ func testSafetyBlocksCriticalRoots() {+ let ig = IgnoreStore()+ XCTAssertFalse(Safety.canRemove("/", ignore: ig).ok)+ XCTAssertFalse(Safety.canRemove(home, ignore: ig).ok)+ XCTAssertFalse(Safety.canRemove("\(home)/Library/Caches", ignore: ig).ok)+ XCTAssertFalse(Safety.canRemove("\(home)/Library", ignore: ig).ok)+ }++ func testSafetyBlocksProviderState() {+ let ig = IgnoreStore()+ XCTAssertFalse(Safety.canRemove("\(home)/Library/Mobile Documents/x", ignore: ig).ok)+ XCTAssertTrue(Safety.isProviderOwned("\(home)/Library/CloudStorage/Dropbox/f"))+ XCTAssertTrue(Safety.isProviderOwned("\(home)/anything/com~apple~CloudDocs/x"))+ }++ func testSafetyBlocksCredentialDirs() {+ let ig = IgnoreStore()+ for dir in [".ssh", ".aws", ".gnupg", ".kube", ".docker", ".claude", ".config", ".cargo"] {+ XCTAssertFalse(Safety.canRemove("\(home)/\(dir)", ignore: ig).ok, "\(dir) must be protected")+ }+ XCTAssertFalse(Safety.isCredentialRoot("\(home)/.docker/buildx/cache"))+ }++ func testValidScanRootRejectsSystemPaths() {+ XCTAssertFalse(Safety.isValidScanRoot("/").ok)+ XCTAssertFalse(Safety.isValidScanRoot("/Library").ok)+ XCTAssertFalse(Safety.isValidScanRoot(home).ok)+ XCTAssertFalse(Safety.isValidScanRoot("\(home)/Library").ok)+ }++ func testCleanerRefusesSymlinkedParent() throws {+ let fm = FileManager.default+ let base = NSTemporaryDirectory() + "pm-symtest-\(getpid())"+ let victim = base + "/victim"+ let victimChild = victim + "/child"+ let link = base + "/link"+ try fm.createDirectory(atPath: victimChild, withIntermediateDirectories: true)+ try fm.createSymbolicLink(atPath: link, withDestinationPath: victim)+ defer { try? fm.removeItem(atPath: base) }++ XCTAssertTrue(Cleaner.parentHasSymlink(link + "/child"))++ let item = ScanItem(path: link + "/child", sizeBytes: 4096, modified: nil)+ let out = Cleaner.remove([item], ignore: IgnoreStore(), dryRun: false)+ XCTAssertEqual(out.removed, 0)+ XCTAssertEqual(out.skipped.count, 1)+ XCTAssertTrue(fm.fileExists(atPath: victimChild), "victim must survive a symlinked-parent delete")+ }++ func testSafetyHonorsIgnoreList() throws {++ let tmp = NSTemporaryDirectory() + "puremac-test-\(getpid())"+ try? FileManager.default.createDirectory(atPath: tmp, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(atPath: tmp) }++ var ig = IgnoreStore()++ XCTAssertTrue(Safety.canRemove(tmp, ignore: ig).ok)+ _ = try ig.add(tmp)+ XCTAssertFalse(Safety.canRemove(tmp, ignore: ig).ok)+ _ = try ig.remove(tmp)+ }+}diff --git a/cli/screenshots/clean.png b/cli/screenshots/clean.pngnew file mode 100644index 0000000..531e8aaBinary files /dev/null and b/cli/screenshots/clean.png differdiff --git a/homebrew/puremac-cli.rb b/homebrew/puremac-cli.rbnew file mode 100644index 0000000..bd6eb90--- /dev/null+++ b/homebrew/puremac-cli.rb@@ -0,0 +1,19 @@+class PuremacCli < Formula+ desc "Clean developer caches, project artifacts, and disk clutter from the terminal"+ homepage "https://github.com/momenbasel/PureMac"+ version "1.0.0"+ url "https://github.com/momenbasel/PureMac/releases/download/cli-v#{version}/puremac-cli-#{version}.tar.gz"+ sha256 "58cd364dc9204e37742312eaec19184041cf92bfdb91c53f64ed01b9e6c48519"+ license "MIT"++ depends_on macos: :big_sur+ depends_on :macos++ def install+ bin.install "puremac"+ end++ test do+ assert_match version.to_s, shell_output("#{bin}/puremac --version")+ end+end