Skip to content
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

feat(linters): Add cli tool for running clang-tidy in parallel. #17

Open
wants to merge 9 commits into
base: main
Choose a base branch
from

Conversation

LinZhihao-723
Copy link
Member

@LinZhihao-723 LinZhihao-723 commented Jan 18, 2025

Description

This PR introduces a cli sub-project for running clang-tidy in parallel. For now, it is almost like a simplified script of the llvm version here.
As discussed offline, we decided to use uv to manage our Python cli scripts.

Validation performed

I have tested this cli by using it to check clp-ffi-py. Here's how it works:

cd $PROJECT_DIR/clp-ffi-py
uv venv
uv pip install $PROJECT_DIR/yscope-dev-utils/cli/clang-tidy-utils
task lint:cpp-format-fix # This is to ensure clang-tidy config has been set
rm -rf build && mkdir build && cd build && cmake .. && cd ..
yscope-clang-tidy-utils -j 10 ./src/clp_ffi_py/ir/native/* -- -p build/compile_commands.json  --line-filter="[{\"name\":\"cpp11_zone.hpp\",\"lines\":[[197,197]]}]"

Here, we parallel 10 clang-tidy tasks with extra clang-tidy arguments -p build/compile_commands.json --line-filter="[{\"name\":\"cpp11_zone.hpp\",\"lines\":[[197,197]]}]" to match what we specify in the linting task here. You can use echo $? to check the return value is 0. If we remove the lint filter in the arguments above, clang-tidy will raise a warning on msgpack's source code and thus the return value of echo $? will be 1 in this case.

Summary by CodeRabbit

  • Documentation

    • Added a README detailing installation, usage instructions, and development commands for the new command-line tool.
  • New Features

    • Launched a CLI utility that enables parallel execution of clang-tidy checks with customizable options.
    • Introduced a central configuration for project metadata, dependencies, and development tooling.
  • Chores

    • Updated version control ignore settings to streamline repository management by excluding unnecessary files and directories.

Copy link

coderabbitai bot commented Jan 18, 2025

Walkthrough

The changes modify the clang-tidy-utils project by updating several configuration and source files. The .gitignore now excludes common Python, caching, and packaging directories. A new README provides comprehensive documentation on usage, installation, and development commands. Additionally, a new pyproject.toml file establishes project metadata, dependencies, and tool configurations. Lastly, a CLI tool is introduced to perform parallel clang-tidy checks utilizing asynchronous Python functions with controlled concurrency. No changes were made to exported or public entities.

Changes

File(s) Change Summary
linters/clang-tidy-utils/.gitignore Added entries to ignore virtual environment directories, Python caches (__pycache__), packaging files (*.egg-info), and development caches (.mypy_cache, .ruff_cache).
linters/clang-tidy-utils/README.md New README documenting the tool’s purpose, installation instructions, usage details, and development commands.
linters/clang-tidy-utils/pyproject.toml New configuration file specifying project metadata (name, version, authors), Python version requirements, dependencies, development dependency groups, and tool settings.
linters/clang-tidy-utils/src/clang_tidy_utils/cli.py New CLI utility that defines a data class for results and several asynchronous functions to execute and manage parallel clang-tidy tasks with concurrency control.

Sequence Diagram(s)

sequenceDiagram
    participant CLI as CLI Command
    participant Main as main()
    participant Scheduler as Task Scheduler
    participant Worker as ClangTidy Task
    CLI->>Main: Invoke CLI with arguments
    Main->>Scheduler: Start parallel execution (_clang_tidy_parallel_execution_entry)
    Scheduler->>Worker: Launch async task with semaphore
    Worker-->>Scheduler: Return ClangTidyResult
    Scheduler-->>Main: Aggregate and return results
    Main->>CLI: Output results and exit
Loading

Suggested reviewers

  • kirkrodrigues
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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.

@LinZhihao-723 LinZhihao-723 changed the title feat(cli): Add cli script for running clang-tidy in parallel. feat(cli): Add a cli tool for running clang-tidy in parallel. Jan 31, 2025
@LinZhihao-723 LinZhihao-723 changed the title feat(cli): Add a cli tool for running clang-tidy in parallel. feat(cli): Add cli tool for running clang-tidy in parallel. Jan 31, 2025
@LinZhihao-723 LinZhihao-723 marked this pull request as ready for review January 31, 2025 01:21
Copy link
Member Author

@LinZhihao-723 LinZhihao-723 left a comment

Choose a reason for hiding this comment

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

We can discuss how to structure the cli scripts/tools. The current layout might not be the best practice.

@@ -0,0 +1,45 @@
[project]
name = "yscope-clang-tidy-utils"
Copy link
Member Author

Choose a reason for hiding this comment

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

We may drop yscope- prefix

Copy link
Member

Choose a reason for hiding this comment

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

I don't have a strong preference, but if we ever do upload this to pypi it probably makes more sense to have the prefix. If we never upload it to pypi the name won't ever really matter right?

Copy link
Member

Choose a reason for hiding this comment

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

I prefer to drop the prefix for now since it's likely this will be an internal tool for the foreseeable future.

Copy link
Member Author

Choose a reason for hiding this comment

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

Removed.

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: 0

🧹 Nitpick comments (6)
cli/clang-tidy-utils/src/yscope_clang_tidy_utils/cli.py (3)

22-30: Consider validating file existence.

While building the argument list, consider verifying that the file exists before passing it to clang-tidy, especially in large codebases where file paths may be stale. This helps provide clearer error messages if the file is missing.


48-50: Handle unresponsive processes more aggressively.

Currently, a process.terminate() signals the process, but clang-tidy or any subprocess may ignore SIGTERM. Consider adding a fallback mechanism (e.g., process.kill()) after a short delay to ensure the process halts cleanly.

 except asyncio.CancelledError:
     process.terminate()
+    try:
+        await asyncio.wait_for(process.wait(), timeout=2)
+    except asyncio.TimeoutError:
+        process.kill()
     raise

76-109: Consider early cancellation upon the first failure.

All tasks continue to run even if one file fails clang-tidy checks. If you'd like to fail early and skip checking subsequent files, you could cancel remaining tasks once an error is detected.

 if 0 != result.ret_code:
     ret_code = 1
+    # Optionally cancel remaining tasks to fail early:
+    for remaining_task in tasks:
+        if not remaining_task.done():
+            remaining_task.cancel()
+    break
cli/clang-tidy-utils/README.md (3)

3-3: Fix grammar in project introduction.

Use "a CLI script" instead of "a CLI scripts" to maintain grammatical correctness.

-This project is a CLI scripts for running [clang-tidy][clang-tidy-home] checks.
+This project is a CLI script for running [clang-tidy][clang-tidy-home] checks.
🧰 Tools
🪛 LanguageTool

[grammar] ~3-~3: The plural noun “scripts” cannot be used with the article “a”. Did you mean “a CLI script”?
Context: ...scope-clang-tidy-utils This project is a CLI scripts for running [clang-tidy][clang-tidy-hom...

(A_NNS)


30-30: Remove trailing punctuation from heading.

Remove the colon in "## Development:" to align with common Markdown style guidelines.

-## Development:
+## Development
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

30-30: Trailing punctuation in heading
Punctuation: ':'

(MD026, no-trailing-punctuation)


41-41: Link reference [uv-venv] is unused.

The link definition “[uv-venv]” is never referenced in the document. Consider removing it for clarity.

-[uv-venv]: https://docs.astral.sh/uv/pip/compatibility/#virtual-environments-by-default
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

41-41: Link and image reference definitions should be needed
Unused link or image reference definition: "uv-venv"

(MD053, link-image-reference-definitions)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c1593f7 and d74ac85.

📒 Files selected for processing (4)
  • cli/clang-tidy-utils/.gitignore (1 hunks)
  • cli/clang-tidy-utils/README.md (1 hunks)
  • cli/clang-tidy-utils/pyproject.toml (1 hunks)
  • cli/clang-tidy-utils/src/yscope_clang_tidy_utils/cli.py (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • cli/clang-tidy-utils/.gitignore
🧰 Additional context used
🪛 LanguageTool
cli/clang-tidy-utils/README.md

[grammar] ~3-~3: The plural noun “scripts” cannot be used with the article “a”. Did you mean “a CLI script”?
Context: ...scope-clang-tidy-utils This project is a CLI scripts for running [clang-tidy][clang-tidy-hom...

(A_NNS)

🪛 markdownlint-cli2 (0.17.2)
cli/clang-tidy-utils/README.md

30-30: Trailing punctuation in heading
Punctuation: ':'

(MD026, no-trailing-punctuation)


41-41: Link and image reference definitions should be needed
Unused link or image reference definition: "uv-venv"

(MD053, link-image-reference-definitions)

🔇 Additional comments (5)
cli/clang-tidy-utils/src/yscope_clang_tidy_utils/cli.py (2)

61-74: Concurrency strategy looks solid.

The approach to wrap each execute_clang_tidy_task with a semaphore is a well-structured way to impose concurrency limits. No immediate procedural concerns here.


111-175: Ensure clang-tidy is installed before calling.

If clang-tidy is missing, the CLI may crash. Consider implementing a preliminary check for clang-tidy’s existence to offer a more helpful error message to the user.

cli/clang-tidy-utils/pyproject.toml (3)

9-10: Verify clang-tidy version compatibility.

Ensure that clang-tidy >= 19.1.0 is fully supported in your environment. In certain older distributions, clang-tidy’s package name or version might differ.


13-18: Development dependencies are well structured.

Declaring formatting, linting, and type-checking tools fosters a consistent development workflow.


20-21: Handy script entry point.

Defining yscope-clang-tidy-utils in [project.scripts] is a user-friendly approach that enhances accessibility and makes the CLI straightforward to run.

Copy link
Member

@kirkrodrigues kirkrodrigues left a comment

Choose a reason for hiding this comment

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

Not a complete review but a few quick comments:

  • Can we move the tool into linters rather than cli?
  • Can we prefix internal functions with _?
  • There are some spelling/grammar mistakes in the README. Can you go over it once more?

@LinZhihao-723
Copy link
Member Author

Not a complete review but a few quick comments:

  • Can we move the tool into linters rather than cli?
  • Can we prefix internal functions with _?
  • There are some spelling/grammar mistakes in the README. Can you go over it once more?

Fixed.

@LinZhihao-723 LinZhihao-723 changed the title feat(cli): Add cli tool for running clang-tidy in parallel. feat(linters): Add cli tool for running clang-tidy in parallel. Feb 10, 2025
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: 0

🧹 Nitpick comments (5)
linters/clang-tidy-utils/src/clang_tidy_utils/cli.py (4)

22-30: Consider validating file existence or providing helpful error messages.
If a file path is invalid, clang-tidy will fail silently here. A quick file check or user-facing error message could enhance usability.


33-58: Robust async approach with graceful cancellation handling.
Terminating the process upon cancellation is a good practice to avoid resource leaks. However, you may consider additional handling if clang-tidy is not installed or is unavailable in PATH.


76-109: Optional: Provide a consolidated summary of failures.
Currently, each file's result is printed individually. For large batches, a final summary of failed files or a short report can improve usability.


111-175: Minor docstring clarity.
In the docstring for _clang_tidy_parallel_execution_entry, the parameter clang_tidy_args is grouped with files in the text. Splitting them out can improve clarity. Also, using sys.exit(ret_code) instead of exit(ret_code) is a common convention to maintain consistent script termination.

linters/clang-tidy-utils/README.md (1)

34-34: Remove trailing punctuation from the heading.
To adhere to markdown style guidelines (MD026), consider removing the colon in “## Development:”.

-## Development:
+## Development
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

34-34: Trailing punctuation in heading
Punctuation: ':'

(MD026, no-trailing-punctuation)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d74ac85 and 817fdef.

📒 Files selected for processing (4)
  • linters/clang-tidy-utils/.gitignore (1 hunks)
  • linters/clang-tidy-utils/README.md (1 hunks)
  • linters/clang-tidy-utils/pyproject.toml (1 hunks)
  • linters/clang-tidy-utils/src/clang_tidy_utils/cli.py (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • linters/clang-tidy-utils/.gitignore
  • linters/clang-tidy-utils/pyproject.toml
🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
linters/clang-tidy-utils/README.md

34-34: Trailing punctuation in heading
Punctuation: ':'

(MD026, no-trailing-punctuation)

🔇 Additional comments (3)
linters/clang-tidy-utils/src/clang_tidy_utils/cli.py (3)

1-9: Imports look good.
No issues detected; these imports are succinct and well-structured.


10-19: Good use of a data class for encapsulating clang-tidy results.
This design cleanly stores essential details such as return code and captured outputs.


61-74: Concurrency control is well-handled.
Using a semaphore to limit simultaneous tasks helps balance CPU usage effectively.

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.

3 participants