diff options
Diffstat (limited to 'crates')
53 files changed, 568 insertions, 980 deletions
diff --git a/crates/shirabe-class-map-generator/src/class_map_generator.rs b/crates/shirabe-class-map-generator/src/class_map_generator.rs index 478781c8..670f8448 100644 --- a/crates/shirabe-class-map-generator/src/class_map_generator.rs +++ b/crates/shirabe-class-map-generator/src/class_map_generator.rs @@ -3,7 +3,7 @@ use crate::class_map::ClassMap; use crate::file_list::FileList; use crate::php_file_parser::PhpFileParser; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ InvalidArgumentException, LogicException, PATHINFO_EXTENSION, RuntimeException, explode, getcwd, implode, is_dir, is_file, pathinfo, php_regex, preg_quote, realpath, str_replace, @@ -347,11 +347,9 @@ impl ClassMapGenerator { } // extract a prefix being a protocol://, protocol:, protocol://drive: or simply drive: - let mut r#match = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(r#match) = Preg::is_match3( php_regex!(r"{^( [0-9a-z]{2,}+: (?: // (?: [a-z]: )? )? | [a-z]: )}ix"), &path, - Some(&mut r#match), ) { prefix = r#match .get(&CaptureKey::ByIndex(1)) diff --git a/crates/shirabe-class-map-generator/src/php_file_cleaner.rs b/crates/shirabe-class-map-generator/src/php_file_cleaner.rs index 78041061..5731dbd4 100644 --- a/crates/shirabe-class-map-generator/src/php_file_cleaner.rs +++ b/crates/shirabe-class-map-generator/src/php_file_cleaner.rs @@ -97,15 +97,13 @@ impl PhpFileCleaner { } if char == '<' && self.peek('<') { - let mut r#match = PregMatchedGroups::new(); // Regex pattern compatibility: // PHP matches `<<<`, an optional quote, the identifier, then requires the // closing quote to be the exact same character via `\1`. The `regex` crate has // no backreferences, so the three quote states (none, `'`, `"`) are expanded // into separate alternatives, each capturing the identifier in its own group. - if self.r#match( + if let Some(r#match) = self.r#match( r#"{<<<[ \t]*(?:"([a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)"|'([a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)'|([a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*))(?:\r\n|\n|\r)}A"#, - Some(&mut r#match), ) { self.index += r#match.get(&CaptureKey::ByIndex(0)).map(|s| s.len()).unwrap_or(0); let delimiter = [1, 2, 3] @@ -144,13 +142,9 @@ impl PhpFileCleaner { let end = self.index + entry.length; if end <= self.len && self.contents[self.index..end] == entry.name { let offset = if self.index > 0 { self.index - 1 } else { 0 }; - let mut r#match = PregMatchedGroups::new(); - if Preg::is_match4( - &entry.pattern, - &self.contents, - Some(&mut r#match), - offset, - ) { + if let Some(r#match) = + Preg::is_match4(&entry.pattern, &self.contents, offset) + { return clean + r#match .get(&CaptureKey::ByIndex(0)) @@ -164,8 +158,7 @@ impl PhpFileCleaner { self.index += 1; let rest_pattern = REST_PATTERN.lock().unwrap().clone(); if let Some(rest_pattern) = rest_pattern { - let mut r#match = PregMatchedGroups::new(); - if self.r#match(&rest_pattern, Some(&mut r#match)) { + if let Some(r#match) = self.r#match(&rest_pattern) { let m0 = r#match .get(&CaptureKey::ByIndex(0)) .cloned() @@ -292,7 +285,7 @@ impl PhpFileCleaner { self.index + 1 < self.len && self.contents.as_bytes()[self.index + 1] as char == char } - fn r#match(&self, regex: &str, r#match: Option<&mut PregMatchedGroups>) -> bool { - Preg::is_match4(regex, &self.contents, r#match, self.index) + fn r#match(&self, regex: &str) -> Option<PregMatchedGroups> { + Preg::is_match4(regex, &self.contents, self.index) } } 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 a1207140..e05f4f1a 100644 --- a/crates/shirabe-class-map-generator/src/php_file_parser.rs +++ b/crates/shirabe-class-map-generator/src/php_file_parser.rs @@ -1,7 +1,7 @@ //! ref: composer/vendor/composer/class-map-generator/src/PhpFileParser.php use crate::php_file_cleaner::PhpFileCleaner; -use shirabe_pcre::{CaptureKey, Preg, PregMatchesAll}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ PHP_EOL, RuntimeException, file_exists, file_get_contents, function_exists, is_file, is_readable, ltrim, php_strip_whitespace, str_replace_array, strrpos, substr, trim, @@ -84,8 +84,7 @@ impl PhpFileParser { }}ix", et = extra_types ); - let mut matches = PregMatchesAll::new(); - Preg::match_all2(&pattern2, &contents, &mut matches); + let matches = Preg::match_all2(&pattern2, &contents); let mut classes = vec![]; let mut namespace = String::new(); diff --git a/crates/shirabe-pcre/src/preg.rs b/crates/shirabe-pcre/src/preg.rs index dd6e4950..25feafc9 100644 --- a/crates/shirabe-pcre/src/preg.rs +++ b/crates/shirabe-pcre/src/preg.rs @@ -32,58 +32,31 @@ preg_match_map! { pub struct Preg; impl Preg { - pub fn match3( - pattern: impl PregPattern, - subject: &str, - matches: Option<&mut PregMatchedGroups>, - ) -> bool { - Self::match4(pattern, subject, matches, 0) + pub fn match3(pattern: impl PregPattern, subject: &str) -> Option<PregMatchedGroups> { + Self::match4(pattern, subject, 0) } pub fn match4( pattern: impl PregPattern, subject: &str, - matches: Option<&mut PregMatchedGroups>, offset: usize, - ) -> bool { - let internal = preg_match2(pattern, subject, offset); - - if let Some(out) = matches { - *out = match &internal { - Some(internal) => drop_null_matches(internal), - None => PregMatchedGroups::new(), - }; - } - - internal.is_some() + ) -> Option<PregMatchedGroups> { + preg_match2(pattern, subject, offset).map(|internal| drop_null_matches(&internal)) } pub fn match_all(pattern: impl PregPattern, subject: &str) -> usize { - occurrence_count(&preg_match_all2(pattern, subject)) + Self::match_all2(pattern, subject).occurrence_count() } - pub fn match_all2( - pattern: impl PregPattern, - subject: &str, - matches: &mut PregMatchesAll, - ) -> usize { - *matches = preg_match_all2(pattern, subject); - occurrence_count(matches) + pub fn match_all2(pattern: impl PregPattern, subject: &str) -> PregMatchesAll { + preg_match_all2(pattern, subject) } fn match_all_with_offsets5( pattern: impl PregPattern, subject: &str, - matches: Option<&mut PregMatchesAllWithOffsets>, - ) -> usize { - let internal = preg_match_all_offset_capture(pattern, subject); - let count = internal[&CaptureKey::ByIndex(0)].len(); - - if let Some(out) = matches { - *out = internal; - } - - count + ) -> PregMatchesAllWithOffsets { + preg_match_all_offset_capture(pattern, subject) } pub fn replace(pattern: impl PregPattern, replacement: &str, subject: &str) -> String { @@ -127,44 +100,31 @@ impl Preg { } pub fn is_match(pattern: impl PregPattern, subject: &str) -> bool { - Self::match4(pattern, subject, None, 0) + Self::match4(pattern, subject, 0).is_some() } - pub fn is_match3( - pattern: impl PregPattern, - subject: &str, - matches: Option<&mut PregMatchedGroups>, - ) -> bool { - Self::match4(pattern, subject, matches, 0) + pub fn is_match3(pattern: impl PregPattern, subject: &str) -> Option<PregMatchedGroups> { + Self::match4(pattern, subject, 0) } pub fn is_match4( pattern: impl PregPattern, subject: &str, - matches: Option<&mut PregMatchedGroups>, offset: usize, - ) -> bool { - Self::match4(pattern, subject, matches, offset) + ) -> Option<PregMatchedGroups> { + Self::match4(pattern, subject, offset) } - pub fn is_match_named( - pattern: impl PregPattern, - subject: &str, - matches: &mut PregNamedGroups, - ) -> bool { - let internal = preg_match2(pattern, subject, 0); - let result = internal.is_some(); - - matches.clear(); - if let Some(internal) = internal { - for (key, value) in internal { - if let (CaptureKey::ByName(name), Some(value)) = (key, value) { - matches.insert(name, value); - } - } - } - - result + pub fn is_match_named(pattern: impl PregPattern, subject: &str) -> Option<PregNamedGroups> { + Some( + preg_match2(pattern, subject, 0)? + .into_iter() + .filter_map(|(key, value)| match (key, value) { + (CaptureKey::ByName(name), Some(value)) => Some((name, value)), + _ => None, + }) + .collect(), + ) } /// `is_match3` with the groups positioned by number rather than keyed, for callers that only @@ -184,20 +144,15 @@ impl Preg { ) } - pub fn is_match_all( - pattern: impl PregPattern, - subject: &str, - matches: &mut PregMatchesAll, - ) -> bool { - Self::match_all2(pattern, subject, matches) > 0 + pub fn is_match_all(pattern: impl PregPattern, subject: &str) -> PregMatchesAll { + Self::match_all2(pattern, subject) } pub fn is_match_all_with_offsets3( pattern: impl PregPattern, subject: &str, - matches: Option<&mut PregMatchesAllWithOffsets>, - ) -> bool { - Self::match_all_with_offsets5(pattern, subject, matches) > 0 + ) -> PregMatchesAllWithOffsets { + Self::match_all_with_offsets5(pattern, subject) } } @@ -209,9 +164,3 @@ fn drop_null_matches(matches: &PregMatches) -> PregMatchedGroups { .filter_map(|(key, value)| value.clone().map(|value| (key.clone(), value))) .collect() } - -// PHP's `preg_match_all` returns the number of occurrences; every column of a -// PREG_PATTERN_ORDER map holds one entry per occurrence. -fn occurrence_count(matches: &PregMatchesAll) -> usize { - matches[&CaptureKey::ByIndex(0)].len() -} diff --git a/crates/shirabe-php-shim/src/preg.rs b/crates/shirabe-php-shim/src/preg.rs index c2aa0df3..e758fd20 100644 --- a/crates/shirabe-php-shim/src/preg.rs +++ b/crates/shirabe-php-shim/src/preg.rs @@ -96,6 +96,20 @@ preg_match_map! { pub struct PregMatchesAllWithOffsets(CaptureKey => Vec<(Option<String>, i64)>); } +impl PregMatchesAll { + /// The number PHP's `preg_match_all` returns: every column holds one entry per occurrence. + pub fn occurrence_count(&self) -> usize { + self[&CaptureKey::ByIndex(0)].len() + } +} + +impl PregMatchesAllWithOffsets { + /// The number PHP's `preg_match_all` returns: every column holds one entry per occurrence. + pub fn occurrence_count(&self) -> usize { + self[&CaptureKey::ByIndex(0)].len() + } +} + pub fn preg_quote(str: &str, delimiter: Option<char>) -> String { // Regex pattern compatibility: // PHP's preg_quote escapes `<` and `>` (PCRE treats `\<`/`\>` as literals), but the `regex` diff --git a/crates/shirabe-symfony-finder/src/finder.rs b/crates/shirabe-symfony-finder/src/finder.rs index 27a7d2d6..cc78ebe3 100644 --- a/crates/shirabe-symfony-finder/src/finder.rs +++ b/crates/shirabe-symfony-finder/src/finder.rs @@ -642,9 +642,9 @@ fn is_regex(str: &str) -> bool { // PHP 8.2+ available modifiers. let available_modifiers = "imsxuADUn"; - let mut matches = PregMatchedGroups::new(); + let matches = PregMatchedGroups::new(); let pattern = format!("/^(.{{3,}}?)[{available_modifiers}]*$/"); - if Preg::is_match3(&pattern, str, Some(&mut matches)) { + if let Some(matches) = Preg::is_match3(&pattern, str) { let group = matches .get(&CaptureKey::ByIndex(1)) .cloned() @@ -688,10 +688,9 @@ fn comparator_test(operator: &str, test: i64, target: i64) -> bool { /// `DateComparator::__construct`, returning `(operator, target unix timestamp)`. fn parse_date_comparator(test: &str) -> (String, i64) { let pattern = "#^\\s*(==|!=|[<>]=?|after|since|before|until)?\\s*(.+?)\\s*$#i"; - let mut matches = PregMatchedGroups::new(); - if !Preg::is_match3(pattern, test, Some(&mut matches)) { + let Some(matches) = Preg::is_match3(pattern, test) else { panic!("Don't understand \"{test}\" as a date test."); - } + }; let date = matches .get(&CaptureKey::ByIndex(2)) diff --git a/crates/shirabe/src/autoload/autoload_generator.rs b/crates/shirabe/src/autoload/autoload_generator.rs index 9a4a4c26..b6835b61 100644 --- a/crates/shirabe/src/autoload/autoload_generator.rs +++ b/crates/shirabe/src/autoload/autoload_generator.rs @@ -559,12 +559,9 @@ return array( { let content = file_get_contents(format!("{}/autoload.php", vendor_path)).unwrap_or_default(); - let mut matches = PregMatchedGroups::new(); - if Preg::match3( - php_regex!("{ComposerAutoloaderInit([^:\\s]+)::}"), - &content, - Some(&mut matches), - ) { + if let Some(matches) = + Preg::match3(php_regex!("{ComposerAutoloaderInit([^:\\s]+)::}"), &content) + { suffix = matches.get(&CaptureKey::ByIndex(1)).cloned(); } } @@ -1155,12 +1152,8 @@ return array( let package = &item.0; let links = array_merge_map(package.get_replaces(), package.get_provides()); for (_k, link) in &links { - let mut matches = PregMatchedGroups::new(); - if Preg::match3( - php_regex!("{^ext-(.+)$}iD"), - link.get_target(), - Some(&mut matches), - ) && let Some(ext) = matches.get(&CaptureKey::ByIndex(1)).cloned() + if let Some(matches) = Preg::match3(php_regex!("{^ext-(.+)$}iD"), link.get_target()) + && let Some(ext) = matches.get(&CaptureKey::ByIndex(1)).cloned() { extension_providers .entry(ext) @@ -1201,13 +1194,9 @@ return array( required_php_64bit = true; } - let mut matches = PregMatchedGroups::new(); if check_platform.as_bool() == Some(true) - && Preg::match3( - php_regex!("{^ext-(.+)$}iD"), - link.get_target(), - Some(&mut matches), - ) + && let Some(matches) = + Preg::match3(php_regex!("{^ext-(.+)$}iD"), link.get_target()) { let ext_key = matches .get(&CaptureKey::ByIndex(1)) diff --git a/crates/shirabe/src/cache.rs b/crates/shirabe/src/cache.rs index e1964959..793a2a07 100644 --- a/crates/shirabe/src/cache.rs +++ b/crates/shirabe/src/cache.rs @@ -6,7 +6,7 @@ use crate::util::Filesystem; use crate::util::Platform; use crate::util::Silencer; use chrono::Utc; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ ErrorException, bin2hex, clearstatcache, date_format_to_strftime, dirname, disk_free_space, file_exists, file_get_contents, file_put_contents, filemtime, function_exists, hash_file, @@ -186,13 +186,11 @@ impl Cache { true, crate::io::DEBUG, ); - let mut m = PregMatchedGroups::new(); - if Preg::match3( + if let Some(m) = Preg::match3( php_regex!( r"{^file_put_contents\(\): Only ([0-9]+) of ([0-9]+) bytes written}" ), e.get_message(), - Some(&mut m), ) { // Remove partial file. unlink(&temp_file_name); diff --git a/crates/shirabe/src/command/archive_command.rs b/crates/shirabe/src/command/archive_command.rs index 1d7165ac..09066c9f 100644 --- a/crates/shirabe/src/command/archive_command.rs +++ b/crates/shirabe/src/command/archive_command.rs @@ -26,7 +26,7 @@ use crate::util::Platform; use crate::util::ProcessExecutor; use crate::util::r#loop::Loop; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::{LogicException, get_debug_type, impl_php_class, php_regex}; use shirabe_symfony_console::command::Command; use shirabe_symfony_console::input::InputInterface; @@ -228,25 +228,21 @@ impl ArchiveCommand { min_stability = "stable".to_string(); } - if let Some(version_str) = &version { - let mut matches = PregMatchedGroups::new(); - if Preg::match3( - php_regex!(r"{@(stable|RC|beta|alpha|dev)$}i"), - version_str, - Some(&mut matches), - ) { - let m1 = matches - .get(&CaptureKey::ByIndex(1)) - .cloned() - .unwrap_or_default(); - let m0 = matches - .get(&CaptureKey::ByIndex(0)) - .cloned() - .unwrap_or_default(); - min_stability = VersionParser::normalize_stability(&m1)?; - let full_match_len = m0.len(); - version = Some(version_str[..version_str.len() - full_match_len].to_string()); - } + if let Some(version_str) = &version + && let Some(matches) = + Preg::match3(php_regex!(r"{@(stable|RC|beta|alpha|dev)$}i"), version_str) + { + let m1 = matches + .get(&CaptureKey::ByIndex(1)) + .cloned() + .unwrap_or_default(); + let m0 = matches + .get(&CaptureKey::ByIndex(0)) + .cloned() + .unwrap_or_default(); + min_stability = VersionParser::normalize_stability(&m1)?; + let full_match_len = m0.len(); + version = Some(version_str[..version_str.len() - full_match_len].to_string()); } let mut repo_set = RepositorySet::new( diff --git a/crates/shirabe/src/command/config_command.rs b/crates/shirabe/src/command/config_command.rs index 550ddf3c..86375f49 100644 --- a/crates/shirabe/src/command/config_command.rs +++ b/crates/shirabe/src/command/config_command.rs @@ -18,7 +18,7 @@ use crate::util::Filesystem; use crate::util::Platform; use crate::util::Silencer; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ InvalidArgumentException, PhpMixed, RuntimeException, array_is_list, array_merge, escapeshellcmd, exec, explode, file_exists, impl_php_class, implode, in_array_loose, @@ -701,11 +701,9 @@ impl Command for ConfigCommand { let mut source = config.borrow_mut().get_source_of_value(&setting_key); let mut value: PhpMixed; - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(matches) = Preg::is_match3( php_regex!("/^repos?(?:itories)?(?:\\.(.+))?/"), &setting_key, - Some(&mut matches), ) { if matches.get(&CaptureKey::ByIndex(1)).is_none() { value = data @@ -929,12 +927,9 @@ impl Command for ConfigCommand { return Ok(0); } // handle preferred-install per-package config - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!("/^preferred-install\\.(.+)/"), - &setting_key, - Some(&mut matches), - ) { + if let Some(matches) = + Preg::is_match3(php_regex!("/^preferred-install\\.(.+)/"), &setting_key) + { if input.borrow().get_option("unset")?.as_bool() == Some(true) { self.config_source .borrow_mut() @@ -967,11 +962,9 @@ impl Command for ConfigCommand { } // handle allow-plugins config setting elements true or false to add/remove - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(matches) = Preg::is_match3( php_regex!("{^allow-plugins\\.([a-zA-Z0-9/*-]+)}"), &setting_key, - Some(&mut matches), ) { if input.borrow().get_option("unset")?.as_bool() == Some(true) { self.config_source @@ -1037,12 +1030,9 @@ impl Command for ConfigCommand { } // handle repositories - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!("/^repos?(?:itories)?\\.(.+)/"), - &setting_key, - Some(&mut matches), - ) { + if let Some(matches) = + Preg::is_match3(php_regex!("/^repos?(?:itories)?\\.(.+)/"), &setting_key) + { if input.borrow().get_option("unset")?.as_bool() == Some(true) { self.config_source .borrow_mut() @@ -1106,16 +1096,11 @@ impl Command for ConfigCommand { } return Err(RuntimeException::new("You must pass the type and a url. Example: shirabe config repositories.foo vcs https://bar.com".to_string()) - .into()); + .into()); } // handle extra - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!("/^extra\\.(.+)/"), - &setting_key, - Some(&mut matches), - ) { + if let Some(matches) = Preg::is_match3(php_regex!("/^extra\\.(.+)/"), &setting_key) { if input.borrow().get_option("unset")?.as_bool() == Some(true) { self.config_source .borrow_mut() @@ -1187,12 +1172,7 @@ impl Command for ConfigCommand { } // handle suggest - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!("/^suggest\\.(.+)/"), - &setting_key, - Some(&mut matches), - ) { + if let Some(matches) = Preg::is_match3(php_regex!("/^suggest\\.(.+)/"), &setting_key) { if input.borrow().get_option("unset")?.as_bool() == Some(true) { self.config_source .borrow_mut() @@ -1226,12 +1206,7 @@ impl Command for ConfigCommand { } // handle platform - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!("/^platform\\.(.+)/"), - &setting_key, - Some(&mut matches), - ) { + if let Some(matches) = Preg::is_match3(php_regex!("/^platform\\.(.+)/"), &setting_key) { if input.borrow().get_option("unset")?.as_bool() == Some(true) { self.config_source .borrow_mut() @@ -1348,13 +1323,11 @@ impl Command for ConfigCommand { } // handle auth - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(matches) = Preg::is_match3( php_regex!( "/^(bitbucket-oauth|github-oauth|gitlab-oauth|gitlab-token|http-basic|custom-headers|bearer|forgejo-token)\\.(.+)/" ), &setting_key, - Some(&mut matches), ) { if input.borrow().get_option("unset")?.as_bool() == Some(true) { self.auth_config_source @@ -1474,12 +1447,7 @@ impl Command for ConfigCommand { } // Check if the header is in correct "Name: Value" format - let mut header_parts = PregMatchedGroups::new(); - if !Preg::is_match3( - php_regex!("/^[^:]+:\\s*.+$/"), - header, - Some(&mut header_parts), - ) { + if Preg::is_match3(php_regex!("/^[^:]+:\\s*.+$/"), header).is_none() { return Err(RuntimeException::new(format!( "Header \"{}\" is not in \"Header-Name: Header-Value\" format", header @@ -1527,12 +1495,7 @@ impl Command for ConfigCommand { } // handle script - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!("/^scripts\\.(.+)/"), - &setting_key, - Some(&mut matches), - ) { + if let Some(matches) = Preg::is_match3(php_regex!("/^scripts\\.(.+)/"), &setting_key) { if input.borrow().get_option("unset")?.as_bool() == Some(true) { self.config_source .borrow_mut() @@ -1770,11 +1733,13 @@ fn build_unique_config_values() -> IndexMap<String, (ValidatorFn, NormalizerFn)> "cache-files-maxsize".to_string(), ( Box::new(|val| { - PhpMixed::Bool(Preg::is_match3( - php_regex!("/^\\s*([0-9.]+)\\s*(?:([kmg])(?:i?b)?)?\\s*$/i"), - val.as_string().unwrap_or(""), - None, - )) + PhpMixed::Bool( + Preg::is_match3( + php_regex!("/^\\s*([0-9.]+)\\s*(?:([kmg])(?:i?b)?)?\\s*$/i"), + val.as_string().unwrap_or(""), + ) + .is_some(), + ) }), Box::new(|val| val.clone()), ), diff --git a/crates/shirabe/src/command/create_project_command.rs b/crates/shirabe/src/command/create_project_command.rs index 33bfb021..ae46da30 100644 --- a/crates/shirabe/src/command/create_project_command.rs +++ b/crates/shirabe/src/command/create_project_command.rs @@ -37,7 +37,7 @@ use crate::util::Filesystem; use crate::util::Platform; use crate::util::ProcessExecutor; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ InvalidArgumentException, PhpMixed, RuntimeException, UnexpectedValueException, array_pop, @@ -526,34 +526,26 @@ impl CreateProjectCommand { if package_version.is_none() { stability = Some("stable".to_string()); } else { - let ok = { - let mut matched = PregMatchedGroups::new(); - let ok = Preg::is_match3( - format!( - "{{^[^,\\s]*?@({})$}}i", - implode( - "|", - &STABILITIES - .keys() - .map(|k| k.to_string()) - .collect::<Vec<_>>() - ) - ), - package_version.as_deref().unwrap_or(""), - Some(&mut matched), + let matched = Preg::is_match3( + format!( + "{{^[^,\\s]*?@({})$}}i", + implode( + "|", + &STABILITIES + .keys() + .map(|k| k.to_string()) + .collect::<Vec<_>>() + ) + ), + package_version.as_deref().unwrap_or(""), + ); + if let Some(matched) = matched { + stability = Some( + matched + .get(&CaptureKey::ByIndex(1)) + .cloned() + .unwrap_or_default(), ); - if ok { - stability = Some( - matched - .get(&CaptureKey::ByIndex(1)) - .cloned() - .unwrap_or_default(), - ); - } - ok - }; - if ok { - // stability already set above } else { stability = Some(VersionParser::parse_stability( package_version.as_deref().unwrap_or(""), diff --git a/crates/shirabe/src/command/diagnose_command.rs b/crates/shirabe/src/command/diagnose_command.rs index aa581c82..ff9e0e63 100644 --- a/crates/shirabe/src/command/diagnose_command.rs +++ b/crates/shirabe/src/command/diagnose_command.rs @@ -33,7 +33,7 @@ use crate::util::ProcessExecutor; use crate::util::http::ProxyManager; use crate::util::http::RequestProxy; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ AnyThrowable, CmpOp, InvalidArgumentException, PHP_EOL, PhpClass as _, PhpMixed, @@ -862,11 +862,9 @@ impl DiagnoseCommand { warnings.insert("zlib".to_string(), PhpMixed::Bool(true)); } - let mut phpinfo_match = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(phpinfo_match) = Preg::is_match3( php_regex!("{Configure Command(?: *</td><td class=\"v\">| *=> *)(.*?)(?:</td>|$)}m"), &diagnostics.phpinfo_general, - Some(&mut phpinfo_match), ) { let configure = phpinfo_match .get(&CaptureKey::ByIndex(1)) diff --git a/crates/shirabe/src/command/init_command.rs b/crates/shirabe/src/command/init_command.rs index 243df290..f9a504be 100644 --- a/crates/shirabe/src/command/init_command.rs +++ b/crates/shirabe/src/command/init_command.rs @@ -19,7 +19,7 @@ use crate::util::Filesystem; use crate::util::ProcessExecutor; use crate::util::Silencer; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups, PregMatchesAll}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ FILE_IGNORE_NEW_LINES, InvalidArgumentException, PHP_EOL, PHP_SERVER, PhpMixed, @@ -90,11 +90,9 @@ impl InitCommand { &self, author: &str, ) -> anyhow::Result<IndexMap<String, Option<String>>> { - let mut m = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(m) = Preg::is_match3( php_regex!(r#"/^(?P<name>[- .,\p{L}\p{N}\p{Mn}\'’\"()]+)(?:\s+<(?P<email>.+?)>)?$/u"#), author, - Some(&mut m), ) { let email = m.get(&CaptureKey::ByName("email".to_string())).cloned(); if let Some(ref email) = email @@ -175,8 +173,8 @@ impl InitCommand { ) == 0 { *self.git_config.borrow_mut() = Some(IndexMap::new()); - let mut m = PregMatchesAll::new(); - if Preg::is_match_all(php_regex!(r"{^([^=]+)=(.*)$}m"), &output, &mut m) { + let m = Preg::is_match_all(php_regex!(r"{^([^=]+)=(.*)$}m"), &output); + if m.occurrence_count() > 0 { let keys: Vec<Option<String>> = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); let values: Vec<Option<String>> = diff --git a/crates/shirabe/src/command/package_discovery_trait.rs b/crates/shirabe/src/command/package_discovery_trait.rs index 877cc7da..4745a7d5 100644 --- a/crates/shirabe/src/command/package_discovery_trait.rs +++ b/crates/shirabe/src/command/package_discovery_trait.rs @@ -19,7 +19,7 @@ use crate::repository::RepositorySet; use crate::repository::{RepositoryInterface, SearchResult}; use crate::util::Filesystem; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ Exception, InvalidArgumentException, LogicException, PHP_EOL, PhpMixed, array_keys, @@ -330,11 +330,9 @@ pub trait PackageDiscoveryTrait: BaseCommand { } } - let mut m = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(m) = Preg::is_match3( php_regex!(r"{^\s*(?P<name>[\S/]+)(?:\s+(?P<version>\S+))?\s*$}"), &selection, - Some(&mut m), ) { if let Some(v) = m.get(&CaptureKey::ByName("version".to_string())).cloned() diff --git a/crates/shirabe/src/command/show_command.rs b/crates/shirabe/src/command/show_command.rs index e8be4da5..419de424 100644 --- a/crates/shirabe/src/command/show_command.rs +++ b/crates/shirabe/src/command/show_command.rs @@ -36,7 +36,7 @@ use crate::repository::RepositoryUtils; use crate::repository::RootPackageRepository; use crate::util::PackageInfo; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ CmpOp, DATE_ATOM, InvalidArgumentException, LogicException, PhpMixed, UnexpectedValueException, array_search, date_format_to_strftime, date_local, extension_loaded, impl_php_class, @@ -1372,12 +1372,10 @@ impl ShowCommand { } if target_version.is_none() { - let mut groups = PregMatchedGroups::new(); if major_only - && Preg::is_match3( + && let Some(groups) = Preg::is_match3( php_regex!(r"{^(?P<zero_major>(?:0\.)+)?(?P<first_meaningful>\d+)\.}"), &package.get_version(), - Some(&mut groups), ) { let zero_major = groups diff --git a/crates/shirabe/src/config.rs b/crates/shirabe/src/config.rs index 3a320d6f..796e23fc 100644 --- a/crates/shirabe/src/config.rs +++ b/crates/shirabe/src/config.rs @@ -647,18 +647,16 @@ impl Config { // numbers with kb/mb/gb support, without env var support "cache-files-maxsize" => { let raw = self.config.get(key).map(php_to_string).unwrap_or_default(); - let mut matches = PregMatchedGroups::new(); - if !Preg::is_match3( + let Some(matches) = Preg::is_match3( php_regex!(r"/^\s*([0-9.]+)\s*(?:([kmg])(?:i?b)?)?\s*$/i"), &raw, - Some(&mut matches), - ) { + ) else { return Err(RuntimeException::new(format!( "Could not parse the value of '{}': {}", key, raw )) .into()); - } + }; let mut size = matches .get(&CaptureKey::ByIndex(1)) .cloned() diff --git a/crates/shirabe/src/dependency_resolver/pool_builder.rs b/crates/shirabe/src/dependency_resolver/pool_builder.rs index 7dd40c4b..9e2e18ea 100644 --- a/crates/shirabe/src/dependency_resolver/pool_builder.rs +++ b/crates/shirabe/src/dependency_resolver/pool_builder.rs @@ -786,7 +786,7 @@ impl PoolBuilder { fn is_update_allowed(&self, package: PackageInterfaceHandle) -> bool { for pattern in &self.update_allow_list { let pattern_regexp = base_package::package_name_to_regexp(pattern); - if Preg::is_match3(&pattern_regexp, &package.get_name(), None) { + if Preg::is_match3(&pattern_regexp, &package.get_name()).is_some() { return true; } } @@ -813,13 +813,13 @@ impl PoolBuilder { .borrow_mut() .get_packages()? { - if Preg::is_match3(&pattern_regexp, &package.get_name(), None) { + if Preg::is_match3(&pattern_regexp, &package.get_name()).is_some() { continue 'outer; } } // update pattern matches a root require? => all good, probably a new package for (package_name, _constraint) in request.get_requires() { - if Preg::is_match3(&pattern_regexp, package_name, None) { + if Preg::is_match3(&pattern_regexp, package_name).is_some() { if PlatformRepository::is_platform_package(package_name) { matched_platform_package = true; continue; diff --git a/crates/shirabe/src/dependency_resolver/problem.rs b/crates/shirabe/src/dependency_resolver/problem.rs index c75a0d31..80f0e5db 100644 --- a/crates/shirabe/src/dependency_resolver/problem.rs +++ b/crates/shirabe/src/dependency_resolver/problem.rs @@ -10,7 +10,7 @@ use crate::repository::LockArrayRepository; use crate::repository::PlatformRepository; use crate::repository::RepositorySet; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ CmpOp, LogicException, PhpMixed, extension_loaded, implode, loosely_compare, php_regex, spl_object_hash, sprintf, str_replace, stripos, strpos, strtolower, substr, substr_count, @@ -220,7 +220,6 @@ impl Problem { installed_map, learned_pool, )?; - let mut m = PregMatchedGroups::new(); let matched = if matches!( rule_ref.get_reason(), rule::RULE_PACKAGE_REQUIRES | rule::RULE_PACKAGE_CONFLICT @@ -230,12 +229,11 @@ impl Problem { r"{^(?P<package>\S+) (?P<version>\S+) (?P<type>requires|conflicts)}" ), &message, - Some(&mut m), ) } else { - false + None }; - if matched { + if let Some(m) = matched { message = str_replace("%", "%%", &message); let template = Preg::replace(php_regex!(r"{^\S+ \S+ }"), "%s%s ", &message); messages.push(template.clone()); @@ -559,7 +557,7 @@ impl Problem { if let Some(c) = constraint && c.is_constraint() && c.get_operator() == Some(CmpOp::Eq) - && Preg::is_match3(php_regex!(r"{^dev-.*#.*}"), &c.get_pretty_string(), None) + && Preg::is_match3(php_regex!(r"{^dev-.*#.*}"), &c.get_pretty_string()).is_some() { let new_constraint = Preg::replace( php_regex!(r"{ +as +([^,\s|]+)$}"), @@ -993,7 +991,7 @@ impl Problem { )); } - if !Preg::is_match3(php_regex!(r"{^[A-Za-z0-9_./-]+$}"), package_name, None) { + if Preg::is_match3(php_regex!(r"{^[A-Za-z0-9_./-]+$}"), package_name).is_none() { let illegal_chars = Preg::replace(php_regex!(r"{[A-Za-z0-9_./-]+}"), "", package_name); return Ok(( @@ -1383,11 +1381,7 @@ impl Problem { && c.get_operator() == Some(CmpOp::Eq) && !c.get_version().starts_with("dev-") { - if !Preg::is_match3( - php_regex!(r"{^\d+(?:\.\d+)*$}"), - &c.get_pretty_string(), - None, - ) { + if Preg::is_match3(php_regex!(r"{^\d+(?:\.\d+)*$}"), &c.get_pretty_string()).is_none() { return format!(" {} (exact version match)", c.get_pretty_string()); } diff --git a/crates/shirabe/src/downloader/git_downloader.rs b/crates/shirabe/src/downloader/git_downloader.rs index f60b231d..d3f4441a 100644 --- a/crates/shirabe/src/downloader/git_downloader.rs +++ b/crates/shirabe/src/downloader/git_downloader.rs @@ -17,7 +17,7 @@ use crate::util::Platform; use crate::util::ProcessExecutor; use crate::util::Url; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups, PregMatchesAll}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ CmpOp, PhpMixed, RuntimeException, array_map, basename, dirname, impl_php_class, implode, in_array_strict, is_dir, php_regex, preg_quote, preg_split, realpath, rtrim, strlen, strpos, @@ -95,26 +95,20 @@ impl GitDownloader { } let mut refs = trim(&output, None); - let mut head_match = PregMatchedGroups::new(); - if !Preg::is_match3( - php_regex!(r"{^([a-f0-9]+) HEAD$}mi"), - &refs, - Some(&mut head_match), - ) { + let Some(head_match) = Preg::is_match3(php_regex!(r"{^([a-f0-9]+) HEAD$}mi"), &refs) else { // could not match the HEAD for some reason return Ok(None); - } + }; let head_ref = head_match .get(&CaptureKey::ByIndex(1)) .cloned() .unwrap_or_default(); - let mut branches_match = PregMatchesAll::new(); - if !Preg::is_match_all( + let branches_match = Preg::is_match_all( format!("{{^{} refs/heads/(.+)$}}mi", preg_quote(&head_ref, None)), &refs, - &mut branches_match, - ) { + ); + if branches_match.occurrence_count() == 0 { // not on a branch, we are either on a not-modified tag or some sort of detached head, so skip this return Ok(None); } @@ -137,15 +131,14 @@ impl GitDownloader { // try to find matching branch names in remote repos for candidate in &candidate_branches { - let mut m = PregMatchesAll::new(); - if Preg::is_match_all( + let m = Preg::is_match_all( format!( "{{^[a-f0-9]+ refs/remotes/((?:[^/]+)/{})$}}mi", preg_quote(candidate, None) ), &refs, - &mut m, - ) { + ); + if m.occurrence_count() > 0 { let matches: Vec<Option<String>> = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); for match_ in matches { @@ -510,14 +503,12 @@ impl GitDownloader { fn set_push_url(&self, path: &str, url: &str) { // set push url for github projects - let mut match_ = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(match_) = Preg::is_match3( format!( "{{^(?:https?|git)://{}/([^/]+)/([^/]+?)(?:\\.git)?$}}", GitUtil::get_github_domains_regex(&self.inner.config.borrow()) ), url, - Some(&mut match_), ) { let protocols = self.inner.config.borrow_mut().get("github-protocols"); let m1 = match_ @@ -1114,31 +1105,23 @@ impl VcsDownloader for GitDownloader { &mut output, Some(&path), ) == 0 + && let Some(origin_match) = + Preg::is_match3(php_regex!(r"{^origin\s+(?P<url>\S+)}m"), &output) + && let Some(composer_match) = + Preg::is_match3(php_regex!(r"{^composer\s+(?P<url>\S+)}m"), &output) { - let mut origin_match = PregMatchedGroups::new(); - let mut composer_match = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!(r"{^origin\s+(?P<url>\S+)}m"), - &output, - Some(&mut origin_match), - ) && Preg::is_match3( - php_regex!(r"{^composer\s+(?P<url>\S+)}m"), - &output, - Some(&mut composer_match), - ) { - let origin_url = origin_match - .get(&CaptureKey::ByName("url".to_string())) - .cloned() - .unwrap_or_default(); - let composer_url = composer_match - .get(&CaptureKey::ByName("url".to_string())) - .cloned() - .unwrap_or_default(); - if origin_url == composer_url - && Some(composer_url.as_str()) != target.get_source_url().as_deref() - { - update_origin_url = true; - } + let origin_url = origin_match + .get(&CaptureKey::ByName("url".to_string())) + .cloned() + .unwrap_or_default(); + let composer_url = composer_match + .get(&CaptureKey::ByName("url".to_string())) + .cloned() + .unwrap_or_default(); + if origin_url == composer_url + && Some(composer_url.as_str()) != target.get_source_url().as_deref() + { + update_origin_url = true; } } if update_origin_url && target.get_source_url().is_some() { diff --git a/crates/shirabe/src/downloader/svn_downloader.rs b/crates/shirabe/src/downloader/svn_downloader.rs index 29662be8..ce908206 100644 --- a/crates/shirabe/src/downloader/svn_downloader.rs +++ b/crates/shirabe/src/downloader/svn_downloader.rs @@ -15,7 +15,7 @@ use crate::util::Filesystem; use crate::util::ProcessExecutor; use crate::util::Svn as SvnUtil; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ CmpOp, PhpMixed, RuntimeException, impl_php_class, is_dir, php_regex, preg_split, version_compare, @@ -383,8 +383,7 @@ impl VcsDownloader for SvnDownloader { } let url_pattern = "#<url>(.*)</url>#"; - let mut matches = PregMatchedGroups::new(); - let base_url = if Preg::match3(url_pattern, &output, Some(&mut matches)) { + let base_url = if let Some(matches) = Preg::match3(url_pattern, &output) { matches .get(&CaptureKey::ByIndex(1)) .cloned() diff --git a/crates/shirabe/src/downloader/zip_downloader.rs b/crates/shirabe/src/downloader/zip_downloader.rs index 91078dc9..cefada15 100644 --- a/crates/shirabe/src/downloader/zip_downloader.rs +++ b/crates/shirabe/src/downloader/zip_downloader.rs @@ -8,7 +8,7 @@ use crate::package::PackageInterfaceHandle; use crate::util::IniHelper; use crate::util::Platform; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ CmpOp, ErrorException, PhpMixed, RuntimeException, UnexpectedValueException, ZipArchive, @@ -113,20 +113,15 @@ impl ZipDownloader { .execute(&[command_spec[1].as_str()], &mut output, None::<&str>) .unwrap_or(1) == 0 + && let Some(m) = + Preg::is_match3(php_regex!(r"{^\s*7-Zip(?:\s\[64\])?\s([0-9.]+)}"), &output) { - let mut m = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!(r"{^\s*7-Zip(?:\s\[64\])?\s([0-9.]+)}"), - &output, - Some(&mut m), - ) { - let m1 = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); - 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, - )); - } + let m1 = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); + 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/event_dispatcher/event_dispatcher.rs b/crates/shirabe/src/event_dispatcher/event_dispatcher.rs index c1a7d8f9..f03f82db 100644 --- a/crates/shirabe/src/event_dispatcher/event_dispatcher.rs +++ b/crates/shirabe/src/event_dispatcher/event_dispatcher.rs @@ -21,7 +21,7 @@ use crate::script::Event as ScriptEvent; use crate::util::Platform; use crate::util::ProcessExecutor; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_rpc::{ PhpThrow, PluginValue, RustMethodDispatcher, RustObjHandle, call_function, call_function_with_dispatcher, call_php_method, call_static_method, @@ -962,12 +962,9 @@ try {{ } // match somename (not in quote, and not a qualified path) and if it is not a valid path from CWD then try to find it // in $PATH. This allows support for `@php foo` where foo is a binary name found in PATH but not an actual relative path - let mut m = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!("{^[^\\'\"\\s/\\\\]+}"), - &path_and_args, - Some(&mut m), - ) { + if let Some(m) = + Preg::is_match3(php_regex!("{^[^\\'\"\\s/\\\\]+}"), &path_and_args) + { let m0 = m.get(&CaptureKey::ByIndex(0)).cloned().unwrap_or_default(); if !file_exists(&m0) { diff --git a/crates/shirabe/src/installer/binary_installer.rs b/crates/shirabe/src/installer/binary_installer.rs index 606e943f..9a7a2153 100644 --- a/crates/shirabe/src/installer/binary_installer.rs +++ b/crates/shirabe/src/installer/binary_installer.rs @@ -8,7 +8,7 @@ use crate::util::Filesystem; use crate::util::Platform; use crate::util::ProcessExecutor; use crate::util::Silencer; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ PhpMixed, basename, basename_with_suffix, chmod, dirname, fclose, fgets, file_exists, file_get_contents5, file_put_contents, fopen, is_dir, is_file, is_link, php_regex, realpath, @@ -201,11 +201,9 @@ impl BinaryInstaller { } Err(_) => String::new(), }; - let mut m = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(m) = Preg::is_match3( php_regex!(r"{^#!/(?:usr/bin/env )?(?:[^/]+/)*(.+)$}m"), &line, - Some(&mut m), ) { return trim( m.get(&CaptureKey::ByIndex(1)) diff --git a/crates/shirabe/src/json/json_file.rs b/crates/shirabe/src/json/json_file.rs index 040f472a..ca8b11e0 100644 --- a/crates/shirabe/src/json/json_file.rs +++ b/crates/shirabe/src/json/json_file.rs @@ -8,7 +8,7 @@ use crate::json::JsonValidationException; use crate::util::Filesystem; use crate::util::HttpDownloader; use crate::util::Silencer; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ InvalidArgumentException, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE, @@ -554,12 +554,7 @@ impl JsonFile { } pub fn detect_indenting(json: Option<&str>) -> String { - let mut m = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!(r##"#^([ \t]+)"#m"##), - json.unwrap_or(""), - Some(&mut m), - ) { + if let Some(m) = Preg::is_match3(php_regex!(r##"#^([ \t]+)"#m"##), json.unwrap_or("")) { return m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); } diff --git a/crates/shirabe/src/json/json_manipulator.rs b/crates/shirabe/src/json/json_manipulator.rs index 425eb192..c58f316d 100644 --- a/crates/shirabe/src/json/json_manipulator.rs +++ b/crates/shirabe/src/json/json_manipulator.rs @@ -4,7 +4,7 @@ use crate::json::JsonFile; use crate::json::json_grammar::{self, ValueKind}; use crate::repository::PlatformRepository; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups, PregNamedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ InvalidArgumentException, LogicException, PhpMixed, addcslashes, array_key_exists, array_keys, array_reverse, empty, explode, implode, in_array_loose, is_array, is_int, is_numeric, @@ -35,7 +35,7 @@ impl JsonManipulator { if contents.is_empty() { contents = "{}".to_string(); } - if !Preg::is_match3(php_regex!("#^\\{(.*)\\}$#s"), &contents, None) { + if Preg::is_match3(php_regex!("#^\\{(.*)\\}$#s"), &contents).is_none() { return Err(InvalidArgumentException::new( "The json file must be an object ({})".to_string(), ) @@ -112,12 +112,9 @@ impl JsonManipulator { &links[value_end..] ); } else { - let mut groups = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!("#^\\s*\\{\\s*\\S+.*?(\\s*\\}\\s*)$#s"), - &links, - Some(&mut groups), - ) { + if let Some(groups) = + Preg::is_match3(php_regex!("#^\\s*\\{\\s*\\S+.*?(\\s*\\}\\s*)$#s"), &links) + { let groups_1 = groups .get(&CaptureKey::ByIndex(1)) .cloned() @@ -740,13 +737,11 @@ impl JsonManipulator { &children[cm.value_end..] ); } else { - let mut leading_match = PregNamedGroups::new(); - if Preg::is_match_named( + if let Some(leading_match) = Preg::is_match_named( php_regex!( "#^\\{(?P<leadingspace>\\s*?)(?P<content>\\S+.*?)?(?P<trailingspace>\\s*)\\}$#s" ), &children, - &mut leading_match, ) { let mut whitespace = leading_match .get("trailingspace") @@ -899,7 +894,7 @@ impl JsonManipulator { // try and find a match for the subkey let key_regex = str_replace("/", "\\\\?/", &preg_quote(&name_owned, None)); let mut children_clean: Option<String> = None; - if Preg::is_match3(format!("{{\"{}\"\\s*:}}i", key_regex), &children, None) { + if Preg::is_match3(format!("{{\"{}\"\\s*:}}i", key_regex), &children).is_some() { // find best match for the value of "name". The PHP pattern `"name"\s*:\s*(?&json)` is // not anchored, so it can match the key at several nesting levels; collect every such // occurrence and keep the longest, reproducing PHP's behaviour. @@ -942,11 +937,9 @@ impl JsonManipulator { let children_clean = children_clean.ok_or_else(|| InvalidArgumentException::new("JsonManipulator: $childrenClean is not defined. Please report at https://github.com/nsfisis/php-shirabe/issues/new.".to_string()))?; // no child data left, $name was the only key in - let mut empty_match = PregNamedGroups::new(); - if Preg::is_match_named( + if let Some(empty_match) = Preg::is_match_named( php_regex!("#^\\{\\s*?(?P<content>\\S+.*?)?(?P<trailingspace>\\s*)\\}$#s"), &children_clean, - &mut empty_match, ) && empty_match.get("content").is_none() { self.contents = format!( @@ -1039,13 +1032,11 @@ impl JsonManipulator { return Ok(false); } - let mut leading_match = PregNamedGroups::new(); - if Preg::is_match_named( + if let Some(leading_match) = Preg::is_match_named( php_regex!( "#^\\[(?P<leadingspace>\\s*?)(?P<content>\\S+.*?)?(?P<trailingspace>\\s*)\\]$#s" ), &children, - &mut leading_match, ) { let leading_whitespace = leading_match .get("leadingspace") @@ -1330,12 +1321,8 @@ impl JsonManipulator { } // append at the end of the file and keep whitespace - let mut tail_match = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!("#[^{\\s](\\s*)\\}$#"), - &self.contents, - Some(&mut tail_match), - ) { + if let Some(tail_match) = Preg::is_match3(php_regex!("#[^{\\s](\\s*)\\}$#"), &self.contents) + { let tail_match_1 = tail_match .get(&CaptureKey::ByIndex(1)) .cloned() @@ -1411,8 +1398,8 @@ impl JsonManipulator { // check that we are not leaving a dangling comma on the previous line if the last line was removed let mut start = self.contents[..m.key_pos].to_string(); let end = self.contents[e..].to_string(); - if Preg::is_match3(php_regex!("#,\\s*$#"), &start, None) - && Preg::is_match3(php_regex!("#^\\}$#"), &end, None) + if Preg::is_match3(php_regex!("#,\\s*$#"), &start).is_some() + && Preg::is_match3(php_regex!("#^\\}$#"), &end).is_some() { start = rtrim( &Preg::replace(php_regex!("#,(\\s*)$#"), "$1", &start), @@ -1421,7 +1408,7 @@ impl JsonManipulator { } self.contents = format!("{}{}", start, end); - if Preg::is_match3(php_regex!("#^\\{\\s*\\}\\s*$#"), &self.contents, None) { + if Preg::is_match3(php_regex!("#^\\{\\s*\\}\\s*$#"), &self.contents).is_some() { self.contents = "{\n}".to_string(); } diff --git a/crates/shirabe/src/package/loader/root_package_loader.rs b/crates/shirabe/src/package/loader/root_package_loader.rs index bbcf294f..b7216c62 100644 --- a/crates/shirabe/src/package/loader/root_package_loader.rs +++ b/crates/shirabe/src/package/loader/root_package_loader.rs @@ -15,7 +15,7 @@ use crate::repository::RepositoryManager; use crate::util::Platform; use crate::util::ProcessExecutor; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ PhpMixed, RuntimeException, UnexpectedValueException, php_regex, preg_split, strtolower, }; @@ -252,11 +252,9 @@ impl RootPackageLoader { mut aliases: Vec<IndexMap<String, String>>, ) -> Vec<IndexMap<String, String>> { for (req_name, req_version) in requires { - let mut m = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(m) = Preg::is_match3( php_regex!(r"{(?:^|\| *|, *)([^,\s#|]+)(?:#[^ ]+)? +as +([^,\s|]+)(?:$| *\|| *,)}"), req_version, - Some(&mut m), ) { let m1 = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); let m2 = m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default(); @@ -318,8 +316,7 @@ impl RootPackageLoader { let mut matched = false; for constraint in &constraints { - let mut m = PregMatchedGroups::new(); - if Preg::is_match3(&pattern, constraint, Some(&mut m)) { + if let Some(m) = Preg::is_match3(&pattern, constraint) { let name = strtolower(req_name); let m1 = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); let normalized_m1 = VersionParser::normalize_stability(&m1).unwrap_or_default(); @@ -365,12 +362,8 @@ impl RootPackageLoader { ) -> IndexMap<String, String> { for (req_name, req_version) in requires { let req_version = Preg::replace(php_regex!(r"{^([^,\s@]+) as .+$}"), "$1", req_version); - let mut m = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!(r"{^[^,\s@]+?#([a-f0-9]+)$}"), - &req_version, - Some(&mut m), - ) && VersionParser::parse_stability(&req_version) == "dev" + if let Some(m) = Preg::is_match3(php_regex!(r"{^[^,\s@]+?#([a-f0-9]+)$}"), &req_version) + && VersionParser::parse_stability(&req_version) == "dev" { let name = strtolower(req_name); references.insert( diff --git a/crates/shirabe/src/package/locker.rs b/crates/shirabe/src/package/locker.rs index 5c99b967..6e7145ae 100644 --- a/crates/shirabe/src/package/locker.rs +++ b/crates/shirabe/src/package/locker.rs @@ -24,7 +24,7 @@ use crate::repository::RootPackageRepository; use crate::util::Git as GitUtil; use crate::util::ProcessExecutor; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ DATE_RFC3339, LogicException, PhpMixed, RuntimeException, array_intersect, array_keys, @@ -843,21 +843,17 @@ impl Locker { ]), &mut output, path.as_deref(), - )? { - let mut m = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!(r"{^\s*(\d+)\s*}"), - output.as_string().unwrap_or(""), - Some(&mut m), - ) { - let ts = m - .get(&CaptureKey::ByIndex(1)) - .cloned() - .unwrap_or_default() - .parse::<i64>() - .unwrap_or(0); - datetime = chrono::DateTime::from_timestamp(ts, 0); - } + )? && let Some(m) = Preg::is_match3( + php_regex!(r"{^\s*(\d+)\s*}"), + output.as_string().unwrap_or(""), + ) { + let ts = m + .get(&CaptureKey::ByIndex(1)) + .cloned() + .unwrap_or_default() + .parse::<i64>() + .unwrap_or(0); + datetime = chrono::DateTime::from_timestamp(ts, 0); } } _ => {} diff --git a/crates/shirabe/src/package/version/version_bumper.rs b/crates/shirabe/src/package/version/version_bumper.rs index dbeff6a0..6911fb14 100644 --- a/crates/shirabe/src/package/version/version_bumper.rs +++ b/crates/shirabe/src/package/version/version_bumper.rs @@ -5,7 +5,7 @@ use crate::package::dumper::ArrayDumper; use crate::package::loader::ArrayLoader; use crate::package::version::VersionParser; use crate::util::Platform; -use shirabe_pcre::{CaptureKey, Preg, PregMatchesAllWithOffsets}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::php_regex; use shirabe_semver::Intervals; use shirabe_semver::constraint::AnyConstraint; @@ -77,8 +77,8 @@ impl VersionBumper { major = major ); - let mut matches = PregMatchesAllWithOffsets::new(); - if Preg::is_match_all_with_offsets3(&pattern, &pretty_constraint, Some(&mut matches)) { + let matches = Preg::is_match_all_with_offsets3(&pattern, &pretty_constraint); + if matches.occurrence_count() > 0 { let mut modified = pretty_constraint.clone(); let constraint_matches = matches .get(&CaptureKey::ByName("constraint".to_string())) diff --git a/crates/shirabe/src/package/version/version_guesser.rs b/crates/shirabe/src/package/version/version_guesser.rs index 4b5187f2..14fcf5f6 100644 --- a/crates/shirabe/src/package/version/version_guesser.rs +++ b/crates/shirabe/src/package/version/version_guesser.rs @@ -12,7 +12,7 @@ use crate::util::ProcessExecutor; use crate::util::Svn as SvnUtil; use crate::util::sync_executor; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ PhpMixed, RuntimeException, array_keys, array_map, array_merge, empty, function_exists, implode, is_string, json_encode, php_regex, preg_quote, str_replace, strlen, strnatcasecmp, @@ -228,49 +228,43 @@ impl VersionGuesser { // find current branch and collect all branch names for branch in self.process.borrow().split_lines(&output) { - if !branch.is_empty() { - let mut m = PregMatchedGroups::new(); - if Preg::is_match3( + if !branch.is_empty() + && let Some(m) = Preg::is_match3( php_regex!( r"{^(?:\* ) *(\(no branch\)|\(detached from \S+\)|\(HEAD detached at \S+\)|\S+) *([a-f0-9]+) .*$}" ), &branch, - Some(&mut m), - ) { - let g1 = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); - let g2 = m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default(); - if g1 == "(no branch)" - || strpos(&g1, "(detached ") == Some(0) - || strpos(&g1, "(HEAD detached at") == Some(0) - { - version = Some(format!("dev-{}", g2)); - pretty_version = version.clone(); - is_feature_branch = true; - is_detached = true; - } else { - version = Some(self.version_parser.normalize_branch(&g1)?); - pretty_version = Some(format!("dev-{}", g1)); - is_feature_branch = self.is_feature_branch(package_config, Some(&g1)); - } - - commit = Some(g2); + ) + { + let g1 = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); + let g2 = m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default(); + if g1 == "(no branch)" + || strpos(&g1, "(detached ") == Some(0) + || strpos(&g1, "(HEAD detached at") == Some(0) + { + version = Some(format!("dev-{}", g2)); + pretty_version = version.clone(); + is_feature_branch = true; + is_detached = true; + } else { + version = Some(self.version_parser.normalize_branch(&g1)?); + pretty_version = Some(format!("dev-{}", g1)); + is_feature_branch = self.is_feature_branch(package_config, Some(&g1)); } + + commit = Some(g2); } - if !branch.is_empty() && { - let mut tmp = PregMatchedGroups::new(); - !Preg::is_match3(php_regex!(r"{^ *.+/HEAD }"), &branch, Some(&mut tmp)) - } { - let mut m = PregMatchedGroups::new(); - if Preg::is_match3( + if !branch.is_empty() + && Preg::is_match3(php_regex!(r"{^ *.+/HEAD }"), &branch).is_none() + && let Some(m) = Preg::is_match3( php_regex!( r"{^(?:\* )? *((?:remotes/(?:origin|upstream)/)?[^\s/]+) *([a-f0-9]+) .*$}" ), &branch, - Some(&mut m), - ) { - branches.push(m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default()); - } + ) + { + branches.push(m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default()); } } @@ -756,12 +750,7 @@ impl VersionGuesser { .into()); } }; - let mut m = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!(r"{^(\d+(?:\.\d+)*)-dev$}i"), - &version, - Some(&mut m), - ) { + if let Some(m) = Preg::is_match3(php_regex!(r"{^(\d+(?:\.\d+)*)-dev$}i"), &version) { return Ok(format!( "{}.x-dev", m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default() diff --git a/crates/shirabe/src/platform/version.rs b/crates/shirabe/src/platform/version.rs index 2bcb4c38..b89d052b 100644 --- a/crates/shirabe/src/platform/version.rs +++ b/crates/shirabe/src/platform/version.rs @@ -1,6 +1,6 @@ //! ref: composer/src/Composer/Platform/Version.php -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::{CmpOp, php_regex, version_compare}; pub struct Version; @@ -9,16 +9,12 @@ impl Version { pub fn parse_openssl(openssl_version: &str, is_fips: &mut bool) -> Option<String> { *is_fips = false; - let mut matches = PregMatchedGroups::new(); - if !Preg::match3( + let matches = Preg::match3( php_regex!( r"/^(?P<version>[0-9.]+)(?P<patch>[a-z]{0,2})(?P<suffix>(?:-?(?:dev|pre|alpha|beta|rc|fips)[\d]*)*)(?:-\w+)?(?: \(.+?\))?$/" ), openssl_version, - Some(&mut matches), - ) { - return None; - } + )?; let version = matches .get(&CaptureKey::ByName("version".to_string())) @@ -55,14 +51,10 @@ impl Version { } pub fn parse_libjpeg(libjpeg_version: &str) -> Option<String> { - let mut matches = PregMatchedGroups::new(); - if !Preg::match3( + let matches = Preg::match3( php_regex!(r"/^(?P<major>\d+)(?P<minor>[a-z]*)$/"), libjpeg_version, - Some(&mut matches), - ) { - return None; - } + )?; let major = matches .get(&CaptureKey::ByName("major".to_string())) @@ -80,14 +72,10 @@ impl Version { } pub fn parse_zoneinfo_version(zoneinfo_version: &str) -> Option<String> { - let mut matches = PregMatchedGroups::new(); - if !Preg::match3( + let matches = Preg::match3( php_regex!(r"/^(?P<year>\d{4})(?P<revision>[a-z]*)$/"), zoneinfo_version, - Some(&mut matches), - ) { - return None; - } + )?; let year = matches .get(&CaptureKey::ByName("year".to_string())) diff --git a/crates/shirabe/src/plugin/plugin_manager.rs b/crates/shirabe/src/plugin/plugin_manager.rs index b02a702d..0ebc56e6 100644 --- a/crates/shirabe/src/plugin/plugin_manager.rs +++ b/crates/shirabe/src/plugin/plugin_manager.rs @@ -260,7 +260,7 @@ impl PluginManager { } if package.get_name() == "symfony/flex" - && Preg::is_match3(php_regex!("{^[0-9.]+$}"), &package.get_version(), None) + && Preg::is_match3(php_regex!("{^[0-9.]+$}"), &package.get_version()).is_some() && 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>", @@ -1242,7 +1242,7 @@ impl PluginManager { .map(|(k, v)| (k.clone(), *v)) .collect(); for (pattern, allow) in &rules_snapshot { - if Preg::is_match3(pattern, package, None) { + if Preg::is_match3(pattern, package).is_some() { return Ok(*allow); } } diff --git a/crates/shirabe/src/repository/composer_repository.rs b/crates/shirabe/src/repository/composer_repository.rs index 33703709..6feb4359 100644 --- a/crates/shirabe/src/repository/composer_repository.rs +++ b/crates/shirabe/src/repository/composer_repository.rs @@ -37,7 +37,7 @@ use futures::StreamExt; use futures::stream::FuturesOrdered; use indexmap::IndexMap; use shirabe_metadata_minifier::MetadataMinifier; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ AnyThrowable, CmpOp, InvalidArgumentException, LogicException, PHP_EOL, PhpMixed, @@ -245,11 +245,9 @@ impl ComposerRepository { .to_string(); // force url for packagist.org to repo.packagist.org - let mut match_packagist = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(match_packagist) = Preg::is_match3( php_regex!(r"{^(?P<proto>https?)://packagist\.org/?$}i"), &url, - Some(&mut match_packagist), ) { let proto = match_packagist .get(&CaptureKey::ByName("proto".to_string())) @@ -781,11 +779,9 @@ impl ComposerRepository { if self.has_providers()? || self.lazy_providers_url.is_some() { // optimize search for "^foo/bar" where at least "^foo/" is present by loading this directly from the listUrl if present - let mut match_groups = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(match_groups) = Preg::is_match3( php_regex!(r"{^\^(?P<query>(?P<vendor>[a-z0-9_.-]+)/[a-z0-9_.-]*)\*?$}i"), &query, - Some(&mut match_groups), ) && let Some(list_url) = self.list_url.as_ref() { let q = match_groups @@ -2430,12 +2426,7 @@ impl ComposerRepository { } if url.starts_with('/') { - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!(r"{^[^:]++://[^/]*+}"), - &self.url, - Some(&mut matches), - ) { + if let Some(matches) = Preg::is_match3(php_regex!(r"{^[^:]++://[^/]*+}"), &self.url) { return Ok(format!( "{}{}", matches diff --git a/crates/shirabe/src/repository/platform_repository.rs b/crates/shirabe/src/repository/platform_repository.rs index 6c25d967..29f66647 100644 --- a/crates/shirabe/src/repository/platform_repository.rs +++ b/crates/shirabe/src/repository/platform_repository.rs @@ -16,7 +16,7 @@ use crate::plugin::plugin_interface::{self}; use crate::repository::ArrayRepository; use crate::repository::RepositoryInterface; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_rpc::PlatformInfo; use shirabe_php_shim::{ InvalidArgumentException, PhpMixed, UnexpectedValueException, array_map_str_fn, @@ -316,11 +316,9 @@ impl PlatformRepository { let info = platform_info.get_extension_info(name); // librabbitmq version => 0.9.0 - let mut librabbitmq_matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(librabbitmq_matches) = Preg::is_match3( php_regex!("/^librabbitmq version => (?<version>.+)$/im"), info, - Some(&mut librabbitmq_matches), ) { self.add_library( &mut libraries, @@ -335,11 +333,9 @@ impl PlatformRepository { } // AMQP protocol version => 0-9-1 - let mut protocol_matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(protocol_matches) = Preg::is_match3( php_regex!("/^AMQP protocol version => (?<version>.+)$/im"), info, - Some(&mut protocol_matches), ) { let version_str = protocol_matches .get(&CaptureKey::ByName("version".to_string())) @@ -360,12 +356,9 @@ impl PlatformRepository { let info = platform_info.get_extension_info(name); // BZip2 Version => 1.0.6, 6-Sept-2010 - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!("/^BZip2 Version => (?<version>.*),/im"), - info, - Some(&mut matches), - ) { + if let Some(matches) = + Preg::is_match3(php_regex!("/^BZip2 Version => (?<version>.*),/im"), info) + { self.add_library( &mut libraries, name, @@ -393,11 +386,9 @@ impl PlatformRepository { let info = platform_info.get_extension_info(name); // SSL Version => OpenSSL/1.0.1t - let mut ssl_matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(ssl_matches) = Preg::is_match3( php_regex!("{^SSL Version => (?<library>[^/]+)/(?<version>.+)$}im"), info, - Some(&mut ssl_matches), ) { let ssl_library_raw = ssl_matches .get(&CaptureKey::ByName("library".to_string())) @@ -428,11 +419,9 @@ impl PlatformRepository { } else { let (shortlib, ssl_lib); if library.starts_with("(securetransport)") { - let mut securetransport_matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(securetransport_matches) = Preg::is_match3( php_regex!("{^\\(securetransport\\) ([a-z0-9]+)}"), &library, - Some(&mut securetransport_matches), ) { shortlib = "securetransport".to_string(); let m1 = securetransport_matches @@ -460,13 +449,11 @@ impl PlatformRepository { } // libSSH Version => libssh2/1.4.3 - let mut ssh_matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(ssh_matches) = Preg::is_match3( php_regex!( "{^libSSH Version => (?<library>[^/]+)/(?<version>.+?)(?:/.*)?$}im" ), info, - Some(&mut ssh_matches), ) { let ssh_library = ssh_matches .get(&CaptureKey::ByName("library".to_string())) @@ -487,12 +474,9 @@ impl PlatformRepository { } // ZLib Version => 1.2.8 - let mut zlib_matches = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!("{^ZLib Version => (?<version>.+)$}im"), - info, - Some(&mut zlib_matches), - ) { + if let Some(zlib_matches) = + Preg::is_match3(php_regex!("{^ZLib Version => (?<version>.+)$}im"), info) + { self.add_library( &mut libraries, &format!("{}-zlib", name), @@ -510,12 +494,9 @@ impl PlatformRepository { let info = platform_info.get_extension_info(name); // timelib version => 2018.03 - let mut timelib_matches = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!("/^timelib version => (?<version>.+)$/im"), - info, - Some(&mut timelib_matches), - ) { + if let Some(timelib_matches) = + Preg::is_match3(php_regex!("/^timelib version => (?<version>.+)$/im"), info) + { self.add_library( &mut libraries, &format!("{}-timelib", name), @@ -529,23 +510,19 @@ impl PlatformRepository { } // Timezone Database => internal - let mut zoneinfo_source_matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(zoneinfo_source_matches) = Preg::is_match3( php_regex!("/^Timezone Database => (?<source>internal|external)$/im"), info, - Some(&mut zoneinfo_source_matches), ) { let external = zoneinfo_source_matches .get(&CaptureKey::ByName("source".to_string())) .map(|s| s == "external") .unwrap_or(false); - let mut zoneinfo_matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(zoneinfo_matches) = Preg::is_match3( php_regex!( "/^\"Olson\" Timezone Database Version => (?<version>.+?)(?:\\.system)?$/im" ), info, - Some(&mut zoneinfo_matches), ) { let zoneinfo_version = zoneinfo_matches .get(&CaptureKey::ByName("version".to_string())) @@ -554,15 +531,15 @@ impl PlatformRepository { // If the timezonedb is provided by ext/timezonedb, register that version as a replacement if external && loaded_extensions.iter().any(|n| n == "timezonedb") { self.add_library( - &mut libraries, - "timezonedb-zoneinfo", - Some(&zoneinfo_version), - Some( - "zoneinfo (\"Olson\") database for date (replaced by timezonedb)", - ), - &[format!("{}-zoneinfo", name)], - &[], - )?; + &mut libraries, + "timezonedb-zoneinfo", + Some(&zoneinfo_version), + Some( + "zoneinfo (\"Olson\") database for date (replaced by timezonedb)", + ), + &[format!("{}-zoneinfo", name)], + &[], + )?; } else { self.add_library( &mut libraries, @@ -581,12 +558,9 @@ impl PlatformRepository { let info = platform_info.get_extension_info(name); // libmagic => 537 - let mut magic_matches = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!("/^libmagic => (?<version>.+)$/im"), - info, - Some(&mut magic_matches), - ) { + if let Some(magic_matches) = + Preg::is_match3(php_regex!("/^libmagic => (?<version>.+)$/im"), info) + { self.add_library( &mut libraries, &format!("{}-libmagic", name), @@ -617,11 +591,9 @@ impl PlatformRepository { let info = platform_info.get_extension_info(name); - let mut libjpeg_matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(libjpeg_matches) = Preg::is_match3( php_regex!("/^libJPEG Version => (?<version>.+?)(?: compatible)?$/im"), info, - Some(&mut libjpeg_matches), ) { let libjpeg_version = libjpeg_matches .get(&CaptureKey::ByName("version".to_string())) @@ -638,12 +610,9 @@ impl PlatformRepository { )?; } - let mut libpng_matches = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!("/^libPNG Version => (?<version>.+)$/im"), - info, - Some(&mut libpng_matches), - ) { + if let Some(libpng_matches) = + Preg::is_match3(php_regex!("/^libPNG Version => (?<version>.+)$/im"), info) + { self.add_library( &mut libraries, &format!("{}-libpng", name), @@ -656,11 +625,9 @@ impl PlatformRepository { )?; } - let mut freetype_matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(freetype_matches) = Preg::is_match3( php_regex!("/^FreeType Version => (?<version>.+)$/im"), info, - Some(&mut freetype_matches), ) { self.add_library( &mut libraries, @@ -674,11 +641,9 @@ impl PlatformRepository { )?; } - let mut libxpm_matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(libxpm_matches) = Preg::is_match3( php_regex!("/^libXpm Version => (?<versionId>\\d+)$/im"), info, - Some(&mut libxpm_matches), ) { let version_id: i64 = libxpm_matches .get(&CaptureKey::ByName("versionId".to_string())) @@ -748,12 +713,9 @@ impl PlatformRepository { &[], )?; } else { - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!("/^ICU version => (?<version>.+)$/im"), - info, - Some(&mut matches), - ) { + if let Some(matches) = + Preg::is_match3(php_regex!("/^ICU version => (?<version>.+)$/im"), info) + { self.add_library( &mut libraries, "icu", @@ -768,11 +730,9 @@ impl PlatformRepository { } // ICU TZData version => 2019c - let mut zoneinfo_matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(zoneinfo_matches) = Preg::is_match3( php_regex!("/^ICU TZData version => (?<version>.*)$/im"), info, - Some(&mut zoneinfo_matches), ) { let zi_version = zoneinfo_matches .get(&CaptureKey::ByName("version".to_string())) @@ -833,11 +793,9 @@ impl PlatformRepository { Self::imagick_get_version_string(image_magick_version); // 6.x: ImageMagick 6.2.9 08/24/06 Q16 http://www.imagemagick.org // 7.x: ImageMagick 7.0.8-34 Q16 x86_64 2019-03-23 https://imagemagick.org - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(matches) = Preg::is_match3( php_regex!("/^ImageMagick (?<version>[\\d.]+)(?:-(?<patch>\\d+))?/"), &image_magick_version_str, - Some(&mut matches), ) { let mut version_built = matches .get(&CaptureKey::ByName("version".to_string())) @@ -861,17 +819,12 @@ impl PlatformRepository { "ldap" => { let info = platform_info.get_extension_info(name); - let mut matches = PregMatchedGroups::new(); - let mut vendor_matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(matches) = Preg::is_match3( php_regex!("/^Vendor Version => (?<versionId>\\d+)$/im"), info, - Some(&mut matches), - ) && Preg::is_match3( - php_regex!("/^Vendor Name => (?<vendor>.+)$/im"), - info, - Some(&mut vendor_matches), - ) { + ) && let Some(vendor_matches) = + Preg::is_match3(php_regex!("/^Vendor Name => (?<vendor>.+)$/im"), info) + { let version_id: i64 = matches .get(&CaptureKey::ByName("versionId".to_string())) .and_then(|s| s.parse().ok()) @@ -921,12 +874,9 @@ impl PlatformRepository { let info = platform_info.get_extension_info(name); // libmbfl version => 1.3.2 - let mut libmbfl_matches = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!("/^libmbfl version => (?<version>.+)$/im"), - info, - Some(&mut libmbfl_matches), - ) { + if let Some(libmbfl_matches) = + Preg::is_match3(php_regex!("/^libmbfl version => (?<version>.+)$/im"), info) + { self.add_library( &mut libraries, &format!("{}-libmbfl", name), @@ -957,13 +907,11 @@ impl PlatformRepository { // Multibyte regex (oniguruma) version => 5.9.5 // oniguruma version => 6.9.0 } else { - let mut oniguruma_matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(oniguruma_matches) = Preg::is_match3( php_regex!( "/^(?:oniguruma|Multibyte regex \\(oniguruma\\)) version => (?<version>.+)$/im" ), info, - Some(&mut oniguruma_matches), ) { self.add_library( &mut libraries, @@ -983,11 +931,9 @@ impl PlatformRepository { let info = platform_info.get_extension_info(name); // libmemcached version => 1.0.18 - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(matches) = Preg::is_match3( php_regex!("/^libmemcached version => (?<version>.+)$/im"), info, - Some(&mut matches), ) { self.add_library( &mut libraries, @@ -1009,11 +955,9 @@ impl PlatformRepository { _ => "".to_string(), }; // OpenSSL 1.1.1g 21 Apr 2020 - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(matches) = Preg::is_match3( php_regex!("{^(?:OpenSSL|LibreSSL)?\\s*(?<version>\\S+)}i"), &openssl_text_str, - Some(&mut matches), ) { let version = matches .get(&CaptureKey::ByName("version".to_string())) @@ -1050,11 +994,9 @@ impl PlatformRepository { let info = platform_info.get_extension_info(name); // PCRE Unicode Version => 12.1.0 - let mut pcre_unicode_matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(pcre_unicode_matches) = Preg::is_match3( php_regex!("/^PCRE Unicode Version => (?<version>.+)$/im"), info, - Some(&mut pcre_unicode_matches), ) { self.add_library( &mut libraries, @@ -1072,13 +1014,11 @@ impl PlatformRepository { "mysqlnd" | "pdo_mysql" => { let info = platform_info.get_extension_info(name); - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(matches) = Preg::is_match3( php_regex!( "/^(?:Client API version|Version) => mysqlnd (?<version>.+?) /mi" ), info, - Some(&mut matches), ) { self.add_library( &mut libraries, @@ -1096,11 +1036,9 @@ impl PlatformRepository { "mongodb" => { let info = platform_info.get_extension_info(name); - let mut libmongoc_matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(libmongoc_matches) = Preg::is_match3( php_regex!("/^libmongoc bundled version => (?<version>.+)$/im"), info, - Some(&mut libmongoc_matches), ) { self.add_library( &mut libraries, @@ -1114,11 +1052,9 @@ impl PlatformRepository { )?; } - let mut libbson_matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(libbson_matches) = Preg::is_match3( php_regex!("/^libbson bundled version => (?<version>.+)$/im"), info, - Some(&mut libbson_matches), ) { self.add_library( &mut libraries, @@ -1152,11 +1088,9 @@ impl PlatformRepository { // intentional fall-through to next case... let info = platform_info.get_extension_info(name); - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(matches) = Preg::is_match3( php_regex!("/^PostgreSQL\\(libpq\\) Version => (?<version>.*)$/im"), info, - Some(&mut matches), ) { self.add_library( &mut libraries, @@ -1175,11 +1109,9 @@ impl PlatformRepository { "pdo_pgsql" => { let info = platform_info.get_extension_info(name); - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(matches) = Preg::is_match3( php_regex!("/^PostgreSQL\\(libpq\\) Version => (?<version>.*)$/im"), info, - Some(&mut matches), ) { self.add_library( &mut libraries, @@ -1199,11 +1131,9 @@ impl PlatformRepository { // Used Library => Compiled => Linked // libpq => 14.3 (Ubuntu 14.3-1.pgdg22.04+1) => 15.0.2 - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(matches) = Preg::is_match3( php_regex!("/^libpq => (?<compiled>.+) => (?<linked>.+)$/im"), info, - Some(&mut matches), ) { self.add_library( &mut libraries, @@ -1277,12 +1207,9 @@ impl PlatformRepository { "sqlite3" | "pdo_sqlite" => { let info = platform_info.get_extension_info(name); - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!("/^SQLite Library => (?<version>.+)$/im"), - info, - Some(&mut matches), - ) { + if let Some(matches) = + Preg::is_match3(php_regex!("/^SQLite Library => (?<version>.+)$/im"), info) + { self.add_library( &mut libraries, &format!("{}-sqlite", name), @@ -1299,12 +1226,9 @@ impl PlatformRepository { "ssh2" => { let info = platform_info.get_extension_info(name); - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!("/^libssh2 version => (?<version>.+)$/im"), - info, - Some(&mut matches), - ) { + if let Some(matches) = + Preg::is_match3(php_regex!("/^libssh2 version => (?<version>.+)$/im"), info) + { self.add_library( &mut libraries, &format!("{}-libssh2", name), @@ -1335,13 +1259,11 @@ impl PlatformRepository { )?; let info = platform_info.get_extension_info("xsl"); - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(matches) = Preg::is_match3( php_regex!( "/^libxslt compiled against libxml Version => (?<version>.+)$/im" ), info, - Some(&mut matches), ) { self.add_library( &mut libraries, @@ -1359,12 +1281,9 @@ impl PlatformRepository { "yaml" => { let info = platform_info.get_extension_info("yaml"); - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!("/^LibYAML Version => (?<version>.+)$/im"), - info, - Some(&mut matches), - ) { + if let Some(matches) = + Preg::is_match3(php_regex!("/^LibYAML Version => (?<version>.+)$/im"), info) + { self.add_library( &mut libraries, &format!("{}-libyaml", name), @@ -1416,11 +1335,9 @@ impl PlatformRepository { // Linked Version => 1.2.8 } else { let info = platform_info.get_extension_info(name); - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(matches) = Preg::is_match3( php_regex!("/^Linked Version => (?<version>.+)$/im"), info, - Some(&mut matches), ) { self.add_library( &mut libraries, @@ -1619,11 +1536,9 @@ impl PlatformRepository { Ok(v) => v, Err(_) => { extra_description = Some(format!(" (actual version: {})", pretty_version)); - let mut m = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(m) = Preg::is_match3( php_regex!("{^(\\d+\\.\\d+\\.\\d+(?:\\.\\d+)?)}"), &pretty_version, - Some(&mut m), ) { pretty_version = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); } else { diff --git a/crates/shirabe/src/repository/vcs/forgejo_driver.rs b/crates/shirabe/src/repository/vcs/forgejo_driver.rs index 9a656a65..9e156418 100644 --- a/crates/shirabe/src/repository/vcs/forgejo_driver.rs +++ b/crates/shirabe/src/repository/vcs/forgejo_driver.rs @@ -15,7 +15,7 @@ use crate::util::ForgejoRepositoryData; use crate::util::ForgejoUrl; use crate::util::http::Response; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ PhpMixed, RuntimeException, base64_decode, explode, extension_loaded, php_regex, urlencode, @@ -584,8 +584,7 @@ impl ForgejoDriver { let links = explode(",", &header); for link in links { - let mut m = PregMatchedGroups::new(); - if Preg::match3(php_regex!(r#"{<(.+?)>; *rel="next"}"#), &link, Some(&mut m)) + if let Some(m) = Preg::match3(php_regex!(r#"{<(.+?)>; *rel="next"}"#), &link) && let Some(url) = m.get(&CaptureKey::ByIndex(1)) { return Some(url.clone()); diff --git a/crates/shirabe/src/repository/vcs/git_bitbucket_driver.rs b/crates/shirabe/src/repository/vcs/git_bitbucket_driver.rs index 964c4b10..cf1f5f98 100644 --- a/crates/shirabe/src/repository/vcs/git_bitbucket_driver.rs +++ b/crates/shirabe/src/repository/vcs/git_bitbucket_driver.rs @@ -15,7 +15,7 @@ use crate::util::Bitbucket; use crate::util::http::Response; use chrono::{DateTime, FixedOffset}; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ InvalidArgumentException, LogicException, PhpMixed, RuntimeException, array_key_exists, @@ -84,18 +84,16 @@ impl GitBitbucketDriver { /// @inheritDoc pub fn initialize(&mut self) -> anyhow::Result<()> { - let mut m = PregMatchedGroups::new(); - if !Preg::is_match3( + let Some(m) = Preg::is_match3( php_regex!(r"#^https?://bitbucket\.org/([^/]+)/([^/]+?)(?:\.git|/?)?$#i"), &self.inner.url, - Some(&mut m), - ) { + ) else { return Err(InvalidArgumentException::new(format!( "The Bitbucket repository URL {} is invalid. It must be the HTTPS URL of a Bitbucket repository.", self.inner.url.clone(), )) .into()); - } + }; self.owner = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); self.repository = m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default(); diff --git a/crates/shirabe/src/repository/vcs/git_driver.rs b/crates/shirabe/src/repository/vcs/git_driver.rs index c46a6664..99275e98 100644 --- a/crates/shirabe/src/repository/vcs/git_driver.rs +++ b/crates/shirabe/src/repository/vcs/git_driver.rs @@ -14,7 +14,7 @@ use crate::util::Url; use chrono::TimeZone; use chrono::{DateTime, FixedOffset, Utc}; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ InvalidArgumentException, RuntimeException, dirname, is_dir, is_writable, realpath, @@ -198,14 +198,12 @@ impl GitDriver { let branches = self.inner.process.borrow().split_lines(&output); if !branches.contains(&"* master".to_string()) { for branch in &branches { - if !branch.is_empty() { - let mut caps = PregMatchedGroups::new(); - if Preg::match3(php_regex!(r"{^\* +(\S+)}"), branch, Some(&mut caps)) - && let Some(name) = caps.get(&CaptureKey::ByIndex(1)) - { - self.root_identifier = Some(name.clone()); - break; - } + if !branch.is_empty() + && let Some(caps) = Preg::match3(php_regex!(r"{^\* +(\S+)}"), branch) + && let Some(name) = caps.get(&CaptureKey::ByIndex(1)) + { + self.root_identifier = Some(name.clone()); + break; } } } @@ -310,21 +308,20 @@ impl GitDriver { Some(&self.repo_dir), ); for tag in self.inner.process.borrow().split_lines(&output) { - if !tag.is_empty() { - let mut caps = PregMatchedGroups::new(); - if Preg::match3( + if !tag.is_empty() + && let Some(caps) = Preg::match3( php_regex!(r"{^([a-f0-9]{40}) refs/tags/(\S+?)(\^\{\})?$}"), &tag, - Some(&mut caps), - ) && let (Some(hash), Some(name)) = ( + ) + && let (Some(hash), Some(name)) = ( caps.get(&CaptureKey::ByIndex(1)), caps.get(&CaptureKey::ByIndex(2)), - ) { - self.tags - .as_mut() - .unwrap() - .insert(name.clone(), hash.clone()); - } + ) + { + self.tags + .as_mut() + .unwrap() + .insert(name.clone(), hash.clone()); } } } @@ -349,19 +346,19 @@ impl GitDriver { Some(&self.repo_dir), ); for branch in self.inner.process.borrow().split_lines(&output) { - if !branch.is_empty() && !Preg::is_match(php_regex!(r"{^ *[^/]+/HEAD }"), &branch) { - let mut caps = PregMatchedGroups::new(); - if Preg::match3( + if !branch.is_empty() + && !Preg::is_match(php_regex!(r"{^ *[^/]+/HEAD }"), &branch) + && let Some(caps) = Preg::match3( php_regex!(r"{^(?:\* )? *(\S+) *([a-f0-9]+)(?: .*)?$}"), &branch, - Some(&mut caps), - ) && let (Some(name), Some(hash)) = ( + ) + && let (Some(name), Some(hash)) = ( caps.get(&CaptureKey::ByIndex(1)), caps.get(&CaptureKey::ByIndex(2)), - ) && !name.starts_with('-') - { - branches.insert(name.clone(), hash.clone()); - } + ) + && !name.starts_with('-') + { + branches.insert(name.clone(), hash.clone()); } } diff --git a/crates/shirabe/src/repository/vcs/github_driver.rs b/crates/shirabe/src/repository/vcs/github_driver.rs index 10a61feb..7cbceaf2 100644 --- a/crates/shirabe/src/repository/vcs/github_driver.rs +++ b/crates/shirabe/src/repository/vcs/github_driver.rs @@ -14,7 +14,7 @@ use crate::util::GitHub; use crate::util::http::Response; use chrono::{DateTime, FixedOffset}; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ InvalidArgumentException, PhpMixed, RuntimeException, array_diff, array_map, @@ -70,20 +70,18 @@ impl GitHubDriver { } pub fn initialize(&mut self) -> anyhow::Result<()> { - let mut match_ = PregMatchedGroups::new(); - if !Preg::is_match3( + let Some(match_) = Preg::is_match3( php_regex!( r"#^(?:(?:https?|git)://([^/]+)/|git@([^:]+):/?)([^/]+)/([^/]+?)(?:\.git|/)?$#" ), &self.inner.url, - Some(&mut match_), - ) { + ) else { return Err(InvalidArgumentException::new(format!( "The GitHub repository URL {} is invalid.", self.inner.url.clone(), )) .into()); - } + }; self.owner = match_ .get(&CaptureKey::ByIndex(3)) @@ -495,16 +493,14 @@ impl GitHubDriver { let mut key: Option<String> = None; for line in preg_split(php_regex!(r"{\r?\n}"), &funding) { let line = trim(&line, None); - let mut m = PregMatchedGroups::new(); - if Preg::is_match3(php_regex!(r"{^(\w+)\s*:\s*(.+)$}"), &line, Some(&mut m)) { + if let Some(m) = Preg::is_match3(php_regex!(r"{^(\w+)\s*:\s*(.+)$}"), &line) { let g1 = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); let g2 = m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default(); if g2 == "[" { key = Some(g1); continue; } - let mut m2 = PregMatchedGroups::new(); - if Preg::is_match3(php_regex!(r"{^\[(.*?)\](?:\s*#.*)?$}"), &g2, Some(&mut m2)) { + if let Some(m2) = Preg::is_match3(php_regex!(r"{^\[(.*?)\](?:\s*#.*)?$}"), &g2) { let inner = m2.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); for item in array_map( |s: &String| trim(s, None), @@ -518,11 +514,9 @@ impl GitHubDriver { ); result.push(entry); } - } else if Preg::is_match3( - php_regex!(r"{^([^#].*?)(?:\s+#.*)?$}"), - &g2, - Some(&mut m2), - ) { + } else if let Some(m2) = + Preg::is_match3(php_regex!(r"{^([^#].*?)(?:\s+#.*)?$}"), &g2) + { let mut entry = IndexMap::new(); entry.insert("type".to_string(), PhpMixed::String(g1.clone())); entry.insert( @@ -535,17 +529,12 @@ impl GitHubDriver { result.push(entry); } key = None; - } else if Preg::is_match3(php_regex!(r"{^(\w+)\s*:\s*#\s*$}"), &line, Some(&mut m)) { + } else if let Some(m) = Preg::is_match3(php_regex!(r"{^(\w+)\s*:\s*#\s*$}"), &line) { key = Some(m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default()); - } else if key.is_some() && { - let mut tmp = PregMatchedGroups::new(); - Preg::is_match3(php_regex!(r"{^-\s*(.+)(?:\s+#.*)?$}"), &line, Some(&mut m)) - || Preg::is_match3(php_regex!(r"{^(.+),(?:\s*#.*)?$}"), &line, Some(&mut tmp)) - && { - m = tmp; - true - } - } { + } else if key.is_some() + && let Some(m) = Preg::is_match3(php_regex!(r"{^-\s*(.+)(?:\s+#.*)?$}"), &line) + .or_else(|| Preg::is_match3(php_regex!(r"{^(.+),(?:\s*#.*)?$}"), &line)) + { let mut entry = IndexMap::new(); entry.insert( "type".to_string(), @@ -936,16 +925,14 @@ impl GitHubDriver { url: &str, _deep: bool, ) -> anyhow::Result<bool> { - let mut matches = PregMatchedGroups::new(); - if !Preg::is_match3( + let Some(matches) = Preg::is_match3( php_regex!( r"#^((?:https?|git)://([^/]+)/|git@([^:]+):/?)([^/]+)/([^/]+?)(?:\.git|/)?$#" ), url, - Some(&mut matches), - ) { + ) else { return Ok(false); - } + }; let origin_url = matches .get(&CaptureKey::ByIndex(2)) @@ -1284,8 +1271,7 @@ impl GitHubDriver { let links = explode(",", &header); for link in &links { - let mut m = PregMatchedGroups::new(); - if Preg::is_match3(php_regex!(r#"{<(.+?)>; *rel="next"}"#), link, Some(&mut m)) { + if let Some(m) = Preg::is_match3(php_regex!(r#"{<(.+?)>; *rel="next"}"#), link) { return Some(m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default()); } } diff --git a/crates/shirabe/src/repository/vcs/gitlab_driver.rs b/crates/shirabe/src/repository/vcs/gitlab_driver.rs index c141cc9a..1887ddc4 100644 --- a/crates/shirabe/src/repository/vcs/gitlab_driver.rs +++ b/crates/shirabe/src/repository/vcs/gitlab_driver.rs @@ -15,7 +15,7 @@ use crate::util::HttpDownloader; use crate::util::http::Response; use chrono::{DateTime, FixedOffset}; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ InvalidArgumentException, LogicException, PhpMixed, RuntimeException, array_search_mixed, @@ -81,14 +81,13 @@ impl GitLabDriver { /// /// SSH urls use https by default. Set "secure-http": false on the repository config to use http instead. pub fn initialize(&mut self) -> anyhow::Result<()> { - let mut match_ = PregMatchedGroups::new(); - if !Preg::is_match3(Self::URL_REGEX, &self.inner.url, Some(&mut match_)) { + let Some(match_) = Preg::is_match3(Self::URL_REGEX, &self.inner.url) else { return Err(InvalidArgumentException::new(format!( "The GitLab repository URL {} is invalid. It must be the HTTP URL of a GitLab project.", self.inner.url.clone(), )) .into()); - } + }; let guessed_domain = match_ .get(&CaptureKey::ByName("domain".to_string())) @@ -945,10 +944,9 @@ impl GitLabDriver { url: &str, _deep: bool, ) -> anyhow::Result<bool> { - let mut match_ = PregMatchedGroups::new(); - if !Preg::is_match3(Self::URL_REGEX, url, Some(&mut match_)) { + let Some(match_) = Preg::is_match3(Self::URL_REGEX, url) else { return Ok(false); - } + }; let scheme = match_ .get(&CaptureKey::ByName("scheme".to_string())) @@ -1011,12 +1009,7 @@ impl GitLabDriver { let links = explode(",", &header); for link in &links { - let mut match_ = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!(r#"{<(.+?)>; *rel="next"}"#), - link, - Some(&mut match_), - ) { + if let Some(match_) = Preg::is_match3(php_regex!(r#"{<(.+?)>; *rel="next"}"#), link) { return Some( match_ .get(&CaptureKey::ByIndex(1)) diff --git a/crates/shirabe/src/repository/vcs/hg_driver.rs b/crates/shirabe/src/repository/vcs/hg_driver.rs index d617099e..0933a643 100644 --- a/crates/shirabe/src/repository/vcs/hg_driver.rs +++ b/crates/shirabe/src/repository/vcs/hg_driver.rs @@ -11,7 +11,7 @@ use crate::util::Hg as HgUtils; use crate::util::Url; use chrono::{DateTime, FixedOffset, Utc}; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{PhpMixed, RuntimeException, dirname, is_dir, is_writable, php_regex}; @@ -232,14 +232,13 @@ impl HgDriver { Some(&self.repo_dir), ); for tag in self.inner.process.borrow().split_lines(&output) { - if !tag.is_empty() { - let mut m = PregMatchedGroups::new(); - if Preg::match3(php_regex!(r"(^([^\s]+)\s+\d+:(.*)$)"), &tag, Some(&mut m)) { - tags.insert( - m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(), - m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default(), - ); - } + if !tag.is_empty() + && let Some(m) = Preg::match3(php_regex!(r"(^([^\s]+)\s+\d+:(.*)$)"), &tag) + { + tags.insert( + m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(), + m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default(), + ); } } tags.shift_remove("tip"); @@ -262,20 +261,16 @@ impl HgDriver { Some(&self.repo_dir), ); for branch in self.inner.process.borrow().split_lines(&output) { - if !branch.is_empty() { - let mut m = PregMatchedGroups::new(); - if Preg::match3( - php_regex!(r"(^([^\s]+)\s+\d+:([a-f0-9]+))"), - &branch, - Some(&mut m), - ) { - let name = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); - if !name.starts_with('-') { - branches.insert( - name, - m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default(), - ); - } + if !branch.is_empty() + && let Some(m) = + Preg::match3(php_regex!(r"(^([^\s]+)\s+\d+:([a-f0-9]+))"), &branch) + { + let name = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); + if !name.starts_with('-') { + branches.insert( + name, + m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default(), + ); } } } @@ -287,20 +282,16 @@ impl HgDriver { Some(&self.repo_dir), ); for branch in self.inner.process.borrow().split_lines(&output) { - if !branch.is_empty() { - let mut m = PregMatchedGroups::new(); - if Preg::match3( - php_regex!(r"(^(?:[\s*]*)([^\s]+)\s+\d+:(.*)$)"), - &branch, - Some(&mut m), - ) { - let name = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); - if !name.starts_with('-') { - bookmarks.insert( - name, - m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default(), - ); - } + if !branch.is_empty() + && let Some(m) = + Preg::match3(php_regex!(r"(^(?:[\s*]*)([^\s]+)\s+\d+:(.*)$)"), &branch) + { + let name = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); + if !name.starts_with('-') { + bookmarks.insert( + name, + m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default(), + ); } } } diff --git a/crates/shirabe/src/repository/vcs/svn_driver.rs b/crates/shirabe/src/repository/vcs/svn_driver.rs index db8c43f0..05380a17 100644 --- a/crates/shirabe/src/repository/vcs/svn_driver.rs +++ b/crates/shirabe/src/repository/vcs/svn_driver.rs @@ -13,7 +13,7 @@ use crate::util::Svn as SvnUtil; use crate::util::Url; use chrono::{DateTime, FixedOffset, Utc}; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ PhpMixed, RuntimeException, php_regex, stripos, strrpos, strtr, substr, trim, @@ -317,18 +317,14 @@ impl SvnDriver { &format!("{}{}{}", self.base_url, path, rev), )?; for line in self.inner.process.borrow().split_lines(&output) { - if !line.is_empty() { - let mut m = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!(r"{^Last Changed Date: ([^(]+)}"), - &line, - Some(&mut m), - ) { - let date_str = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); - return Ok(shirabe_php_shim::date_create::<Utc>(date_str.trim()) - .ok() - .map(|d| d.fixed_offset())); - } + if !line.is_empty() + && let Some(m) = + Preg::is_match3(php_regex!(r"{^Last Changed Date: ([^(]+)}"), &line) + { + let date_str = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); + return Ok(shirabe_php_shim::date_create::<Utc>(date_str.trim()) + .ok() + .map(|d| d.fixed_offset())); } } @@ -349,28 +345,23 @@ impl SvnDriver { let mut last_rev: i64 = 0; for line in self.inner.process.borrow().split_lines(&output) { let line = trim(&line, None); - if !line.is_empty() { - let mut m = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!(r"{^\s*(\S+).*?(\S+)\s*$}"), - &line, - Some(&mut m), - ) { - let rev: i64 = m - .get(&CaptureKey::ByIndex(1)) - .and_then(|s| s.parse().ok()) - .unwrap_or(0); - let path = - m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default(); - if path == "./" { - last_rev = rev; - } else { - let identifier = self.build_identifier( - &format!("/{}/{}", self.tags_path, path), - std::cmp::max(last_rev, rev), - ); - tags.insert(path.trim_end_matches('/').to_string(), identifier); - } + if !line.is_empty() + && let Some(m) = + Preg::is_match3(php_regex!(r"{^\s*(\S+).*?(\S+)\s*$}"), &line) + { + let rev: i64 = m + .get(&CaptureKey::ByIndex(1)) + .and_then(|s| s.parse().ok()) + .unwrap_or(0); + let path = m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default(); + if path == "./" { + last_rev = rev; + } else { + let identifier = self.build_identifier( + &format!("/{}/{}", self.tags_path, path), + std::cmp::max(last_rev, rev), + ); + tags.insert(path.trim_end_matches('/').to_string(), identifier); } } } @@ -400,27 +391,23 @@ impl SvnDriver { if !output.is_empty() { for line in self.inner.process.borrow().split_lines(&output) { let line = trim(&line, None); - if !line.is_empty() { - let mut m = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!(r"{^\s*(\S+).*?(\S+)\s*$}"), - &line, - Some(&mut m), - ) { - let rev: i64 = m - .get(&CaptureKey::ByIndex(1)) - .and_then(|s| s.parse().ok()) - .unwrap_or(0); - let path = m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default(); - if path == "./" { - let identifier = self.build_identifier( - &format!("/{}", self.trunk_path.clone().unwrap_or_default()), - rev, - ); - branches.insert("trunk".to_string(), identifier.clone()); - self.root_identifier = Some(identifier); - break; - } + if !line.is_empty() + && let Some(m) = + Preg::is_match3(php_regex!(r"{^\s*(\S+).*?(\S+)\s*$}"), &line) + { + let rev: i64 = m + .get(&CaptureKey::ByIndex(1)) + .and_then(|s| s.parse().ok()) + .unwrap_or(0); + let path = m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default(); + if path == "./" { + let identifier = self.build_identifier( + &format!("/{}", self.trunk_path.clone().unwrap_or_default()), + rev, + ); + branches.insert("trunk".to_string(), identifier.clone()); + self.root_identifier = Some(identifier); + break; } } } @@ -442,29 +429,23 @@ impl SvnDriver { .split_lines(&trim(&output, None)) { let line = trim(&line, None); - if !line.is_empty() { - let mut m = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!(r"{^\s*(\S+).*?(\S+)\s*$}"), - &line, - Some(&mut m), - ) { - let rev: i64 = m - .get(&CaptureKey::ByIndex(1)) - .and_then(|s| s.parse().ok()) - .unwrap_or(0); - let path = - m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default(); - if path == "./" { - last_rev = rev; - } else { - let identifier = self.build_identifier( - &format!("/{}/{}", self.branches_path, path), - std::cmp::max(last_rev, rev), - ); - branches - .insert(path.trim_end_matches('/').to_string(), identifier); - } + if !line.is_empty() + && let Some(m) = + Preg::is_match3(php_regex!(r"{^\s*(\S+).*?(\S+)\s*$}"), &line) + { + let rev: i64 = m + .get(&CaptureKey::ByIndex(1)) + .and_then(|s| s.parse().ok()) + .unwrap_or(0); + let path = m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default(); + if path == "./" { + last_rev = rev; + } else { + let identifier = self.build_identifier( + &format!("/{}/{}", self.branches_path, path), + std::cmp::max(last_rev, rev), + ); + branches.insert(path.trim_end_matches('/').to_string(), identifier); } } } diff --git a/crates/shirabe/src/util/composer_mirror.rs b/crates/shirabe/src/util/composer_mirror.rs index 1455613d..7344bfaf 100644 --- a/crates/shirabe/src/util/composer_mirror.rs +++ b/crates/shirabe/src/util/composer_mirror.rs @@ -1,6 +1,6 @@ //! ref: composer/src/Composer/Util/ComposerMirror.php -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::{hash, php_regex}; pub struct ComposerMirror; @@ -53,14 +53,11 @@ impl ComposerMirror { url: &str, r#type: Option<&str>, ) -> String { - let mut gh_matches = PregMatchedGroups::new(); - let mut bb_matches = PregMatchedGroups::new(); - let normalized_url = if Preg::match3( + let normalized_url = if let Some(gh_matches) = Preg::match3( php_regex!( r"#^(?:(?:https?|git)://github\.com/|git@github\.com:)([^/]+)/(.+?)(?:\.git)?$#" ), url, - Some(&mut gh_matches), ) { format!( "gh-{}/{}", @@ -73,10 +70,9 @@ impl ComposerMirror { .cloned() .unwrap_or_default(), ) - } else if Preg::match3( + } else if let Some(bb_matches) = Preg::match3( php_regex!(r"#^https://bitbucket\.org/([^/]+)/(.+?)(?:\.git)?/?$#"), url, - Some(&mut bb_matches), ) { format!( "bb-{}/{}", diff --git a/crates/shirabe/src/util/filesystem.rs b/crates/shirabe/src/util/filesystem.rs index 21512a81..d59df55e 100644 --- a/crates/shirabe/src/util/filesystem.rs +++ b/crates/shirabe/src/util/filesystem.rs @@ -246,7 +246,7 @@ impl Filesystem { return Ok(Some(true)); } - if Preg::is_match3(php_regex!("{^(?:[a-z]:)?[/\\\\]+$}i"), directory, None) { + if Preg::is_match3(php_regex!("{^(?:[a-z]:)?[/\\\\]+$}i"), directory).is_some() { return Err(RuntimeException::new(format!("Aborting an attempted deletion of {}, this was probably not intended, if it is a real use case please report it.", directory)) .into()); } @@ -578,7 +578,7 @@ impl Filesystem { let mut common_path = to.clone(); while strpos(&format!("{}/", from), &format!("{}/", common_path)) != Some(0) && "/" != common_path - && !Preg::is_match3(php_regex!("{^[A-Z]:/?$}i"), &common_path, None) + && Preg::is_match3(php_regex!("{^[A-Z]:/?$}i"), &common_path).is_none() { common_path = strtr(&dirname(&common_path), "\\", "/"); } @@ -635,7 +635,7 @@ impl Filesystem { let mut common_path = to.clone(); while strpos(&format!("{}/", from), &format!("{}/", common_path)) != Some(0) && "/" != common_path - && !Preg::is_match3(php_regex!("{^[A-Z]:/?$}i"), &common_path, None) + && Preg::is_match3(php_regex!("{^[A-Z]:/?$}i"), &common_path).is_none() && "." != common_path { common_path = strtr(&dirname(&common_path), "\\", "/"); @@ -735,11 +735,9 @@ impl Filesystem { } // extract a prefix being a protocol://, protocol:, protocol://drive: or simply drive: - let mut prefix_match = shirabe_pcre::PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(prefix_match) = Preg::is_match3( php_regex!("{^( [0-9a-z]{2,}+: (?: // (?: [a-z]: )? )? | [a-z]: )}ix"), &path, - Some(&mut prefix_match), ) { prefix = prefix_match .get(&shirabe_pcre::CaptureKey::ByIndex(1)) @@ -785,7 +783,7 @@ impl Filesystem { /// And other possible unforeseen disasters, see https://github.com/composer/composer/pull/9422 pub fn trim_trailing_slash(path: &str) -> String { let mut path = path.to_string(); - if !Preg::is_match3(php_regex!("{^[/\\\\]+$}"), &path, None) { + if Preg::is_match3(php_regex!("{^[/\\\\]+$}"), &path).is_none() { path = rtrim(&path, Some("/\\")); } @@ -802,15 +800,15 @@ impl Filesystem { "{^(file://(?!//)|/(?!/)|/?[a-z]:[\\\\/]|\\.\\.[\\\\/]|[a-z0-9_.-]+[\\\\/])}i" ), path, - None, - ); + ) + .is_some(); } Preg::is_match3( php_regex!("{^(file://|/|/?[a-z]:[\\\\/]|\\.\\.[\\\\/]|[a-z0-9_.-]+[\\\\/])}i"), path, - None, ) + .is_some() } pub fn get_platform_path(path: &str) -> String { diff --git a/crates/shirabe/src/util/forgejo_url.rs b/crates/shirabe/src/util/forgejo_url.rs index 7a5d2b10..e5304f5d 100644 --- a/crates/shirabe/src/util/forgejo_url.rs +++ b/crates/shirabe/src/util/forgejo_url.rs @@ -37,10 +37,7 @@ impl ForgejoUrl { pub fn try_from(repo_url: Option<&str>) -> Option<Self> { let repo_url = repo_url?; - let mut matches = shirabe_pcre::PregMatchedGroups::new(); - if !Preg::match3(Self::URL_REGEX, repo_url, Some(&mut matches)) { - return None; - } + let matches = Preg::match3(Self::URL_REGEX, repo_url)?; use shirabe_pcre::CaptureKey; let m: Vec<String> = (0..5) .map(|i| { diff --git a/crates/shirabe/src/util/git.rs b/crates/shirabe/src/util/git.rs index 0f463aea..2b012d4c 100644 --- a/crates/shirabe/src/util/git.rs +++ b/crates/shirabe/src/util/git.rs @@ -226,11 +226,9 @@ impl Git { &mut output, cwd, )?; - let mut m = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(m) = Preg::is_match3( php_regex!(r"{^(?:composer|origin)\s+https?://(.+):(.+)@([^/]+)}im"), &output, - Some(&mut m), ) { let m3 = m.get(&CaptureKey::ByIndex(3)).cloned().unwrap_or_default(); if !self.io.has_authentication(&m3) { @@ -248,14 +246,12 @@ impl Git { let protocols = self.config.borrow_mut().get("github-protocols"); // public github, autoswitch protocols // @phpstan-ignore composerPcre.maybeUnsafeStrictGroups - let mut m = PregMatchedGroups::new(); - if Preg::is_match3( + if let Some(m) = Preg::is_match3( format!( "{{^(?:https?|git)://{}/(.*)}}", Self::get_github_domains_regex(&self.config.borrow()) ), url, - Some(&mut m), ) { let mut messages: Vec<String> = vec![]; let protocols_list: Vec<String> = match &protocols { @@ -344,23 +340,23 @@ impl Git { let mut error_msg = self.process.borrow().get_error_output().to_string(); // private github repository without ssh key access, try https with auth // @phpstan-ignore composerPcre.maybeUnsafeStrictGroups - let mut m = PregMatchedGroups::new(); let github_matched = Preg::is_match3( format!( "{{^git@{}:(.+?)\\.git$}}i", Self::get_github_domains_regex(&self.config.borrow()) ), url, - Some(&mut m), - ) || Preg::is_match3( - format!( - "{{^https?://{}/(.*?)(?:\\.git)?$}}i", - Self::get_github_domains_regex(&self.config.borrow()) - ), - url, - Some(&mut m), - ); - if github_matched { + ) + .or_else(|| { + Preg::is_match3( + format!( + "{{^https?://{}/(.*?)(?:\\.git)?$}}i", + Self::get_github_domains_regex(&self.config.borrow()) + ), + url, + ) + }); + if let Some(m) = github_matched { let m1 = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); let m2 = m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default(); if !self.io.has_authentication(&m1) { @@ -410,15 +406,12 @@ impl Git { credentials = vec![rawurlencode(&username), rawurlencode(&password)]; error_msg = self.process.borrow().get_error_output().to_string(); } - } else if Preg::is_match3( + } else if let Some(m) = Preg::is_match3( php_regex!(r"{^(https?)://(bitbucket\.org)/(.*?)(?:\.git)?$}i"), url, - Some(&mut m), - ) || Preg::is_match3( - php_regex!(r"{^(git)@(bitbucket\.org):(.+?\.git)$}i"), - url, - Some(&mut m), - ) { + ) + .or_else(|| Preg::is_match3(php_regex!(r"{^(git)@(bitbucket\.org):(.+?\.git)$}i"), url)) + { // bitbucket either through oauth or app password, with fallback to ssh. let mut bitbucket_util = Bitbucket::new( self.io.clone(), @@ -556,21 +549,22 @@ impl Git { } error_msg = self.process.borrow().get_error_output().to_string(); - } else if Preg::is_match3( + } else if let Some(m) = Preg::is_match3( format!( "{{^(git)@{}:(.+?\\.git)$}}i", Self::get_gitlab_domains_regex(&self.config.borrow()) ), url, - Some(&mut m), - ) || Preg::is_match3( - format!( - "{{^(https?)://{}/(.*)}}i", - Self::get_gitlab_domains_regex(&self.config.borrow()) - ), - url, - Some(&mut m), - ) { + ) + .or_else(|| { + Preg::is_match3( + format!( + "{{^(https?)://{}/(.*)}}i", + Self::get_gitlab_domains_regex(&self.config.borrow()) + ), + url, + ) + }) { let mut m1 = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); let m2 = m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default(); let m3 = m.get(&CaptureKey::ByIndex(3)).cloned().unwrap_or_default(); @@ -1090,14 +1084,7 @@ impl Git { } fn get_authentication_failure(&self, url: &str) -> Option<PregMatchedGroups> { - let mut m = PregMatchedGroups::new(); - if !Preg::is_match3( - php_regex!(r"{^(https?://)([^/]+)(.*)$}i"), - url, - Some(&mut m), - ) { - return None; - } + let m = Preg::is_match3(php_regex!(r"{^(https?://)([^/]+)(.*)$}i"), url)?; let auth_failures = [ "fatal: Authentication failed", @@ -1179,12 +1166,9 @@ impl Git { .borrow() .split_lines(output_mixed.as_string().unwrap_or("")); for line in lines { - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!(r"{^\s*HEAD branch:\s(.+)\s*$}m"), - &line, - Some(&mut matches), - ) { + if let Some(matches) = + Preg::is_match3(php_regex!(r"{^\s*HEAD branch:\s(.+)\s*$}m"), &line) + { return Ok(Some( matches .get(&CaptureKey::ByIndex(1)) @@ -1307,15 +1291,11 @@ impl Git { &mut output, Option::<&str>::None, ); - if exit_code == 0 { - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!(r"/^git version (\d+(?:\.\d+)+)/m"), - &output, - Some(&mut matches), - ) { - *version = Some(matches.get(&CaptureKey::ByIndex(1)).cloned()); - } + if exit_code == 0 + && let Some(matches) = + Preg::is_match3(php_regex!(r"/^git version (\d+(?:\.\d+)+)/m"), &output) + { + *version = Some(matches.get(&CaptureKey::ByIndex(1)).cloned()); } } version.clone().unwrap_or(None) diff --git a/crates/shirabe/src/util/github.rs b/crates/shirabe/src/util/github.rs index b7659572..9c22a2b3 100644 --- a/crates/shirabe/src/util/github.rs +++ b/crates/shirabe/src/util/github.rs @@ -8,7 +8,7 @@ use crate::io::io_interface; use crate::util::HttpDownloader; use crate::util::ProcessExecutor; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{PhpMixed, date_local, in_array_loose, php_regex, stripos, strtolower}; @@ -325,12 +325,7 @@ impl GitHub { if stripos(header, "x-github-sso: required").is_none() { continue; } - let mut caps = PregMatchedGroups::new(); - if Preg::match3( - php_regex!(r"{\burl=(?P<url>[^\s;]+)}"), - header, - Some(&mut caps), - ) { + if let Some(caps) = Preg::match3(php_regex!(r"{\burl=(?P<url>[^\s;]+)}"), header) { return caps.get(&CaptureKey::ByName("url".to_string())).cloned(); } } diff --git a/crates/shirabe/src/util/hg.rs b/crates/shirabe/src/util/hg.rs index d9e58623..29d305f0 100644 --- a/crates/shirabe/src/util/hg.rs +++ b/crates/shirabe/src/util/hg.rs @@ -5,7 +5,7 @@ use crate::io::IOInterface; use crate::io::IOInterfaceImmutable; use crate::util::ProcessExecutor; use crate::util::Url; -use shirabe_pcre::{Preg, PregNamedGroups}; +use shirabe_pcre::Preg; use shirabe_php_shim::{php_regex, rawurlencode}; use std::sync::OnceLock; @@ -56,16 +56,14 @@ impl Hg { } // Try with the authentication information available - let mut matches = PregNamedGroups::new(); let matched = Preg::is_match_named( php_regex!( r"{^(?P<proto>ssh|https?)://(?:(?P<user>[^:@]+)(?::(?P<pass>[^:@]+))?@)?(?P<host>[^/]+)(?P<path>/.*)?}mi" ), &url, - &mut matches, ); - if matched + if let Some(matches) = matched && self .io .has_authentication(matches.get("host").map(|s| s.as_str()).unwrap_or("")) diff --git a/crates/shirabe/src/util/http/response.rs b/crates/shirabe/src/util/http/response.rs index 6ce52643..ea961768 100644 --- a/crates/shirabe/src/util/http/response.rs +++ b/crates/shirabe/src/util/http/response.rs @@ -65,8 +65,7 @@ impl Response { let mut value = None; let pattern = format!("{{^{}:\\s*(.+?)\\s*$}}i", preg_quote(name, None)); for header in headers { - let mut matches = shirabe_pcre::PregMatchedGroups::new(); - if Preg::match3(&pattern, header, Some(&mut matches)) + if let Some(matches) = Preg::match3(&pattern, header) && let Some(s) = matches.get(&shirabe_pcre::CaptureKey::ByIndex(1)) { value = Some(s.clone()); diff --git a/crates/shirabe/src/util/http_downloader.rs b/crates/shirabe/src/util/http_downloader.rs index c478d445..b06d7004 100644 --- a/crates/shirabe/src/util/http_downloader.rs +++ b/crates/shirabe/src/util/http_downloader.rs @@ -16,7 +16,7 @@ use crate::util::http::CurlDownloader; use crate::util::http::Response; use crate::util::sync_executor; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ InvalidArgumentException, LogicException, PhpMixed, array_replace_recursive, extension_loaded, @@ -240,12 +240,8 @@ impl HttpDownloader { let origin = Url::get_origin(&self.config.borrow(), url); // capture username/password from URL if there is one - let mut m = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!(r"{^https?://([^:/]+):([^@/]+)@([^/]+)}i"), - url, - Some(&mut m), - ) { + if let Some(m) = Preg::is_match3(php_regex!(r"{^https?://([^:/]+):([^@/]+)@([^/]+)}i"), url) + { self.io.borrow_mut().set_authentication( origin.clone(), rawurldecode( diff --git a/crates/shirabe/src/util/process_executor.rs b/crates/shirabe/src/util/process_executor.rs index d87e2ff4..48fa415f 100644 --- a/crates/shirabe/src/util/process_executor.rs +++ b/crates/shirabe/src/util/process_executor.rs @@ -216,17 +216,16 @@ impl ProcessExecutor { let mut process: Process; if is_string(&command) { let mut command_str = command.as_string().unwrap_or("").to_string(); - if Platform::is_windows() { - let mut m = PregMatchedGroups::new(); - if Preg::is_match3(php_regex!(r"{^([^:/\\]++) }"), &command_str, Some(&mut m)) { - let m1 = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); - command_str = substr_replace( - &command_str, - &Self::escape(&Self::get_executable(&m1)), - 0, - Some(strlen(&m1)), - ); - } + if Platform::is_windows() + && let Some(m) = Preg::is_match3(php_regex!(r"{^([^:/\\]++) }"), &command_str) + { + let m1 = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); + command_str = substr_replace( + &command_str, + &Self::escape(&Self::get_executable(&m1)), + 0, + Some(strlen(&m1)), + ); } process = Process::from_shell_commandline( diff --git a/crates/shirabe/src/util/remote_filesystem.rs b/crates/shirabe/src/util/remote_filesystem.rs index 40a69f28..0bc004ce 100644 --- a/crates/shirabe/src/util/remote_filesystem.rs +++ b/crates/shirabe/src/util/remote_filesystem.rs @@ -13,7 +13,7 @@ use crate::util::Url; use crate::util::http::ProxyManager; use crate::util::http::Response; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ PhpMixed, RuntimeException, STREAM_NOTIFY_FAILURE, STREAM_NOTIFY_FILE_SIZE_IS, @@ -148,8 +148,7 @@ impl RemoteFilesystem { pub fn find_status_code(headers: &[String]) -> Option<i64> { let mut value: Option<i64> = None; for header in headers { - let mut m = PregMatchedGroups::new(); - if Preg::is_match3(php_regex!("{^HTTP/\\S+ (\\d+)}i"), header, Some(&mut m)) { + if let Some(m) = Preg::is_match3(php_regex!("{^HTTP/\\S+ (\\d+)}i"), header) { value = m .get(&CaptureKey::ByIndex(1)) .and_then(|s| s.parse().ok()) diff --git a/crates/shirabe/src/util/svn.rs b/crates/shirabe/src/util/svn.rs index d07b3ffe..8018efa5 100644 --- a/crates/shirabe/src/util/svn.rs +++ b/crates/shirabe/src/util/svn.rs @@ -6,7 +6,7 @@ use crate::io::IOInterfaceImmutable; use crate::io::io_interface; use crate::util::Platform; use crate::util::ProcessExecutor; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ LogicException, PhpMixed, RuntimeException, implode, parse_url, php_regex, stripos, strpos, trim, @@ -405,20 +405,14 @@ impl Svn { &["svn".to_string(), "--version".to_string()], &mut output, None, - ) { - let mut matches = PregMatchedGroups::new(); - if Preg::is_match3( - php_regex!(r"{(\d+(?:\.\d+)+)}"), - &output, - Some(&mut matches), - ) { - *cached = Some( - matches - .get(&CaptureKey::ByIndex(1)) - .cloned() - .unwrap_or_default(), - ); - } + ) && let Some(matches) = Preg::is_match3(php_regex!(r"{(\d+(?:\.\d+)+)}"), &output) + { + *cached = Some( + matches + .get(&CaptureKey::ByIndex(1)) + .cloned() + .unwrap_or_default(), + ); } } diff --git a/crates/shirabe/src/util/url.rs b/crates/shirabe/src/util/url.rs index 3afcd962..0a3722eb 100644 --- a/crates/shirabe/src/util/url.rs +++ b/crates/shirabe/src/util/url.rs @@ -2,7 +2,7 @@ use crate::config::Config; use crate::util::GitHub; -use shirabe_pcre::{CaptureKey, Preg, PregMatchedGroups}; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::{PhpMixed, in_array_strict, parse_url, php_regex}; pub struct Url; @@ -14,13 +14,11 @@ impl Url { .unwrap_or_default(); if host == "api.github.com" || host == "github.com" || host == "www.github.com" { - let mut m = PregMatchedGroups::new(); - if Preg::match3( + if let Some(m) = Preg::match3( php_regex!( r"{^https?://(?:www\.)?github\.com/([^/]+)/([^/]+)/(zip|tar)ball/(.+)$}i" ), &url, - Some(&mut m), ) { url = format!( "https://api.github.com/repos/{}/{}/{}ball/{}", @@ -29,12 +27,11 @@ impl Url { m.get(&CaptureKey::ByIndex(3)).cloned().unwrap_or_default(), r#ref ); - } else if Preg::match3( + } else if let Some(m) = Preg::match3( php_regex!( r"{^https?://(?:www\.)?github\.com/([^/]+)/([^/]+)/archive/.+\.(zip|tar)(?:\.gz)?$}i" ), &url, - Some(&mut m), ) { url = format!( "https://api.github.com/repos/{}/{}/{}ball/{}", @@ -43,12 +40,11 @@ impl Url { m.get(&CaptureKey::ByIndex(3)).cloned().unwrap_or_default(), r#ref ); - } else if Preg::match3( + } else if let Some(m) = Preg::match3( php_regex!( r"{^https?://api\.github\.com/repos/([^/]+)/([^/]+)/(zip|tar)ball(?:/.+)?$}i" ), &url, - Some(&mut m), ) { url = format!( "https://api.github.com/repos/{}/{}/{}ball/{}", @@ -59,13 +55,11 @@ impl Url { ); } } else if host == "bitbucket.org" || host == "www.bitbucket.org" { - let mut m = PregMatchedGroups::new(); - if Preg::match3( + if let Some(m) = Preg::match3( php_regex!( r"{^https?://(?:www\.)?bitbucket\.org/([^/]+)/([^/]+)/get/(.+)\.(zip|tar\.gz|tar\.bz2)$}i" ), &url, - Some(&mut m), ) { url = format!( "https://bitbucket.org/{}/{}/get/{}.{}", @@ -76,13 +70,11 @@ impl Url { ); } } else if host == "gitlab.com" || host == "www.gitlab.com" { - let mut m = PregMatchedGroups::new(); - if Preg::match3( + if let Some(m) = Preg::match3( php_regex!( r"{^https?://(?:www\.)?gitlab\.com/api/v[34]/projects/([^/]+)/repository/archive\.(zip|tar\.gz|tar\.bz2|tar)\?sha=.+$}i" ), &url, - Some(&mut m), ) { url = format!( "https://gitlab.com/api/v4/projects/{}/repository/archive.{}?sha={}", diff --git a/crates/shirabe/tests/all_functional_test.rs b/crates/shirabe/tests/all_functional_test.rs index 500f822e..8578ed43 100644 --- a/crates/shirabe/tests/all_functional_test.rs +++ b/crates/shirabe/tests/all_functional_test.rs @@ -8,7 +8,7 @@ use indexmap::IndexMap; use serial_test::serial; use shirabe::util::filesystem::Filesystem; -use shirabe_pcre::preg::{Preg, PregMatchedGroups}; +use shirabe_pcre::preg::Preg; use shirabe_php_shim::{CaptureKey, PhpMixed, intval, php_regex, preg_split_delim_capture}; use std::path::{Path, PathBuf}; @@ -141,15 +141,13 @@ fn expect_matches(expected: &str, output: &str) { line += 1; } if eb[i] == b'%' { - let mut m = PregMatchedGroups::new(); - if !Preg::is_match3(php_regex!("{%(.+?)%}"), &expected[i..], Some(&mut m)) { + let Some(m) = Preg::is_match3(php_regex!("{%(.+?)%}"), &expected[i..]) else { panic!("Failed to match %...% in {}", &expected[i..]); - } + }; let regex = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap(); let pattern = format!("{{{}}}", regex); - let mut m = PregMatchedGroups::new(); - if Preg::is_match3(&pattern, &output[j..], Some(&mut m)) { + if let Some(m) = Preg::is_match3(&pattern, &output[j..]) { let full = m.get(&CaptureKey::ByIndex(0)).cloned().unwrap(); i += regex.len() + 2; j += full.len(); |
