core

package
v1.12.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 28, 2026 License: MIT Imports: 13 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	Reset = colorReset
	Cyan  = colorCyan
	Gray  = colorGray
	Bold_ = colorBold
)

Exported ANSI codes for callers that build their own colored output.

View Source
const (
	AnalysisPrefix = "analysis_"
	CleanupPrefix  = "cleanup_"
)

Prefixes of the per-run report folders. Analysis runs hold report.md and report.json; cleanup runs hold audit.json.

View Source
const AnalyzerTimeoutSeconds = 180

AnalyzerTimeoutSeconds is a global guardrail shared by all analyzers running in parallel — it is a safety net against a runaway walk, NOT the primary mechanism that keeps scans fast. The repos analyzer bounds its own cost by collecting target paths cheaply and measuring their sizes with a concurrent worker pool (see ReposAnalyzer.Analyze), so it stays well under this budget.

View Source
const DefaultMinSizeMB = 50

DefaultMinSizeMB is the minimum file size (in MB) to flag in downloads

Variables

View Source
var (
	// HomeDir is the current user's home directory
	HomeDir string

	// RepoRoots are directories to scan for node_modules, .venv, __pycache__
	RepoRoots []string

	// BrowserCachePaths maps browser name to its cache directory
	BrowserCachePaths map[string]string

	// LogDirs are directories containing log files
	LogDirs []string

	// DownloadDirs are directories to scan for large/old downloads
	DownloadDirs []string

	// AppSupportDir is ~/Library/Application Support
	AppSupportDir string

	// OllamaModelsDir is where Ollama stores downloaded LLM models
	OllamaModelsDir string

	// DevCachePaths maps tool name to its cache directory
	DevCachePaths map[string]string

	// XcodeDerivedData is the Xcode DerivedData path
	XcodeDerivedData string

	// XcodeArchives is the Xcode Archives path
	XcodeArchives string

	// XcodeSimulators is the CoreSimulator Devices path
	XcodeSimulators string

	// DockerRawPath is the Docker Desktop virtual disk image
	DockerRawPath string

	// TrashDir is the user's Trash directory
	TrashDir string

	// BlacklistedPaths are app bundle IDs that must never be deleted
	BlacklistedPaths map[string]bool

	// BlacklistedPrefixes are path prefixes under which nothing is deleted
	BlacklistedPrefixes []string
)
View Source
var HistoryDirOverride string

HistoryDirOverride redirects the watch history folder; tests only.

View Source
var ReportsDirOverride string

ReportsDirOverride redirects the reports folder. It exists only so tests never touch the real one; production code leaves it empty.

Functions

func Bold

func Bold(msg string, args ...any)

Bold prints bold text

func Colorize added in v1.2.0

func Colorize(code, s string) string

Colorize wraps s in the given ANSI code and a reset.

func DigestStrings added in v1.7.2

func DigestStrings(ids []string) string

DigestStrings returns the SHA-256 (hex) of ids sorted and newline-joined. Sorting makes the digest independent of discovery order, so the same set of targets always yields the same value. It is the shared fingerprint behind the MCP preview → confirm_plan handshake (Docker cleanup and batch clean). The input slice is not modified.

func Error

func Error(msg string, args ...any)

Error prints an error message

func FormatBytes

func FormatBytes(b int64) string

FormatBytes returns a human-readable byte string (e.g. "1.5 GB")

func HistoryDir added in v1.12.0

func HistoryDir() string

HistoryDir is where the listening mode keeps its daily JSONL history: a sibling of ReportsDir (<user config dir>/mac-toolkit/history).

func Info

func Info(msg string, args ...any)

Info prints an informational message

func IsAffirmative added in v1.6.0

func IsAffirmative(s string) bool

IsAffirmative reports whether s is an unambiguous human "yes". It is the single source of truth for the deletion gate shared by the CLI (confirmFinalDeletion) and the TUI confirmation modal, so both agree on exactly which words open the gate and neither can drift.

It accepts the Spanish and English affirmatives "si"/"sí"/"yes"/"y", case-insensitively and after trimming surrounding whitespace. Everything else — including an empty string, a negative, or an ambiguous phrase like "s i" — returns false, so the safe default is always to NOT delete.

func NewReportDir added in v1.9.0

func NewReportDir(prefix string) string

NewReportDir returns the folder path for a new run, e.g. <ReportsDir>/analysis_20260102_150405. It does not create it.

func ProgressBar added in v1.2.0

func ProgressBar(pct, width int) string

ProgressBar renders a fixed-width unicode bar for a 0..100 percentage, colored green/yellow/red by fill level. width is the number of cells.

func ReportsDir added in v1.9.0

func ReportsDir() string

ReportsDir is the ONE place where the toolkit stores reports and audit logs: <user config dir>/mac-toolkit/reports (on macOS, ~/Library/Application Support/mac-toolkit/reports). The path is absolute on purpose: a relative "reports" folder depended on the directory the terminal was launched from, so a report saved from one place could not be found from another.

func RiskColor

func RiskColor(r RiskLevel) string

RiskColor returns the ANSI color for a risk level

func SeverityColor

func SeverityColor(s Severity) string

SeverityColor returns the ANSI color for a severity level

func Success

func Success(msg string, args ...any)

Success prints a success message

func Warn

func Warn(msg string, args ...any)

Warn prints a warning message

Types

type AnalysisResult

type AnalysisResult struct {
	Domain    string          `json:"domain"`
	Severity  Severity        `json:"severity"`
	TotalSize int64           `json:"total_size_bytes"`
	Items     []CleanableItem `json:"items"`
	Summary   string          `json:"summary"`
	Timestamp time.Time       `json:"timestamp"`
	Error     string          `json:"error,omitempty"`
}

AnalysisResult holds the result of analyzing one domain

func RunAnalyzers

func RunAnalyzers(tasks []RunnerTask, timeoutSecs int) []AnalysisResult

RunAnalyzers executes all analyzer tasks in parallel with a timeout. Returns results for all domains, including error results for timeouts/failures.

type AnalyzeFunc

type AnalyzeFunc func() (AnalysisResult, error)

AnalyzeFunc is the signature for any analyzer's Analyze method

type ApprovalEngine

type ApprovalEngine struct {
	Mode    ApprovalMode
	DryRun  bool
	Execute bool
	// contains filtered or unexported fields
}

ApprovalEngine handles user approval for cleanup operations

func NewApprovalEngine

func NewApprovalEngine(mode ApprovalMode, dryRun, execute bool) *ApprovalEngine

NewApprovalEngine creates a new approval engine

func (*ApprovalEngine) FilterItems

func (a *ApprovalEngine) FilterItems(results []AnalysisResult) []CleanableItem

FilterItems applies the approval mode to filter items the user wants to delete. Returns only the approved items.

type ApprovalMode

type ApprovalMode string

ApprovalMode defines how the user approves deletions

const (
	ApprovalDeal      ApprovalMode = "deal"
	ApprovalCategory  ApprovalMode = "category"
	ApprovalItem      ApprovalMode = "item"
	ApprovalChecklist ApprovalMode = "checklist"
)

type CleanableItem

type CleanableItem struct {
	Path         string    `json:"path"`
	SizeBytes    int64     `json:"size_bytes"`
	Label        string    `json:"label"`
	Domain       string    `json:"domain"`
	SafeToDelete bool      `json:"safe_to_delete"`
	Reason       string    `json:"reason"`
	AgeDays      int       `json:"age_days,omitempty"`
	Risk         RiskLevel `json:"risk"`
}

CleanableItem represents a single file or directory that can be cleaned

type DeleteResult

type DeleteResult struct {
	Path      string `json:"path"`
	Result    string `json:"result"` // success, skipped-blacklisted, skipped-dry-run, skipped-not-found, failure
	SizeBytes int64  `json:"size_bytes,omitempty"`
	Error     string `json:"error,omitempty"`
}

DeleteResult records what happened when deleting an item

type DiskSnapshot added in v1.2.0

type DiskSnapshot struct {
	TotalBytes int64
	UsedBytes  int64
	AvailBytes int64
	PctUsed    int
	OK         bool
}

DiskSnapshot is a lightweight view of the data volume usage, used by the banner and any caller that needs a quick free-space reading without running a full analysis.

func ReadDiskSnapshot added in v1.2.0

func ReadDiskSnapshot() DiskSnapshot

ReadDiskSnapshot returns current usage of the macOS data volume via `df`. On any parse/exec error it returns a snapshot with OK=false so callers can degrade gracefully instead of failing.

type ReportEntry added in v1.9.0

type ReportEntry struct {
	Name     string // folder name, e.g. analysis_20260102_150405
	Dir      string // absolute path of the folder
	Path     string // absolute path of report.md
	Size     int64  // bytes of every report file in the folder (share variant included)
	ModTime  time.Time
	Formats  []string // formats of the full report found in the folder: md, json, html
	HasShare bool     // the folder holds a share variant
}

ReportEntry describes one saved analysis report.

func LatestReport added in v1.9.0

func LatestReport() (ReportEntry, bool, error)

LatestReport returns the newest saved analysis report; ok is false when none exists.

func ListReports added in v1.9.0

func ListReports() ([]ReportEntry, error)

ListReports returns the saved analysis reports, newest first. A missing folder is not an error (nothing saved yet); folders without a report.md (cleanup audits, partial runs) are skipped.

type RiskLevel

type RiskLevel string

RiskLevel represents the risk of deleting an item

const (
	RiskSafe   RiskLevel = "safe"
	RiskWarn   RiskLevel = "warn"
	RiskDanger RiskLevel = "danger"
)

type RunnerTask

type RunnerTask struct {
	Domain    string
	AnalyzeFn AnalyzeFunc
}

RunnerTask pairs a domain name with its analyze function

type Severity

type Severity string

Severity represents analysis severity based on size

const (
	SeverityCritical Severity = "critical"
	SeverityHigh     Severity = "high"
	SeverityMedium   Severity = "medium"
	SeverityLow      Severity = "low"
)

func SeverityFromSize

func SeverityFromSize(bytes int64) Severity

SeverityFromSize returns severity based on total bytes

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL