Skip to content

Add verbose #78

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed

Add verbose #78

wants to merge 4 commits into from

Conversation

shenxianpeng
Copy link
Collaborator

@shenxianpeng shenxianpeng commented Jul 3, 2025

Summary by CodeRabbit

  • New Features

    • Added support for a verbose mode in clang-format and clang-tidy hooks, providing detailed debug output during execution.
    • Introduced utility functions for enhanced subprocess logging and debug printing.
  • Documentation

    • Updated README with a new section on enabling verbose output and debugging for clang-format and clang-tidy hooks.
    • Added an example pre-commit configuration file demonstrating verbose mode usage.
  • Tests

    • Expanded test coverage for verbose mode and main function behaviors in both clang-format and clang-tidy hooks.

@github-actions github-actions bot added the documentation Improvements or additions to documentation label Jul 3, 2025
Copy link

sonarqubecloud bot commented Jul 3, 2025

Copy link

coderabbitai bot commented Jul 3, 2025

Walkthrough

Verbose output and debugging support were added to the clang-format and clang-tidy hooks, including new command-line flags, utility functions for verbose subprocess execution, and expanded documentation. Example configurations and tests for verbose/debug behavior were introduced. The pre-commit testing script and configuration files were updated to reflect and test these enhancements.

Changes

File(s) Change Summary
README.md Added "Verbose Output and Debugging" section with usage instructions, YAML examples, and troubleshooting guidance.
cpp_linter_hooks/clang_format.py
cpp_linter_hooks/clang_tidy.py
Added --verbose argument, refactored subprocess execution to use utility for logging, and improved error handling.
cpp_linter_hooks/util.py Introduced debug_print and run_subprocess_with_logging for verbose/debug subprocess execution and output.
testing/pre-commit-config-verbose.yaml Added new example pre-commit config enabling verbose mode for clang-format and clang-tidy hooks.
testing/run.sh Modified to include the new verbose pre-commit config in testing loop.
tests/test_clang_format.py
tests/test_clang_tidy.py
Added tests for verbose/debug output, subprocess invocation, and main function error handling.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant PreCommit
    participant HookScript
    participant Util

    User->>PreCommit: Runs pre-commit with --verbose
    PreCommit->>HookScript: Executes clang-format/clang-tidy hook with --verbose
    HookScript->>Util: Calls run_subprocess_with_logging(command, tool_name, verbose)
    Util->>HookScript: Returns (exit_code, output)
    HookScript->>PreCommit: Prints debug info (if verbose), returns result
    PreCommit->>User: Displays detailed output and exit code
Loading

Suggested labels

enhancement

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
cpp_linter_hooks/util.py (1)

75-81: Simplify nested if statements as suggested by static analysis.

The nested if statements can be combined for better readability.

-        # Special handling for clang-tidy warnings/errors
-        if tool_name == "clang-tidy" and (
-            "warning:" in combined_output or "error:" in combined_output
-        ):
-            if retval == 0:  # Only override if it was successful
-                retval = 1
-                debug_print("Found warnings/errors, setting exit code to 1", verbose)
+        # Special handling for clang-tidy warnings/errors
+        if (tool_name == "clang-tidy" and 
+            ("warning:" in combined_output or "error:" in combined_output) and
+            retval == 0):  # Only override if it was successful
+            retval = 1
+            debug_print("Found warnings/errors, setting exit code to 1", verbose)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0339700 and 596db1b.

📒 Files selected for processing (8)
  • README.md (1 hunks)
  • cpp_linter_hooks/clang_format.py (2 hunks)
  • cpp_linter_hooks/clang_tidy.py (2 hunks)
  • cpp_linter_hooks/util.py (2 hunks)
  • testing/pre-commit-config-verbose.yaml (1 hunks)
  • testing/run.sh (1 hunks)
  • tests/test_clang_format.py (2 hunks)
  • tests/test_clang_tidy.py (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
tests/test_clang_format.py (3)
cpp_linter_hooks/clang_format.py (2)
  • run_clang_format (19-37)
  • main (40-44)
cpp_linter_hooks/clang_tidy.py (1)
  • main (37-41)
tests/test_clang_tidy.py (1)
  • test_verbose_output (68-94)
tests/test_clang_tidy.py (2)
tests/test_clang_format.py (1)
  • test_verbose_output (86-112)
cpp_linter_hooks/clang_tidy.py (1)
  • run_clang_tidy (19-34)
cpp_linter_hooks/clang_tidy.py (1)
cpp_linter_hooks/util.py (3)
  • ensure_installed (113-126)
  • debug_print (17-20)
  • run_subprocess_with_logging (23-88)
🪛 Ruff (0.11.9)
cpp_linter_hooks/util.py

75-78: Use a single if statement instead of nested if statements

Combine if statements using and

(SIM102)

🪛 GitHub Actions: Test
tests/test_clang_tidy.py

[error] 61-61: Test failure: test_main_as_script did not raise SystemExit as expected.

🔇 Additional comments (22)
cpp_linter_hooks/util.py (2)

17-21: LGTM! Clean and focused utility function.

The debug_print function is well-implemented with a clear purpose and simple interface.


23-89: Comprehensive subprocess utility with solid error handling.

The run_subprocess_with_logging function provides excellent centralized handling for subprocess execution with verbose logging, dry-run support, and tool-specific behavior. The implementation correctly handles:

  • Subprocess execution with proper output capture
  • Dry-run mode for clang-format
  • Special exit code handling for clang-tidy warnings/errors
  • Comprehensive error handling
testing/run.sh (1)

4-4: Good addition to test the new verbose configuration.

Adding the verbose configuration file to the test loop ensures the new verbose functionality is properly exercised during testing.

README.md (1)

84-121: Excellent documentation for the new verbose debugging features.

The new "Verbose Output and Debugging" section provides comprehensive guidance for users:

  • Clear configuration examples with verbose flags
  • Detailed explanation of verbose output contents
  • Practical debugging scenarios and use cases
  • Proper command-line examples

This documentation will be very helpful for users troubleshooting issues with the hooks.

testing/pre-commit-config-verbose.yaml (1)

1-26: Well-structured example configuration with excellent documentation.

This verbose configuration file provides:

  • Complete working example with both clang-format and clang-tidy
  • Clear comments explaining usage and benefits
  • Specific guidance for troubleshooting (e.g., exit code 247)
  • Proper file patterns and argument combinations

This will be very useful for users who need to debug hook issues.

tests/test_clang_format.py (3)

70-83: Good test coverage for the main() function edge case.

The test_main_empty_output test properly validates the behavior when clang-format returns an error with empty output, ensuring the main function handles this scenario correctly.


86-113: Comprehensive test for verbose mode functionality.

The test_verbose_output test effectively verifies:

  • Debug messages are printed to stderr when verbose mode is enabled
  • The subprocess utility is called with correct parameters
  • Mocking is properly used to isolate the functionality

This ensures the verbose feature works as expected.


115-169: Excellent test coverage for error conditions and dry-run mode.

The additional verbose tests (test_verbose_with_error and test_verbose_dry_run) provide comprehensive coverage of:

  • Error handling in verbose mode
  • Dry-run mode behavior with verbose output
  • Proper return value validation
  • Correct subprocess utility integration

These tests ensure robust behavior across different scenarios.

tests/test_clang_tidy.py (4)

4-4: Good addition of necessary import.

The patch import is correctly added to support the new test functions that use mocking.


68-95: Excellent test coverage for verbose output.

This test properly mocks the necessary functions and verifies that verbose mode produces the expected debug output. The test structure and assertions are well-designed.


97-126: Good test coverage for verbose mode with warnings.

The test correctly simulates the scenario where clang-tidy returns warnings and verifies that the output is properly handled and return codes are correctly propagated.


128-151: Good test coverage for file not found scenarios.

The test properly simulates the FileNotFoundError scenario and verifies the error handling behavior in verbose mode.

cpp_linter_hooks/clang_tidy.py (5)

4-9: Good refactoring to use centralized utility functions.

The imports have been updated to use the new utility functions from util.py, which centralizes subprocess handling and verbose logging functionality.


14-16: Proper addition of verbose argument.

The verbose argument is correctly added with appropriate short and long forms, following standard CLI conventions.


25-34: Excellent refactoring with proper verbose support.

The function has been well-refactored to:

  • Extract the verbose flag from arguments
  • Add debug logging for version and executable path
  • Use the centralized run_subprocess_with_logging utility function
  • Pass the correct parameters including dry_run=False for clang-tidy

This maintains the same functionality while adding verbose support and improving code consistency.


39-40: Appropriate use of pragma no cover comments.

The pragma comments are correctly applied to the error handling code in the main function, which is typically not covered in unit tests.


44-44: Appropriate use of pragma no cover comment.

The pragma comment is correctly applied to the main guard, which is typically not covered in unit tests.

cpp_linter_hooks/clang_format.py (5)

4-9: Good refactoring to use centralized utility functions.

The imports have been updated to use the new utility functions from util.py, maintaining consistency with the clang_tidy.py refactoring.


14-16: Proper addition of verbose argument.

The verbose argument is correctly added with the same format as clang_tidy.py, ensuring consistency across the codebase.


25-37: Excellent refactoring with proper verbose and dry-run support.

The function has been well-refactored to:

  • Extract the verbose flag from arguments
  • Add debug logging for version and executable path
  • Detect dry-run mode from the command arguments
  • Use the centralized run_subprocess_with_logging utility function
  • Pass the correct parameters including the dry-run flag

This maintains the same functionality while adding verbose support and improving code consistency with clang_tidy.py.


42-43: Appropriate use of pragma no cover comments.

The pragma comments are correctly applied to the error handling code in the main function, consistent with the clang_tidy.py implementation.


47-47: Appropriate use of pragma no cover comment.

The pragma comment is correctly applied to the main guard, consistent with the clang_tidy.py implementation.

Comment on lines +55 to +66
def test_main_as_script():
"""Test the if __name__ == '__main__' behavior"""
with patch("cpp_linter_hooks.clang_tidy.main") as mock_main:
mock_main.return_value = 42

# This would normally raise SystemExit, but we're mocking main()
with pytest.raises(SystemExit) as exc_info:
# Simulate running the script directly
exec("if __name__ == '__main__': raise SystemExit(main())")

assert exc_info.value.code == 42

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix the test logic for main script execution.

The test is failing because it's not actually testing the module's if __name__ == '__main__' behavior. The exec() statement executes a generic condition that doesn't relate to the clang_tidy module.

-def test_main_as_script():
-    """Test the if __name__ == '__main__' behavior"""
-    with patch("cpp_linter_hooks.clang_tidy.main") as mock_main:
-        mock_main.return_value = 42
-
-        # This would normally raise SystemExit, but we're mocking main()
-        with pytest.raises(SystemExit) as exc_info:
-            # Simulate running the script directly
-            exec("if __name__ == '__main__': raise SystemExit(main())")
-
-        assert exc_info.value.code == 42
+def test_main_as_script():
+    """Test the if __name__ == '__main__' behavior"""
+    with patch("cpp_linter_hooks.clang_tidy.main") as mock_main:
+        mock_main.return_value = 42
+        
+        # Import the module to trigger the if __name__ == '__main__' check
+        with patch("cpp_linter_hooks.clang_tidy.__name__", "__main__"):
+            with pytest.raises(SystemExit) as exc_info:
+                import cpp_linter_hooks.clang_tidy
+                
+        assert exc_info.value.code == 42

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 GitHub Actions: Test

[error] 61-61: Test failure: test_main_as_script did not raise SystemExit as expected.

🤖 Prompt for AI Agents
In tests/test_clang_tidy.py around lines 55 to 66, the test incorrectly uses
exec() with a generic if __name__ == '__main__' condition that does not invoke
the actual clang_tidy module's main function. To fix this, modify the test to
execute the clang_tidy module as a script, for example by using runpy.run_module
or a similar approach that triggers the module's real __main__ behavior,
ensuring the test properly verifies the module's script execution and SystemExit
with the mocked main return value.

@shenxianpeng shenxianpeng deleted the add-verbose branch July 3, 2025 22:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant