Disk Cleanup Tool with LLM Code Generation: A Practical Guide

    This guide explains how to use an LLM to generate a cross-platform disk space analysis and cleanup tool from a single structured prompt. It covers prompt design, a reference Python skeleton, read-only defaults, whitelist and path validation safeguards, pre-launch testing, and performance considerations for large file counts. Readers will learn how to turn a one-off troubleshooting script into a reliable, maintainable operations asset.

    1. Background: What Disk Alerts Really Demand

    A full disk on a development machine, test server, or edge node is one of the most common failures in day-to-day operations. Broken log rotation, piled-up temporary build artifacts, and unbounded cache growth can exhaust available space within hours, triggering cascading problems: failed writes, databases that cannot flush to disk, and containers that fail to start. The traditional approach is to enter directories manually, run usage commands layer by layer, and decide from experience which files are safe to delete. It is slow and carries a real risk of deleting the wrong thing.

    Handing this kind of task to a code-capable model is a worthwhile approach: describe the goal in one natural-language sentence and let the model produce a runnable disk analysis and cleanup program. Compared with hand-written scripts, generative coding compresses the “clarify requirements, draft code, review manually” cycle into a very short window. It is especially well suited to tool-style tasks like this one, where the logic is fairly standard but the details depend on the local environment.

    2. Prompt Design: The Structured Elements Behind a One-Line Prompt

    A “one-line prompt” does not mean a careless sentence. A good short prompt usually implies four elements: goal, input, output, and safety boundaries. A template like the following works well:

    1. Write a cross-platform disk space analysis and cleanup tool:
    2. 1) Scan a specified root directory, aggregate usage by first- and second-level
    3. subdirectories, and print the Top N in descending order;
    4. 2) Support a --dry-run mode that only prints the deletion list without deleting;
    5. 3) Restrict deletion targets to a configurable whitelist of directories
    6. (e.g., temp directories, build caches);
    7. 4) Output both a human-readable report and a machine-readable JSON format.

    The sentence is short, yet it states what to do, what to scan, how to present results, and what must not be touched. In practice, it also helps to specify the runtime environment (operating system, runtime version) and dependency constraints so the model does not pull in unnecessary third-party libraries.

    3. Reference Skeleton for the Generated Code

    A robust implementation typically has four stages: scan, aggregate, filter, and execute. The sketch below shows the structure:

    1. import os, json, argparse
    2. def human(n):
    3. for u in ['B','KB','MB','GB','TB']:
    4. if n < 1024: return f"{n:.1f}{u}"
    5. n /= 1024
    6. return f"{n:.1f}PB"
    7. def scan(root):
    8. stat = {}
    9. for dirpath, _, files in os.walk(root):
    10. for f in files:
    11. p = os.path.join(dirpath, f)
    12. try: size = os.path.getsize(p)
    13. except OSError: continue
    14. top = os.path.relpath(p, root).split(os.sep)[0]
    15. stat[top] = stat.get(top, 0) + size
    16. return sorted(stat.items(), key=lambda x: -x[1])
    17. def main():
    18. ap = argparse.ArgumentParser()
    19. ap.add_argument('root'); ap.add_argument('--top', type=int, default=10)
    20. ap.add_argument('--dry-run', action='store_true')
    21. ap.add_argument('--json', action='store_true')
    22. a = ap.parse_args()
    23. data = scan(a.root)
    24. if a.json:
    25. print(json.dumps(dict(data), ensure_ascii=False, indent=2)); return
    26. for name, size in data[:a.top]:
    27. print(f"{human(size):>10} {name}")
    28. if __name__ == '__main__':
    29. main()

    This skeleton is deliberately “read-only first”: by default it only measures and displays. Deletion must be triggered by an explicit switch other than --dry-run, which reduces the chance of accidental deletion at the mechanism level.

    4. Safety Boundaries: The First Principle of Cleanup Tools

    A cleanup program is far riskier than an analysis program, so safety design has to come first:

    • Read-only by default: never perform any write operation unless a deletion flag is explicitly enabled.
    • Whitelist mechanism: allow deletion only of pre-configured directory patterns; forbid recursive deletion of the root directory, system directories, and mount points.
    • Path validation: normalize the concatenated absolute path and confirm it actually resides inside the allowed root directory.
    • Second confirmation before deletion: print the deletion list and the estimated space to be freed, then require manual confirmation or a delay window before execution.
    • Full audit trail: record operation logs for later review and traceability.

    5. Verification and Testing: The Pre-Launch Checklist

    Generated code must not go straight into production. At minimum, cover the following checks: build large files and nested directories in a temporary sandbox and confirm the reported numbers match actual usage; verify that --dry-run performs no deletion; test exception handling with edge-case inputs such as symbolic links, files with insufficient permissions, and overly long paths; finally, run a canary deployment on a small set of machines and watch resource usage and execution time.

    6. Performance and Engineering Considerations

    When the scan target reaches millions of files, single-threaded traversal can become the bottleneck. Options include concurrent traversal, incremental caching (record directory mtime to skip unchanged subtrees), and persisting results for reuse. If the tool needs to be shared by multiple people and run long-term, reports can be stored in object storage on Baidu AI Cloud, with log services and monitoring alerts tracking disk watermarks and a container platform hosting scheduled jobs. That turns a one-off script into a sustainable operations capability.

    7. A Rational View of Inference Latency and Local Deployment

    In real use, response speed matters as much as generation quality. Different access methods vary in throughput and stability, depending on network links, service load, and context length. For latency-sensitive scenarios or cases where data must stay on-premises, a local deployment can trade quantization and concurrent scheduling for throughput; streaming output, result caching, and asynchronous task execution can further improve the interaction experience. A complete toolchain often determines final efficiency more than the choice of a single model.

    8. Summary

    The value of generating a disk cleanup program from one sentence is not to replace engineers, but to automate repetitive work and leave time for safety design and verification. Master the four principles of structured prompts, read-only first, whitelists, and audit trails, then package the result with general cloud capabilities, and a one-off troubleshooting script becomes a stable, reliable operations asset.