diff options
Diffstat (limited to 'crates')
28 files changed, 267 insertions, 292 deletions
diff --git a/crates/shirabe-class-map-generator/src/php_file_parser.rs b/crates/shirabe-class-map-generator/src/php_file_parser.rs index 8d64dbdd..cf30c240 100644 --- a/crates/shirabe-class-map-generator/src/php_file_parser.rs +++ b/crates/shirabe-class-map-generator/src/php_file_parser.rs @@ -5,7 +5,7 @@ use anyhow::anyhow; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ - HHVM_VERSION, PHP_EOL, PHP_VERSION_ID, RuntimeException, error_get_last, file_exists, + CmpOp, HHVM_VERSION, PHP_EOL, PHP_VERSION_ID, RuntimeException, error_get_last, file_exists, file_get_contents, function_exists, is_file, is_readable, ltrim, php_strip_whitespace, str_replace_array, strrpos, substr, trim, version_compare, }; @@ -186,7 +186,8 @@ impl PhpFileParser { let mut extra_types = String::new(); let mut extra_types_array: Vec<String> = vec![]; if PHP_VERSION_ID >= 80100 - || (HHVM_VERSION.is_some() && version_compare(HHVM_VERSION.unwrap(), "3.3", ">=")) + || (HHVM_VERSION.is_some() + && version_compare(HHVM_VERSION.unwrap(), "3.3", CmpOp::Ge)) { extra_types += "|enum"; extra_types_array = vec!["enum".to_string()]; diff --git a/crates/shirabe-php-shim/src/runtime.rs b/crates/shirabe-php-shim/src/runtime.rs index 66f357cf..a059a59d 100644 --- a/crates/shirabe-php-shim/src/runtime.rs +++ b/crates/shirabe-php-shim/src/runtime.rs @@ -265,22 +265,50 @@ pub fn spl_autoload_functions() -> Vec<PhpMixed> { Vec::new() } -pub fn version_compare(_v1: &str, _v2: &str, _op: &str) -> bool { - let c = php_version_compare(_v1, _v2); - match _op { - "<" | "lt" => c < 0, - "<=" | "le" => c <= 0, - ">" | "gt" => c > 0, - ">=" | "ge" => c >= 0, - "==" | "=" | "eq" => c == 0, - "!=" | "<>" | "ne" => c != 0, - // TODO(phase-c): PHP returns null for an unknown operator; this bool signature reports false. - _ => false, +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CmpOp { + Lt, + Le, + Eq, + Ne, + Ge, + Gt, +} + +impl std::fmt::Display for CmpOp { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + CmpOp::Lt => "<", + CmpOp::Le => "<=", + CmpOp::Eq => "==", + CmpOp::Ne => "!=", + CmpOp::Ge => ">=", + CmpOp::Gt => ">", + }) } } -pub fn version_compare_2(_v1: &str, _v2: &str) -> i64 { - php_version_compare(_v1, _v2) as i64 +pub fn version_compare(v1: &str, v2: &str, op: CmpOp) -> bool { + let ord = version_compare_ordering(v1, v2); + match op { + CmpOp::Lt => ord.is_lt(), + CmpOp::Le => ord.is_le(), + CmpOp::Eq => ord.is_eq(), + CmpOp::Ne => ord.is_ne(), + CmpOp::Ge => ord.is_ge(), + CmpOp::Gt => ord.is_gt(), + } +} + +pub fn version_compare_ordering(v1: &str, v2: &str) -> std::cmp::Ordering { + let ord = php_version_compare(v1, v2); + if ord < 0 { + std::cmp::Ordering::Less + } else if ord > 0 { + std::cmp::Ordering::Greater + } else { + std::cmp::Ordering::Equal + } } // TODO(php-runtime): the previous handler should be restored in the PHP runtime. diff --git a/crates/shirabe-semver/src/compiling_matcher.rs b/crates/shirabe-semver/src/compiling_matcher.rs index 142fd0d6..0d637037 100644 --- a/crates/shirabe-semver/src/compiling_matcher.rs +++ b/crates/shirabe-semver/src/compiling_matcher.rs @@ -3,25 +3,17 @@ use crate::constraint::AnyConstraint; use crate::constraint::SimpleConstraint; use indexmap::IndexMap; +use shirabe_php_shim::CmpOp; use std::sync::Mutex; use std::sync::OnceLock; +// Rust does not support eval(), so the compiled checker path is always disabled. +// The COMPILED_CHECKER_CACHE is retained structurally but never populated. static COMPILED_CHECKER_CACHE: OnceLock< Mutex<IndexMap<String, Box<dyn Fn(String, bool) -> bool + Send + Sync>>>, > = OnceLock::new(); static RESULT_CACHE: OnceLock<Mutex<IndexMap<String, bool>>> = OnceLock::new(); -// Rust does not support eval(), so the compiled checker path is always disabled. -// The COMPILED_CHECKER_CACHE is retained structurally but never populated. -static TRANS_OP_INT: &[(i64, &str)] = &[ - (SimpleConstraint::OP_EQ, SimpleConstraint::STR_OP_EQ), - (SimpleConstraint::OP_LT, SimpleConstraint::STR_OP_LT), - (SimpleConstraint::OP_LE, SimpleConstraint::STR_OP_LE), - (SimpleConstraint::OP_GT, SimpleConstraint::STR_OP_GT), - (SimpleConstraint::OP_GE, SimpleConstraint::STR_OP_GE), - (SimpleConstraint::OP_NE, SimpleConstraint::STR_OP_NE), -]; - pub struct CompilingMatcher; impl CompilingMatcher { @@ -39,8 +31,13 @@ impl CompilingMatcher { Self::compiled_checker_cache().lock().unwrap().clear(); } - pub fn r#match(constraint: &AnyConstraint, operator: i64, version: String) -> bool { - let result_cache_key = format!("{}{};{}", operator, constraint, version); + pub fn r#match(constraint: &AnyConstraint, operator: CmpOp, version: String) -> bool { + let result_cache_key = format!( + "{}{};{}", + SimpleConstraint::get_operator_constant(operator), + constraint, + version + ); { let cache = Self::result_cache().lock().unwrap(); @@ -49,13 +46,8 @@ impl CompilingMatcher { } } - let trans_op = TRANS_OP_INT - .iter() - .find(|(op, _)| *op == operator) - .map(|(_, s)| *s) - .expect("unknown operator"); let result = - constraint.matches(&SimpleConstraint::new(trans_op.to_string(), version, None).into()); + constraint.matches(&SimpleConstraint::new(operator.to_string(), version, None).into()); Self::result_cache() .lock() diff --git a/crates/shirabe-semver/src/constraint/any_constraint.rs b/crates/shirabe-semver/src/constraint/any_constraint.rs index 37541deb..33c2f7d0 100644 --- a/crates/shirabe-semver/src/constraint/any_constraint.rs +++ b/crates/shirabe-semver/src/constraint/any_constraint.rs @@ -5,6 +5,7 @@ use crate::constraint::MatchAllConstraint; use crate::constraint::MatchNoneConstraint; use crate::constraint::MultiConstraint; use crate::constraint::SimpleConstraint; +use shirabe_php_shim::CmpOp; /// Corresponds to PHP's `ConstraintInterface`. #[derive(Clone, Debug)] @@ -36,7 +37,7 @@ impl AnyConstraint { } } - pub fn compile(&self, other_operator: i64) -> String { + pub fn compile(&self, other_operator: CmpOp) -> String { match self { Self::Simple(c) => c.compile(other_operator), Self::Multi(c) => c.compile(other_operator), @@ -82,10 +83,10 @@ impl AnyConstraint { matches!(self, Self::Simple(_)) } - pub fn get_operator(&self) -> &'static str { + pub fn get_operator(&self) -> Option<CmpOp> { match self { - Self::Simple(c) => c.get_operator(), - _ => "", + Self::Simple(c) => Some(c.get_operator()), + _ => None, } } diff --git a/crates/shirabe-semver/src/constraint/bound.rs b/crates/shirabe-semver/src/constraint/bound.rs index 25904248..6230684d 100644 --- a/crates/shirabe-semver/src/constraint/bound.rs +++ b/crates/shirabe-semver/src/constraint/bound.rs @@ -1,6 +1,7 @@ //! ref: composer/vendor/composer/semver/src/Constraint/Bound.php use anyhow::bail; +use shirabe_php_shim::version_compare_ordering; #[derive(Debug, Clone, PartialEq)] pub struct Bound { @@ -42,7 +43,7 @@ impl Bound { } let compare_result = - shirabe_php_shim::version_compare_2(self.get_version(), other.get_version()); + version_compare_ordering(self.get_version(), other.get_version()) as i8; if compare_result != 0 { return Ok((if operator == ">" { 1 } else { -1 }) == compare_result); diff --git a/crates/shirabe-semver/src/constraint/match_all_constraint.rs b/crates/shirabe-semver/src/constraint/match_all_constraint.rs index 8d4e8705..5bf8ebd9 100644 --- a/crates/shirabe-semver/src/constraint/match_all_constraint.rs +++ b/crates/shirabe-semver/src/constraint/match_all_constraint.rs @@ -1,6 +1,7 @@ //! ref: composer/vendor/composer/semver/src/Constraint/MatchAllConstraint.php use crate::constraint::Bound; +use shirabe_php_shim::CmpOp; #[derive(Debug, Clone, Default)] pub struct MatchAllConstraint { @@ -12,7 +13,7 @@ impl MatchAllConstraint { Self { pretty_string } } - pub fn compile(&self, _other_operator: i64) -> String { + pub fn compile(&self, _other_operator: CmpOp) -> String { "true".to_string() } diff --git a/crates/shirabe-semver/src/constraint/match_none_constraint.rs b/crates/shirabe-semver/src/constraint/match_none_constraint.rs index 08cb3194..fd2b0c6e 100644 --- a/crates/shirabe-semver/src/constraint/match_none_constraint.rs +++ b/crates/shirabe-semver/src/constraint/match_none_constraint.rs @@ -1,6 +1,7 @@ //! ref: composer/vendor/composer/semver/src/Constraint/MatchNoneConstraint.php use crate::constraint::Bound; +use shirabe_php_shim::CmpOp; #[derive(Debug, Clone)] pub struct MatchNoneConstraint { @@ -12,7 +13,7 @@ impl MatchNoneConstraint { Self { pretty_string } } - pub fn compile(&self, _other_operator: i64) -> String { + pub fn compile(&self, _other_operator: CmpOp) -> String { "false".to_string() } diff --git a/crates/shirabe-semver/src/constraint/multi_constraint.rs b/crates/shirabe-semver/src/constraint/multi_constraint.rs index 05cc16e3..4e9b8cf5 100644 --- a/crates/shirabe-semver/src/constraint/multi_constraint.rs +++ b/crates/shirabe-semver/src/constraint/multi_constraint.rs @@ -3,6 +3,7 @@ use crate::constraint::AnyConstraint; use crate::constraint::Bound; use crate::constraint::MatchAllConstraint; +use shirabe_php_shim::CmpOp; #[derive(Debug, Clone)] pub struct MultiConstraint { @@ -198,7 +199,7 @@ impl MultiConstraint { (constraints, conjunctive) } - pub fn compile(&self, other_operator: i64) -> String { + pub fn compile(&self, other_operator: CmpOp) -> String { let mut parts = Vec::new(); for constraint in &self.constraints { let code = constraint.compile(other_operator); diff --git a/crates/shirabe-semver/src/constraint/simple_constraint.rs b/crates/shirabe-semver/src/constraint/simple_constraint.rs index 5a853824..fa08ce85 100644 --- a/crates/shirabe-semver/src/constraint/simple_constraint.rs +++ b/crates/shirabe-semver/src/constraint/simple_constraint.rs @@ -1,61 +1,33 @@ //! ref: composer/vendor/composer/semver/src/Constraint/Constraint.php use crate::constraint::Bound; -use anyhow::bail; +use shirabe_php_shim::{CmpOp, var_export_str, version_compare}; /// Corresponds to PHP's `Constraint`. #[derive(Debug, Clone)] pub struct SimpleConstraint { - pub(crate) operator: i64, + pub(crate) operator: CmpOp, pub(crate) version: String, pub(crate) pretty_string: Option<String>, } impl SimpleConstraint { - pub const OP_EQ: i64 = 0; - pub const OP_LT: i64 = 1; - pub const OP_LE: i64 = 2; - pub const OP_GT: i64 = 3; - pub const OP_GE: i64 = 4; - pub const OP_NE: i64 = 5; - - pub const STR_OP_EQ: &'static str = "=="; - pub const STR_OP_EQ_ALT: &'static str = "="; - pub const STR_OP_LT: &'static str = "<"; - pub const STR_OP_LE: &'static str = "<="; - pub const STR_OP_GT: &'static str = ">"; - pub const STR_OP_GE: &'static str = ">="; - pub const STR_OP_NE: &'static str = "!="; - pub const STR_OP_NE_ALT: &'static str = "<>"; - - fn trans_op_str(op: &str) -> Option<i64> { + fn trans_op_str(op: &str) -> Option<CmpOp> { match op { - "=" => Some(Self::OP_EQ), - "==" => Some(Self::OP_EQ), - "<" => Some(Self::OP_LT), - "<=" => Some(Self::OP_LE), - ">" => Some(Self::OP_GT), - ">=" => Some(Self::OP_GE), - "<>" => Some(Self::OP_NE), - "!=" => Some(Self::OP_NE), + "=" => Some(CmpOp::Eq), + "==" => Some(CmpOp::Eq), + "<" => Some(CmpOp::Lt), + "<=" => Some(CmpOp::Le), + ">" => Some(CmpOp::Gt), + ">=" => Some(CmpOp::Ge), + "<>" => Some(CmpOp::Ne), + "!=" => Some(CmpOp::Ne), _ => None, } } - fn trans_op_int(op: i64) -> &'static str { - match op { - Self::OP_EQ => "==", - Self::OP_LT => "<", - Self::OP_LE => "<=", - Self::OP_GT => ">", - Self::OP_GE => ">=", - Self::OP_NE => "!=", - _ => panic!("unknown operator: {}", op), - } - } - pub fn new(operator: String, version: String, pretty_string: Option<String>) -> Self { - let op_int = Self::trans_op_str(&operator).unwrap_or_else(|| { + let op = Self::trans_op_str(&operator).unwrap_or_else(|| { // PHP raises InvalidArgumentException; in the Rust port keep that as a panic // because invalid operators are programmer errors caught during porting. panic!( @@ -66,7 +38,7 @@ impl SimpleConstraint { }); Self { - operator: op_int, + operator: op, version, pretty_string, } @@ -76,77 +48,80 @@ impl SimpleConstraint { &self.version } - pub fn get_operator(&self) -> &'static str { - Self::trans_op_int(self.operator) + pub fn get_operator(&self) -> CmpOp { + self.operator } pub fn get_supported_operators() -> Vec<&'static str> { vec!["=", "==", "<", "<=", ">", ">=", "<>", "!="] } - pub fn get_operator_constant(operator: &str) -> i64 { - Self::trans_op_str(operator).expect("valid operator") + pub fn get_operator_constant(operator: CmpOp) -> i64 { + match operator { + CmpOp::Eq => 0, + CmpOp::Lt => 1, + CmpOp::Le => 2, + CmpOp::Gt => 3, + CmpOp::Ge => 4, + CmpOp::Ne => 5, + } + } + + pub fn from_operator_constant(constant: i64) -> Option<CmpOp> { + Some(match constant { + 0 => CmpOp::Eq, + 1 => CmpOp::Lt, + 2 => CmpOp::Le, + 3 => CmpOp::Gt, + 4 => CmpOp::Ge, + 5 => CmpOp::Ne, + _ => return None, + }) } pub fn version_compare( &self, a: &str, b: &str, - operator: &str, + operator: CmpOp, compare_branches: bool, - ) -> anyhow::Result<bool> { - if Self::trans_op_str(operator).is_none() { - bail!( - "Invalid operator \"{}\" given, expected one of: {}", - operator, - Self::get_supported_operators().join(", ") - ); - } - + ) -> bool { let a_is_branch = a.starts_with("dev-"); let b_is_branch = b.starts_with("dev-"); - if operator == "!=" && (a_is_branch || b_is_branch) { - return Ok(a != b); + if operator == CmpOp::Ne && (a_is_branch || b_is_branch) { + return a != b; } if a_is_branch && b_is_branch { - return Ok(operator == "==" && a == b); + return operator == CmpOp::Eq && a == b; } + // when branches are not comparable, we make sure dev branches never match anything if !compare_branches && (a_is_branch || b_is_branch) { - return Ok(false); + return false; } - Ok(shirabe_php_shim::version_compare(a, b, operator)) + version_compare(a, b, operator) } - pub fn compile_constraint(&self, other_operator: i64) -> String { + pub fn compile_constraint(&self, other_operator: CmpOp) -> String { if self.version.starts_with("dev-") { - if Self::OP_EQ == self.operator { - if Self::OP_EQ == other_operator { - return format!( - "$b && $v === {}", - shirabe_php_shim::var_export_str(&self.version, true) - ); + if CmpOp::Eq == self.operator { + if CmpOp::Eq == other_operator { + return format!("$b && $v === {}", var_export_str(&self.version, true)); } - if Self::OP_NE == other_operator { - return format!( - "!$b || $v !== {}", - shirabe_php_shim::var_export_str(&self.version, true) - ); + if CmpOp::Ne == other_operator { + return format!("!$b || $v !== {}", var_export_str(&self.version, true)); } return "false".to_string(); } - if Self::OP_NE == self.operator { - if Self::OP_EQ == other_operator { - return format!( - "!$b || $v !== {}", - shirabe_php_shim::var_export_str(&self.version, true) - ); + if CmpOp::Ne == self.operator { + if CmpOp::Eq == other_operator { + return format!("!$b || $v !== {}", var_export_str(&self.version, true)); } - if Self::OP_NE == other_operator { + if CmpOp::Ne == other_operator { return "true".to_string(); } return "!$b".to_string(); @@ -155,69 +130,69 @@ impl SimpleConstraint { return "false".to_string(); } - if Self::OP_EQ == self.operator { - if Self::OP_EQ == other_operator { + if CmpOp::Eq == self.operator { + if CmpOp::Eq == other_operator { return format!( "\\version_compare($v, {}, '==')", - shirabe_php_shim::var_export_str(&self.version, true) + var_export_str(&self.version, true) ); } - if Self::OP_NE == other_operator { + if CmpOp::Ne == other_operator { return format!( "$b || \\version_compare($v, {}, '!=')", - shirabe_php_shim::var_export_str(&self.version, true) + var_export_str(&self.version, true) ); } return format!( "!$b && \\version_compare({}, $v, '{}')", - shirabe_php_shim::var_export_str(&self.version, true), - Self::trans_op_int(other_operator) + var_export_str(&self.version, true), + other_operator ); } - if Self::OP_NE == self.operator { - if Self::OP_EQ == other_operator { + if CmpOp::Ne == self.operator { + if CmpOp::Eq == other_operator { return format!( "$b || (!$b && \\version_compare($v, {}, '!='))", - shirabe_php_shim::var_export_str(&self.version, true) + var_export_str(&self.version, true) ); } - if Self::OP_NE == other_operator { + if CmpOp::Ne == other_operator { return "true".to_string(); } return "!$b".to_string(); } - if Self::OP_LT == self.operator || Self::OP_LE == self.operator { - if Self::OP_LT == other_operator || Self::OP_LE == other_operator { + if CmpOp::Lt == self.operator || CmpOp::Le == self.operator { + if CmpOp::Lt == other_operator || CmpOp::Le == other_operator { return "!$b".to_string(); } - } else if Self::OP_GT == other_operator || Self::OP_GE == other_operator { + } else if CmpOp::Gt == other_operator || CmpOp::Ge == other_operator { return "!$b".to_string(); } - if Self::OP_NE == other_operator { + if CmpOp::Ne == other_operator { return "true".to_string(); } let code_comparison = format!( "\\version_compare($v, {}, '{}')", - shirabe_php_shim::var_export_str(&self.version, true), - Self::trans_op_int(self.operator) + var_export_str(&self.version, true), + self.operator ); - if self.operator == Self::OP_LE && other_operator == Self::OP_GT { + if self.operator == CmpOp::Le && other_operator == CmpOp::Gt { return format!( "!$b && \\version_compare($v, {}, '!=') && {}", - shirabe_php_shim::var_export_str(&self.version, true), + var_export_str(&self.version, true), code_comparison ); } - if self.operator == Self::OP_GE && other_operator == Self::OP_LT { + if self.operator == CmpOp::Ge && other_operator == CmpOp::Lt { return format!( "!$b && \\version_compare($v, {}, '!=') && {}", - shirabe_php_shim::var_export_str(&self.version, true), + var_export_str(&self.version, true), code_comparison ); } @@ -226,13 +201,13 @@ impl SimpleConstraint { } pub fn match_specific(&self, provider: &SimpleConstraint, compare_branches: bool) -> bool { - let no_equal_op = Self::trans_op_int(self.operator).replace('=', ""); - let provider_no_equal_op = Self::trans_op_int(provider.operator).replace('=', ""); + let no_equal_op = self.operator.to_string().replace('=', ""); + let provider_no_equal_op = provider.operator.to_string().replace('=', ""); - let is_equal_op = Self::OP_EQ == self.operator; - let is_non_equal_op = Self::OP_NE == self.operator; - let is_provider_equal_op = Self::OP_EQ == provider.operator; - let is_provider_non_equal_op = Self::OP_NE == provider.operator; + let is_equal_op = CmpOp::Eq == self.operator; + let is_non_equal_op = CmpOp::Ne == self.operator; + let is_provider_equal_op = CmpOp::Eq == provider.operator; + let is_provider_non_equal_op = CmpOp::Ne == provider.operator; if is_non_equal_op || is_provider_non_equal_op { if is_non_equal_op @@ -254,12 +229,15 @@ impl SimpleConstraint { if !is_equal_op && !is_provider_equal_op { return true; } - return self - .version_compare(&provider.version, &self.version, "!=", compare_branches) - .expect("valid operator"); + return self.version_compare( + &provider.version, + &self.version, + CmpOp::Ne, + compare_branches, + ); } - if self.operator != Self::OP_EQ && no_equal_op == provider_no_equal_op { + if self.operator != CmpOp::Eq && no_equal_op == provider_no_equal_op { return !(self.version.starts_with("dev-") || provider.version.starts_with("dev-")); } @@ -269,18 +247,10 @@ impl SimpleConstraint { (&provider.version, &self.version, self.operator) }; - if self - .version_compare( - version1, - version2, - Self::trans_op_int(operator), - compare_branches, - ) - .expect("valid operator") - { - return !(Self::trans_op_int(provider.operator) == provider_no_equal_op - && Self::trans_op_int(self.operator) != no_equal_op - && shirabe_php_shim::version_compare(&provider.version, &self.version, "==")); + if self.version_compare(version1, version2, operator, compare_branches) { + return !(provider.operator.to_string() == provider_no_equal_op + && self.operator.to_string() != no_equal_op + && version_compare(&provider.version, &self.version, CmpOp::Eq)); } false @@ -294,26 +264,25 @@ impl SimpleConstraint { } match self.operator { - Self::OP_EQ => ( + CmpOp::Eq => ( Bound::new(self.version.clone(), true), Bound::new(self.version.clone(), true), ), - Self::OP_LT => (Bound::zero(), Bound::new(self.version.clone(), false)), - Self::OP_LE => (Bound::zero(), Bound::new(self.version.clone(), true)), - Self::OP_GT => ( + CmpOp::Lt => (Bound::zero(), Bound::new(self.version.clone(), false)), + CmpOp::Le => (Bound::zero(), Bound::new(self.version.clone(), true)), + CmpOp::Gt => ( Bound::new(self.version.clone(), false), Bound::positive_infinity(), ), - Self::OP_GE => ( + CmpOp::Ge => ( Bound::new(self.version.clone(), true), Bound::positive_infinity(), ), - Self::OP_NE => (Bound::zero(), Bound::positive_infinity()), - _ => panic!("unknown operator: {}", self.operator), + CmpOp::Ne => (Bound::zero(), Bound::positive_infinity()), } } - pub fn compile(&self, other_operator: i64) -> String { + pub fn compile(&self, other_operator: CmpOp) -> String { self.compile_constraint(other_operator) } @@ -337,6 +306,6 @@ impl SimpleConstraint { impl std::fmt::Display for SimpleConstraint { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{} {}", Self::trans_op_int(self.operator), self.version) + write!(f, "{} {}", self.operator, self.version) } } diff --git a/crates/shirabe-semver/src/intervals.rs b/crates/shirabe-semver/src/intervals.rs index 0f9db7cd..9199b13b 100644 --- a/crates/shirabe-semver/src/intervals.rs +++ b/crates/shirabe-semver/src/intervals.rs @@ -7,6 +7,7 @@ use crate::constraint::MultiConstraint; use crate::constraint::SimpleConstraint; use crate::interval::{DevConstraintSet, Interval}; use indexmap::IndexMap; +use shirabe_php_shim::{CmpOp, array_unique, version_compare, version_compare_ordering}; use std::sync::{Mutex, OnceLock}; #[derive(Debug, Clone)] @@ -138,10 +139,10 @@ impl Intervals { // with the start of the current interval and end of next interval, so // [>=M, <N] || [>N, <P] => [>=M, !=N, <P] but M/P can be skipped if they are // zero/+inf - if interval.get_end().get_operator() == "<" && i + 1 < count { + if interval.get_end().get_operator() == CmpOp::Lt && i + 1 < count { let next_interval = &intervals.numeric[i + 1]; if interval.get_end().get_version() == next_interval.get_start().get_version() - && next_interval.get_start().get_operator() == ">" + && next_interval.get_start().get_operator() == CmpOp::Gt { // only add a start if we didn't already do so, can be skipped if we're // looking at second interval in [>=M, <N] || [>N, <P] || [>P, <Q] where @@ -188,8 +189,8 @@ impl Intervals { // convert back >= x - <= x intervals to == x if interval.get_start().get_version() == interval.get_end().get_version() - && interval.get_start().get_operator() == ">=" - && interval.get_end().get_operator() == "<=" + && interval.get_start().get_operator() == CmpOp::Ge + && interval.get_end().get_operator() == CmpOp::Le { constraints.push( SimpleConstraint::new( @@ -416,7 +417,7 @@ impl Intervals { branches }; - branches.names = shirabe_php_shim::array_unique(&branches.names); + branches.names = array_unique(&branches.names); if numeric_groups.len() == 1 { return Ok(IntervalCollection { @@ -443,13 +444,11 @@ impl Intervals { } borders.sort_by(|a, b| { - let order = shirabe_php_shim::version_compare_2(&a.0, &b.0); - if order == 0 { + let order = version_compare_ordering(&a.0, &b.0); + order.then_with(|| { let diff = op_sort_order(&a.1) - op_sort_order(&b.1); diff.cmp(&0) - } else { - order.cmp(&0) - } + }) }); let mut active_intervals: i64 = 0; @@ -477,9 +476,9 @@ impl Intervals { } else if start.is_some() && active_intervals < activation_threshold { let start_c = start.take().unwrap(); // filter out invalid intervals like > x - <= x, or >= x - < x - if shirabe_php_shim::version_compare(start_c.get_version(), version, "=") - && ((start_c.get_operator() == ">" && operator == "<=") - || (start_c.get_operator() == ">=" && operator == "<")) + if version_compare(start_c.get_version(), version, CmpOp::Eq) + && ((start_c.get_operator() == CmpOp::Gt && operator == "<=") + || (start_c.get_operator() == CmpOp::Ge && operator == "<")) { // skip invalid interval (equivalent to PHP's unset($intervals[$index])) } else { @@ -513,7 +512,7 @@ impl Intervals { // != dev-foo means any numeric version may match, we treat >/< like != they are not // really defined for branches - if op == "!=" { + if op == CmpOp::Ne { intervals.push(Interval::new( Interval::from_zero(), Interval::until_positive_infinity(), @@ -522,7 +521,7 @@ impl Intervals { names: vec![constraint.get_version().to_string()], exclude: true, }; - } else if op == "==" { + } else if op == CmpOp::Eq { branches.names.push(constraint.get_version().to_string()); } @@ -532,7 +531,7 @@ impl Intervals { }); } - if op.starts_with('>') { + if op.to_string().starts_with('>') { // > & >= return Ok(IntervalCollection { numeric: vec![Interval::new( @@ -542,14 +541,14 @@ impl Intervals { branches: Interval::no_dev(), }); } - if op.starts_with('<') { + if op.to_string().starts_with('<') { // < & <= return Ok(IntervalCollection { numeric: vec![Interval::new(Interval::from_zero(), constraint.clone())], branches: Interval::no_dev(), }); } - if op == "!=" { + if op == CmpOp::Ne { // convert !=x to intervals of 0 - <x && >x - +inf + dev* return Ok(IntervalCollection { numeric: vec![ diff --git a/crates/shirabe/src/command/diagnose_command.rs b/crates/shirabe/src/command/diagnose_command.rs index 65240e51..72b58dea 100644 --- a/crates/shirabe/src/command/diagnose_command.rs +++ b/crates/shirabe/src/command/diagnose_command.rs @@ -39,10 +39,10 @@ use shirabe_external_packages::symfony::console::input::InputInterface; use shirabe_external_packages::symfony::console::output::OutputInterface; use shirabe_external_packages::symfony::process::ExecutableFinder; use shirabe_php_shim::{ - InvalidArgumentException, PHP_EOL, PhpMixed, disk_free_space, file_exists, filter_var_boolean, - get_class_err, hash, impl_php_class, implode, is_array, is_string, php_regex, rtrim, - str_contains, str_replace, str_starts_with, strpos, strstr, strstr3, strtolower, trim, - version_compare, + CmpOp, InvalidArgumentException, PHP_EOL, PhpMixed, disk_free_space, file_exists, + filter_var_boolean, get_class_err, hash, impl_php_class, implode, is_array, is_string, + php_regex, rtrim, str_contains, str_replace, str_starts_with, strpos, strstr, strstr3, + strtolower, trim, version_compare, }; #[derive(Debug)] @@ -153,7 +153,7 @@ impl DiagnoseCommand { None => return "<comment>No git process found</>".to_string(), }; - if version_compare("2.24.0", &git_version, ">") { + if version_compare("2.24.0", &git_version, CmpOp::Gt) { return format!( "<warning>Your git version ({}) is too old and possibly will cause issues. Please upgrade to git 2.24 or above</>", git_version @@ -889,9 +889,9 @@ impl DiagnoseCommand { } if diagnostics.has_php_windows_version_build - && (version_compare(&diagnostics.php_version, "7.2.23", "<") - || (version_compare(&diagnostics.php_version, "7.3.0", ">=") - && version_compare(&diagnostics.php_version, "7.3.10", "<"))) + && (version_compare(&diagnostics.php_version, "7.2.23", CmpOp::Lt) + || (version_compare(&diagnostics.php_version, "7.3.0", CmpOp::Ge) + && version_compare(&diagnostics.php_version, "7.3.10", CmpOp::Lt))) { warnings.insert( "onedrive".to_string(), diff --git a/crates/shirabe/src/command/show_command.rs b/crates/shirabe/src/command/show_command.rs index ff20f325..aa63d8e7 100644 --- a/crates/shirabe/src/command/show_command.rs +++ b/crates/shirabe/src/command/show_command.rs @@ -43,7 +43,7 @@ use shirabe_external_packages::symfony::console::formatter::OutputFormatterStyle use shirabe_external_packages::symfony::console::input::InputInterface; use shirabe_external_packages::symfony::console::output::OutputInterface; use shirabe_php_shim::{ - DATE_ATOM, InvalidArgumentException, LogicException, PhpMixed, UnexpectedValueException, + CmpOp, DATE_ATOM, InvalidArgumentException, LogicException, PhpMixed, UnexpectedValueException, array_search, date, date_format_to_strftime, extension_loaded, impl_php_class, in_array_loose, in_array_strict, php_regex, realpath, strtolower, version_compare, }; @@ -841,9 +841,9 @@ impl ShowCommand { .collect(); // uasort($versions, 'version_compare'); versions_pairs.sort_by(|a, b| { - if version_compare(&a.1, &b.1, "<") { + if version_compare(&a.1, &b.1, CmpOp::Lt) { std::cmp::Ordering::Less - } else if version_compare(&a.1, &b.1, ">") { + } else if version_compare(&a.1, &b.1, CmpOp::Gt) { std::cmp::Ordering::Greater } else { std::cmp::Ordering::Equal @@ -1432,7 +1432,7 @@ impl ShowCommand { return false; } - version_compare(&candidate.get_version(), &package_version, "<=") + version_compare(&candidate.get_version(), &package_version, CmpOp::Le) }, )) }; @@ -2343,9 +2343,11 @@ impl Command for ShowCommand { let need_replace = match existing { None => true, Some(PackageOrName::Name(_)) => true, - Some(PackageOrName::Pkg(existing)) => { - version_compare(&existing.get_version(), &package.get_version(), "<") - } + Some(PackageOrName::Pkg(existing)) => version_compare( + &existing.get_version(), + &package.get_version(), + CmpOp::Lt, + ), }; if need_replace { let mut p: crate::package::PackageInterfaceHandle = package.clone(); diff --git a/crates/shirabe/src/dependency_resolver/default_policy.rs b/crates/shirabe/src/dependency_resolver/default_policy.rs index d81c8621..8c1a7697 100644 --- a/crates/shirabe/src/dependency_resolver/default_policy.rs +++ b/crates/shirabe/src/dependency_resolver/default_policy.rs @@ -6,6 +6,7 @@ use crate::package::BasePackageHandle; use crate::package::STABILITIES; use crate::util::Platform; use indexmap::IndexMap; +use shirabe_php_shim::CmpOp; use shirabe_php_shim::PhpMixed; use shirabe_semver::CompilingMatcher; use shirabe_semver::constraint::SimpleConstraint; @@ -205,7 +206,7 @@ impl PolicyInterface for DefaultPolicy { CompilingMatcher::r#match( &SimpleConstraint::new(operator.to_string(), b.get_version(), None).into(), - SimpleConstraint::OP_EQ, + CmpOp::Eq, a.get_version(), ) } diff --git a/crates/shirabe/src/dependency_resolver/pool.rs b/crates/shirabe/src/dependency_resolver/pool.rs index 80534b0a..a0dfd362 100644 --- a/crates/shirabe/src/dependency_resolver/pool.rs +++ b/crates/shirabe/src/dependency_resolver/pool.rs @@ -4,7 +4,7 @@ use crate::advisory::AnySecurityAdvisory; use crate::package::BasePackageHandle; use crate::package::version::VersionParser; use indexmap::IndexMap; -use shirabe_php_shim::{STR_PAD_LEFT, str_pad}; +use shirabe_php_shim::{CmpOp, STR_PAD_LEFT, str_pad}; use shirabe_semver::CompilingMatcher; use shirabe_semver::constraint::AnyConstraint; use shirabe_semver::constraint::SimpleConstraint; @@ -305,11 +305,7 @@ impl Pool { if candidate_name == name { return constraint.is_none() - || CompilingMatcher::r#match( - constraint.unwrap(), - SimpleConstraint::OP_EQ, - candidate_version, - ); + || CompilingMatcher::r#match(constraint.unwrap(), CmpOp::Eq, candidate_version); } let provides = candidate.get_provides(); diff --git a/crates/shirabe/src/dependency_resolver/pool_builder.rs b/crates/shirabe/src/dependency_resolver/pool_builder.rs index 137a36ba..35699a90 100644 --- a/crates/shirabe/src/dependency_resolver/pool_builder.rs +++ b/crates/shirabe/src/dependency_resolver/pool_builder.rs @@ -21,7 +21,7 @@ use crate::repository::RootPackageRepository; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::Preg; use shirabe_php_shim::{ - LogicException, PhpMixed, array_flip_strings, array_map, in_array_strict, microtime, + CmpOp, LogicException, PhpMixed, array_flip_strings, array_map, in_array_strict, microtime, number_format, round, strpos, }; use shirabe_semver::CompilingMatcher; @@ -29,7 +29,6 @@ use shirabe_semver::Intervals; use shirabe_semver::constraint::AnyConstraint; use shirabe_semver::constraint::MatchAllConstraint; use shirabe_semver::constraint::MultiConstraint; -use shirabe_semver::constraint::SimpleConstraint; #[derive(Debug)] pub struct PoolBuilder { @@ -289,7 +288,7 @@ impl PoolBuilder { for (_idx, package_or_alias) in &package_and_aliases { if CompilingMatcher::r#match( &constraint, - SimpleConstraint::OP_EQ, + CmpOp::Eq, package_or_alias.get_version(), ) { found = true; diff --git a/crates/shirabe/src/dependency_resolver/pool_optimizer.rs b/crates/shirabe/src/dependency_resolver/pool_optimizer.rs index 972d2f21..5aca700e 100644 --- a/crates/shirabe/src/dependency_resolver/pool_optimizer.rs +++ b/crates/shirabe/src/dependency_resolver/pool_optimizer.rs @@ -6,7 +6,7 @@ use crate::dependency_resolver::Request; use crate::package::BasePackageHandle; use crate::package::version::VersionParser; use indexmap::IndexMap; -use shirabe_php_shim::{implode, ksort}; +use shirabe_php_shim::{CmpOp, implode, ksort}; use shirabe_semver::CompilingMatcher; use shirabe_semver::Intervals; use shirabe_semver::constraint::AnyConstraint; @@ -156,11 +156,7 @@ impl PoolOptimizer { let constraint = irremovable_package_constraints .get(&package.get_name()) .unwrap(); - if CompilingMatcher::r#match( - constraint, - SimpleConstraint::OP_EQ, - package.get_version().to_string(), - ) { + if CompilingMatcher::r#match(constraint, CmpOp::Eq, package.get_version().to_string()) { self.mark_package_irremovable(package.clone()); } } @@ -252,7 +248,7 @@ impl PoolOptimizer { if CompilingMatcher::r#match( require_constraint, - SimpleConstraint::OP_EQ, + CmpOp::Eq, package.get_version().to_string(), ) { group_hash_parts.push(format!( @@ -265,7 +261,7 @@ impl PoolOptimizer { for (_, link) in package.get_replaces() { if CompilingMatcher::r#match( link.get_constraint(), - SimpleConstraint::OP_EQ, + CmpOp::Eq, package.get_version().to_string(), ) { // Use the same hash part as the regular require hash because that's what the replacement does @@ -283,7 +279,7 @@ impl PoolOptimizer { for (_, conflict_constraint) in conflict_constraints { if CompilingMatcher::r#match( conflict_constraint, - SimpleConstraint::OP_EQ, + CmpOp::Eq, package.get_version().to_string(), ) { group_hash_parts.push(format!( @@ -605,11 +601,7 @@ impl PoolOptimizer { .and_then(|m| m.get(&id)) .map(|p| p.get_version()); if let Some(version_str) = version_str - && !CompilingMatcher::r#match( - link_constraint, - SimpleConstraint::OP_EQ, - version_str, - ) + && !CompilingMatcher::r#match(link_constraint, CmpOp::Eq, version_str) { self.mark_package_for_removal(id); if let Some(map) = package_index.get_mut(require) { diff --git a/crates/shirabe/src/dependency_resolver/problem.rs b/crates/shirabe/src/dependency_resolver/problem.rs index 8ee4b816..f9e525bf 100644 --- a/crates/shirabe/src/dependency_resolver/problem.rs +++ b/crates/shirabe/src/dependency_resolver/problem.rs @@ -13,8 +13,8 @@ use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; use shirabe_external_packages::symfony::console::formatter::OutputFormatter; use shirabe_php_shim::{ - LogicException, PhpMixed, defined, extension_loaded, implode, loosely_compare, php_regex, - phpversion, spl_object_hash, sprintf, str_replace, str_starts_with, stripos, strpos, + CmpOp, LogicException, PhpMixed, defined, extension_loaded, implode, loosely_compare, + php_regex, phpversion, spl_object_hash, sprintf, str_replace, str_starts_with, stripos, strpos, strtolower, substr, substr_count, version_compare, }; use shirabe_semver::constraint::AnyConstraint; @@ -284,9 +284,9 @@ impl Problem { // uksort($versions, 'version_compare') let mut keys: Vec<String> = versions.keys().cloned().collect(); keys.sort_by(|a, b| { - if version_compare(a, b, "<") { + if version_compare(a, b, CmpOp::Lt) { std::cmp::Ordering::Less - } else if version_compare(a, b, ">") { + } else if version_compare(a, b, CmpOp::Gt) { std::cmp::Ordering::Greater } else { std::cmp::Ordering::Equal @@ -564,7 +564,7 @@ impl Problem { if let Some(c) = constraint && c.is_constraint() - && c.get_operator() == SimpleConstraint::STR_OP_EQ + && c.get_operator() == Some(CmpOp::Eq) && Preg::is_match3(php_regex!(r"{^dev-.*#.*}"), &c.get_pretty_string(), None) { let new_constraint = Preg::replace( @@ -578,12 +578,12 @@ impl Problem { MultiConstraint::new( vec![ AnyConstraint::Simple(SimpleConstraint::new( - SimpleConstraint::STR_OP_EQ.to_string(), + "==".to_string(), new_constraint.clone(), None, )), AnyConstraint::Simple(SimpleConstraint::new( - SimpleConstraint::STR_OP_EQ.to_string(), + "==".to_string(), str_replace("#", "+", &new_constraint), None, )), @@ -1102,9 +1102,9 @@ impl Problem { // uksort($package['versions'], 'version_compare') let mut keys: Vec<String> = package.versions.keys().cloned().collect(); keys.sort_by(|a, b| { - if version_compare(a, b, "<") { + if version_compare(a, b, CmpOp::Lt) { std::cmp::Ordering::Less - } else if version_compare(a, b, ">") { + } else if version_compare(a, b, CmpOp::Gt) { std::cmp::Ordering::Greater } else { std::cmp::Ordering::Equal @@ -1386,7 +1386,7 @@ impl Problem { pub(crate) fn constraint_to_text(constraint: Option<&AnyConstraint>) -> String { if let Some(c) = constraint && c.is_constraint() - && c.get_operator() == SimpleConstraint::STR_OP_EQ + && c.get_operator() == Some(CmpOp::Eq) && !str_starts_with(c.get_version(), "dev-") { if !Preg::is_match3( diff --git a/crates/shirabe/src/downloader/git_downloader.rs b/crates/shirabe/src/downloader/git_downloader.rs index 5e57de52..275050fd 100644 --- a/crates/shirabe/src/downloader/git_downloader.rs +++ b/crates/shirabe/src/downloader/git_downloader.rs @@ -19,7 +19,7 @@ use crate::util::Url; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ - PhpMixed, RuntimeException, array_map, basename, dirname, impl_php_class, implode, + CmpOp, PhpMixed, RuntimeException, array_map, basename, dirname, impl_php_class, implode, in_array_strict, is_dir, php_regex, preg_quote, realpath, rtrim, strlen, strpos, substr, trim, version_compare, }; @@ -814,7 +814,7 @@ impl VcsDownloader for GitDownloader { // --dissociate option is only available since git 2.3.0-rc0 if git_version.is_some() - && version_compare(git_version.as_deref().unwrap_or(""), "2.3.0-rc0", ">=") + && version_compare(git_version.as_deref().unwrap_or(""), "2.3.0-rc0", CmpOp::Ge) && Cache::is_usable(&cache_path) { self.inner.io.write_error3( diff --git a/crates/shirabe/src/downloader/svn_downloader.rs b/crates/shirabe/src/downloader/svn_downloader.rs index 99a5bfe6..6a8bdf0e 100644 --- a/crates/shirabe/src/downloader/svn_downloader.rs +++ b/crates/shirabe/src/downloader/svn_downloader.rs @@ -17,7 +17,7 @@ use crate::util::Svn as SvnUtil; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ - PhpMixed, RuntimeException, impl_php_class, is_dir, php_regex, version_compare, + CmpOp, PhpMixed, RuntimeException, impl_php_class, is_dir, php_regex, version_compare, }; #[derive(Debug)] @@ -223,7 +223,11 @@ impl VcsDownloader for SvnDownloader { Some(self.inner.process.clone()), ); let mut flags: Vec<String> = vec![]; - if version_compare(&util.binary_version().unwrap_or_default(), "1.7.0", ">=") { + if version_compare( + &util.binary_version().unwrap_or_default(), + "1.7.0", + CmpOp::Ge, + ) { flags.push("--ignore-ancestry".to_string()); } diff --git a/crates/shirabe/src/downloader/zip_downloader.rs b/crates/shirabe/src/downloader/zip_downloader.rs index 350ea738..8870194c 100644 --- a/crates/shirabe/src/downloader/zip_downloader.rs +++ b/crates/shirabe/src/downloader/zip_downloader.rs @@ -11,10 +11,10 @@ use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; use shirabe_external_packages::symfony::process::ExecutableFinder; use shirabe_php_shim::{ - DIRECTORY_SEPARATOR, ErrorException, PhpMixed, RuntimeException, UnexpectedValueException, - ZipArchive, bin2hex, class_exists, file_exists, file_get_contents, filesize, function_exists, - hash_file, impl_php_class, is_file, json_encode, php_regex, random_int, str_contains, - str_replace, strlen, substr, version_compare, + CmpOp, DIRECTORY_SEPARATOR, ErrorException, PhpMixed, RuntimeException, + UnexpectedValueException, ZipArchive, bin2hex, class_exists, file_exists, file_get_contents, + filesize, function_exists, hash_file, impl_php_class, is_file, json_encode, php_regex, + random_int, str_contains, str_replace, strlen, substr, version_compare, }; use std::sync::Mutex; @@ -120,7 +120,7 @@ impl ZipDownloader { Some(&mut m), ) { let m1 = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); - if version_compare(&m1, "21.01", "<") { + if version_compare(&m1, "21.01", CmpOp::Lt) { self.inner.io.borrow().write_error(&format!( " <warning>Unzipping using {} {} may result in incorrect file permissions. Install {} 21.01+ or unzip to ensure you get correct permissions.</warning>", executable, m1, executable, diff --git a/crates/shirabe/src/package/loader/validating_array_loader.rs b/crates/shirabe/src/package/loader/validating_array_loader.rs index a28df595..a050f2d7 100644 --- a/crates/shirabe/src/package/loader/validating_array_loader.rs +++ b/crates/shirabe/src/package/loader/validating_array_loader.rs @@ -9,10 +9,10 @@ use crate::repository::PlatformRepository; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::Preg; use shirabe_php_shim::{ - E_USER_DEPRECATED, PHP_EOL, PhpMixed, array_intersect_key, array_values, filter_var_email, - get_debug_type, is_array, is_bool, is_int, is_numeric, is_scalar, is_string, json_encode, - parse_url_all, php_regex, php_to_string, str_replace, strcasecmp, strtolower, strtotime, - substr, trigger_error, trim, var_export, + CmpOp, E_USER_DEPRECATED, PHP_EOL, PhpMixed, array_intersect_key, array_values, + filter_var_email, get_debug_type, is_array, is_bool, is_int, is_numeric, is_scalar, is_string, + json_encode, parse_url_all, php_regex, php_to_string, str_replace, strcasecmp, strtolower, + strtotime, substr, trigger_error, trim, var_export, }; use shirabe_semver::Intervals; use shirabe_semver::constraint::AnyConstraint; @@ -1242,7 +1242,7 @@ impl LoaderInterface for ValidatingArrayLoader { && link_type == "require" && link_constraint .as_constraint() - .is_some_and(|c| ["==", "="].contains(&c.get_operator())) + .is_some_and(|c| c.get_operator() == CmpOp::Eq) && AnyConstraint::from(SimpleConstraint::new( ">=".to_string(), "1.0.0.0-dev".to_string(), diff --git a/crates/shirabe/src/package/version/version_selector.rs b/crates/shirabe/src/package/version/version_selector.rs index bf5514a5..84f2beef 100644 --- a/crates/shirabe/src/package/version/version_selector.rs +++ b/crates/shirabe/src/package/version/version_selector.rs @@ -18,7 +18,7 @@ use crate::repository::RepositorySetInterface; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::Preg; use shirabe_php_shim::{ - PHP_MAJOR_VERSION, PHP_MINOR_VERSION, PHP_RELEASE_VERSION, php_regex, strtolower, + CmpOp, PHP_MAJOR_VERSION, PHP_MINOR_VERSION, PHP_RELEASE_VERSION, php_regex, strtolower, version_compare, }; use shirabe_semver::constraint::AnyConstraint; @@ -123,9 +123,9 @@ impl VersionSelector { return std::cmp::Ordering::Less; } - if version_compare(&b.get_version(), &a.get_version(), ">") { + if version_compare(&b.get_version(), &a.get_version(), CmpOp::Gt) { std::cmp::Ordering::Greater - } else if version_compare(&b.get_version(), &a.get_version(), "<") { + } else if version_compare(&b.get_version(), &a.get_version(), CmpOp::Lt) { std::cmp::Ordering::Less } else { std::cmp::Ordering::Equal diff --git a/crates/shirabe/src/platform/version.rs b/crates/shirabe/src/platform/version.rs index feed1b85..87357062 100644 --- a/crates/shirabe/src/platform/version.rs +++ b/crates/shirabe/src/platform/version.rs @@ -2,7 +2,7 @@ use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; -use shirabe_php_shim::{php_regex, version_compare}; +use shirabe_php_shim::{CmpOp, php_regex, version_compare}; pub struct Version; @@ -34,7 +34,7 @@ impl Version { .cloned() .unwrap_or_default(); - let patch = if version_compare(&version, "3.0.0", "<") { + let patch = if version_compare(&version, "3.0.0", CmpOp::Lt) { format!( ".{}", Self::convert_alpha_version_to_int_version(&patch_str) diff --git a/crates/shirabe/src/plugin/php_plugin_value.rs b/crates/shirabe/src/plugin/php_plugin_value.rs index cdef2a79..a61d4873 100644 --- a/crates/shirabe/src/plugin/php_plugin_value.rs +++ b/crates/shirabe/src/plugin/php_plugin_value.rs @@ -68,20 +68,6 @@ fn required_string(context: &str, value: Option<&PluginValue>) -> Result<String, } } -/// PHP's `Constraint` keeps the operator as one of its `OP_*` codes, not as the string its -/// constructor takes. -fn operator_from_code(code: i64) -> Option<&'static str> { - Some(match code { - SimpleConstraint::OP_EQ => SimpleConstraint::STR_OP_EQ, - SimpleConstraint::OP_LT => SimpleConstraint::STR_OP_LT, - SimpleConstraint::OP_LE => SimpleConstraint::STR_OP_LE, - SimpleConstraint::OP_GT => SimpleConstraint::STR_OP_GT, - SimpleConstraint::OP_GE => SimpleConstraint::STR_OP_GE, - SimpleConstraint::OP_NE => SimpleConstraint::STR_OP_NE, - _ => return None, - }) -} - fn constraint_to_wire(constraint: &AnyConstraint) -> PluginValue { // Whether the pretty string was ever set is observable (`getPrettyString()` falls back to the // string form), so an unset one crosses as null rather than as an absent property. @@ -144,11 +130,12 @@ fn constraint_from_wire(value: &PluginValue) -> Result<AnyConstraint, PhpThrow> Ok(match object.class.as_str() { CONSTRAINT_CLASS => { let operator = match object.protected("operator") { - Some(PluginValue::Int(code)) => operator_from_code(*code).ok_or_else(|| { - throw(format!( - "a semver constraint has an unknown operator: {code}" - )) - })?, + Some(PluginValue::Int(code)) => SimpleConstraint::from_operator_constant(*code) + .ok_or_else(|| { + throw(format!( + "a semver constraint has an unknown operator: {code}" + )) + })?, other => { return Err(throw(format!( "a semver constraint operator is not an int, got {other:?}" diff --git a/crates/shirabe/src/plugin/plugin_manager.rs b/crates/shirabe/src/plugin/plugin_manager.rs index 8f005079..18239ce9 100644 --- a/crates/shirabe/src/plugin/plugin_manager.rs +++ b/crates/shirabe/src/plugin/plugin_manager.rs @@ -27,7 +27,7 @@ use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::Preg; use shirabe_php_rpc::{PluginValue, call_function_with_dispatcher}; use shirabe_php_shim::{ - E_USER_DEPRECATED, PhpMixed, RuntimeException, UnexpectedValueException, dirname, empty, + CmpOp, E_USER_DEPRECATED, PhpMixed, RuntimeException, UnexpectedValueException, dirname, empty, file_get_contents, implode, ksort, php_regex, preg_quote, strrpos, strtr_array, substr, trigger_error, trim, var_export, var_export_str, version_compare, }; @@ -263,7 +263,7 @@ impl PluginManager { if package.get_name() == "symfony/flex" && Preg::is_match3(php_regex!("{^[0-9.]+$}"), &package.get_version(), None) - && version_compare(&package.get_version(), "1.9.8", "<") + && version_compare(&package.get_version(), "1.9.8", CmpOp::Lt) { self.io.write_error(&format!("<warning>The \"{}\" plugin {}was skipped because it is not compatible with Composer 2+. Make sure to update it to version 1.9.8 or greater.</warning>", package.get_name(), @@ -1171,7 +1171,7 @@ impl PluginManager { Some(l) => { if l.is_locked() { let api = l.get_plugin_api().unwrap_or_default(); - version_compare(&api, "2.2.0", "<") + version_compare(&api, "2.2.0", CmpOp::Lt) } else { false } diff --git a/crates/shirabe/src/repository/composer_repository.rs b/crates/shirabe/src/repository/composer_repository.rs index 59e1d520..b2476e1e 100644 --- a/crates/shirabe/src/repository/composer_repository.rs +++ b/crates/shirabe/src/repository/composer_repository.rs @@ -39,7 +39,7 @@ use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; use shirabe_metadata_minifier::MetadataMinifier; use shirabe_php_shim::{ - InvalidArgumentException, LogicException, PHP_EOL, PhpMixed, RuntimeException, + CmpOp, InvalidArgumentException, LogicException, PHP_EOL, PhpMixed, RuntimeException, UnexpectedValueException, extension_loaded, hash, http_build_query, json_decode, parse_url_all, php_regex, realpath, strtolower, strtr, urlencode, var_export, }; @@ -2110,7 +2110,7 @@ impl ComposerRepository { } if let Some(c) = constraint - && !CompilingMatcher::r#match(c, SimpleConstraint::OP_EQ, version.clone()) + && !CompilingMatcher::r#match(c, CmpOp::Eq, version.clone()) { continue; } diff --git a/crates/shirabe/src/util/git.rs b/crates/shirabe/src/util/git.rs index 0ee69926..a6f8d79e 100644 --- a/crates/shirabe/src/util/git.rs +++ b/crates/shirabe/src/util/git.rs @@ -16,10 +16,10 @@ use crate::util::{AuthHelper, StoreAuth}; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ - InvalidArgumentException, PHP_EOL, PhpMixed, RuntimeException, array_map, clearstatcache, - explode, implode, in_array_loose, in_array_strict, is_dir, php_regex, preg_quote, rawurldecode, - rawurlencode, str_contains, str_ends_with, str_replace_array, strlen, strpos, substr, trim, - version_compare, + CmpOp, InvalidArgumentException, PHP_EOL, PhpMixed, RuntimeException, array_map, + clearstatcache, explode, implode, in_array_loose, in_array_strict, is_dir, php_regex, + preg_quote, rawurldecode, rawurlencode, str_contains, str_ends_with, str_replace_array, strlen, + strpos, substr, trim, version_compare, }; use std::sync::Mutex; @@ -982,7 +982,7 @@ impl Git { ) -> String { let git_version = Self::get_version(process); if let Some(v) = git_version - && version_compare(&v, "2.10.0-rc0", ">=") + && version_compare(&v, "2.10.0-rc0", CmpOp::Ge) { return " --no-show-signature".to_string(); } @@ -1010,7 +1010,7 @@ impl Git { let git_version = Self::get_version(process); git_version - .map(|v| version_compare(&v, "2.33.0-rc0", ">=")) + .map(|v| version_compare(&v, "2.33.0-rc0", CmpOp::Ge)) .unwrap_or(false) } @@ -1212,7 +1212,7 @@ impl Git { // PHP: $process ?? new ProcessExecutor() let git_version = Self::get_version(process); if let Some(v) = git_version { - if version_compare(&v, "2.3.0", ">=") { + if version_compare(&v, "2.3.0", CmpOp::Ge) { // added in git 2.3.0, prevents prompting the user for username/password if Platform::get_env("GIT_TERMINAL_PROMPT").as_deref() != Some("0") { Platform::put_env("GIT_TERMINAL_PROMPT", "0"); diff --git a/crates/shirabe/src/util/package_sorter.rs b/crates/shirabe/src/util/package_sorter.rs index 4b76c2fe..5687a339 100644 --- a/crates/shirabe/src/util/package_sorter.rs +++ b/crates/shirabe/src/util/package_sorter.rs @@ -3,7 +3,7 @@ use crate::package::Link; use crate::package::PackageInterfaceHandle; use indexmap::IndexMap; -use shirabe_php_shim::{strnatcasecmp, version_compare}; +use shirabe_php_shim::{CmpOp, strnatcasecmp, version_compare}; pub struct PackageSorter; @@ -21,7 +21,7 @@ impl PackageSorter { if candidate.is_default_branch() { return Some(candidate); } - if version_compare(&highest.get_version(), &candidate.get_version(), "<") { + if version_compare(&highest.get_version(), &candidate.get_version(), CmpOp::Lt) { highest = candidate; } } |
