Monday, 25 March 2024

Python: Check if the given semantic version matches all the specified conditions.

import re
from packaging.version import Version

def matches_condition(semver: str, conditions: list[str]) -> bool:
    """
    Check if the given semantic version matches all the specified conditions.

    Args:
    semver (str): The semantic version to check.
    conditions (list[str]): A list of conditions to match against the semantic version.

    Returns:
    bool: True if the semantic version matches all conditions, False otherwise.
    """
    semver_version = Version(semver.replace(" ", ""))
    for condition in conditions:
        condition = condition.replace(" ", "")
        # Use regex to extract operator and version
        match = re.match(r'([><=!]*)(.*)', condition)
        operator, version_str = match.groups()
        version_to_compare = Version(version_str)

        # Default to "==" if no operator is found
        if operator == "" or operator == "==":
            if not (semver_version == version_to_compare):
                return False
        elif operator == ">":
            if not (semver_version > version_to_compare):
                return False
        elif operator == "<":
            if not (semver_version < version_to_compare):
                return False
        elif operator == ">=":
            if not (semver_version >= version_to_compare):
                return False
        elif operator == "<=":
            if not (semver_version <= version_to_compare):
                return False
        elif operator == "!":
            if not (semver_version != version_to_compare):
                return False

    return True

print(matches_condition("1.0.1", ['>=1.0.0', '<2.0.0']))
print(matches_condition("1.0.1", ['>=1.0.0']))
print(matches_condition("1.0.1", ['==1.0.1']))
print(matches_condition("1.0.1", ['1.0.1']))

No comments:

Post a Comment

Parse Wikipedia dump

""" This module processes Wikipedia dump files by extracting individual articles and parsing them into a structured format, ...