LLM-Assisted Programming in Practice: Building a Disk Space Analysis and Cleanup Tool
This article walks through using a large language model to build a disk space analysis and cleanup utility. It covers how to break a vague request into a verifiable specification, the design of the scanning logic, safe cleanup strategies with dry-run and quarantine modes, code validation methods, latency and retry handling for cloud-based LLM inference, and the trade-offs of local model deployment. Readers will learn how to turn a one-sentence request into a reliable tool by letting the LLM draft the code while engineers focus on requirements, quality control, and risk management.
1. Background: The Challenge of Investigating a Full Disk
When disk capacity approaches its limit, most people open a file manager and check directory sizes one level at a time. This approach is inefficient for three reasons. First, large files are scattered across multiple directory levels, so looking at any single layer rarely reveals the problem. Second, cache directories, build artifacts, log files, and leftover downloads accumulate continuously, often with no clear owner. Third, duplicate files are hard to identify by eye.
A reusable disk analysis tool therefore has real practical value. It should be able to compute the usage of each top-level directory, list the largest files, group cleanable items by category, and produce a report for human review.
2. Why This Kind of Task Suits LLM Code Generation
Large language models perform consistently well on the following types of tasks:
- Small tools with clear structure and well-defined boundaries, such as traversing directories, summing sizes, and printing tables.
- Tasks with lots of boilerplate, such as argument parsing, logging output, and exception-handling scaffolding.
- Rapidly iterated prototypes, where developers can adjust output formats and filtering rules over a few rounds of conversation.
The limitations are equally clear. Generated code may contain logical flaws—for example, miscounting symbolic links, ignoring permission errors, or producing unexpected results when joining paths. When deletion is involved, generated code must be manually reviewed and tested before it is ever executed.
3. Requirement Breakdown: Turning One Sentence into a Verifiable Specification
A prompt like “write a disk cleanup program” is too vague and tends to produce unmaintainable results. It is better to break the requirement down into the following specification first:
- Input: the root directory to scan, the number of files to list, and whether to skip symbolic links.
- Statistics: total usage per top-level directory, and a global list of the largest files.
- Classification: candidate cleanup items labeled by category, such as caches, logs, archives, and installers.
- Output: results presented as a text table or a structured format such as JSON.
- Safety constraints: preview only by default with no deletion; deletion requires explicit user confirmation; user document directories must never be touched.
Once requirements are written as a specification, the prompt becomes much more concrete. An effective prompt typically includes the runtime environment, input and output formats, error-handling requirements, and explicit prohibitions. The more specific the prompt, the closer the generated result will be to expectations.
4. Example Implementation: Disk Usage Analysis
The following example code shows the core of the scanning logic. It uses a min-heap to maintain the largest-file list, so memory usage is independent of the total number of files and depends only on the number of retained entries.
import heapqimport osfrom collections import Counterfrom pathlib import Pathdef scan(root, top_n=20):root = Path(root).expanduser().resolve()usage_by_child = Counter()largest = [] # min-heap storing (bytes, path)skipped = 0for current, _dirs, files in os.walk(root, onerror=lambda _e: None):for name in files:path = Path(current) / nametry:if path.is_symlink():continue # skip symlinks to avoid double counting and traversal loopssize = path.stat().st_sizeexcept OSError:skipped += 1 # permission denied or file vanished; record and continuecontinuerelative = path.relative_to(root)top = relative.parts[0] if len(relative.parts) > 1 else "(root-level files)"usage_by_child[top] += sizeheapq.heappush(largest, (size, str(path)))if len(largest) > top_n:heapq.heappop(largest)return usage_by_child, sorted(largest, reverse=True), skipped
Several design decisions in this code are worth noting.
First, symbolic links are skipped. Without this, a linked directory might be counted multiple times, or a link cycle could form, inflating results significantly.
Second, exceptions are caught locally. A failure to read one file does not abort the whole scan, and the number of failures is recorded so the user can judge whether the report is complete.
Third, statistics are separated from presentation. The scan function returns only data; formatting is left to the caller, which makes it easy to plug in other interfaces or export formats later.
5. Cleanup Strategy: Preview First, Delete Later
The main risk in disk cleanup is accidental deletion. The following principles significantly reduce that risk:
- Preview mode by default: all deletion operations first run as “print only”; they execute for real only after user confirmation.
- Restricted cleanup scope: only handle directories that are clearly regenerable, such as known cache paths and temporary build directories. User documents, project source code, and configuration files are excluded from automated cleanup.
- Prefer quarantine over direct deletion: move candidate files to a timestamped quarantine directory, keep them for a period, and delete them in a batch later, so mistakes can be rolled back.
- Keep an operation log: each run generates a log recording file paths, sizes, and execution time.
An example implementation:
def clean(paths, dry_run=True, quarantine_dir=None):for p in paths:if dry_run:print(f"[preview] would process: {p}")continueif quarantine_dir is None:raise ValueError("A quarantine directory is required when preview mode is off")target = Path(quarantine_dir) / Path(p).namePath(p).rename(target) # move instead of delete, so rollback is possible
The function runs in preview mode by default. If the caller disables preview without specifying a quarantine directory, the program raises an error immediately instead of silently deleting files.
6. How to Validate the Generated Code
Before delivery, model-generated code should go through the following validation steps:
- Build a test directory: use a temporary directory containing regular files, nested subdirectories, symbolic links, and permission-denied files, then check whether the statistics match expectations.
- Edge cases: paths containing spaces or non-ASCII characters, filenames with special symbols, empty directories, and a nonexistent root path.
- Unit tests: write separate tests for
scanandclean, covering both normal and exceptional paths. - Trial runs in a real environment: start on a non-critical disk or a small directory, verify that the output matches manual checks, and only then expand the scope.
- Performance observation: test against directories containing large numbers of small files, record scan duration, and decide whether concurrency or incremental scanning is needed.
Validation is often neglected, but it determines whether the tool can be used reliably in real environments over the long term.
7. Latency and Stability of Cloud-Based Inference
When the development workflow depends on a cloud inference service, response speed and connection stability directly affect productivity. Common issues include:
- Throughput drops during peak hours, making the same request noticeably slower.
- Long-lived connections break midway, leaving generated content incomplete.
- Server-side rate limiting or temporary failures cause requests to fail.
These problems can be mitigated on the client side:
- Set reasonable timeouts to avoid threads blocking for long periods.
- Apply exponential backoff to retryable errors, reducing pressure on the service.
- Use streaming output so content is processed as it is generated, reducing perceived wait time.
- Cache completed results locally to avoid duplicate requests.
- For offline batch tasks, use an asynchronous queue and schedule requests during off-peak hours.
Example retry logic:
import timedef call_with_retry(fn, retries=3, base_delay=1.0):for attempt in range(retries):try:return fn()except TimeoutError:if attempt == retries - 1:raisetime.sleep(base_delay * (2 ** attempt))
The key points of this strategy are to retry only recoverable errors such as timeouts, and to cap the maximum number of retries to prevent indefinite waiting.
8. Trade-offs of Local Deployment
Some teams consider deploying models locally to gain lower latency and better data privacy. Before choosing local deployment, evaluate the following dimensions:
- Hardware cost: model inference places high demands on GPU memory and RAM; the configuration must match the model’s scale.
- Model capability: compression methods such as quantization reduce resource usage but typically cost some accuracy, which should be assessed on real tasks.
- Maintenance cost: this includes model updates, environment dependencies, monitoring and alerting, and troubleshooting—all of which require ongoing effort.
- Data sensitivity: when unpublished code or internal data is involved, local deployment reduces the risk of data leaving the organization.
- Network dependence: local deployment works offline, which suits network-constrained environments.
In practice, a hybrid approach is common. Sensitive code and offline tasks are handled by local models, while complex reasoning or quality-critical scenarios use cloud services, with a unified client layer encapsulating the switching logic.
9. Key Takeaways
- Break vague requirements into a specification covering five aspects: input, statistics, classification, output, and safety constraints.
- Let the model generate code, but have engineers review critical logic—especially anything involving deletion.
- Preview by default, prefer quarantine, and limit cleanup scope to data that is clearly regenerable.
- Validate results with constructed test directories and edge cases rather than trusting the surface output of a single run.
- Add timeouts, retries, and caching to cloud calls to reduce the impact of service fluctuations.
- Make an evidence-based choice between cloud and local deployment based on data sensitivity, hardware conditions, and maintenance capacity.
Large language models are well suited to drafting utility scripts, freeing engineers to concentrate on requirement definition, quality control, and risk management. This division of labor gets small tools into production faster and makes the results more reliable.
