Generate a Disk Space Analysis and Cleanup Tool with a Single LLM Prompt

    Running out of disk space is a common issue for developers due to logs, caches, and build artifacts. This article explores how to leverage large language models (LLMs) to instantly generate a customized disk space analysis and cleanup tool using a single prompt. It covers why LLMs excel at this task, how to write effective prompts, core implementation logic in Python, potential extensions, and practical insights on the LLM coding experience.

    Insufficient disk space is one of the most common headaches in daily DevOps: accumulated log files, bloated cache directories, residual build artifacts, and virtual machine images can easily consume hundreds of gigabytes or even terabytes without notice. Traditionally, developers tackle this by manually running du commands layer by layer or searching for ready-made analysis tools. However, with the advancement of large language model (LLM) coding capabilities, a more efficient approach has emerged: using a clear, single-sentence prompt to let the model generate a disk analysis and cleanup program tailored to your needs.

    1. Why a Single Prompt Can Generate a Usable Tool

    LLMs have a natural advantage here because disk space analysis is a classic problem with clear boundaries and mature technical solutions:

    1. Clear Inputs and Outputs: The input is a directory path, and the output is a sorted statistical breakdown of directory and file sizes. It does not involve complex business logic.
    2. Universal Tech Stack: Whether implemented in Python or Shell, the core logic involves traversing directory trees, accumulating file sizes, and formatting output. These are mature patterns frequently found in model training data.
    3. High Fault Tolerance: Even if the generated code has minor flaws, users can quickly locate and fix them, keeping the trial-and-error cost low.

    This also serves as a universal standard for judging which tasks are suitable for LLMs: the clearer the requirements and the more mature the solution, the higher the success rate of single-prompt generation.

    2. How to Write an Effective Prompt

    To get the model to generate high-quality code in one go, the prompt should include several key elements:

    • Clear Goals: Which path to analyze and what output format to use (e.g., a Top N list of largest files, data for a directory proportion pie chart).
    • Specify Language and Environment: For example, “Implement in Python, running on a Linux server.”
    • Supplementary Constraints: Such as ignoring symbolic links to avoid duplicate counting, handling permission-denied directories, and requiring confirmation before deletion.
    • Usage Scenario: Whether it’s for temporary troubleshooting or long-term use determines how robust the code needs to be.

    A reference template:

    1. Please write a disk space analysis tool in Python:
    2. 1. Recursively calculate the total size of each first-level subdirectory under a specified directory;
    3. 2. List the top 20 largest files with their full paths;
    4. 3. Ignore symbolic links, warn and skip directories without permission;
    5. 4. Output results sorted by size in descending order, using human-readable units;
    6. 5. Provide a --delete parameter to delete specified files, requiring confirmation before deletion.

    3. Core Implementation Logic

    The generated program typically contains the following modules. Here is a demonstration of the key logic:

    Directory Size Calculation:

    1. import os
    2. def dir_size(path):
    3. total = 0
    4. for root, dirs, files in os.walk(path):
    5. for f in files:
    6. fp = os.path.join(root, f)
    7. if not os.path.islink(fp):
    8. try:
    9. total += os.path.getsize(fp)
    10. except OSError:
    11. pass # Skip files with no permission or that have disappeared
    12. return total

    Human-Readable Unit Conversion:

    1. def human(n):
    2. for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
    3. if n < 1024:
    4. return f"{n:.1f} {unit}"
    5. n /= 1024

    Safe Deletion Design: The cleanup feature must include a confirmation mechanism and whitelist validation to prevent accidental deletion of system directories. For production environments, it is recommended to output a pending deletion list for manual review before executing the deletion.

    4. Directions for Further Extension

    Once the basic version is working, you can use the same iterative approach to have the model enhance it further:

    1. Visualized Output: Generate treemaps or terminal bar charts to intuitively display space distribution.
    2. Scheduled Monitoring: Combine with scheduled tasks to record space trends for critical directories and trigger alerts when thresholds are exceeded.
    3. Rule-Based Cleanup: Match common cleanable patterns, such as logs older than 30 days or empty temporary directories.
    4. Incremental Caching: Traversing large directory trees can be slow. You can cache directory sizes and invalidate them based on modification time to speed up subsequent analyses.

    5. Observations on the LLM Coding Experience

    Practical use reveals a few key takeaways:

    • Response Speed Impacts Experience: Some models produce lengthy reasoning processes for complex tasks. For simple and clear coding needs, models that think briefly and output code directly offer a better experience. When choosing a model, balance this against task complexity.
    • API Service Stability Matters: Beyond model capabilities, the throughput and connection stability of the inference service directly affect real-world usability in the toolchain, especially in high-frequency calling scenarios.
    • Local Deployment is an Ideal Direction: Deploying a cost-effective model instance locally can eliminate network and quota limitations, while also facilitating customized development assistance by integrating with private code repositories.

    Conclusion

    Engineering problems that are “small but clear,” like disk space analysis, are perfect entry points for AI-assisted programming. By mastering clear prompt writing, understanding how to verify generated code, and continuously iterating and expanding on this basis, you can compress a troubleshooting task that once took an hour into a few minutes. We encourage readers to start from their own pain points, try this approach hands-on, and gradually build their own prompt template library.