Skip to content

feat: get rid of toml and packaging and improve performance #89

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

Merged
merged 6 commits into from
Jul 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 21 additions & 21 deletions cpp_linter_hooks/util.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,34 @@
import sys
import shutil
import toml
import subprocess
from pathlib import Path
import logging
from typing import Optional, List
from packaging.version import Version, InvalidVersion

try:
import tomllib
except ModuleNotFoundError:
import tomli as tomllib

Check warning on line 11 in cpp_linter_hooks/util.py

View check run for this annotation

Codecov / codecov/patch

cpp_linter_hooks/util.py#L10-L11

Added lines #L10 - L11 were not covered by tests

LOG = logging.getLogger(__name__)


def get_version_from_dependency(tool: str) -> Optional[str]:
"""Get the version of a tool from the pyproject.toml dependencies."""
pyproject_path = Path(__file__).parent.parent / "pyproject.toml"
if not pyproject_path.exists():
return None
data = toml.load(pyproject_path)
with open(pyproject_path, "rb") as f:
data = tomllib.load(f)
dependencies = data.get("project", {}).get("dependencies", [])
for dep in dependencies:
if dep.startswith(f"{tool}=="):
return dep.split("==")[1]
return None


DEFAULT_CLANG_FORMAT_VERSION = get_version_from_dependency("clang-format") or "20.1.7"
DEFAULT_CLANG_TIDY_VERSION = get_version_from_dependency("clang-tidy") or "20.1.0"
DEFAULT_CLANG_FORMAT_VERSION = get_version_from_dependency("clang-format")
DEFAULT_CLANG_TIDY_VERSION = get_version_from_dependency("clang-tidy")


CLANG_FORMAT_VERSIONS = [
Expand Down Expand Up @@ -108,29 +113,21 @@


def _resolve_version(versions: List[str], user_input: Optional[str]) -> Optional[str]:
"""Resolve the version based on user input and available versions."""
if user_input is None:
return None
if user_input in versions:
return user_input
try:
user_ver = Version(user_input)
except InvalidVersion:
# Check if the user input is a valid version
return next(v for v in versions if v.startswith(user_input) or v == user_input)
except StopIteration:
LOG.warning("Version %s not found in available versions", user_input)
return None

candidates = [Version(v) for v in versions]
if user_input.count(".") == 0:
matches = [v for v in candidates if v.major == user_ver.major]
elif user_input.count(".") == 1:
matches = [
v
for v in candidates
if f"{v.major}.{v.minor}" == f"{user_ver.major}.{user_ver.minor}"
]
else:
return str(user_ver) if user_ver in candidates else None

return str(max(matches)) if matches else None


def _get_runtime_version(tool: str) -> Optional[str]:
"""Get the runtime version of a tool."""
try:
output = subprocess.check_output([tool, "--version"], text=True)
if tool == "clang-tidy":
Expand All @@ -144,6 +141,7 @@


def _install_tool(tool: str, version: str) -> Optional[Path]:
"""Install a tool using pip."""
try:
subprocess.check_call(
[sys.executable, "-m", "pip", "install", f"{tool}=={version}"]
Expand All @@ -155,6 +153,7 @@


def _resolve_install(tool: str, version: Optional[str]) -> Optional[Path]:
"""Resolve the installation of a tool, checking for version and installing if necessary."""
user_version = _resolve_version(
CLANG_FORMAT_VERSIONS if tool == "clang-format" else CLANG_TIDY_VERSIONS,
version,
Expand Down Expand Up @@ -191,6 +190,7 @@


def ensure_installed(tool: str, version: Optional[str] = None) -> str:
"""Ensure a tool is installed, resolving its version if necessary."""
LOG.info("Ensuring %s is installed", tool)
tool_path = _resolve_install(tool, version)
if tool_path:
Expand Down
3 changes: 1 addition & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ classifiers = [
dependencies = [
"clang-format==20.1.7",
"clang-tidy==20.1.0",
"toml>=0.10.2",
"packaging>=20.0",
"tomli>=1.1.0; python_version < '3.11'",
]
dynamic = ["version"]

Expand Down
2 changes: 1 addition & 1 deletion testing/run.sh
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ failed_cases=`grep -c "Failed" result.txt`

echo $failed_cases " cases failed."

if [ $failed_cases -eq 9 ]; then
if [ $failed_cases -eq 10 ]; then
echo "=============================="
echo "Test cpp-linter-hooks success."
echo "=============================="
Expand Down
20 changes: 10 additions & 10 deletions tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ def test_get_version_from_dependency_success():

with (
patch("pathlib.Path.exists", return_value=True),
patch("toml.load", return_value=mock_toml_content),
patch("cpp_linter_hooks.util.tomllib.load", return_value=mock_toml_content),
):
result = get_version_from_dependency("clang-format")
assert result == "20.1.7"
Expand All @@ -136,7 +136,7 @@ def test_get_version_from_dependency_missing_dependency():

with (
patch("pathlib.Path.exists", return_value=True),
patch("toml.load", return_value=mock_toml_content),
patch("cpp_linter_hooks.util.tomllib.load", return_value=mock_toml_content),
):
result = get_version_from_dependency("clang-format")
assert result is None
Expand All @@ -149,7 +149,7 @@ def test_get_version_from_dependency_malformed_toml():

with (
patch("pathlib.Path.exists", return_value=True),
patch("toml.load", return_value=mock_toml_content),
patch("cpp_linter_hooks.util.tomllib.load", return_value=mock_toml_content),
):
result = get_version_from_dependency("clang-format")
assert result is None
Expand All @@ -161,11 +161,11 @@ def test_get_version_from_dependency_malformed_toml():
"user_input,expected",
[
(None, None),
("20", "20.1.7"), # Should find latest 20.x
("20.1", "20.1.7"), # Should find latest 20.1.x
("20", "20.1.0"), # Should find first 20.x
("20.1", "20.1.0"), # Should find first 20.1.x
("20.1.7", "20.1.7"), # Exact match
("18", "18.1.8"), # Should find latest 18.x
("18.1", "18.1.8"), # Should find latest 18.1.x
("18", "18.1.0"), # Should find first 18.x
("18.1", "18.1.0"), # Should find first 18.1.x
("99", None), # Non-existent major version
("20.99", None), # Non-existent minor version
("invalid", None), # Invalid version string
Expand All @@ -182,9 +182,9 @@ def test_resolve_version_clang_format(user_input, expected):
"user_input,expected",
[
(None, None),
("20", "20.1.0"), # Should find latest 20.x
("18", "18.1.8"), # Should find latest 18.x
("19", "19.1.0.1"), # Should find latest 19.x
("20", "20.1.0"), # Should find first 20.x
("18", "18.1.1"), # Should find first 18.x
("19", "19.1.0"), # Should find first 19.x
("99", None), # Non-existent major version
],
)
Expand Down
Loading