Disk Cleanup with LLM Assistance: A Practical Guide to Safe Space Analysis and Cleanup
This guide shows how to use natural language prompts to generate a disk space analysis and cleanup tool with the help of an LLM coding assistant. It covers the four elements a usable prompt must include, the key areas to review in generated code, layered safety guardrails such as read-only defaults and whitelist-only deletion, a four-step execution and verification workflow, and common issues like long reasoning time and unstable API throughput. The goal is to turn a one-off emergency fix into a reusable engineering capability.
1. Background: Emergency Response When the Disk Is Full
A developer’s local disk filling up is a frequent yet often underestimated problem. Once available space hits zero, compilation failures, database write errors, logs that cannot be flushed, and interrupted dependency installs appear one after another, and the troubleshooting cost far exceeds the cleanup itself. The traditional approach is to open directories layer by layer by hand and delete caches based on experience, which is both slow and prone to accidental deletion.
With an intelligent coding tool, a single natural language request can directly generate a “disk space analysis + cleanup” program. The key to this practice is not whether the model can write code, but whether the requirement description is complete, whether the generated result is reviewed, and whether the execution process has safety boundaries.
2. Requirement Description: What a One-Sentence Prompt Must Include
A vague prompt only yields a vague program. A usable requirement description should cover at least four categories of information:
- Target platform and runtime: specify the operating system and runtime version to avoid generating a script that cannot run.
- Analysis scope and depth: specify the starting directory to scan, whether to recurse, and the statistics dimensions (directory usage, file type usage, top N large files).
- Output form: a console report, a structured data file, or a list sorted by usage.
- Cleanup strategy: analyze only without deleting, list candidates for manual confirmation, or automatically clean whitelisted directories by rule.
Example prompt structure:
On <operating system>, use <runtime> to implement a disk space analysis tool:1. Recursively aggregate the usage of each subdirectory under the given directory and output the top 20 in descending order of size;2. Separately list files larger than 500MB along with their modification time;3. By default, only output a report and do not delete anything;4. Provide a --mode clean parameter that only cleans a user-specified directory whitelist;5. All delete operations first print the paths and total size to be deleted and require a second confirmation.
The more explicit the elements, the more usable the generated code and the less rework later.
3. Review Focus for Generated Code
Code generated by the model can run directly, but it must be reviewed. Focus on the following:
- How delete paths are constructed: whether user input is normalized and validated, and whether path concatenation flaws could cause out-of-bounds deletion.
- Symlink handling: whether it follows soft links outside the target area, causing unintended scanning or deletion.
- Permission and exception handling: whether it skips or aborts on directories without permission, and whether error messages are traceable.
- Resource usage: whether scanning a large directory reads all files into memory at once, causing memory to spike.
- Idempotency: whether repeated runs produce consistent results without duplicate deletion or misjudgment.
A hardened core logic example:
import osfrom pathlib import Pathdef human(size: int) -> str:for unit in ("B", "KB", "MB", "GB", "TB"):if size < 1024:return f"{size:.1f}{unit}"size /= 1024return f"{size:.1f}PB"def scan(root: Path, top_n: int = 20):root = root.resolve()buckets, big_files = {}, []for cur, dirs, files in os.walk(root, followlinks=False):for name in files:fp = Path(cur) / nametry:st = fp.stat()except OSError:continuerel = fp.relative_to(root).parts[0]buckets[rel] = buckets.get(rel, 0) + st.st_sizeif st.st_size > 500 * 1024 * 1024:big_files.append((fp, st.st_size, st.st_mtime))for name, size in sorted(buckets.items(), key=lambda x: -x[1])[:top_n]:print(f"{name:<30}{human(size):>10}")for fp, size, mtime in sorted(big_files, key=lambda x: -x[1]):print(f"BIG {human(size):>10} {fp}")
Note the combination of followlinks=False and resolve(): the former avoids out-of-bounds traversal, and the latter ensures subsequent delete validation is based on the real path.
4. Safety Guardrails: Cleanup Must Be Off by Default
The risk of cleanup tools is asymmetric: an analysis error only costs extra time, while a deletion error can cause irrecoverable loss. It is therefore recommended to set multiple layers of guardrails:
- Read-only by default: without an explicit parameter, only output a report.
- Whitelist mechanism: only allow cleaning a user-configured set of directories and reject all other paths.
- Second confirmation: print the list and total size of files to be deleted, and execute only after interactive confirmation.
- Retention policy: prioritize cleaning caches and temporary files whose modification time is earlier than a set threshold.
- Operation logging: write the path, size, and time of each deletion to a log for traceability.
def safe_delete(target: Path, whitelist):target = target.resolve()if not any(target == w or w in target.parents for w in whitelist):raise PermissionError(f"path not in whitelist: {target}")if target in (Path("/"), Path(target.anchor)):raise PermissionError("refuse to delete root")print(f"will delete: {target}")if input("confirm? [y/N] ").strip().lower() != "y":returntarget.unlink() if target.is_file() else __import__("shutil").rmtree(target)
5. Execution and Verification Workflow
It is recommended to split the workflow into four steps to avoid a one-shot “analyze and delete”:
- Run a read-only scan to confirm the top space consumers match expectations;
- Generate a candidate cleanup list and manually spot-check whether several paths are correct;
- Execute in small batches within a controlled scope, observing logs and changes in available disk space;
- Finalize the configuration into a repeatable routine task and connect it to monitoring and alerting, so you are notified in advance when available space falls below a threshold.
6. Common Issues and General Approaches
Two types of issues related to the model itself often arise in practice.
The first is overly long reasoning. Some models unfold lengthy reasoning before generating, noticeably increasing wait time. Ways to address this include: explicitly stating in the prompt “give runnable code and a brief explanation directly,” splitting a complex task into multiple small tasks generated step by step, and preferring mature solutions over repeated model deliberation for logic with strong determinism.
The second is unstable API throughput and dropped connections. Generative models are usually called through cloud APIs, and speed is affected by server load and network conditions. General mitigations include: segmented generation and resumable progress for long tasks, decoupling generation from execution (write to disk first, then run), adding timeout and retry strategies, and keeping a locally reproducible implementation for critical steps.
import time, randomdef call_with_retry(fn, retries=3, base=1.0):for i in range(retries):try:return fn()except Exception as e:if i == retries - 1:raisetime.sleep(base * (2 ** i) + random.random())
7. Turning a Temporary Script into a Long-Term Capability
A one-off script solves the immediate problem; long-term value comes from consolidation. The tool can be split into three layers: a collection layer responsible for traversal and statistics, a rules layer maintaining the whitelist and retention configuration, and an execution layer responsible for confirmation and logging. Once the three layers are decoupled, the tool can run locally and also be migrated to general cloud product forms such as container platforms or function compute for scheduled execution, with object storage archiving reports, log services, and monitoring alerts completing the loop.
To reduce dependence on cloud APIs, you can evaluate deploying an open source inference framework locally to run a model of appropriate size; the trade-off is the balance among hardware cost, inference speed, and model capability, and not all scenarios are suited to localization.
8. Summary
Using natural language to drive an intelligent coding tool to generate a disk governance program is an efficient path, but real reliability comes from three things: complete prompt elements, reviewed generated code, and cleanup actions with off-by-default and whitelist guardrails. Make these three solid, and supplement them with retries, logging, and monitoring, and you can turn a one-off emergency response into a reusable engineering capability.
