Skip to content

Conversation

shenxianpeng
Copy link
Collaborator

@shenxianpeng shenxianpeng commented Sep 18, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Improved detection of tool versions by reading from declared project dependencies, ensuring clang-format and clang-tidy are identified correctly.
  • Chores

    • Moved clang-format and clang-tidy into project dependencies and trimmed build-only requirements for a leaner build setup.
  • Tests

    • Updated tests to align with the new project dependency layout so version-detection behavior remains covered.

@shenxianpeng shenxianpeng added the bug Something isn't working label Sep 18, 2025
Copy link

coderabbitai bot commented Sep 18, 2025

Walkthrough

Reads clang tool versions from the top-level [project].dependencies in pyproject.toml instead of [build-system].requires; moves clang-format/clang-tidy entries from build-system.requires to project.dependencies and updates tests to match the new TOML layout.

Changes

Cohort / File(s) Summary
Utility function update
cpp_linter_hooks/util.py
get_version_from_dependency now reads the dependencies list from the parsed pyproject TOML (top-level [project].dependencies) and iterates over those entries to find tool==<version>; matching logic and return behavior unchanged.
Build configuration update
pyproject.toml
Removed clang-format==21.1.0 and clang-tidy==21.1.0 from [build-system].requires and added them to [project].dependencies; [build-system].requires now contains only setuptools>=45 and setuptools-scm.
Tests update
tests/test_util.py
Updated tests to supply TOML content with a top-level dependencies list (instead of build-system.requires) for success and missing-dependency cases; assertions unchanged.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Title Check ✅ Passed The title "fix: move clang-tools to project dependencies section" succinctly and accurately captures the primary change in the PR — relocating clang-format/clang-tidy from build-system.requires into the project's dependencies and updating code/tests to match; it is a single clear sentence using a conventional "fix:" prefix and is neither vague nor off-topic.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix-deps

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

Comment @coderabbitai help to get the list of available commands and usage tips.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
cpp_linter_hooks/util.py (1)

157-171: Guard: avoid installing tool==None when no version resolves.

If both user input and defaults are None, _install_tool will attempt pip install clang-format==None. Add a guard and log.

Apply this diff:

     if user_version is None:
         user_version = (
             DEFAULT_CLANG_FORMAT_VERSION
             if tool == "clang-format"
             else DEFAULT_CLANG_TIDY_VERSION
         )
 
-    return _install_tool(tool, user_version)
+    if not user_version:
+        LOG.error("Could not resolve version for %s from input or project dependencies.", tool)
+        return None
+    return _install_tool(tool, user_version)
🧹 Nitpick comments (1)
cpp_linter_hooks/util.py (1)

31-33: Consider lazy-evaluating defaults to avoid import-time I/O.

Reading and parsing pyproject.toml at import time can slow CLI startup and fails in wheel installs where the file isn’t present. Consider resolving defaults on demand or caching on first use.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d56ca2a and 20f9f6e.

📒 Files selected for processing (2)
  • cpp_linter_hooks/util.py (1 hunks)
  • pyproject.toml (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Run benchmarks
🔇 Additional comments (2)
pyproject.toml (2)

2-2: LGTM: build requirements look sane.

setuptools + setuptools-scm under [build-system].requires matches your SCM versioning setup.

If you rely on TOML configuration for setuptools-scm, confirm whether setuptools-scm[toml] is recommended for your minimum supported versions.


37-39: Pinning clang tools under runtime deps aligns with util.py.

Good move; exact pins match the curated version lists in util.py.

If publishing to PyPI, double-check these wheels exist for all supported Python versions/architectures.

Comment on lines 23 to 28
# Check dependencies
dependencies = data.get("dependencies", [])
for dep in dependencies:
if dep.startswith(f"{tool}=="):
return dep.split("==")[1]
return None
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: read from [project].dependencies (not top-level) and strip env markers.

pyproject.toml stores deps under [project].dependencies. Current lookup uses a missing top-level dependencies key, so defaults will always be None. Also, strip any ; ... markers before matching.

Apply this diff:

-    # Check dependencies
-    dependencies = data.get("dependencies", [])
-    for dep in dependencies:
-        if dep.startswith(f"{tool}=="):
-            return dep.split("==")[1]
+    # Check [project].dependencies
+    dependencies = (data.get("project") or {}).get("dependencies", [])  # PEP 621
+    for dep in dependencies:
+        dep_no_marker = dep.split(";", 1)[0].strip()  # drop env markers/extras
+        if dep_no_marker.startswith(f"{tool}=="):
+            return dep_no_marker.split("==", 1)[1]

Optional hardening (outside this hunk): add a fallback to installed metadata if pyproject.toml isn’t present at runtime.

# at top:
from importlib import metadata as _ilmd

# inside get_version_from_dependency(), before final `return None`:
try:
    dist = _ilmd.distribution("cpp_linter_hooks")
    for req in dist.requires or []:
        req_no_marker = req.split(";", 1)[0].strip()
        if req_no_marker.startswith(f"{tool}=="):
            return req_no_marker.split("==", 1)[1]
except _ilmd.PackageNotFoundError:
    pass
🤖 Prompt for AI Agents
In cpp_linter_hooks/util.py around lines 23 to 28, the function currently reads
top-level "dependencies" (which is absent) and doesn't strip environment
markers, so it always returns None for pyproject.toml deps; modify it to read
data.get("project", {}).get("dependencies", []) instead of
data.get("dependencies", []), and when comparing split any marker by taking
dep.split(";", 1)[0].strip() before checking startswith(f"{tool}==") and
extracting the version. Optionally add the fallback: import importlib.metadata
as _ilmd at top and before returning None try to read installed distribution
requirements (catching _ilmd.PackageNotFoundError) and apply the same
marker-stripping logic to find the dependency version.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
tests/test_util.py (1)

249-253: Set non-None defaults for clang tools (tests are failing).

Update cpp_linter_hooks/util.py (lines 31–32) to fall back to the latest curated versions when get_version_from_dependency returns None:

DEFAULT_CLANG_FORMAT_VERSION = get_version_from_dependency("clang-format") or (CLANG_FORMAT_VERSIONS[-1] if CLANG_FORMAT_VERSIONS else None)
DEFAULT_CLANG_TIDY_VERSION = get_version_from_dependency("clang-tidy") or (CLANG_TIDY_VERSIONS[-1] if CLANG_TIDY_VERSIONS else None)

🧹 Nitpick comments (2)
tests/test_util.py (2)

58-59: Same issue in the “missing dependency” test.

Align with [project].dependencies to avoid false positives.

-    mock_toml_content = {"dependencies": ["other-package==1.0.0"]}
+    mock_toml_content = {"project": {"dependencies": ["other-package==1.0.0"]}}

25-45: Optional: add test for [project].dependencies and decide on backward-compatibility

cpp_linter_hooks/util.py uses tomllib.load and reads top-level "dependencies" via data.get("dependencies", []) (around lines 22–24) and does not inspect project -> dependencies. Add the suggested positive test for [project].dependencies and either support both shapes (parametrize tests) or remove top-level support.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 20f9f6e and fdca709.

📒 Files selected for processing (1)
  • tests/test_util.py (2 hunks)
🧰 Additional context used
🪛 GitHub Actions: Test
tests/test_util.py

[error] 249-249: Step failed: coverage run --source=tests,cpp_linter_hooks -m pytest -vv. Test 'test_default_versions' failed with AssertionError: DEFAULT_CLANG_FORMAT_VERSION is None (tests/test_util.py:249).

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Run benchmarks
🔇 Additional comments (1)
tests/test_util.py (1)

28-33: Do not change the test mock without updating util; get_version_from_dependency reads top-level dependencies.

cpp_linter_hooks/util.py uses data.get('dependencies', []) (around lines 23–26) and tests in tests/test_util.py currently mock that shape; either update util to read project.dependencies (e.g. data.get('project', {}).get('dependencies', [])) and then apply your test diff, or leave the test unchanged.

Likely an incorrect or invalid review comment.

Copy link
Contributor

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR fixes the detection of clang-tools versions by moving them from the build dependencies to the project dependencies section in pyproject.toml. This ensures that the version detection utility can properly locate and read the tool versions from the correct section.

  • Moved clang-format and clang-tidy from build-system.requires to project dependencies
  • Updated the version detection utility to read from dependencies instead of build-system.requires
  • Modified test cases to reflect the new dependency structure

Reviewed Changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.

File Description
pyproject.toml Moved clang-format and clang-tidy from build-system.requires to project dependencies
cpp_linter_hooks/util.py Updated get_version_from_dependency to read from dependencies section instead of build-system.requires
tests/test_util.py Updated test data to match new dependency structure

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

Copy link

Copy link

codecov bot commented Sep 18, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.39%. Comparing base (d56ca2a) to head (a212c74).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #118      +/-   ##
==========================================
- Coverage   94.44%   94.39%   -0.06%     
==========================================
  Files           3        3              
  Lines         108      107       -1     
==========================================
- Hits          102      101       -1     
  Misses          6        6              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link

codspeed-hq bot commented Sep 18, 2025

CodSpeed Performance Report

Merging #118 will not alter performance

Comparing fix-deps (a212c74) with main (d56ca2a)

Summary

✅ 60 untouched
⏩ 13 skipped1

Footnotes

  1. 13 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

@shenxianpeng shenxianpeng changed the title fix: move clang-tools to dependencies section fix: move clang-tools to project dependencies section Sep 18, 2025
@shenxianpeng shenxianpeng merged commit 8c45bb1 into main Sep 18, 2025
18 checks passed
@shenxianpeng shenxianpeng deleted the fix-deps branch September 18, 2025 19:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant