diff --git a/cpp_linter_hooks/util.py b/cpp_linter_hooks/util.py index c766123..3f97c13 100644 --- a/cpp_linter_hooks/util.py +++ b/cpp_linter_hooks/util.py @@ -113,15 +113,26 @@ def get_version_from_dependency(tool: str) -> Optional[str]: def _resolve_version(versions: List[str], user_input: Optional[str]) -> Optional[str]: - """Resolve the version based on user input and available versions.""" + """Resolve the latest matching version based on user input and available versions.""" if user_input is None: return None if user_input in versions: return user_input + try: - # 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: + # filter versions that start with the user input + matched_versions = [v for v in versions if v.startswith(user_input)] + if not matched_versions: + raise ValueError + + # define a function to parse version strings into tuples for comparison + def parse_version(v: str): + return tuple(map(int, v.split("."))) + + # return the latest version + return max(matched_versions, key=parse_version) + + except ValueError: LOG.warning("Version %s not found in available versions", user_input) return None diff --git a/testing/run.sh b/testing/run.sh index b176b06..3407656 100644 --- a/testing/run.sh +++ b/testing/run.sh @@ -29,7 +29,7 @@ failed_cases=`grep -c "Failed" result.txt` echo $failed_cases " cases failed." -if [ $failed_cases -eq 10 ]; then +if [ $failed_cases -eq 9 ]; then echo "==============================" echo "Test cpp-linter-hooks success." echo "==============================" diff --git a/tests/test_util.py b/tests/test_util.py index 86a4ecd..ecf5258 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -161,11 +161,11 @@ def test_get_version_from_dependency_malformed_toml(): "user_input,expected", [ (None, None), - ("20", "20.1.0"), # Should find first 20.x - ("20.1", "20.1.0"), # Should find first 20.1.x + ("20", "20.1.7"), # Should find latest 20.x + ("20.1", "20.1.7"), # Should find latest 20.1.x ("20.1.7", "20.1.7"), # Exact match - ("18", "18.1.0"), # Should find first 18.x - ("18.1", "18.1.0"), # Should find first 18.1.x + ("18", "18.1.8"), # Should find latest 18.x + ("18.1", "18.1.8"), # Should find latest 18.1.x ("99", None), # Non-existent major version ("20.99", None), # Non-existent minor version ("invalid", None), # Invalid version string @@ -182,9 +182,9 @@ def test_resolve_version_clang_format(user_input, expected): "user_input,expected", [ (None, None), - ("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 + ("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 ("99", None), # Non-existent major version ], )