Disk Space Analysis and Cleanup with LLM-Generated Tools

    This article explains how to turn a one-line natural language request into a structured disk space analysis and cleanup tool with the help of an AI coding assistant. It breaks the requirement into scanning, sorting, disposal, and reporting layers, provides sample Python code, and emphasizes safety gates such as read-only defaults, path validation, dry-run mode, and operation logging. It also covers performance optimizations for large directories and practical guidance for handling model inference latency, along with a deployment checklist for safe and reusable disk space governance.

    1. Background: What Capacity Alerts Really Require

    A full disk on a development machine, test server, or local workstation is a frequent operational issue. On the surface it is simply a lack of space, but a closer look reveals three underlying needs:

    1. Fast localization — quickly identify what is consuming the space.
    2. Stable remediation — cleanup actions must be reversible and auditable.
    3. Reusability — a tool written once should serve different environments over time.

    The traditional approach is to enter directories manually, check their sizes layer by layer, and delete logs, caches, and temporary files based on experience. This works when there are few files, but efficiency drops sharply as directory depth and file count grow, and accidental deletion becomes likely. Using an intelligent coding tool to generate an automated script is a direct response to this pain point.

    2. Requirement Breakdown: From One Sentence to an Engineering Task

    The original scenario provides only a single natural language description as input. To produce a reliable program, the requirement must be structured during the prompting stage. It helps to divide it into four layers:

    1. Scanning layer: traverse the specified root directory and measure the size of each directory and file.
    2. Sorting layer: output results in descending order by size, with threshold filtering and depth limits.
    3. Disposal layer: classify cleanup candidates into “safe to delete”, “requires manual confirmation”, and “do not touch”.
    4. Reporting layer: produce structured output for further analysis and archiving.

    An example of a well-organized prompt:

    1. Implement a command-line disk analysis tool with the following requirements:
    2. 1. Input: root directory path, maximum recursion depth, size threshold;
    3. 2. Output: a list of directories sorted by size in descending order, annotated with file count and last modified time;
    4. 3. Provide cleanup suggestions for caches, logs, and temporary directories, but do not delete anything by default;
    5. 4. Support two modes: --dry-run and --confirm;
    6. 5. Use only the standard library and avoid extra dependencies.

    The value of this style is that it converts vague intent into a clear input/output contract, significantly reducing the chance that the generated result deviates from expectations.

    3. Core Implementation and Sample Code

    The quality of the generated result depends on how well the prompt constrains boundary conditions. The following is a typical skeleton for the scanning and reporting stages:

    1. import os
    2. from dataclasses import dataclass
    3. @dataclass
    4. class Entry:
    5. path: str
    6. size: int
    7. files: int
    8. def scan(root: str, max_depth: int, threshold: int):
    9. results = []
    10. for current, dirs, files in os.walk(root):
    11. depth = current[len(root):].count(os.sep)
    12. if depth >= max_depth:
    13. dirs[:] = []
    14. total = 0
    15. for name in files:
    16. try:
    17. total += os.path.getsize(os.path.join(current, name))
    18. except OSError:
    19. continue
    20. if total >= threshold:
    21. results.append(Entry(current, total, len(files)))
    22. return sorted(results, key=lambda x: x.size, reverse=True)

    In the disposal stage, safety design matters more than functionality. A “whitelist plus secondary confirmation” strategy is recommended: generate deletion suggestions only for paths that clearly belong to caches or temporary artifacts, and mark everything else as pending manual judgment.

    4. Safety Boundaries: Four Gates a Cleanup Tool Must Not Skip

    1. Read-only by default: the program only scans and reports unless deletion is explicitly enabled.
    2. Path validation: normalize target paths and reject out-of-bounds access and symbolic link escapes.
    3. Dry-run first: print the list of actions to be performed, and execute only after confirmation.
    4. Operation logging: record the time, path, and size of every deletion for traceability.
    1. def safe_remove(target: str, root: str, dry_run: bool):
    2. real_root = os.path.realpath(root)
    3. real_target = os.path.realpath(target)
    4. if not real_target.startswith(real_root):
    5. raise ValueError("Target path is out of bounds; operation rejected")
    6. if dry_run:
    7. print(f"[dry-run] Will delete: {real_target}")
    8. return
    9. os.remove(real_target)

    5. Performance and Usability Optimization

    When a directory contains millions of files, a naive traversal can take a long time. Common optimization techniques include: limiting recursion depth, skipping known low-value directories, pruning early based on thresholds, and outputting results in batches instead of loading everything into memory at once. For long-running use, scan results can be written to a local file and combined with scheduled tasks for periodic sampling, enabling trend comparison.

    6. A General Understanding of Model Inference Latency

    In practice, some developers observe fluctuations in generation speed. This is usually related to load scheduling of the inference service, context length, output length, and network stability, and is a common phenomenon in the industry. Engineering responses include: reducing prompt redundancy, generating step by step instead of requesting a complete program at once, asking the model to output a design before code for critical logic, and keeping a local library of reusable code snippets. For scenarios with higher requirements for timeliness and data compliance, a self-built pipeline can be constructed on top of general capabilities from Baidu AI Cloud (such as container platforms, object storage, log services, and monitoring alerts) to close the loop of generation, validation, execution, and auditing.

    7. Deployment Checklist

    • Define the scan root directory and depth limit to avoid full-disk traversal.
    • Specify the input/output contract and safety modes clearly in the prompt.
    • Run dry-run before execution and keep complete operation logs.
    • Manually review generated code, focusing on path handling and exception capture.
    • Put the tool under version control to form an iterable internal asset.

    In summary, the essence of disk space governance is “fast localization + safe disposal + continuous reuse”. By using intelligent coding tools to convert a one-sentence requirement into a structured program, and adding strict safety gates and engineering processes, space can be released efficiently and managed over the long term while keeping data safe.