Skip to content

feat(groq): Monitors root disk usage and warns with apocalyptic emojis when a configurable threshold is exceeded.#5117

Open
polsala wants to merge 1 commit into
mainfrom
ai/groq-20260706-0402
Open

feat(groq): Monitors root disk usage and warns with apocalyptic emojis when a configurable threshold is exceeded.#5117
polsala wants to merge 1 commit into
mainfrom
ai/groq-20260706-0402

Conversation

@polsala

@polsala polsala commented Jul 6, 2026

Copy link
Copy Markdown
Owner

Implementation Summary

  • Utility: nightly-disk-space-guardian
  • Provider: groq
  • Location: bash-utils/nightly-nightly-disk-space-guardian-3
  • Files Created: 3
  • Description: Monitors root disk usage and warns with apocalyptic emojis when a configurable threshold is exceeded.

Rationale

  • Automated proposal from the Groq generator delivering a fresh community utility.
  • This utility was generated using the groq AI provider.

Why safe to merge

  • Utility is isolated to bash-utils/nightly-nightly-disk-space-guardian-3.
  • README + tests ship together (see folder contents).
  • No secrets or credentials touched.
  • All changes are additive and self-contained.

Test Plan

  • Follow the instructions in the generated README at bash-utils/nightly-nightly-disk-space-guardian-3/README.md
  • Run tests located in bash-utils/nightly-nightly-disk-space-guardian-3/tests/

Links

  • Generated docs and examples committed alongside this change.

Mock Justification

  • Not applicable; generator did not introduce new mocks.

…s when a configurable threshold is exceeded.
@polsala

polsala commented Jul 6, 2026

Copy link
Copy Markdown
Owner Author

🤖 Review by GROQ Agent

✅ What's solid

  • Self‑contained utility – the script lives in its own folder, has no external dependencies beyond standard Unix tools (df, awk, bash built‑ins).
  • Fail‑fast defaultsset -euo pipefail protects against unset variables and pipeline failures.
  • Configurable threshold – users can override the default 80 % via a positional argument.
  • Deterministic testing hook – the DF_OUTPUT env‑var lets the test suite inject fake df output without touching the real filesystem.
  • Clear exit‑code contract0 (OK), 1 (warning), 2 (parse error) is documented and respected in the code.
  • Readable README – purpose, features, installation, usage, exit‑code table, and a quick test command are all present.

🧪 Tests

  • Coverage of main branches – the three tests hit the “below threshold”, “above threshold”, and “invalid df output” paths.
  • Simple assertion helperassert_equal makes failures easy to read.

Actionable improvements

  1. Validate the threshold argument

    if ! [[ "$THRESHOLD" =~ ^[0-9]+$ ]] || (( THRESHOLD < 0 || THRESHOLD > 100 )); then
        echo "Threshold must be an integer between 0 and 100."
        exit 2
    fi

    Add a test that passes a non‑numeric or out‑of‑range value and expects exit 2.

  2. Make the “above‑threshold” test deterministic
    The script picks a random warning message, which is fine for production but makes the test flaky if you ever decide to assert the exact string. Consider exposing a MESSAGE_INDEX env‑var for test injection, e.g.:

    idx=${MESSAGE_INDEX:-$(( RANDOM % ${#MESSAGES[@]} ))}

    Then the test can set MESSAGE_INDEX=0 and assert the exact message.

  3. Add a test for missing df command
    Simulate command -v df failing (e.g., unset -f df or PATH=) and verify the script exits with a non‑zero code and a helpful error.

  4. Edge‑case test for multiple root lines
    On some systems df / may return more than one line (e.g., overlay filesystems). Ensure the script still picks the correct % value. A test could set DF_OUTPUT with two root‑like lines and assert the right one is used.

🔒 Security

  • No credential handling – the utility does not read or write secrets.
  • Controlled environment injectionDF_OUTPUT is deliberately used for testing; it does not affect production runs because it is only consulted when set.

Actionable improvements

  1. Sanitize any external input – the only external input is the positional argument. Adding the numeric validation (see Tests) also mitigates potential injection via malformed arguments.
  2. Avoid eval or command substitution on untrusted data – the script already uses simple echo | awk pipelines, which is safe. Just keep this discipline if future enhancements add more complex parsing.

🧩 Docs/DX

  • Installation snippet points to utils/bash-utils/nightly-disk-space-guardian/src/disk_guardian.sh, but the repository layout uses bash-utils/nightly-nightly-disk-space-guardian-3. Align the path in the README with the actual location or provide a generic “clone the repo and run chmod +x src/disk_guardian.sh”.
  • Usage examples are clear, but they could mention that the threshold argument must be an integer (0‑100).
  • Testing instructions assume the user is in utils/bash-utils/...; again, adjust to the real path or use a relative cd "$(dirname "$0")/../tests" pattern.

Suggested additions

### Advanced usage
```bash
# Override the random message (useful for CI)
MESSAGE_INDEX=2 ./src/disk_guardian.sh 75

Compatibility notes

  • The script relies on df -h output where the Use% column is the 5th field. On macOS, df -h places the percentage in the 4th column; you can force POSIX output with df -P -h / for consistent parsing.

## 🧱 Mocks/Fakes
- The PR states “Not applicable; generator did not introduce new mocks.”  
- The `DF_OUTPUT` env‑var is effectively a **fake** for `df`. This is a lightweight and appropriate approach for a Bash utility.  

**Potential enhancement**
- If the project later adopts a test harness (e.g., Bats), consider wrapping the `df` call in a function (`get_df_output`) that can be overridden in tests, making the mock more explicit and reusable across multiple scripts.

---  

Overall, the utility is functional, well‑documented, and has a solid test foundation. The suggestions above focus on tightening input validation, improving test determinism, and polishing the documentation to reduce friction for downstream users.

@polsala

polsala commented Jul 6, 2026

Copy link
Copy Markdown
Owner Author

🤖 Review by GEMINI Agent

✅ What's solid

  • Clear Purpose and Features: The README.md clearly outlines the utility's purpose and features, including configurability and deterministic testing.
  • Robust Scripting Practices: The disk_guardian.sh script uses #!/usr/bin/env bash and set -euo pipefail, which are excellent practices for robust shell scripting, ensuring early exit on errors and preventing common pitfalls.
  • Testability via Environment Variable: The DF_OUTPUT environment variable for injecting df output is a highly effective pattern for making shell scripts easily testable without relying on actual system commands. This is a significant strength.
  • Comprehensive Test Suite: The test_disk_guardian.sh includes tests for usage below threshold, usage above threshold (checking for any valid warning message), and handling invalid df output, demonstrating good test coverage for the core logic.
  • Randomized Warning Messages: The use of an array of apocalyptic emojis and random selection adds a fun, thematic touch as described in the PR.
  • Clear Exit Codes: The script defines and uses distinct exit codes (0, 1, 2) for different outcomes, which is crucial for automation and integration into other systems.

🧪 Tests

  • Brittle df Output Parsing: The script relies on specific column numbers and line positions (tail -n +2 | head -n 1, awk '{print $5}') from df -h /. While df -h / often provides consistent output for the root filesystem, this can be fragile across different Unix-like systems or df versions.
    • Actionable Feedback: Consider a more robust parsing method, perhaps by explicitly looking for the / mount point in the df output, or by using grep with a regex to find the line containing the root filesystem and then extracting the percentage.
    • Example:
      # More robust parsing for the root filesystem line
      USAGE_LINE=$(echo "$DF_DATA" | grep -E '^/dev/[^[:space:]]+[[:space:]]+.*[[:space:]]+/([[:space:]]|$)' | head -n 1)
      # Then extract the percentage, potentially using a regex to be more specific
      if [[ "$USAGE_LINE" =~ ([0-9]+)% ]]; then
        USAGE_PCT="${BASH_REMATCH[1]}"
      else
        echo "Failed to parse disk usage percentage from line: $USAGE_LINE"
        exit 2
      fi
  • Test Script Path Hardcoding: The README.md contains incorrect paths for both installation and testing instructions.
    • Actionable Feedback: Update the README.md to reflect the correct utility path: bash-utils/nightly-nightly-disk-space-guardian-3.
    • Example (Installation):
      chmod +x bash-utils/nightly-nightly-disk-space-guardian-3/src/disk_guardian.sh
    • Example (Testing):
      cd bash-utils/nightly-nightly-disk-space-guardian-3/tests
      bash test_disk_guardian.sh
  • Test for Edge Cases (Threshold): The current tests cover below and above the threshold. Consider adding a test case where the disk usage is exactly at the threshold.
    • Actionable Feedback: Add a test case to verify behavior when USAGE_PCT equals THRESHOLD. Based on (( USAGE_PCT > THRESHOLD )), it should report "safe".
    • Example:
      # -------------------------------------------------------------------
      # Test 4: Usage at threshold (should report OK)
      # -------------------------------------------------------------------
      export DF_OUTPUT=$'Filesystem      Size  Used Avail Use% Mounted on\n/dev/sda1        100G   80G   20G  80% /'
      output=$($SCRIPT 80)
      expected="✅ Disk usage is safe: 80% (threshold 80%)."
      assert_equal "$expected" "$output" "usage-at-threshold"
  • Test for Non-Integer Threshold: The script implicitly assumes the threshold is an integer. While df percentages are typically integers, passing non-integer thresholds might lead to unexpected behavior or errors in the (( ... )) arithmetic context.
    • Actionable Feedback: Add input validation for the THRESHOLD argument to ensure it's an integer between 0 and 100.
    • Example:
      # ... inside disk_guardian.sh, after THRESHOLD is set
      if ! [[ "$THRESHOLD" =~ ^[0-9]+$ ]] || (( THRESHOLD < 0 || THRESHOLD > 100 )); then
        echo "Error: Threshold must be an integer between 0 and 100."
        exit 2
      fi
      Then, add a test case for this validation.

🔒 Security

  • Command Injection Risk: The script uses echo "$DF_DATA" | .... If DF_DATA were user-controlled (which it is for testing via DF_OUTPUT), and contained malicious shell commands, it could lead to command injection. While DF_OUTPUT is intended for internal testing, it's a vector to be aware of.
    • Actionable Feedback: Ensure that DF_DATA is treated as raw string data and not executed. The current piping to awk and tr is generally safe, but if future modifications introduce eval or command substitution on DF_DATA, it would be vulnerable. For df output, it's generally safe, but good to note for broader utility.
  • Path Handling: The chmod +x instruction in the README.md uses a relative path. If the utility is copied or moved, this path might break.
    • Actionable Feedback: Recommend using $(dirname "$0") or similar relative pathing within the script itself if it needs to reference other files, and for installation instructions, advise users to adapt the path or provide a more robust installation method (e.g., make install). For a standalone script, this is less critical, but worth noting for broader utility.

🧩 Docs/DX

  • Inconsistent Naming: The PR title and body refer to nightly-nightly-disk-space-guardian-3, but the README.md and script refer to nightly-disk-space-guardian. This inconsistency can cause confusion.
    • Actionable Feedback: Standardize the utility name across all files and the PR description. If the -3 suffix is part of the official name, it should be in the README.md and file paths. If it's an internal versioning, it should be omitted from user-facing documentation.
  • Installation Instructions Clarity: The installation section in README.md suggests cloning the repository or copying the utility folder. For a single bash script, simply copying the script and making it executable is often sufficient.
    • Actionable Feedback: Simplify the installation instructions to focus on making the script executable, perhaps suggesting where to place it in the user's PATH for easier access.
    • Example:
      # Copy the script to a location in your PATH, e.g., /usr/local/bin
      sudo cp bash-utils/nightly-nightly-disk-space-guardian-3/src/disk_guardian.sh /usr/local/bin/disk_guardian
      sudo chmod +x /usr/local/bin/disk_guardian
  • Dependency Declaration: The README.md mentions "Works on any Unix-like system with df." This is good, but explicitly listing df as a dependency under a "Dependencies" section could be clearer.
    • Actionable Feedback: Add a dedicated "Dependencies" section to the README.md listing df.

🧱 Mocks/Fakes

  • Mock Justification: The PR body states "Not applicable; generator did not introduce new mocks." However, the DF_OUTPUT environment variable serves as a mock/fake for the df command's output, which is a crucial part of the testing strategy.
    • Actionable Feedback: Update the "Mock Justification" in the PR body to acknowledge the use of DF_OUTPUT as an environmental mock for df output, explaining its purpose in enabling deterministic testing. This clarifies the testing approach and highlights a good design choice.
    • Example: "The utility uses the DF_OUTPUT environment variable to mock the output of the df command, allowing for deterministic and isolated testing of the parsing and logic without relying on the actual system's disk state."
  • Scope of Mocking: The current mocking strategy is effective for df output. If the script were to grow and interact with other external commands or services, consider how those would be mocked to maintain test isolation and speed.
    • Actionable Feedback: For future enhancements, if the script integrates with other external commands or APIs, consider extending the mocking strategy (e.g., using functions in bash tests to override commands, or dedicated test doubles) to maintain the high testability achieved with DF_OUTPUT.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant