matches_requirement

Function matches_requirement 

Source
pub fn matches_requirement(version: &str, requirement: &str) -> Result<bool>
Expand description

Check if a version string satisfies a version requirement.

This utility function provides standalone version matching without requiring a VersionResolver instance. It supports semantic version requirements and special keywords for direct version-to-requirement comparison.

§Arguments

  • version - The version string to test (supports v prefixes)
  • requirement - The requirement string to match against

§Returns

Returns Ok(true) if the version satisfies the requirement, Ok(false) if it doesn’t match, or Err for invalid version/requirement strings.

§Supported Requirements

  • Special keywords: "*" (wildcard, always matches)
  • Exact versions: "1.0.0" (must match exactly)
  • Caret ranges: "^1.0.0" (compatible within major version)
  • Tilde ranges: "~1.2.0" (compatible within minor version)
  • Comparison ranges: ">=1.0.0", "<2.0.0"
  • Complex ranges: ">=1.0.0, <2.0.0" (multiple constraints)

§Examples

use agpm_cli::version::matches_requirement;

// Exact version matching
assert!(matches_requirement("1.0.0", "1.0.0")?);
assert!(matches_requirement("v1.0.0", "1.0.0")?); // v prefix ignored
assert!(!matches_requirement("1.0.1", "1.0.0")?);

// Caret range matching (compatible within major version)
assert!(matches_requirement("1.2.3", "^1.0.0")?);
assert!(matches_requirement("1.9.9", "^1.0.0")?);
assert!(!matches_requirement("2.0.0", "^1.0.0")?); // Major version change

// Tilde range matching (compatible within minor version)
assert!(matches_requirement("1.2.5", "~1.2.0")?);
assert!(!matches_requirement("1.3.0", "~1.2.0")?); // Minor version change

// Comparison ranges
assert!(matches_requirement("1.5.0", ">=1.0.0")?);
assert!(!matches_requirement("0.9.0", ">=1.0.0")?);

// Wildcard
assert!(matches_requirement("any.version", "*")?);

§Complex Range Matching

use agpm_cli::version::matches_requirement;

// Multiple constraints
assert!(matches_requirement("1.5.0", ">=1.0.0, <2.0.0")?);
assert!(!matches_requirement("2.0.0", ">=1.0.0, <2.0.0")?);

// Pre-release handling
assert!(matches_requirement("1.0.0-beta.1", "^1.0.0-beta")?);

§Version Prefix Handling

The function handles both namespace prefixes and v prefixes:

  • "v1.0.0" is treated as "1.0.0"
  • "V2.1.3" is treated as "2.1.3"
  • "agents-v1.2.0" requires "agents-^v1.0.0" (prefixes must match)
  • Unprefixed versions don’t match prefixed requirements and vice versa

§Error Cases

This function returns errors for:

  • Invalid semantic version strings
  • Malformed requirement syntax
  • Unparseable version ranges

§Use Cases

This function is useful for:

  • Quick version compatibility checks
  • Input validation in CLI tools
  • Testing version constraints programmatically
  • Implementing custom version resolution logic