Disk Space Analysis and Cleanup with LLMs: A Practical Engineering Guide
This article walks through building a disk space analysis and cleanup tool with the help of an AI coding assistant. It covers how to turn a one-line prompt into a concrete engineering spec, a read-only scanning and aggregation design, multi-layered safety guardrails for deletion, performance and UX optimizations for million-file scans, and practical tips for reviewing and validating generated code. The goal is a reliable everyday utility rather than a throwaway script.
1. The Problem: Engineering Pressure When Storage Runs Low
A developer’s local disk filling up is a frequent problem that is easy to underestimate. Log buildup, dependency caches, build artifacts, container image layers, and duplicate datasets can quietly consume terabytes of storage. By the time the system starts reporting write failures, databases that cannot flush to disk, or interrupted builds, the window for troubleshooting is often very short.
The traditional approach relies on scattered command-line combinations: descending into directories level by level, sorting by size, and manually judging which files are safe to delete. This approach has three problems. First, it is inefficient; searching through a large number of directories layer by layer takes a long time. Second, it is risky; the chance of accidentally deleting a critical file rises with fatigue. Third, it is not reusable; every time a similar issue appears, you have to figure things out from scratch.
Recent improvements in AI coding tools have opened a new path for these “one-off but urgent” engineering tasks: describe the requirement in one natural-language sentence and let the model produce a runnable analysis and cleanup program directly. This article focuses on that practice, discussing how to design such a program and the engineering points to watch when using AI coding tools.
2. Requirement Abstraction: Turning a One-Line Prompt into an Engineering Spec
A prompt like “write me a disk space analysis and cleanup program” looks simple, but producing reliable code requires filling in key constraints. It helps to organize the requirements along these dimensions:
- Scan scope: Scan the entire disk, or limit it to a specific working directory? Should system directories and mount points be excluded?
- Output format: Aggregate sizes by directory, or list the top N largest files? Is visualization or report export needed?
- Cleanup strategy: Only generate a list of cleanup candidates for manual confirmation, or support automatic deletion? Should filtering by extension, modification time, or size threshold be supported?
- Safety boundary: Is a second confirmation required before deletion? Is a trash-style soft delete or a rollback-capable quarantine directory supported?
- Runtime environment: Target operating system, third-party library dependencies, and whether symbolic links and insufficient-permission cases need to be handled.
Writing these constraints clearly will significantly improve the usability of the generated code. A practical prompt template looks like this:
Write a cross-platform disk space analysis script:1. Recursively scan a specified root directory, aggregate usage by first-level subdirectory, and output the top 20 in descending order;2. Support --min-size and --older-than filters to locate large and stale files;3. Default to read-only analysis; deletion requires an explicit --delete flag with per-item interactive confirmation;4. Before deletion, move files to a quarantine directory and output a rollback-capable operation log;5. Handle insufficient permissions and symbolic links gracefully without interrupting the overall scan.
3. Core Design: Scanning, Aggregation, and Presentation
3.1 Scanning Strategy
The first principle of disk analysis is read-only. The program should not perform any write operations during the scanning phase, avoiding distorted results caused by modifying data while analyzing it. The implementation uses depth-first traversal, accumulating size for each file and rolling the total of subdirectories up to the parent directory when recursion returns. To improve speed, use system calls to obtain file sizes directly instead of opening file contents.
Three boundary cases need special handling: symbolic links (to avoid double counting and out-of-bounds traversal), permission-restricted directories (log and skip them rather than throwing an exception that interrupts the run), and files currently being written (whose size may change momentarily, which is normal).
3.2 Aggregation and Sorting
Organize the results into a “directory tree + size” structure so you can locate space hotspots from the top down. Sort the output by size in descending order and limit the number of entries to avoid flooding the terminal with massive results. A sketch of the structure:
results = [] # (path, size_bytes, is_dir)results.sort(key=lambda x: x[1], reverse=True)for path, size, is_dir in results[:20]:print(f"{size/1024**3:8.2f} GB {'[D]' if is_dir else '[F]'} {path}")
3.3 Safety Guardrails for Cleanup
Cleanup capability must be built on multiple layers of guardrails:
- Read-only by default: Without an explicit deletion flag, the program never performs deletion.
- Per-item confirmation: List each candidate file’s size, modification time, and path for the user to confirm one by one.
- Soft delete first: Move to a quarantine directory instead of erasing directly, preserving a rollback window.
- Operation log: Record the time, path, and size of every move and deletion for auditing and recovery.
- Blacklist protection: Hard-code protection for critical system directories, version control metadata directories, and similar paths, forbidding deletion.
4. Performance and Experience Optimization
When the scan reaches millions of files, performance becomes critical. Options include: using concurrent traversal to improve I/O throughput while limiting concurrency to avoid saturating the disk; using incremental updates during aggregation instead of repeatedly recomputing everything; and caching results locally so a second analysis only incrementally scans the changed parts.
For interaction, a three-stage flow of “analyze first, filter next, clean up last” is recommended, letting the user stop at any step. For common cleanup scenarios (such as build caches and log archives), preset rules can be built in, but those presets must also be confirmed by the user before execution.
5. Engineering Advice for Using AI Coding Tools
A few lessons are worth summarizing when using AI coding assistance to generate this kind of tool:
- Put constraints in the prompt: Specifying read-only by default, confirmation before deletion, and fault-tolerance requirements significantly reduces rework.
- Always review after generation: Focus on deletion paths, boundary conditions, and exception handling; never run unreviewed code directly.
- Validate in small steps: Build test data in a temporary directory first, verify the scanning and cleanup logic, and only then use it on a real disk.
- Watch response stability: Model services from different cloud providers or platforms vary in throughput and connection stability. For long tasks, run them in segments and keep intermediate results; where necessary, consider a localized deployment to reduce dependence on the network link.
6. Conclusion
Disk space governance may look like a minor operations chore, but it is an important part of a developer’s day-to-day efficiency. Describe the requirement clearly, design the safety guardrails properly, and polish performance and experience, and a script quickly generated by an AI coding tool can become a reliable everyday utility. In cloud service ecosystems such as Baidu AI Cloud, developers can also combine such tools with general cloud product capabilities like object storage, log services, and monitoring and alerting, extending local governance into an integrated cloud storage governance workflow.
