diff options
Diffstat (limited to 'crates/shirabe/src')
87 files changed, 783 insertions, 499 deletions
diff --git a/crates/shirabe/src/advisory/partial_security_advisory.rs b/crates/shirabe/src/advisory/partial_security_advisory.rs index d5ff9997..4f07c8ca 100644 --- a/crates/shirabe/src/advisory/partial_security_advisory.rs +++ b/crates/shirabe/src/advisory/partial_security_advisory.rs @@ -6,7 +6,7 @@ use crate::package::version::VersionParser; use chrono::{DateTime, Utc}; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::Preg; -use shirabe_php_shim::PhpMixed; +use shirabe_php_shim::{PhpMixed, php_regex}; use shirabe_semver::constraint::AnyConstraint; use shirabe_semver::constraint::SimpleConstraint; @@ -37,8 +37,11 @@ impl PartialSecurityAdvisory { let constraint: AnyConstraint = match parser.parse_constraints(affected_versions_str) { Ok(c) => c, Err(_) => { - let affected_version = - Preg::replace(r"{(^[>=<^~]*[\d.]+).*}", "$1", affected_versions_str); + let affected_version = Preg::replace( + php_regex!(r"{(^[>=<^~]*[\d.]+).*}"), + "$1", + affected_versions_str, + ); match parser.parse_constraints(&affected_version) { Ok(c) => c, Err(_) => SimpleConstraint::new( diff --git a/crates/shirabe/src/autoload/autoload_generator.rs b/crates/shirabe/src/autoload/autoload_generator.rs index be56ff8a..49eade41 100644 --- a/crates/shirabe/src/autoload/autoload_generator.rs +++ b/crates/shirabe/src/autoload/autoload_generator.rs @@ -27,7 +27,7 @@ use shirabe_external_packages::symfony::console::formatter::OutputFormatter; use shirabe_php_shim::{ InvalidArgumentException, PhpMixed, array_keys, array_map, array_merge_map, array_merge_recursive, array_shift, array_slice_strs, array_unique, bin2hex, explode, - file_exists, file_get_contents, hash, implode, is_array, ksort, ltrim, preg_quote, + file_exists, file_get_contents, hash, implode, is_array, ksort, ltrim, php_regex, preg_quote, random_bytes, realpath, str_contains, str_replace, str_starts_with, strlen, strpos, strtr, substr, substr_count, trim, unlink, var_export, }; @@ -514,7 +514,7 @@ impl AutoloadGenerator { file_get_contents(format!("{}/autoload.php", vendor_path)).unwrap_or_default(); let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::match3( - "{ComposerAutoloaderInit([^:\\s]+)::}", + php_regex!("{ComposerAutoloaderInit([^:\\s]+)::}"), &content, Some(&mut matches), ) { @@ -704,7 +704,9 @@ impl AutoloadGenerator { for pattern in &excluded { // extract the constant string prefix of the pattern here, until we reach a non-escaped regex special character let pattern_processed = Preg::replace( - "{^(([^.+*?\\[^\\]$(){}=!<>|:\\\\#-]+|\\\\[.+*?\\[^\\]$(){}=!<>|:#-])*).*}", + php_regex!( + "{^(([^.+*?\\[^\\]$(){}=!<>|:\\\\#-]+|\\\\[.+*?\\[^\\]$(){}=!<>|:#-])*).*}" + ), "$1", pattern, ); @@ -1072,7 +1074,7 @@ impl AutoloadGenerator { } } - if Preg::is_match("{\\.phar([\\\\/]|$)}", &path) { + if Preg::is_match(php_regex!("{\\.phar([\\\\/]|$)}"), &path) { base_dir = format!("'phar://' . {}", base_dir); } @@ -1098,8 +1100,11 @@ impl AutoloadGenerator { let links = array_merge_map(package.get_replaces(), package.get_provides()); for (_k, link) in &links { let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::match3("{^ext-(.+)$}iD", link.get_target(), Some(&mut matches)) - && let Some(ext) = matches.get(&CaptureKey::ByIndex(1)).cloned() + if Preg::match3( + php_regex!("{^ext-(.+)$}iD"), + link.get_target(), + Some(&mut matches), + ) && let Some(ext) = matches.get(&CaptureKey::ByIndex(1)).cloned() { extension_providers .entry(ext) @@ -1141,7 +1146,11 @@ impl AutoloadGenerator { let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if check_platform.as_bool() == Some(true) - && Preg::match3("{^ext-(.+)$}iD", link.get_target(), Some(&mut matches)) + && Preg::match3( + php_regex!("{^ext-(.+)$}iD"), + link.get_target(), + Some(&mut matches), + ) { let ext_key = matches .get(&CaptureKey::ByIndex(1)) @@ -1662,8 +1671,11 @@ class ComposerStaticInit{} ); m }); - let value = shirabe_php_shim::ltrim(&Preg::replace("/^ */m", " $0$0", &value), None); - let value = Preg::replace("/ +$/m", "", &value); + let value = shirabe_php_shim::ltrim( + &Preg::replace(php_regex!("/^ */m"), " $0$0", &value), + None, + ); + let value = Preg::replace(php_regex!("/ +$/m"), "", &value); file.push_str(&format!( " public static ${} = {};\n\n", @@ -1785,7 +1797,7 @@ class ComposerStaticInit{} ); path_str = ltrim( &Preg::replace( - &format!("{{^{}}}", target_dir), + format!("{{^{}}}", target_dir), "", <rim(&path_str, Some("\\/")), ), @@ -1804,7 +1816,7 @@ class ComposerStaticInit{} if r#type == "exclude-from-classmap" { // first escape user input let p = Preg::replace( - "{/+}", + php_regex!("{/+}"), "/", &preg_quote(&trim(&strtr(&path_str, "\\", "/"), Some("/")), None), ); @@ -1821,7 +1833,7 @@ class ComposerStaticInit{} let updir_cell: std::cell::RefCell<Option<String>> = std::cell::RefCell::new(None); let p = Preg::replace_callback( - "{^((?:(?:\\\\\\.){1,2}+/)+)}", + php_regex!("{^((?:(?:\\\\\\.){1,2}+/)+)}"), |matches: &IndexMap<CaptureKey, String>| -> String { // undo preg_quote for the matched string *updir_cell.borrow_mut() = Some(str_replace( diff --git a/crates/shirabe/src/cache.rs b/crates/shirabe/src/cache.rs index e203eb18..21e8f252 100644 --- a/crates/shirabe/src/cache.rs +++ b/crates/shirabe/src/cache.rs @@ -11,7 +11,7 @@ use shirabe_external_packages::symfony::finder::Finder; 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, - is_dir, is_writable, mkdir, random_bytes, random_int, rename, time, unlink, + is_dir, is_writable, mkdir, php_regex, random_bytes, random_int, rename, time, unlink, }; use std::sync::Mutex; @@ -94,7 +94,10 @@ impl Cache { } pub fn is_usable(path: &str) -> bool { - !Preg::is_match(r"{(^|[\\\\/])(\$null|nul|NUL|/dev/null)([\\\\/]|$)}", path) + !Preg::is_match( + php_regex!(r"{(^|[\\\\/])(\$null|nul|NUL|/dev/null)([\\\\/]|$)}"), + path, + ) } pub fn is_enabled(&mut self) -> bool { @@ -124,7 +127,7 @@ impl Cache { /// @return string|false pub fn read(&mut self, file: &str) -> Option<String> { if self.is_enabled() { - let file = Preg::replace(&format!("{{[^{}]}}i", self.allowlist), "-", file); + let file = Preg::replace(format!("{{[^{}]}}i", self.allowlist), "-", file); let full_path = format!("{}{}", self.root, file); if file_exists(&full_path) { self.io.write_error3( @@ -144,7 +147,7 @@ impl Cache { let was_enabled = self.enabled == Some(true); if self.is_enabled() && !self.read_only { - let file = Preg::replace(&format!("{{[^{}]}}i", self.allowlist), "-", file); + let file = Preg::replace(format!("{{[^{}]}}i", self.allowlist), "-", file); self.io.write_error3( &format!("Writing {}{} into cache", self.root, file), @@ -185,7 +188,9 @@ impl Cache { ); let mut m = indexmap::IndexMap::new(); if Preg::match3( - r"{^file_put_contents\(\): Only ([0-9]+) of ([0-9]+) bytes written}", + php_regex!( + r"{^file_put_contents\(\): Only ([0-9]+) of ([0-9]+) bytes written}" + ), &e.message, Some(&mut m), ) { @@ -223,7 +228,7 @@ impl Cache { /// Copy a file into the cache pub fn copy_from(&mut self, file: &str, source: &str) -> bool { if self.is_enabled() && !self.read_only { - let file = Preg::replace(&format!("{{[^{}]}}i", self.allowlist), "-", file); + let file = Preg::replace(format!("{{[^{}]}}i", self.allowlist), "-", file); let full_path = format!("{}{}", self.root, file); self.filesystem .borrow_mut() @@ -252,7 +257,7 @@ impl Cache { /// Copy a file out of the cache pub fn copy_to(&mut self, file: &str, target: &str) -> anyhow::Result<bool> { if self.is_enabled() { - let file = Preg::replace(&format!("{{[^{}]}}i", self.allowlist), "-", file); + let file = Preg::replace(format!("{{[^{}]}}i", self.allowlist), "-", file); let full_path = format!("{}{}", self.root, file); if file_exists(&full_path) { let touch_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { @@ -312,7 +317,7 @@ impl Cache { pub fn remove(&mut self, file: &str) -> bool { if self.is_enabled() && !self.read_only { - let file = Preg::replace(&format!("{{[^{}]}}i", self.allowlist), "-", file); + let file = Preg::replace(format!("{{[^{}]}}i", self.allowlist), "-", file); let full_path = format!("{}{}", self.root, file); if file_exists(&full_path) { return self @@ -343,7 +348,7 @@ impl Cache { /// @phpstan-return int<0, max>|false pub fn get_age(&mut self, file: &str) -> Option<i64> { if self.is_enabled() { - let file = Preg::replace(&format!("{{[^{}]}}i", self.allowlist), "-", file); + let file = Preg::replace(format!("{{[^{}]}}i", self.allowlist), "-", file); let full_path = format!("{}{}", self.root, file); if file_exists(&full_path) && let Some(mtime) = filemtime(&full_path) @@ -461,7 +466,7 @@ impl Cache { /// @return string|false pub fn sha1(&mut self, file: &str) -> Option<String> { if self.is_enabled() { - let file = Preg::replace(&format!("{{[^{}]}}i", self.allowlist), "-", file); + let file = Preg::replace(format!("{{[^{}]}}i", self.allowlist), "-", file); let full_path = format!("{}{}", self.root, file); if file_exists(&full_path) { return hash_file("sha1", &full_path); @@ -474,7 +479,7 @@ impl Cache { /// @return string|false pub fn sha256(&mut self, file: &str) -> Option<String> { if self.is_enabled() { - let file = Preg::replace(&format!("{{[^{}]}}i", self.allowlist), "-", file); + let file = Preg::replace(format!("{{[^{}]}}i", self.allowlist), "-", file); let full_path = format!("{}{}", self.root, file); if file_exists(&full_path) { return hash_file("sha256", &full_path); diff --git a/crates/shirabe/src/command/archive_command.rs b/crates/shirabe/src/command/archive_command.rs index 2a099c89..cd2d1648 100644 --- a/crates/shirabe/src/command/archive_command.rs +++ b/crates/shirabe/src/command/archive_command.rs @@ -27,7 +27,7 @@ use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; use shirabe_external_packages::symfony::console::command::command::Command; use shirabe_external_packages::symfony::console::input::InputInterface; use shirabe_external_packages::symfony::console::output::OutputInterface; -use shirabe_php_shim::{LogicException, get_debug_type}; +use shirabe_php_shim::{LogicException, get_debug_type, php_regex}; #[derive(Debug)] pub struct ArchiveCommand { @@ -379,7 +379,7 @@ impl ArchiveCommand { if let Some(version_str) = &version { let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::match3( - r"{@(stable|RC|beta|alpha|dev)$}i", + php_regex!(r"{@(stable|RC|beta|alpha|dev)$}i"), version_str, Some(&mut matches), ) { diff --git a/crates/shirabe/src/command/bump_command.rs b/crates/shirabe/src/command/bump_command.rs index e6c565c1..8f27fcb8 100644 --- a/crates/shirabe/src/command/bump_command.rs +++ b/crates/shirabe/src/command/bump_command.rs @@ -19,7 +19,9 @@ use shirabe_external_packages::composer::pcre::Preg; use shirabe_external_packages::symfony::console::command::command::Command; use shirabe_external_packages::symfony::console::input::InputInterface; use shirabe_external_packages::symfony::console::output::OutputInterface; -use shirabe_php_shim::{PhpMixed, file_get_contents, file_put_contents, is_writable, strtolower}; +use shirabe_php_shim::{ + PhpMixed, file_get_contents, file_put_contents, is_writable, php_regex, strtolower, +}; #[derive(Debug)] pub struct BumpCommand { @@ -171,7 +173,7 @@ impl BumpCommand { let packages_filter = if !packages_filter.is_empty() { let packages_filter: Vec<String> = packages_filter .iter() - .map(|constraint| Preg::replace(r"{[:= ].+}", "", constraint)) + .map(|constraint| Preg::replace(php_regex!(r"{[:= ].+}"), "", constraint)) .collect(); let unique_lower: Vec<String> = packages_filter .iter() diff --git a/crates/shirabe/src/command/config_command.rs b/crates/shirabe/src/command/config_command.rs index 6c2e7777..6d40c307 100644 --- a/crates/shirabe/src/command/config_command.rs +++ b/crates/shirabe/src/command/config_command.rs @@ -24,7 +24,7 @@ use shirabe_external_packages::symfony::console::output::OutputInterface; use shirabe_php_shim::{ InvalidArgumentException, PhpMixed, RuntimeException, array_is_list, array_merge, escapeshellcmd, exec, explode, file_exists, file_get_contents, implode, in_array, is_array, - is_bool, is_dir, is_numeric, is_object, is_string, json_encode, str_replace, strpos, + is_bool, is_dir, is_numeric, is_object, is_string, json_encode, php_regex, str_replace, strpos, strtolower, system, touch, var_export, }; use shirabe_semver::VersionParser; @@ -350,7 +350,7 @@ impl Command for ConfigCommand { let mut value: PhpMixed; let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^repos?(?:itories)?(?:\\.(.+))?/", + php_regex!("/^repos?(?:itories)?(?:\\.(.+))?/"), &setting_key, Some(&mut matches), ) { @@ -589,7 +589,7 @@ impl Command for ConfigCommand { // handle preferred-install per-package config let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^preferred-install\\.(.+)/", + php_regex!("/^preferred-install\\.(.+)/"), &setting_key, Some(&mut matches), ) { @@ -630,7 +630,7 @@ impl Command for ConfigCommand { // handle allow-plugins config setting elements true or false to add/remove let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "{^allow-plugins\\.([a-zA-Z0-9/*-]+)}", + php_regex!("{^allow-plugins\\.([a-zA-Z0-9/*-]+)}"), &setting_key, Some(&mut matches), ) { @@ -703,7 +703,7 @@ impl Command for ConfigCommand { // handle repositories let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^repos?(?:itories)?\\.(.+)/", + php_regex!("/^repos?(?:itories)?\\.(.+)/"), &setting_key, Some(&mut matches), ) { @@ -778,7 +778,11 @@ impl Command for ConfigCommand { // handle extra let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::is_match3("/^extra\\.(.+)/", &setting_key, Some(&mut matches)) { + if Preg::is_match3( + php_regex!("/^extra\\.(.+)/"), + &setting_key, + Some(&mut matches), + ) { if input.borrow().get_option("unset")?.as_bool() == Some(true) { self.config_source .borrow_mut() @@ -851,7 +855,11 @@ impl Command for ConfigCommand { // handle suggest let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::is_match3("/^suggest\\.(.+)/", &setting_key, Some(&mut matches)) { + if Preg::is_match3( + php_regex!("/^suggest\\.(.+)/"), + &setting_key, + Some(&mut matches), + ) { if input.borrow().get_option("unset")?.as_bool() == Some(true) { self.config_source .borrow_mut() @@ -889,7 +897,11 @@ impl Command for ConfigCommand { // handle platform let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::is_match3("/^platform\\.(.+)/", &setting_key, Some(&mut matches)) { + if Preg::is_match3( + php_regex!("/^platform\\.(.+)/"), + &setting_key, + Some(&mut matches), + ) { if input.borrow().get_option("unset")?.as_bool() == Some(true) { self.config_source .borrow_mut() @@ -1013,7 +1025,9 @@ impl Command for ConfigCommand { // handle auth let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^(bitbucket-oauth|github-oauth|gitlab-oauth|gitlab-token|http-basic|custom-headers|bearer|forgejo-token)\\.(.+)/", + php_regex!( + "/^(bitbucket-oauth|github-oauth|gitlab-oauth|gitlab-token|http-basic|custom-headers|bearer|forgejo-token)\\.(.+)/" + ), &setting_key, Some(&mut matches), ) { @@ -1153,7 +1167,11 @@ impl Command for ConfigCommand { // Check if the header is in correct "Name: Value" format let mut header_parts: IndexMap<CaptureKey, String> = IndexMap::new(); - if !Preg::is_match3("/^[^:]+:\\s*.+$/", header, Some(&mut header_parts)) { + if !Preg::is_match3( + php_regex!("/^[^:]+:\\s*.+$/"), + header, + Some(&mut header_parts), + ) { return Err(RuntimeException { message: format!( "Header \"{}\" is not in \"Header-Name: Header-Value\" format", @@ -1208,7 +1226,11 @@ impl Command for ConfigCommand { // handle script let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::is_match3("/^scripts\\.(.+)/", &setting_key, Some(&mut matches)) { + if Preg::is_match3( + php_regex!("/^scripts\\.(.+)/"), + &setting_key, + Some(&mut matches), + ) { if input.borrow().get_option("unset")?.as_bool() == Some(true) { self.config_source .borrow_mut() @@ -1407,7 +1429,11 @@ impl ConfigCommand { || (key == "repositories" && k.is_none())) { let mut new_k = k.clone().unwrap_or_default(); - new_k.push_str(&Preg::replace("{^config\\.}", "", &format!("{}.", key))); + new_k.push_str(&Preg::replace( + php_regex!("{^config\\.}"), + "", + &format!("{}.", key), + )); k = Some(new_k); self.list_configuration( value_inner, @@ -1466,13 +1492,13 @@ impl ConfigCommand { } else { k.clone().unwrap() }; - let id = Preg::replace("{\\..*$}", "", &id_source); + let id = Preg::replace(php_regex!("{\\..*$}"), "", &id_source); let id = Preg::replace( - "{[^a-z0-9]}i", + php_regex!("{[^a-z0-9]}i"), "-", &strtolower(&shirabe_php_shim::trim(&id, Some(" \t\n\r\0\u{0B}"))), ); - let id = Preg::replace("{-+}", "-", &id); + let id = Preg::replace(php_regex!("{-+}"), "-", &id); format!("https://getcomposer.org/doc/06-config.md#{}", id) }; if is_string(&raw_val) @@ -1707,7 +1733,7 @@ fn build_unique_config_values() -> IndexMap<String, (ValidatorFn, NormalizerFn)> ( Box::new(|val| { PhpMixed::Bool(Preg::is_match3( - "/^\\s*([0-9.]+)\\s*(?:([kmg])(?:i?b)?)?\\s*$/i", + php_regex!("/^\\s*([0-9.]+)\\s*(?:([kmg])(?:i?b)?)?\\s*$/i"), val.as_string().unwrap_or(""), None, )) diff --git a/crates/shirabe/src/command/create_project_command.rs b/crates/shirabe/src/command/create_project_command.rs index 4544cb63..9a2c4755 100644 --- a/crates/shirabe/src/command/create_project_command.rs +++ b/crates/shirabe/src/command/create_project_command.rs @@ -735,7 +735,7 @@ impl CreateProjectCommand { let ok = { let mut matched: IndexMap<CaptureKey, String> = IndexMap::new(); let ok = Preg::is_match3( - &format!( + format!( "{{^[^,\\s]*?@({})$}}i", implode( "|", diff --git a/crates/shirabe/src/command/diagnose_command.rs b/crates/shirabe/src/command/diagnose_command.rs index e457fbb2..d726efd4 100644 --- a/crates/shirabe/src/command/diagnose_command.rs +++ b/crates/shirabe/src/command/diagnose_command.rs @@ -44,8 +44,8 @@ use shirabe_php_shim::{ PHP_BINARY, PHP_EOL, PHP_VERSION, PHP_VERSION_ID, PHP_WINDOWS_VERSION_BUILD, PhpMixed, defined, disk_free_space, extension_loaded, file_exists, filter_var_boolean, function_exists, get_class_err, hash, implode, ini_get, ioncube_loader_iversion, ioncube_loader_version, - is_array, is_string, ob_get_clean, ob_start, phpinfo, rtrim, str_contains, str_replace, - str_starts_with, strpos, strstr, strtolower, trim, version_compare, + is_array, is_string, ob_get_clean, ob_start, php_regex, phpinfo, rtrim, str_contains, + str_replace, str_starts_with, strpos, strstr, strtolower, trim, version_compare, }; #[derive(Debug)] @@ -1176,7 +1176,9 @@ impl DiagnoseCommand { let mut phpinfo_match: IndexMap<CaptureKey, String> = IndexMap::new(); if phpinfo_str.is_some() && Preg::is_match3( - "{Configure Command(?: *</td><td class=\"v\">| *=> *)(.*?)(?:</td>|$)}m", + php_regex!( + "{Configure Command(?: *</td><td class=\"v\">| *=> *)(.*?)(?:</td>|$)}m" + ), phpinfo_str.as_ref().unwrap(), Some(&mut phpinfo_match), ) diff --git a/crates/shirabe/src/command/fund_command.rs b/crates/shirabe/src/command/fund_command.rs index 65ae2c94..c40a3760 100644 --- a/crates/shirabe/src/command/fund_command.rs +++ b/crates/shirabe/src/command/fund_command.rs @@ -14,7 +14,7 @@ use shirabe_external_packages::symfony::console::command::command::Command; use shirabe_external_packages::symfony::console::formatter::OutputFormatter; use shirabe_external_packages::symfony::console::input::InputInterface; use shirabe_external_packages::symfony::console::output::OutputInterface; -use shirabe_php_shim::PhpMixed; +use shirabe_php_shim::{PhpMixed, php_regex}; use shirabe_semver::constraint::AnyConstraint; use shirabe_semver::constraint::MatchAllConstraint; @@ -60,8 +60,10 @@ impl FundCommand { .and_then(|v| v.as_string()) .unwrap_or(""); if r#type == "github" - && let Some(matches) = - Preg::is_match_with_indexed_captures(r"{^https://github.com/([^/]+)$}", &url) + && let Some(matches) = Preg::is_match_with_indexed_captures( + php_regex!(r"{^https://github.com/([^/]+)$}"), + &url, + ) && let Some(sponsor) = matches.into_iter().nth(1) { url = format!("https://github.com/sponsors/{}", sponsor); diff --git a/crates/shirabe/src/command/global_command.rs b/crates/shirabe/src/command/global_command.rs index a1f5f72e..dd1ec9c2 100644 --- a/crates/shirabe/src/command/global_command.rs +++ b/crates/shirabe/src/command/global_command.rs @@ -15,7 +15,7 @@ use shirabe_external_packages::symfony::console::input::ArrayInput; use shirabe_external_packages::symfony::console::input::InputInterface; use shirabe_external_packages::symfony::console::input::StringInput; use shirabe_external_packages::symfony::console::output::OutputInterface; -use shirabe_php_shim::{LogicException, RuntimeException, chdir}; +use shirabe_php_shim::{LogicException, RuntimeException, chdir, php_regex}; use std::path::Path; #[derive(Debug)] @@ -100,7 +100,7 @@ impl GlobalCommand { } let new_input_str = Preg::replace4( - r"{\bg(?:l(?:o(?:b(?:a(?:l)?)?)?)?)?\b}", + php_regex!(r"{\bg(?:l(?:o(?:b(?:a(?:l)?)?)?)?)?\b}"), "", &Self::input_to_string(&*input.borrow())?, 1, @@ -153,7 +153,10 @@ impl Command for GlobalCommand { input: std::rc::Rc<std::cell::RefCell<dyn InputInterface>>, output: std::rc::Rc<std::cell::RefCell<dyn OutputInterface>>, ) -> anyhow::Result<i64> { - let tokens = Preg::split(r"{\s+}", &Self::input_to_string(&*input.borrow())?); + let tokens = Preg::split( + php_regex!(r"{\s+}"), + &Self::input_to_string(&*input.borrow())?, + ); let mut args: Vec<String> = vec![]; for token in &tokens { if !token.is_empty() && !token.starts_with('-') { diff --git a/crates/shirabe/src/command/init_command.rs b/crates/shirabe/src/command/init_command.rs index f0f07a56..6b3503b0 100644 --- a/crates/shirabe/src/command/init_command.rs +++ b/crates/shirabe/src/command/init_command.rs @@ -28,7 +28,7 @@ use shirabe_php_shim::{ FILE_IGNORE_NEW_LINES, InvalidArgumentException, PHP_EOL, PHP_SERVER, PhpMixed, array_flip_strings, array_intersect_key, array_map, basename, empty, explode, file, file_exists, file_get_contents, file_put_contents, get_current_user, implode, is_dir, - is_string, preg_quote, realpath, str_replace, strpos, strtolower, trim, ucwords, + is_string, php_regex, preg_quote, realpath, str_replace, strpos, strtolower, trim, ucwords, }; use shirabe_spdx_licenses::SpdxLicenses; @@ -143,7 +143,7 @@ impl Command for InitCommand { if options.contains_key("name") && !Preg::is_match( - r"{^[a-z0-9]([_.-]?[a-z0-9]+)*\/[a-z0-9](([_.]|-{1,2})?[a-z0-9]+)*$}D", + php_regex!(r"{^[a-z0-9]([_.-]?[a-z0-9]+)*\/[a-z0-9](([_.]|-{1,2})?[a-z0-9]+)*$}D"), options .get("name") .and_then(|v| v.as_string()) @@ -556,7 +556,7 @@ impl Command for InitCommand { } if !Preg::is_match( - r"{^[a-z0-9]([_.-]?[a-z0-9]+)*\/[a-z0-9](([_.]|-{1,2})?[a-z0-9]+)*$}D", + php_regex!(r"{^[a-z0-9]([_.-]?[a-z0-9]+)*\/[a-z0-9](([_.]|-{1,2})?[a-z0-9]+)*$}D"), value.as_string().unwrap_or(""), ) { return Err(InvalidArgumentException { @@ -877,7 +877,7 @@ impl Command for InitCommand { value_str }; - if !Preg::is_match(r"{^[^/][A-Za-z0-9\-_/]+/$}", &value_or_default) + if !Preg::is_match(php_regex!(r"{^[^/][A-Za-z0-9\-_/]+/$}"), &value_or_default) { return Err(InvalidArgumentException { message: format!( @@ -921,7 +921,7 @@ impl InitCommand { ) -> anyhow::Result<IndexMap<String, Option<String>>> { let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - r#"/^(?P<name>[- .,\p{L}\p{N}\p{Mn}\'’\"()]+)(?:\s+<(?P<email>.+?)>)?$/u"#, + php_regex!(r#"/^(?P<name>[- .,\p{L}\p{N}\p{Mn}\'’\"()]+)(?:\s+<(?P<email>.+?)>)?$/u"#), author, Some(&mut m), ) { @@ -988,7 +988,7 @@ impl InitCommand { let namespace: Vec<String> = array_map( |part: &String| { - let part = Preg::replace(r"/[^a-z0-9]/i", " ", part); + let part = Preg::replace(php_regex!(r"/[^a-z0-9]/i"), " ", part); let part = ucwords(&part); str_replace(" ", "", &part) }, @@ -1015,7 +1015,7 @@ impl InitCommand { { *self.git_config.borrow_mut() = Some(IndexMap::new()); let mut m: IndexMap<CaptureKey, Vec<String>> = IndexMap::new(); - if Preg::is_match_all3(r"{^([^=]+)=(.*)$}m", &output, Some(&mut m)) { + if Preg::is_match_all3(php_regex!(r"{^([^=]+)=(.*)$}m"), &output, Some(&mut m)) { let keys: Vec<String> = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); let values: Vec<String> = m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default(); @@ -1174,14 +1174,14 @@ impl InitCommand { fn sanitize_package_name_component(&self, name: &str) -> String { let name = Preg::replace( - r"{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}", + php_regex!(r"{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}"), "$1$3-$2$4", name, ); let name = strtolower(&name); - let name = Preg::replace(r"{^[_.-]+|[_.-]+$|[^a-z0-9_.-]}u", "", &name); + let name = Preg::replace(php_regex!(r"{^[_.-]+|[_.-]+$|[^a-z0-9_.-]}u"), "", &name); - Preg::replace(r"{([_.-]){2,}}u", "$1", &name) + Preg::replace(php_regex!(r"{([_.-]){2,}}u"), "$1", &name) } fn get_default_package_name(&self) -> String { diff --git a/crates/shirabe/src/command/package_discovery_trait.rs b/crates/shirabe/src/command/package_discovery_trait.rs index e5427514..f8f7cede 100644 --- a/crates/shirabe/src/command/package_discovery_trait.rs +++ b/crates/shirabe/src/command/package_discovery_trait.rs @@ -24,7 +24,7 @@ use shirabe_external_packages::symfony::console::output::OutputInterface; use shirabe_php_shim::{ Exception, InvalidArgumentException, LogicException, PHP_EOL, PhpMixed, array_keys, array_slice, asort, explode, file_get_contents, implode, in_array, is_array, is_file, - is_numeric, json_decode, levenshtein, strlen, strpos, trim, + is_numeric, json_decode, levenshtein, php_regex, strlen, strpos, trim, }; /// @internal @@ -145,7 +145,7 @@ pub trait PackageDiscoveryTrait: BaseCommand { for mut requirement in requires_norm { if requirement.contains_key("version") && Preg::is_match( - r"{^\d+(\.\d+)?$}", + php_regex!(r"{^\d+(\.\d+)?$}"), requirement.get("version").map(|s| s.as_str()).unwrap_or(""), ) { @@ -337,7 +337,7 @@ pub trait PackageDiscoveryTrait: BaseCommand { let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - r"{^\s*(?P<name>[\S/]+)(?:\s+(?P<version>\S+))?\s*$}", + php_regex!(r"{^\s*(?P<name>[\S/]+)(?:\s+(?P<version>\S+))?\s*$}"), &selection, Some(&mut m), ) { diff --git a/crates/shirabe/src/command/remove_command.rs b/crates/shirabe/src/command/remove_command.rs index e7686efd..776fca79 100644 --- a/crates/shirabe/src/command/remove_command.rs +++ b/crates/shirabe/src/command/remove_command.rs @@ -396,7 +396,7 @@ impl Command for RemoveCommand { .unwrap_or_default(); let type_keys_refs: Vec<&str> = type_keys.iter().map(|s| s.as_str()).collect(); let matches_in_type = Preg::grep( - &base_package::package_name_to_regexp(package), + base_package::package_name_to_regexp(package), &type_keys_refs, ); @@ -409,7 +409,7 @@ impl Command for RemoveCommand { let alt_type_keys_refs: Vec<&str> = alt_type_keys.iter().map(|s| s.as_str()).collect(); let matches_in_alt_type = Preg::grep( - &base_package::package_name_to_regexp(package), + base_package::package_name_to_regexp(package), &alt_type_keys_refs, ); diff --git a/crates/shirabe/src/command/repository_command.rs b/crates/shirabe/src/command/repository_command.rs index 06ecfb4f..c42b70c4 100644 --- a/crates/shirabe/src/command/repository_command.rs +++ b/crates/shirabe/src/command/repository_command.rs @@ -15,7 +15,8 @@ use shirabe_external_packages::symfony::console::command::command::Command; use shirabe_external_packages::symfony::console::input::InputInterface; use shirabe_external_packages::symfony::console::output::OutputInterface; use shirabe_php_shim::{ - InvalidArgumentException, PHP_URL_HOST, PhpMixed, RuntimeException, parse_url, strtolower, + InvalidArgumentException, PHP_URL_HOST, PhpMixed, RuntimeException, parse_url, php_regex, + strtolower, }; #[derive(Debug)] @@ -287,7 +288,7 @@ impl Command for RepositoryCommand { })); } let arg1_str = arg1.as_deref().unwrap(); - let repo_config: PhpMixed = if Preg::is_match(r"{^\s*\{}", arg1_str) { + let repo_config: PhpMixed = if Preg::is_match(php_regex!(r"{^\s*\{}"), arg1_str) { JsonFile::parse_json(Some(arg1_str), None)? } else { if arg2.is_none() { diff --git a/crates/shirabe/src/command/script_alias_command.rs b/crates/shirabe/src/command/script_alias_command.rs index 17629162..5cc4af58 100644 --- a/crates/shirabe/src/command/script_alias_command.rs +++ b/crates/shirabe/src/command/script_alias_command.rs @@ -10,7 +10,7 @@ use shirabe_external_packages::composer::pcre::Preg; use shirabe_external_packages::symfony::console::command::command::Command; use shirabe_external_packages::symfony::console::input::InputInterface; use shirabe_external_packages::symfony::console::output::OutputInterface; -use shirabe_php_shim::{InvalidArgumentException, LogicException, PhpMixed, is_string}; +use shirabe_php_shim::{InvalidArgumentException, LogicException, PhpMixed, is_string, php_regex}; #[derive(Debug)] pub struct ScriptAliasCommand { @@ -138,7 +138,7 @@ impl Command for ScriptAliasCommand { // TODO(phase-c): InputInterface lacks to_string; use a placeholder until it is modeled. let input_as_string = String::new(); let _ = input; - let script_alias_input = Preg::replace4(r"{^\S+ ?}", "", &input_as_string, 1); + let script_alias_input = Preg::replace4(php_regex!(r"{^\S+ ?}"), "", &input_as_string, 1); let mut flags = indexmap::IndexMap::new(); flags.insert( "script-alias-input".to_string(), diff --git a/crates/shirabe/src/command/show_command.rs b/crates/shirabe/src/command/show_command.rs index a63e08cf..8d1f67ff 100644 --- a/crates/shirabe/src/command/show_command.rs +++ b/crates/shirabe/src/command/show_command.rs @@ -41,8 +41,8 @@ use shirabe_external_packages::symfony::console::input::InputInterface; use shirabe_external_packages::symfony::console::output::OutputInterface; use shirabe_php_shim::{ DATE_ATOM, InvalidArgumentException, LogicException, PhpMixed, UnexpectedValueException, - array_search, date, date_format_to_strftime, extension_loaded, in_array, realpath, strtolower, - version_compare, + array_search, date, date_format_to_strftime, extension_loaded, in_array, php_regex, realpath, + strtolower, version_compare, }; use shirabe_semver::Semver; use shirabe_semver::constraint::AnyConstraint; @@ -2775,7 +2775,7 @@ impl ShowCommand { let mut groups: IndexMap<CaptureKey, String> = IndexMap::new(); if major_only && Preg::is_match3( - r"{^(?P<zero_major>(?:0\.)+)?(?P<first_meaningful>\d+)\.}", + php_regex!(r"{^(?P<zero_major>(?:0\.)+)?(?P<first_meaningful>\d+)\.}"), &package.get_version(), Some(&mut groups), ) @@ -2802,7 +2802,8 @@ impl ShowCommand { } if patch_only { - let trimmed_version = Preg::replace(r"{(\.0)+$}D", "", &package.get_version()); + let trimmed_version = + Preg::replace(php_regex!(r"{(\.0)+$}D"), "", &package.get_version()); let parts_needed = if trimmed_version.starts_with('0') { 4 } else { diff --git a/crates/shirabe/src/command/update_command.rs b/crates/shirabe/src/command/update_command.rs index 0163f6bc..0d212350 100644 --- a/crates/shirabe/src/command/update_command.rs +++ b/crates/shirabe/src/command/update_command.rs @@ -31,7 +31,7 @@ use shirabe_external_packages::symfony::console::input::InputInterface; use shirabe_external_packages::symfony::console::output::OutputInterface; use shirabe_php_shim::{ InvalidArgumentException, PhpMixed, RuntimeException, array_filter, array_intersect, - array_keys, array_merge_map, array_search_in_vec, in_array, strtolower, + array_keys, array_merge_map, array_search_in_vec, in_array, php_regex, strtolower, }; use shirabe_semver::Intervals; use shirabe_semver::constraint::MultiConstraint; @@ -184,7 +184,7 @@ impl Command for UpdateCommand { if !packages.is_empty() { let allowlist_packages_with_requirements: Vec<String> = array_filter(&packages, |pkg: &String| -> bool { - Preg::is_match(r"{\S+[ =:]\S+}", pkg) + Preg::is_match(php_regex!(r"{\S+[ =:]\S+}"), pkg) }); for (package, constraint) in self.format_requirements(allowlist_packages_with_requirements.clone())? @@ -194,7 +194,8 @@ impl Command for UpdateCommand { // replace the foo/bar:req by foo/bar in the allowlist for package in &allowlist_packages_with_requirements { - let package_name = Preg::replace(r"{^([^ =:]+)[ =:].*$}", "$1", package); + let package_name = + Preg::replace(php_regex!(r"{^([^ =:]+)[ =:].*$}"), "$1", package); if let Some(idx) = array_search_in_vec(package, &packages) { packages[idx] = package_name; } @@ -266,7 +267,7 @@ impl Command for UpdateCommand { continue; } let matches = Preg::is_match_with_indexed_captures( - r"{^(\d+\.\d+\.\d+)}", + php_regex!(r"{^(\d+\.\d+\.\d+)}"), &package.get_version(), ); let Some(matches) = matches else { diff --git a/crates/shirabe/src/composer.rs b/crates/shirabe/src/composer.rs index e28fb00d..a0a8f248 100644 --- a/crates/shirabe/src/composer.rs +++ b/crates/shirabe/src/composer.rs @@ -12,6 +12,7 @@ use crate::plugin::PluginManager; use crate::repository::RepositoryManagerInterface; use crate::util::r#loop::Loop; use shirabe_external_packages::composer::pcre::Preg; +use shirabe_php_shim::php_regex; // TODO: change this information to Shirabe version. pub const VERSION: &str = "2.9.7"; @@ -24,7 +25,7 @@ pub fn get_version() -> String { if VERSION == "@package_version@" { return SOURCE_VERSION.to_string(); } - if !BRANCH_ALIAS_VERSION.is_empty() && Preg::is_match("{^[a-f0-9]{40}$}", VERSION) { + if !BRANCH_ALIAS_VERSION.is_empty() && Preg::is_match(php_regex!("{^[a-f0-9]{40}$}"), VERSION) { return format!("{}+{}", BRANCH_ALIAS_VERSION, VERSION); } VERSION.to_string() diff --git a/crates/shirabe/src/config.rs b/crates/shirabe/src/config.rs index d1cd4212..bc172bd2 100644 --- a/crates/shirabe/src/config.rs +++ b/crates/shirabe/src/config.rs @@ -12,8 +12,8 @@ use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ E_USER_DEPRECATED, PHP_URL_HOST, PHP_URL_SCHEME, PhpMixed, RuntimeException, array_key_exists, array_merge, array_search_mixed, array_unique, empty, filter_var_url, implode, in_array, - is_array, is_string, parse_url, php_to_string, rtrim, strtolower, strtoupper, strtr, substr, - trigger_error, + is_array, is_string, parse_url, php_regex, php_to_string, rtrim, strtolower, strtoupper, strtr, + substr, trigger_error, }; use crate::advisory::Auditor; @@ -497,7 +497,7 @@ impl Config { .to_string(); if is_composer && Preg::is_match( - r"{^https?://(?:[a-z0-9-.]+\.)?packagist.org(/|$)}", + php_regex!(r"{^https?://(?:[a-z0-9-.]+\.)?packagist.org(/|$)}"), &repo_url, ) { @@ -676,7 +676,7 @@ impl Config { .to_string(); let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if !Preg::is_match3( - r"/^\s*([0-9.]+)\s*(?:([kmg])(?:i?b)?)?\s*$/i", + php_regex!(r"/^\s*([0-9.]+)\s*(?:([kmg])(?:i?b)?)?\s*$/i"), &raw, Some(&mut matches), ) { @@ -1046,7 +1046,7 @@ impl Config { let value_str = value.as_string().unwrap_or("").to_string(); let mut error = None; let result = Preg::replace_callback( - r"#\{\$(.+)\}#", + php_regex!(r"#\{\$(.+)\}#"), |m: &IndexMap<CaptureKey, String>| -> String { let key_match = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); match self.get_with_flags(&key_match, flags) { @@ -1069,7 +1069,7 @@ impl Config { /// /// Since the dirs might not exist yet we can not call realpath or it will fail. fn realpath(&self, path: &str) -> String { - if Preg::is_match(r"{^(?:/|[a-z]:|[a-z0-9.]+://|\\\\\\\\)}i", path) { + if Preg::is_match(php_regex!(r"{^(?:/|[a-z]:|[a-z0-9.]+://|\\\\\\\\)}i"), path) { return path.to_string(); } @@ -1115,7 +1115,7 @@ impl Config { repo_options: &IndexMap<String, PhpMixed>, ) -> anyhow::Result<()> { // Return right away if the URL is malformed or custom (see issue #5173), but only for non-HTTP(S) URLs - if !filter_var_url(url) && !Preg::is_match(r"{^https?://}", url) { + if !filter_var_url(url) && !Preg::is_match(php_regex!(r"{^https?://}"), url) { return Ok(()); } diff --git a/crates/shirabe/src/console/application.rs b/crates/shirabe/src/console/application.rs index 55854f11..577d8704 100644 --- a/crates/shirabe/src/console/application.rs +++ b/crates/shirabe/src/console/application.rs @@ -99,8 +99,8 @@ use shirabe_php_shim::{ disk_free_space, extension_loaded, file_exists, file_get_contents, file_put_contents, function_exists, getcwd, getmypid, glob, in_array, ini_set, is_array, is_dir, is_file, is_string, is_subclass_of, json_decode, memory_get_peak_usage, memory_get_usage, microtime, - php_uname, posix_getuid, random_bytes, realpath, restore_error_handler, round, str_contains, - str_replace, strpos, strtoupper, sys_get_temp_dir, time, unlink, + php_regex, php_uname, posix_getuid, random_bytes, realpath, restore_error_handler, round, + str_contains, str_replace, strpos, strtoupper, sys_get_temp_dir, time, unlink, }; /// The PHP `Composer\Console\Application` and `Symfony\Component\Console\Application` are @@ -882,7 +882,7 @@ impl Application { .map(|p| shirabe_php_shim::preg_quote(&p, None)) .collect(); let expr = format!("{}{}", shirabe_php_shim::implode("[^:]*:", &parts), "[^:]*"); - let namespaces = shirabe_php_shim::preg_grep(&format!("{{^{}}}", expr), &all_namespaces); + let namespaces = shirabe_php_shim::preg_grep(format!("{{^{}}}", expr), &all_namespaces); if namespaces.is_empty() { let mut message = format!( @@ -983,15 +983,15 @@ impl Application { .map(|p| shirabe_php_shim::preg_quote(&p, None)) .collect(); let expr = format!("{}{}", shirabe_php_shim::implode("[^:]*:", &parts), "[^:]*"); - let mut commands = shirabe_php_shim::preg_grep(&format!("{{^{}}}", expr), &all_commands); + let mut commands = shirabe_php_shim::preg_grep(format!("{{^{}}}", expr), &all_commands); if commands.is_empty() { - commands = shirabe_php_shim::preg_grep(&format!("{{^{}}}i", expr), &all_commands); + commands = shirabe_php_shim::preg_grep(format!("{{^{}}}i", expr), &all_commands); } // if no commands matched or we just matched namespaces if commands.is_empty() - || shirabe_php_shim::preg_grep(&format!("{{^{}$}}i", expr), &commands).is_empty() + || shirabe_php_shim::preg_grep(format!("{{^{}$}}i", expr), &commands).is_empty() { if let Some(pos) = shirabe_php_shim::strrpos(name, ":") { // check if a namespace exists and contains commands @@ -1278,7 +1278,7 @@ impl Application { }; let mut lines: Vec<(String, i64)> = Vec::new(); let split = if !message.is_empty() { - shirabe_php_shim::preg_split(r"/\r?\n/", &message) + shirabe_php_shim::preg_split(php_regex!(r"/\r?\n/"), &message) } else { Vec::new() }; @@ -1723,7 +1723,7 @@ impl Application { let mut m: indexmap::IndexMap<shirabe_php_shim::CaptureKey, Option<String>> = indexmap::IndexMap::new(); while shirabe_php_shim::preg_match2( - r"/.{1,10000}/u", + php_regex!(r"/.{1,10000}/u"), &utf8_string, &mut m, 0, diff --git a/crates/shirabe/src/dependency_resolver/lock_transaction.rs b/crates/shirabe/src/dependency_resolver/lock_transaction.rs index fb345626..1beedd24 100644 --- a/crates/shirabe/src/dependency_resolver/lock_transaction.rs +++ b/crates/shirabe/src/dependency_resolver/lock_transaction.rs @@ -6,6 +6,7 @@ use crate::dependency_resolver::Transaction; use crate::package::PackageInterfaceHandle; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::Preg; +use shirabe_php_shim::php_regex; #[derive(Debug)] pub struct LockTransaction { @@ -159,12 +160,14 @@ impl LockTransaction { if package.get_dist_url().is_some() && present_package.get_dist_reference().is_some() && Preg::is_match( - r"{^https?://(?:(?:www\.)?bitbucket\.org|(api\.)?github\.com|(?:www\.)?gitlab\.com)/}i", + php_regex!( + r"{^https?://(?:(?:www\.)?bitbucket\.org|(api\.)?github\.com|(?:www\.)?gitlab\.com)/}i" + ), &package.get_dist_url().unwrap(), ) { let new_dist_url = Preg::replace( - r"{(?<=/|sha=)[a-f0-9]{40}(?=/|$)}i", + php_regex!(r"{(?<=/|sha=)[a-f0-9]{40}(?=/|$)}i"), &present_package.get_dist_reference().unwrap(), &package.get_dist_url().unwrap(), ); diff --git a/crates/shirabe/src/dependency_resolver/problem.rs b/crates/shirabe/src/dependency_resolver/problem.rs index 08885103..855638cf 100644 --- a/crates/shirabe/src/dependency_resolver/problem.rs +++ b/crates/shirabe/src/dependency_resolver/problem.rs @@ -13,7 +13,7 @@ use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; use shirabe_external_packages::symfony::console::formatter::OutputFormatter; use shirabe_php_shim::{ - LogicException, PhpMixed, defined, extension_loaded, implode, in_array, phpversion, + LogicException, PhpMixed, defined, extension_loaded, implode, in_array, php_regex, phpversion, spl_object_hash, sprintf, str_replace, str_starts_with, stripos, strpos, strtolower, substr, substr_count, version_compare, }; @@ -229,7 +229,9 @@ impl Problem { true, ) { Preg::is_match3( - r"{^(?P<package>\S+) (?P<version>\S+) (?P<type>requires|conflicts)}", + php_regex!( + r"{^(?P<package>\S+) (?P<version>\S+) (?P<type>requires|conflicts)}" + ), &message, Some(&mut m), ) @@ -238,7 +240,7 @@ impl Problem { }; if matched { message = str_replace("%", "%%", &message); - let template = Preg::replace(r"{^\S+ \S+ }", "%s%s ", &message); + let template = Preg::replace(php_regex!(r"{^\S+ \S+ }"), "%s%s ", &message); messages.push(template.clone()); let pkg_key = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); let m2 = m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default(); @@ -305,8 +307,11 @@ impl Problem { }; if versions_list.len() > 1 { // remove the s from requires/conflicts to correct grammar - let message_var = - Preg::replace(r"{^(%s%s (?:require|conflict))s}", "$1", message); + let message_var = Preg::replace( + php_regex!(r"{^(%s%s (?:require|conflict))s}"), + "$1", + message, + ); result.push(sprintf( &message_var, &[ @@ -560,9 +565,13 @@ impl Problem { if let Some(c) = constraint && c.is_constraint() && c.get_operator() == SimpleConstraint::STR_OP_EQ - && Preg::is_match3(r"{^dev-.*#.*}", &c.get_pretty_string(), None) + && Preg::is_match3(php_regex!(r"{^dev-.*#.*}"), &c.get_pretty_string(), None) { - let new_constraint = Preg::replace(r"{ +as +([^,\s|]+)$}", "", &c.get_pretty_string()); + let new_constraint = Preg::replace( + php_regex!(r"{ +as +([^,\s|]+)$}"), + "", + &c.get_pretty_string(), + ); let packages = repository_set.find_packages( package_name, Some( @@ -1011,8 +1020,8 @@ impl Problem { )); } - if !Preg::is_match3(r"{^[A-Za-z0-9_./-]+$}", package_name, None) { - let illegal_chars = Preg::replace(r"{[A-Za-z0-9_./-]+}", "", package_name); + if !Preg::is_match3(php_regex!(r"{^[A-Za-z0-9_./-]+$}"), package_name, None) { + let illegal_chars = Preg::replace(php_regex!(r"{[A-Za-z0-9_./-]+}"), "", package_name); return Ok(( format!("- Root composer.json requires {}, it ", package_name), @@ -1223,7 +1232,7 @@ impl Problem { .or_default() .push(pretty.clone()); } else { - let key = Preg::replace(r"{^(\d+)\..*}", "$1", version); + let key = Preg::replace(php_regex!(r"{^(\d+)\..*}"), "$1", version); by_major.entry(key).or_default().push(pretty.clone()); } } @@ -1400,7 +1409,11 @@ impl Problem { && c.get_operator() == SimpleConstraint::STR_OP_EQ && !str_starts_with(c.get_version(), "dev-") { - if !Preg::is_match3(r"{^\d+(?:\.\d+)*$}", &c.get_pretty_string(), None) { + if !Preg::is_match3( + php_regex!(r"{^\d+(?:\.\d+)*$}"), + &c.get_pretty_string(), + None, + ) { return format!(" {} (exact version match)", c.get_pretty_string()); } diff --git a/crates/shirabe/src/downloader/fossil_downloader.rs b/crates/shirabe/src/downloader/fossil_downloader.rs index 7663c014..7f610463 100644 --- a/crates/shirabe/src/downloader/fossil_downloader.rs +++ b/crates/shirabe/src/downloader/fossil_downloader.rs @@ -13,7 +13,7 @@ use crate::util::Filesystem; use crate::util::ProcessExecutor; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::Preg; -use shirabe_php_shim::{PhpMixed, RuntimeException}; +use shirabe_php_shim::{PhpMixed, RuntimeException, php_regex}; #[derive(Debug)] pub struct FossilDownloader { @@ -237,7 +237,7 @@ impl VcsDownloader for FossilDownloader { let lines: Vec<String> = if trimmed.is_empty() { vec![] } else { - Preg::split(r"{\r?\n}", &trimmed) + Preg::split(php_regex!(r"{\r?\n}"), &trimmed) }; for line in lines { diff --git a/crates/shirabe/src/downloader/git_downloader.rs b/crates/shirabe/src/downloader/git_downloader.rs index cbd429c9..52fd7b1b 100644 --- a/crates/shirabe/src/downloader/git_downloader.rs +++ b/crates/shirabe/src/downloader/git_downloader.rs @@ -19,7 +19,7 @@ use crate::util::Url; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ - PhpMixed, RuntimeException, array_map, basename, dirname, implode, in_array, is_dir, + PhpMixed, RuntimeException, array_map, basename, dirname, implode, in_array, is_dir, php_regex, preg_quote, realpath, rtrim, strlen, strpos, substr, trim, version_compare, }; @@ -96,7 +96,11 @@ impl GitDownloader { let mut refs = trim(&output, None); let mut head_match: IndexMap<CaptureKey, String> = IndexMap::new(); - if !Preg::is_match3(r"{^([a-f0-9]+) HEAD$}mi", &refs, Some(&mut head_match)) { + if !Preg::is_match3( + php_regex!(r"{^([a-f0-9]+) HEAD$}mi"), + &refs, + Some(&mut head_match), + ) { // could not match the HEAD for some reason return Ok(None); } @@ -107,7 +111,7 @@ impl GitDownloader { let mut branches_match: IndexMap<CaptureKey, Vec<String>> = IndexMap::new(); if !Preg::is_match_all3( - &format!("{{^{} refs/heads/(.+)$}}mi", preg_quote(&head_ref, None)), + format!("{{^{} refs/heads/(.+)$}}mi", preg_quote(&head_ref, None)), &refs, Some(&mut branches_match), ) { @@ -132,7 +136,7 @@ impl GitDownloader { for candidate in &candidate_branches { let mut m: IndexMap<CaptureKey, Vec<String>> = IndexMap::new(); if Preg::is_match_all3( - &format!( + format!( "{{^[a-f0-9]+ refs/remotes/((?:[^/]+)/{})$}}mi", preg_quote(candidate, None) ), @@ -276,7 +280,11 @@ impl GitDownloader { // If the non-existent branch is actually the name of a file, the file // is checked out. - let mut branch = Preg::replace(r"{(?:^dev-|(?:\.x)?-dev$)}i", "", pretty_version); + let mut branch = Preg::replace( + php_regex!(r"{(?:^dev-|(?:\.x)?-dev$)}i"), + "", + pretty_version, + ); // Closure equivalent: $execute = function(array $command) use (&$output, $path) { ... }; // Inlined below at each call site. @@ -296,10 +304,10 @@ impl GitDownloader { // check whether non-commitish are branches or tags, and fetch branches with the remote name let git_ref = reference.to_string(); - if !Preg::is_match(r"{^[a-f0-9]{40}$}", reference) + if !Preg::is_match(php_regex!(r"{^[a-f0-9]{40}$}"), reference) && branches.is_some() && Preg::is_match( - &format!("{{^\\s+composer/{}$}}m", preg_quote(reference, None)), + format!("{{^\\s+composer/{}$}}m", preg_quote(reference, None)), branches.as_deref().unwrap_or(""), ) { @@ -342,15 +350,15 @@ impl GitDownloader { } // try to checkout branch by name and then reset it so it's on the proper branch name - if Preg::is_match(r"{^[a-f0-9]{40}$}", reference) { + if Preg::is_match(php_regex!(r"{^[a-f0-9]{40}$}"), reference) { // add 'v' in front of the branch if it was stripped when generating the pretty name if branches.is_some() && !Preg::is_match( - &format!("{{^\\s+composer/{}$}}m", preg_quote(&branch, None)), + format!("{{^\\s+composer/{}$}}m", preg_quote(&branch, None)), branches.as_deref().unwrap_or(""), ) && Preg::is_match( - &format!("{{^\\s+composer/v{}$}}m", preg_quote(&branch, None)), + format!("{{^\\s+composer/v{}$}}m", preg_quote(&branch, None)), branches.as_deref().unwrap_or(""), ) { @@ -502,7 +510,7 @@ impl GitDownloader { // set push url for github projects let mut match_: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - &format!( + format!( "{{^(?:https?|git)://{}/([^/]+)/([^/]+?)(?:\\.git)?$}}", GitUtil::get_github_domains_regex(&self.inner.config.borrow()) ), @@ -661,7 +669,8 @@ impl GitDownloader { } pub(crate) fn get_short_hash(&self, reference: &str) -> String { - if !self.inner.io.is_verbose() && Preg::is_match(r"{^[0-9a-f]{40}$}", reference) { + if !self.inner.io.is_verbose() && Preg::is_match(php_regex!(r"{^[0-9a-f]{40}$}"), reference) + { return substr(reference, 0, Some(10)); } @@ -1127,11 +1136,11 @@ impl VcsDownloader for GitDownloader { let mut origin_match: IndexMap<CaptureKey, String> = IndexMap::new(); let mut composer_match: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - r"{^origin\s+(?P<url>\S+)}m", + php_regex!(r"{^origin\s+(?P<url>\S+)}m"), &output, Some(&mut origin_match), ) && Preg::is_match3( - r"{^composer\s+(?P<url>\S+)}m", + php_regex!(r"{^composer\s+(?P<url>\S+)}m"), &output, Some(&mut composer_match), ) { @@ -1212,7 +1221,7 @@ impl VcsDownloader for GitDownloader { let changes: Vec<String> = array_map( |elem: &String| format!(" {}", elem), - &Preg::split(r"{\s*\r?\n\s*}", &changes), + &Preg::split(php_regex!(r"{\s*\r?\n\s*}"), &changes), ); self.inner.io.write_error3( &format!( diff --git a/crates/shirabe/src/downloader/svn_downloader.rs b/crates/shirabe/src/downloader/svn_downloader.rs index cd48daeb..b2dd7f58 100644 --- a/crates/shirabe/src/downloader/svn_downloader.rs +++ b/crates/shirabe/src/downloader/svn_downloader.rs @@ -16,7 +16,7 @@ use crate::util::ProcessExecutor; use crate::util::Svn as SvnUtil; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; -use shirabe_php_shim::{PhpMixed, RuntimeException, is_dir, version_compare}; +use shirabe_php_shim::{PhpMixed, RuntimeException, is_dir, php_regex, version_compare}; #[derive(Debug)] pub struct SvnDownloader { @@ -278,7 +278,7 @@ impl VcsDownloader for SvnDownloader { } let changes_str = changes.unwrap(); - let changes: Vec<String> = Preg::split(r"{\s*\r?\n\s*}", &changes_str) + let changes: Vec<String> = Preg::split(php_regex!(r"{\s*\r?\n\s*}"), &changes_str) .into_iter() .map(|elem| format!(" {}", elem)) .collect(); @@ -364,8 +364,8 @@ impl VcsDownloader for SvnDownloader { to_reference: &str, path: &str, ) -> anyhow::Result<String> { - if Preg::is_match(r"{@(\d+)$}", from_reference) - && Preg::is_match(r"{@(\d+)$}", to_reference) + if Preg::is_match(php_regex!(r"{@(\d+)$}"), from_reference) + && Preg::is_match(php_regex!(r"{@(\d+)$}"), to_reference) { // retrieve the svn base url from the checkout folder let command = vec![ @@ -411,8 +411,8 @@ impl VcsDownloader for SvnDownloader { }; // strip paths from references and only keep the actual revision - let from_revision = Preg::replace(r"{.*@(\d+)$}", "$1", from_reference); - let to_revision = Preg::replace(r"{.*@(\d+)$}", "$1", to_reference); + let from_revision = Preg::replace(php_regex!(r"{.*@(\d+)$}"), "$1", from_reference); + let to_revision = Preg::replace(php_regex!(r"{.*@(\d+)$}"), "$1", to_reference); let command = vec![ "svn".to_string(), @@ -469,7 +469,7 @@ impl ChangeReportInterface for SvnDownloader { Some(path), ); - Ok(if Preg::is_match("{^ *[^X ] +}m", &output) { + Ok(if Preg::is_match(php_regex!("{^ *[^X ] +}m"), &output) { Some(output) } else { None diff --git a/crates/shirabe/src/downloader/zip_downloader.rs b/crates/shirabe/src/downloader/zip_downloader.rs index bc0c9e48..1415d276 100644 --- a/crates/shirabe/src/downloader/zip_downloader.rs +++ b/crates/shirabe/src/downloader/zip_downloader.rs @@ -13,8 +13,8 @@ use shirabe_external_packages::symfony::process::ExecutableFinder; use shirabe_php_shim::{ DIRECTORY_SEPARATOR, ErrorException, PhpMixed, RuntimeException, UnexpectedValueException, ZipArchive, bin2hex, class_exists, file_exists, file_get_contents, filesize, function_exists, - hash_file, is_file, json_encode, random_int, str_contains, str_replace, strlen, substr, - version_compare, + hash_file, is_file, json_encode, php_regex, random_int, str_contains, str_replace, strlen, + substr, version_compare, }; use std::sync::Mutex; @@ -113,7 +113,7 @@ impl ZipDownloader { { let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - r"{^\s*7-Zip(?:\s\[64\])?\s([0-9.]+)}", + php_regex!(r"{^\s*7-Zip(?:\s\[64\])?\s([0-9.]+)}"), &output, Some(&mut m), ) { diff --git a/crates/shirabe/src/event_dispatcher/event_dispatcher.rs b/crates/shirabe/src/event_dispatcher/event_dispatcher.rs index 88d82177..49de9605 100644 --- a/crates/shirabe/src/event_dispatcher/event_dispatcher.rs +++ b/crates/shirabe/src/event_dispatcher/event_dispatcher.rs @@ -25,10 +25,10 @@ use shirabe_external_packages::symfony::process::PhpExecutableFinder; use shirabe_php_shim::{ InvalidArgumentException, PATH_SEPARATOR, PhpMixed, RuntimeException, array_pop, array_push, array_search_in_vec, array_splice, class_exists, defined, file_exists, get_class, implode, - ini_get, is_a, is_array, is_callable, is_object, is_string, krsort, preg_quote, realpath, - spl_autoload_functions, spl_autoload_register, spl_autoload_unregister, spl_object_hash, - str_contains, str_ends_with, str_replace, str_starts_with, strlen, strpos, strtoupper, substr, - trim, + ini_get, is_a, is_array, is_callable, is_object, is_string, krsort, php_regex, preg_quote, + realpath, spl_autoload_functions, spl_autoload_register, spl_autoload_unregister, + spl_object_hash, str_contains, str_ends_with, str_replace, str_starts_with, strlen, strpos, + strtoupper, substr, trim, }; /// Represents a callable listener. PHP's `callable` may be a string (command, script, or @@ -306,7 +306,7 @@ impl EventDispatcher { if let Callable::String(ref s) = callable && str_contains(s, "@no_additional_args") { - let replaced = Preg::replace("{ ?@no_additional_args}", "", s); + let replaced = Preg::replace(php_regex!("{ ?@no_additional_args}"), "", s); callable = Callable::String(replaced); additional_args = Vec::new(); } @@ -652,13 +652,13 @@ impl EventDispatcher { if !possible_local_binaries.is_empty() { for local_exec in &possible_local_binaries { if Preg::is_match( - &format!("{{\\b{}$}}", preg_quote(&callable_str, None)), + format!("{{\\b{}$}}", preg_quote(&callable_str, None)), local_exec, ) { let caller = BinaryInstaller::determine_binary_caller(local_exec); exec = Preg::replace( - &format!("{{^{}}}", preg_quote(&callable_str, None)), + format!("{{^{}}}", preg_quote(&callable_str, None)), &format!("{} {}", caller, local_exec), &exec, ); @@ -684,7 +684,7 @@ impl EventDispatcher { let mut path_and_args = substr(&exec, 5, None); if Platform::is_windows() { path_and_args = Preg::replace_callback( - "{^\\S+}", + php_regex!("{^\\S+}"), |m| str_replace("/", "\\", &m[0]), &path_and_args, ); @@ -692,8 +692,11 @@ impl EventDispatcher { // 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: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::is_match3("{^[^\\'\"\\s/\\\\]+}", &path_and_args, Some(&mut m)) - { + if Preg::is_match3( + php_regex!("{^[^\\'\"\\s/\\\\]+}"), + &path_and_args, + Some(&mut m), + ) { let m0 = m.get(&CaptureKey::ByIndex(0)).cloned().unwrap_or_default(); if !file_exists(&m0) { @@ -702,7 +705,7 @@ impl EventDispatcher { let mut path_to_exec = path_to_exec; if Platform::is_windows() { let exec_without_ext = Preg::replace( - "{\\.(exe|bat|cmd|com)$}i", + php_regex!("{\\.(exe|bat|cmd|com)$}i"), "", &path_to_exec, ); @@ -729,7 +732,7 @@ impl EventDispatcher { if Platform::is_windows() { exec = Preg::replace_callback( - "{^\\S+}", + php_regex!("{^\\S+}"), |m| str_replace("/", "\\", &m[0]), &exec, ); @@ -1080,7 +1083,7 @@ impl EventDispatcher { let bin_dir = realpath(&bin_dir).unwrap_or(bin_dir); let path_value = Platform::get_env(path_env).unwrap_or_default(); if !Preg::is_match( - &format!( + format!( "{{(^|{}){}($|{})}}", PATH_SEPARATOR, preg_quote(&bin_dir, None), diff --git a/crates/shirabe/src/installer/binary_installer.rs b/crates/shirabe/src/installer/binary_installer.rs index 31e2e7b5..1fc5af0d 100644 --- a/crates/shirabe/src/installer/binary_installer.rs +++ b/crates/shirabe/src/installer/binary_installer.rs @@ -12,8 +12,8 @@ use indexmap::IndexMap; use shirabe_external_packages::composer::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, realpath, rmdir, - substr, trim, umask, + file_get_contents5, file_put_contents, fopen, is_dir, is_file, is_link, php_regex, realpath, + rmdir, substr, trim, umask, }; /// Seam over the BinaryInstaller methods reached through LibraryInstaller, so tests can inject a @@ -204,7 +204,7 @@ impl BinaryInstaller { }; let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - r"{^#!/(?:usr/bin/env )?(?:[^/]+/)*(.+)$}m", + php_regex!(r"{^#!/(?:usr/bin/env )?(?:[^/]+/)*(.+)$}m"), &line, Some(&mut m), ) { @@ -325,9 +325,10 @@ impl BinaryInstaller { file_get_contents5(bin, false, PhpMixed::Null, 0, Some(500)).unwrap_or_default(); // For php files, we generate a PHP proxy instead of a shell one, // which allows calling the proxy with a custom php process - if let Some(m) = - Preg::is_match_with_indexed_captures(r"{^(#!.*\r?\n)?[\r\n\t ]*<\?php}", &bin_contents) - { + if let Some(m) = Preg::is_match_with_indexed_captures( + php_regex!(r"{^(#!.*\r?\n)?[\r\n\t ]*<\?php}"), + &bin_contents, + ) { // carry over the existing shebang if present, otherwise add our own let proxy_code = if m.get(1).is_none() { "#!/usr/bin/env php".to_string() diff --git a/crates/shirabe/src/installer/library_installer.rs b/crates/shirabe/src/installer/library_installer.rs index c0b2ebc9..c3ebad16 100644 --- a/crates/shirabe/src/installer/library_installer.rs +++ b/crates/shirabe/src/installer/library_installer.rs @@ -127,7 +127,7 @@ impl LibraryInstaller { && !target_dir.is_empty() { let replaced = Preg::replace( - &format!( + format!( "{{/*{}/?$}}", preg_quote(&target_dir, None).replace('/', "/+") ), diff --git a/crates/shirabe/src/installer/suggested_packages_reporter.rs b/crates/shirabe/src/installer/suggested_packages_reporter.rs index adbfebe1..1b33289c 100644 --- a/crates/shirabe/src/installer/suggested_packages_reporter.rs +++ b/crates/shirabe/src/installer/suggested_packages_reporter.rs @@ -8,6 +8,7 @@ use crate::repository::RepositoryInterface; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::Preg; use shirabe_external_packages::symfony::console::formatter::OutputFormatter; +use shirabe_php_shim::php_regex; #[derive(Debug)] pub struct SuggestedPackagesReporter { @@ -206,6 +207,6 @@ impl SuggestedPackagesReporter { } fn remove_control_characters(&self, string: &str) -> String { - Preg::replace("/[[:cntrl:]]/", "", &string.replace('\n', " ")) + Preg::replace(php_regex!("/[[:cntrl:]]/"), "", &string.replace('\n', " ")) } } diff --git a/crates/shirabe/src/io/base_io.rs b/crates/shirabe/src/io/base_io.rs index 9cd0d333..126c1201 100644 --- a/crates/shirabe/src/io/base_io.rs +++ b/crates/shirabe/src/io/base_io.rs @@ -10,7 +10,7 @@ use shirabe_external_packages::composer::pcre::Preg; use shirabe_external_packages::psr::log::LogLevel; use shirabe_php_shim::{ JSON_INVALID_UTF8_IGNORE, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE, PhpMixed, - UnexpectedValueException, array_merge, in_array, json_encode_ex, + UnexpectedValueException, array_merge, in_array, json_encode_ex, php_regex, }; fn log_context(context: &[(&str, &str)]) -> IndexMap<String, PhpMixed> { @@ -141,7 +141,7 @@ pub trait BaseIO: IOInterface { config.merge(&config_outer, "implicit-due-to-auth"); } - if !Preg::is_match(r"{^[.A-Za-z0-9_]+$}", &token_str) { + if !Preg::is_match(php_regex!(r"{^[.A-Za-z0-9_]+$}"), &token_str) { return Err(anyhow::anyhow!(UnexpectedValueException { message: format!( "Your github oauth token for {} contains invalid characters: \"{}\"", diff --git a/crates/shirabe/src/io/buffer_io.rs b/crates/shirabe/src/io/buffer_io.rs index 72c452be..0aaa5e07 100644 --- a/crates/shirabe/src/io/buffer_io.rs +++ b/crates/shirabe/src/io/buffer_io.rs @@ -9,8 +9,8 @@ use shirabe_external_packages::symfony::console::input::StringInput; use shirabe_external_packages::symfony::console::output::OutputInterface; use shirabe_external_packages::symfony::console::output::StreamOutput; use shirabe_php_shim::{ - PHP_EOL, PhpMixed, PhpResource, RuntimeException, SEEK_SET, fopen, fseek, fwrite, rewind, - stream_get_contents, strip_tags, + PHP_EOL, PhpMixed, PhpResource, RuntimeException, SEEK_SET, fopen, fseek, fwrite, php_regex, + rewind, stream_get_contents, strip_tags, }; #[derive(Debug)] @@ -76,7 +76,7 @@ impl BufferIO { let mut output = output; loop { let next = Preg::replace_callback( - r"{(^|\n|\x08)(.+?)(\x08+)}", + php_regex!(r"{(^|\n|\x08)(.+?)(\x08+)}"), |matches: &indexmap::IndexMap< shirabe_external_packages::composer::pcre::CaptureKey, String, diff --git a/crates/shirabe/src/json/json_file.rs b/crates/shirabe/src/json/json_file.rs index 075e1f64..0ce55e55 100644 --- a/crates/shirabe/src/json/json_file.rs +++ b/crates/shirabe/src/json/json_file.rs @@ -14,8 +14,8 @@ use shirabe_external_packages::seld::json_lint::{ParsingException, ParsingExcept use shirabe_php_shim::{ InvalidArgumentException, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE, PhpMixed, RuntimeException, UnexpectedValueException, dirname, file_exists, file_get_contents, - file_put_contents, is_dir, is_file, json_decode, json_encode_ex, mkdir, realpath, str_contains, - str_ends_with, str_repeat, strlen, strpos, usleep, + file_put_contents, is_dir, is_file, json_decode, json_encode_ex, mkdir, php_regex, realpath, + str_contains, str_ends_with, str_repeat, strlen, strpos, usleep, }; #[derive(Debug, Clone)] @@ -113,7 +113,7 @@ impl JsonFile { http_downloader: Option<std::rc::Rc<std::cell::RefCell<HttpDownloader>>>, io: Option<std::rc::Rc<std::cell::RefCell<dyn IOInterface>>>, ) -> anyhow::Result<Self> { - if http_downloader.is_none() && Preg::is_match(r"{^https?://}i", &path) { + if http_downloader.is_none() && Preg::is_match(php_regex!(r"{^https?://}i"), &path) { return Err(InvalidArgumentException { message: "http urls require a HttpDownloader instance to be passed".to_string(), code: 0, @@ -466,7 +466,7 @@ impl JsonFile { // Pretty printing and not using default indentation let indent_owned = options.indent.clone(); return Preg::replace_callback( - r"#^ {4,}#m", + php_regex!(r"#^ {4,}#m"), move |m: &indexmap::IndexMap< shirabe_external_packages::composer::pcre::CaptureKey, String, @@ -510,7 +510,9 @@ impl JsonFile { { let mut count: usize = 0; let replaced = Preg::replace5( - r#"{\r?\n<<<<<<< [^\r\n]+\r?\n\s+"content-hash": *"[0-9a-f]+", *\r?\n(?:\|{7} [^\r\n]+\r?\n\s+"content-hash": *"[0-9a-f]+", *\r?\n)?=======\r?\n\s+"content-hash": *"[0-9a-f]+", *\r?\n>>>>>>> [^\r\n]+(\r?\n)}"#, + php_regex!( + r#"{\r?\n<<<<<<< [^\r\n]+\r?\n\s+"content-hash": *"[0-9a-f]+", *\r?\n(?:\|{7} [^\r\n]+\r?\n\s+"content-hash": *"[0-9a-f]+", *\r?\n)?=======\r?\n\s+"content-hash": *"[0-9a-f]+", *\r?\n>>>>>>> [^\r\n]+(\r?\n)}"# + ), " \"content-hash\": \"VCS merge conflict detected. Please run `composer update --lock`.\",$1", json, -1, @@ -574,7 +576,11 @@ impl JsonFile { pub fn detect_indenting(json: Option<&str>) -> String { let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::is_match3(r##"#^([ \t]+)"#m"##, json.unwrap_or(""), Some(&mut m)) { + if Preg::is_match3( + php_regex!(r##"#^([ \t]+)"#m"##), + json.unwrap_or(""), + Some(&mut m), + ) { 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 b11178ff..e501940c 100644 --- a/crates/shirabe/src/json/json_manipulator.rs +++ b/crates/shirabe/src/json/json_manipulator.rs @@ -8,8 +8,8 @@ use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ InvalidArgumentException, LogicException, PhpMixed, addcslashes, array_key_exists, array_keys, array_reverse, empty, explode, implode, in_array, is_array, is_int, is_numeric, json_decode, - php_truthy, preg_quote, rtrim, str_contains, str_repeat, str_replace, strlen, strnatcmp, - strpos, substr, trim, uksort, + php_regex, php_truthy, preg_quote, rtrim, str_contains, str_repeat, str_replace, strlen, + strnatcmp, strpos, substr, trim, uksort, }; #[derive(Debug)] @@ -35,7 +35,7 @@ impl JsonManipulator { if contents.is_empty() { contents = "{}".to_string(); } - if !Preg::is_match3("#^\\{(.*)\\}$#s", &contents, None) { + if !Preg::is_match3(php_regex!("#^\\{(.*)\\}$#s"), &contents, None) { return Err(InvalidArgumentException { message: "The json file must be an object ({})".to_string(), code: 0, @@ -115,7 +115,7 @@ impl JsonManipulator { } else { let mut groups: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "#^\\s*\\{\\s*\\S+.*?(\\s*\\}\\s*)$#s", + php_regex!("#^\\s*\\{\\s*\\S+.*?(\\s*\\}\\s*)$#s"), &links, Some(&mut groups), ) { @@ -125,7 +125,7 @@ impl JsonManipulator { .unwrap_or_default(); // link missing but non empty links links = Preg::replace( - &format!("{{{}$}}", preg_quote(&groups_1, None)), + format!("{{{}$}}", preg_quote(&groups_1, None)), // addcslashes is used to double up backslashes/$ since preg_replace resolves them as back references otherwise, see #1588 &addcslashes( &format!( @@ -175,7 +175,7 @@ impl JsonManipulator { let replacements = ["0-$0", "1-$0", "2-$0", "3-$0", "4-$0"]; let mut result = requirement.to_string(); for (p, r) in patterns.iter().zip(replacements.iter()) { - result = Preg::replace(p, r, &result); + result = Preg::replace(*p, r, &result); } result } else { @@ -738,7 +738,9 @@ impl JsonManipulator { } else { let mut leading_match: IndexMap<String, String> = IndexMap::new(); if Preg::is_match_named( - "#^\\{(?P<leadingspace>\\s*?)(?P<content>\\S+.*?)?(?P<trailingspace>\\s*)\\}$#s", + php_regex!( + "#^\\{(?P<leadingspace>\\s*?)(?P<content>\\S+.*?)?(?P<trailingspace>\\s*)\\}$#s" + ), &children, &mut leading_match, ) { @@ -762,7 +764,7 @@ impl JsonManipulator { // child missing but non empty children if append { children = Preg::replace( - &format!("#{}}}$#", whitespace), + format!("#{}}}$#", whitespace), &addcslashes( &format!( ",{}{}{}{}: {}{}}}", @@ -780,7 +782,7 @@ impl JsonManipulator { } else { whitespace = leading_space.clone(); children = Preg::replace( - &format!("#^{{{}#", whitespace), + format!("#^{{{}#", whitespace), &addcslashes( &format!( "{{{}{}: {},{}{}{}", @@ -894,7 +896,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, None) { // 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. @@ -908,7 +910,7 @@ impl JsonManipulator { } let mut count_out: usize = 0; let cleaned = Preg::replace5( - &format!("{{,\\s*{}}}i", preg_quote(&best_match, None)), + format!("{{,\\s*{}}}i", preg_quote(&best_match, None)), "", &children, -1, @@ -916,7 +918,7 @@ impl JsonManipulator { ); if 1 != count_out { let cleaned2 = Preg::replace5( - &format!("{{{}\\s*,?\\s*}}i", preg_quote(&best_match, None)), + format!("{{{}\\s*,?\\s*}}i", preg_quote(&best_match, None)), "", &cleaned, -1, @@ -942,7 +944,7 @@ impl JsonManipulator { // no child data left, $name was the only key in let mut empty_match: IndexMap<String, String> = IndexMap::new(); if Preg::is_match_named( - "#^\\{\\s*?(?P<content>\\S+.*?)?(?P<trailingspace>\\s*)\\}$#s", + php_regex!("#^\\{\\s*?(?P<content>\\S+.*?)?(?P<trailingspace>\\s*)\\}$#s"), &children_clean, &mut empty_match, ) && empty_match.get("content").is_none() @@ -1039,7 +1041,9 @@ impl JsonManipulator { let mut leading_match: IndexMap<String, String> = IndexMap::new(); if Preg::is_match_named( - "#^\\[(?P<leadingspace>\\s*?)(?P<content>\\S+.*?)?(?P<trailingspace>\\s*)\\]$#s", + php_regex!( + "#^\\[(?P<leadingspace>\\s*?)(?P<content>\\S+.*?)?(?P<trailingspace>\\s*)\\]$#s" + ), &children, &mut leading_match, ) { @@ -1067,7 +1071,7 @@ impl JsonManipulator { // child missing but non empty children if append { children = Preg::replace( - &format!("#{}\\]$#", whitespace), + format!("#{}\\]$#", whitespace), &addcslashes( &format!( ",{}{}{}]", @@ -1082,7 +1086,7 @@ impl JsonManipulator { } else { whitespace = leading_whitespace.clone(); children = Preg::replace( - &format!("#^\\[{}#", whitespace), + format!("#^\\[{}#", whitespace), &addcslashes( &format!( "[{}{},{}", @@ -1330,13 +1334,17 @@ impl JsonManipulator { // append at the end of the file and keep whitespace let mut tail_match: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::is_match3("#[^{\\s](\\s*)\\}$#", &self.contents, Some(&mut tail_match)) { + if Preg::is_match3( + php_regex!("#[^{\\s](\\s*)\\}$#"), + &self.contents, + Some(&mut tail_match), + ) { let tail_match_1 = tail_match .get(&CaptureKey::ByIndex(1)) .cloned() .unwrap_or_default(); self.contents = Preg::replace( - &format!("#{}\\}}$#", tail_match_1), + format!("#{}\\}}$#", tail_match_1), &addcslashes( &format!( ",{}{}{}: {}{}}}", @@ -1356,7 +1364,7 @@ impl JsonManipulator { // append at the end of the file self.contents = Preg::replace( - "#\\}$#", + php_regex!("#\\}$#"), &addcslashes( &format!( "{}{}: {}{}}}", @@ -1406,15 +1414,17 @@ 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("#,\\s*$#", &start, None) && Preg::is_match3("#^\\}$#", &end, None) { + if Preg::is_match3(php_regex!("#,\\s*$#"), &start, None) + && Preg::is_match3(php_regex!("#^\\}$#"), &end, None) + { start = rtrim( - &Preg::replace("#,(\\s*)$#", "$1", &start), + &Preg::replace(php_regex!("#,(\\s*)$#"), "$1", &start), Some(&self.indent), ); } self.contents = format!("{}{}", start, end); - if Preg::is_match3("#^\\{\\s*\\}\\s*$#", &self.contents, None) { + if Preg::is_match3(php_regex!("#^\\{\\s*\\}\\s*$#"), &self.contents, None) { self.contents = "{\n}".to_string(); } diff --git a/crates/shirabe/src/package/archiver/archivable_files_finder.rs b/crates/shirabe/src/package/archiver/archivable_files_finder.rs index 67f2fdaa..ad2b41ab 100644 --- a/crates/shirabe/src/package/archiver/archivable_files_finder.rs +++ b/crates/shirabe/src/package/archiver/archivable_files_finder.rs @@ -57,7 +57,7 @@ impl ArchivableFilesFinder { } let relative_path = Preg::replace( - &format!("#^{}#", preg_quote(&sources_clone, Some('#'))), + format!("#^{}#", preg_quote(&sources_clone, Some('#'))), "", &fs.normalize_path(&realpath.to_string_lossy()), ); diff --git a/crates/shirabe/src/package/archiver/archive_manager.rs b/crates/shirabe/src/package/archiver/archive_manager.rs index eaeab9ce..52132be9 100644 --- a/crates/shirabe/src/package/archiver/archive_manager.rs +++ b/crates/shirabe/src/package/archiver/archive_manager.rs @@ -12,8 +12,8 @@ use crate::util::r#loop::Loop; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::Preg; use shirabe_php_shim::{ - InvalidArgumentException, RuntimeException, bin2hex, file_exists, random_bytes, realpath, - sys_get_temp_dir, + InvalidArgumentException, RuntimeException, bin2hex, file_exists, php_regex, random_bytes, + realpath, sys_get_temp_dir, }; pub struct ArchiveManager { @@ -58,7 +58,7 @@ impl ArchiveManager { ) -> anyhow::Result<IndexMap<String, String>> { let base_name = match package.get_archive_name() { Some(name) => name.to_string(), - None => Preg::replace("#[^a-z0-9-_]#i", "-", &package.get_name()), + None => Preg::replace(php_regex!("#[^a-z0-9-_]#i"), "-", &package.get_name()), }; let mut parts: IndexMap<String, String> = IndexMap::new(); @@ -66,7 +66,7 @@ impl ArchiveManager { let dist_reference = package.get_dist_reference(); if let Some(ref dist_ref) = dist_reference { - if Preg::is_match("{^[a-f0-9]{40}$}", dist_ref) { + if Preg::is_match(php_regex!("{^[a-f0-9]{40}$}"), dist_ref) { parts.insert("dist_reference".to_string(), dist_ref.to_string()); if let Some(dist_type) = package.get_dist_type() { parts.insert("dist_type".to_string(), dist_type.to_string()); diff --git a/crates/shirabe/src/package/archiver/git_exclude_filter.rs b/crates/shirabe/src/package/archiver/git_exclude_filter.rs index 8620bddc..85842411 100644 --- a/crates/shirabe/src/package/archiver/git_exclude_filter.rs +++ b/crates/shirabe/src/package/archiver/git_exclude_filter.rs @@ -3,6 +3,7 @@ use crate::package::archiver::BaseExcludeFilter; use crate::package::archiver::BaseExcludeFilterBase; use shirabe_external_packages::composer::pcre::Preg; +use shirabe_php_shim::php_regex; use std::path::Path; pub struct GitExcludeFilter { @@ -35,7 +36,7 @@ impl GitExcludeFilter { } fn parse_git_attributes_line_static(line: &str) -> Option<(String, bool, bool)> { - let parts = Preg::split(r"#\s+#", line); + let parts = Preg::split(php_regex!(r"#\s+#"), line); if parts.len() == 2 && parts[1] == "export-ignore" { return Some(BaseExcludeFilterBase::generate_pattern(&parts[0])); diff --git a/crates/shirabe/src/package/loader/array_loader.rs b/crates/shirabe/src/package/loader/array_loader.rs index b85fbe61..07937c31 100644 --- a/crates/shirabe/src/package/loader/array_loader.rs +++ b/crates/shirabe/src/package/loader/array_loader.rs @@ -20,7 +20,7 @@ use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::Preg; use shirabe_php_shim::{ E_USER_DEPRECATED, PhpMixed, UnexpectedValueException, is_scalar, is_string, json_encode, - ltrim, stripos, strpos, strtolower, strval, substr, trigger_error, trim, + ltrim, php_regex, stripos, strpos, strtolower, strval, substr, trigger_error, trim, }; #[derive(Debug)] @@ -504,7 +504,7 @@ impl ArrayLoader { && !shirabe_php_shim::empty(time_value) { let time_str = time_value.as_string().unwrap_or(""); - let time = if Preg::is_match(r"/^\d++$/D", time_str) { + let time = if Preg::is_match(php_regex!(r"/^\d++$/D"), time_str) { format!("@{}", time_str) } else { time_str.to_string() @@ -674,7 +674,7 @@ impl ArrayLoader { if let Some(alias_normalized) = alias_normalized && !alias_normalized.is_empty() { - let pretty_alias = Preg::replace(r"{(\.9{7})+}", ".x", &alias_normalized); + let pretty_alias = Preg::replace(php_regex!(r"{(\.9{7})+}"), ".x", &alias_normalized); return Ok(match package { CompleteOrRootPackage::Root(root) => RootAliasPackageHandle::new( @@ -938,7 +938,7 @@ impl ArrayLoader { && default_branch_is_true && self .version_parser - .parse_numeric_alias_prefix(&Preg::replace(r"{^v}", "", &version_str)) + .parse_numeric_alias_prefix(&Preg::replace(php_regex!(r"{^v}"), "", &version_str)) .is_none() { return Ok(Some(VersionParser::DEFAULT_BRANCH_ALIAS.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 83cda30b..b3ed8c41 100644 --- a/crates/shirabe/src/package/loader/root_package_loader.rs +++ b/crates/shirabe/src/package/loader/root_package_loader.rs @@ -16,7 +16,9 @@ use crate::util::Platform; use crate::util::ProcessExecutor; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; -use shirabe_php_shim::{PhpMixed, RuntimeException, UnexpectedValueException, strtolower}; +use shirabe_php_shim::{ + PhpMixed, RuntimeException, UnexpectedValueException, php_regex, strtolower, +}; #[derive(Debug)] pub struct RootPackageLoader { @@ -261,7 +263,7 @@ impl RootPackageLoader { for (req_name, req_version) in requires { let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - r"{(?:^|\| *|, *)([^,\s#|]+)(?:#[^ ]+)? +as +([^,\s|]+)(?:$| *\|| *,)}", + php_regex!(r"{(?:^|\| *|, *)([^,\s#|]+)(?:#[^ ]+)? +as +([^,\s|]+)(?:$| *\|| *,)}"), req_version, Some(&mut m), ) { @@ -315,7 +317,7 @@ impl RootPackageLoader { for (req_name, req_version) in requires { let mut constraints: Vec<String> = vec![]; - let or_split = Preg::split(r"{\s*\|\|?\s*}", req_version.trim()); + let or_split = Preg::split(php_regex!(r"{\s*\|\|?\s*}"), req_version.trim()); for or_constraint in &or_split { let and_split = shirabe_semver::split_and_constraints(or_constraint); for and_constraint in and_split { @@ -348,8 +350,9 @@ impl RootPackageLoader { } for constraint in &constraints { - let req_version_stripped = Preg::replace(r"{^([^,\s@]+) as .+$}", "$1", constraint); - if Preg::is_match(r"{^[^,\s@]+$}", &req_version_stripped) { + let req_version_stripped = + Preg::replace(php_regex!(r"{^([^,\s@]+) as .+$}"), "$1", constraint); + if Preg::is_match(php_regex!(r"{^[^,\s@]+$}"), &req_version_stripped) { let stability_name = VersionParser::parse_stability(&req_version_stripped); if stability_name != "stable" { let name = strtolower(req_name); @@ -373,10 +376,13 @@ impl RootPackageLoader { mut references: IndexMap<String, String>, ) -> IndexMap<String, String> { for (req_name, req_version) in requires { - let req_version = Preg::replace(r"{^([^,\s@]+) as .+$}", "$1", req_version); + let req_version = Preg::replace(php_regex!(r"{^([^,\s@]+) as .+$}"), "$1", req_version); let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::is_match3(r"{^[^,\s@]+?#([a-f0-9]+)$}", &req_version, Some(&mut m)) - && VersionParser::parse_stability(&req_version) == "dev" + if Preg::is_match3( + php_regex!(r"{^[^,\s@]+?#([a-f0-9]+)$}"), + &req_version, + Some(&mut m), + ) && VersionParser::parse_stability(&req_version) == "dev" { let name = strtolower(req_name); references.insert( diff --git a/crates/shirabe/src/package/loader/validating_array_loader.rs b/crates/shirabe/src/package/loader/validating_array_loader.rs index 4d7965f8..28ae7d9b 100644 --- a/crates/shirabe/src/package/loader/validating_array_loader.rs +++ b/crates/shirabe/src/package/loader/validating_array_loader.rs @@ -11,8 +11,8 @@ use shirabe_external_packages::composer::pcre::Preg; use shirabe_php_shim::{ E_USER_DEPRECATED, PHP_EOL, PhpMixed, array_intersect_key, array_values, filter_var_email, get_debug_type, is_array, is_bool, is_int, is_numeric, is_scalar, is_string, json_encode, - parse_url_all, php_to_string, str_replace, strcasecmp, strtolower, strtotime, substr, - trigger_error, trim, var_export, + parse_url_all, php_regex, php_to_string, str_replace, strcasecmp, strtolower, strtotime, + substr, trigger_error, trim, var_export, }; use shirabe_semver::Intervals; use shirabe_semver::constraint::AnyConstraint; @@ -910,7 +910,7 @@ impl LoaderInterface for ValidatingArrayLoader { self.warnings .borrow_mut() .push(format!("{}.{}", link_type, err)); - } else if !Preg::is_match("{^[A-Za-z0-9_./-]+$}", &package) { + } else if !Preg::is_match(php_regex!("{^[A-Za-z0-9_./-]+$}"), &package) { self.errors.borrow_mut().push(format!( "{}.{} : invalid key, package names must be strings containing only [A-Za-z0-9_./-]", link_type, package @@ -1173,7 +1173,7 @@ impl LoaderInterface for ValidatingArrayLoader { } if let Some(ref_val) = section.get("reference").filter(|_| isset("reference")) { let ref_str = php_to_string(ref_val); - if Preg::is_match("{^\\s*-}", &ref_str) { + if Preg::is_match(php_regex!("{^\\s*-}"), &ref_str) { self.errors.borrow_mut().push(format!( "{}.reference : must not start with a \"-\", \"{}\" given", src_type, ref_str @@ -1182,7 +1182,7 @@ impl LoaderInterface for ValidatingArrayLoader { } if let Some(url_val) = section.get("url").filter(|_| isset("url")) { let url_str = php_to_string(url_val); - if Preg::is_match("{^\\s*-}", &url_str) { + if Preg::is_match(php_regex!("{^\\s*-}"), &url_str) { self.errors.borrow_mut().push(format!( "{}.url : must not start with a \"-\", \"{}\" given", src_type, url_str @@ -1336,7 +1336,9 @@ impl ValidatingArrayLoader { } if !Preg::is_match( - "{^[a-z0-9](?:[_.-]?[a-z0-9]++)*+/[a-z0-9](?:(?:[_.]|-{1,2})?[a-z0-9]++)*+$}iD", + php_regex!( + "{^[a-z0-9](?:[_.-]?[a-z0-9]++)*+/[a-z0-9](?:(?:[_.]|-{1,2})?[a-z0-9]++)*+$}iD" + ), name, ) { return Some(format!( @@ -1359,14 +1361,14 @@ impl ValidatingArrayLoader { )); } - if Preg::is_match("{\\.json$}", name) { + if Preg::is_match(php_regex!("{\\.json$}"), name) { return Some(format!( "{} is invalid, package names can not end in .json, consider renaming it or perhaps using a -json suffix instead.", name )); } - if Preg::is_match("{[A-Z]}", name) { + if Preg::is_match(php_regex!("{[A-Z]}"), name) { if is_link { return Some(format!( "{} is invalid, it should not contain uppercase characters. Please use {} instead.", @@ -1376,7 +1378,7 @@ impl ValidatingArrayLoader { } let suggest_name = Preg::replace( - "{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}", + php_regex!("{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}"), "\\1\\3-\\2\\4", name, ); @@ -1400,7 +1402,7 @@ impl ValidatingArrayLoader { .as_string() .unwrap_or("") .to_string(); - if !Preg::is_match(&format!("{{^{}$}}u", regex), &value) { + if !Preg::is_match(format!("{{^{}$}}u", regex), &value) { let message = format!( "{} : invalid value ({}), must match {}", property, value, regex @@ -1513,7 +1515,7 @@ impl ValidatingArrayLoader { if let Some(regex_str) = regex { let value_str = php_to_string(&value); - if !Preg::is_match(&format!("{{^{}$}}u", regex_str), &value_str) { + if !Preg::is_match(format!("{{^{}$}}u", regex_str), &value_str) { self.warnings.borrow_mut().push(format!( "{}.{} : invalid value ({}), must match {}", property, key, value_str, regex_str diff --git a/crates/shirabe/src/package/locker.rs b/crates/shirabe/src/package/locker.rs index 94f46254..f7542d1f 100644 --- a/crates/shirabe/src/package/locker.rs +++ b/crates/shirabe/src/package/locker.rs @@ -29,7 +29,7 @@ use shirabe_external_packages::seld::json_lint::ParsingException; use shirabe_php_shim::{ DATE_RFC3339, LogicException, PhpMixed, RuntimeException, array_intersect, array_keys, array_map, array_merge, file_get_contents, filemtime, function_exists, hash, in_array, is_int, - ksort, realpath, strcmp, strtolower, touch2, trim, usort, + ksort, php_regex, realpath, strcmp, strtolower, touch2, trim, usort, }; /// Reads/writes project lockfile (composer.lock). @@ -849,7 +849,7 @@ impl Locker { ), None, ); - if Preg::is_match(r"{^\s*\d+\s*$}", &output_str) { + if Preg::is_match(php_regex!(r"{^\s*\d+\s*$}"), &output_str) { let ts = trim(&output_str, None).parse::<i64>().unwrap_or(0); datetime = chrono::DateTime::from_timestamp(ts, 0); } @@ -871,7 +871,7 @@ impl Locker { )? { let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - r"{^\s*(\d+)\s*}", + php_regex!(r"{^\s*(\d+)\s*}"), output.as_string().unwrap_or(""), Some(&mut m), ) { diff --git a/crates/shirabe/src/package/package.rs b/crates/shirabe/src/package/package.rs index ce22b755..e0bee0e6 100644 --- a/crates/shirabe/src/package/package.rs +++ b/crates/shirabe/src/package/package.rs @@ -11,7 +11,9 @@ use crate::util::ComposerMirror; use chrono::{DateTime, Utc}; use indexmap::{IndexMap, IndexSet}; use shirabe_external_packages::composer::pcre::Preg; -use shirabe_php_shim::{E_USER_DEPRECATED, LogicException, PhpMixed, strpos, trigger_error}; +use shirabe_php_shim::{ + E_USER_DEPRECATED, LogicException, PhpMixed, php_regex, strpos, trigger_error, +}; /// Mirror entry, e.g. `['url' => 'https://...', 'preferred' => true]`. #[derive(Debug, Clone)] @@ -138,7 +140,7 @@ impl Package { let target_dir = self.target_dir.as_ref()?; let replaced = Preg::replace( - "{ (?:^|[\\\\/]+) \\.\\.? (?:[\\\\/]+|$) (?:\\.\\.? (?:[\\\\/]+|$) )*}x", + php_regex!("{ (?:^|[\\\\/]+) \\.\\.? (?:[\\\\/]+|$) (?:\\.\\.? (?:[\\\\/]+|$) )*}x"), "/", target_dir, ); @@ -415,13 +417,15 @@ impl Package { // TODO generalize this a bit for self-managed/on-prem versions? Some kind of replace token in dist urls which allow this? if self.get_dist_url().is_some() && Preg::is_match( - "{^https?://(?:(?:www\\.)?bitbucket\\.org|(api\\.)?github\\.com|(?:www\\.)?gitlab\\.com)/}i", + php_regex!( + "{^https?://(?:(?:www\\.)?bitbucket\\.org|(api\\.)?github\\.com|(?:www\\.)?gitlab\\.com)/}i" + ), &self.get_dist_url().unwrap_or_default(), ) { self.set_dist_reference(Some(reference.clone())); self.set_dist_url(Some(Preg::replace( - "{(?<=/|sha=)[a-f0-9]{40}(?=/|$)}i", + php_regex!("{(?<=/|sha=)[a-f0-9]{40}(?=/|$)}i"), &reference, &self.get_dist_url().unwrap_or_default(), ))); diff --git a/crates/shirabe/src/package/version/version_bumper.rs b/crates/shirabe/src/package/version/version_bumper.rs index 4f2d3242..e1f58942 100644 --- a/crates/shirabe/src/package/version/version_bumper.rs +++ b/crates/shirabe/src/package/version/version_bumper.rs @@ -7,6 +7,7 @@ use crate::package::version::VersionParser; use crate::util::Platform; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; +use shirabe_php_shim::php_regex; use shirabe_semver::Intervals; use shirabe_semver::constraint::AnyConstraint; @@ -45,11 +46,12 @@ impl VersionBumper { return Ok(pretty_constraint); } - let major = Preg::replace(r"{^([1-9][0-9]*|0\.\d+).*}", "$1", &version); - let version_without_suffix = Preg::replace(r"{(?:\.(?:0|9999999))+(-dev)?$}", "", &version); + let major = Preg::replace(php_regex!(r"{^([1-9][0-9]*|0\.\d+).*}"), "$1", &version); + let version_without_suffix = + Preg::replace(php_regex!(r"{(?:\.(?:0|9999999))+(-dev)?$}"), "", &version); let new_pretty_constraint = format!("^{}", version_without_suffix); - if !Preg::is_match(r"{^\^\d+(\.\d+)*$}", &new_pretty_constraint) { + if !Preg::is_match(php_regex!(r"{^\^\d+(\.\d+)*$}"), &new_pretty_constraint) { return Ok(pretty_constraint); } diff --git a/crates/shirabe/src/package/version/version_guesser.rs b/crates/shirabe/src/package/version/version_guesser.rs index 249646c4..add59ead 100644 --- a/crates/shirabe/src/package/version/version_guesser.rs +++ b/crates/shirabe/src/package/version/version_guesser.rs @@ -15,7 +15,7 @@ use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ PHP_INT_MAX, PhpMixed, RuntimeException, array_keys, array_map, array_merge, empty, - function_exists, implode, is_string, json_encode, preg_quote, str_replace, strlen, + function_exists, implode, is_string, json_encode, php_regex, preg_quote, str_replace, strlen, strnatcasecmp, strpos, substr, trim, usort, }; @@ -163,10 +163,13 @@ impl VersionGuesser { } if "-dev" == substr(version_data.version.as_deref().unwrap_or(""), -4, None) - && Preg::is_match(r"{\.9{7}}", version_data.version.as_deref().unwrap_or("")) + && Preg::is_match( + php_regex!(r"{\.9{7}}"), + version_data.version.as_deref().unwrap_or(""), + ) { version_data.pretty_version = Some(Preg::replace( - r"{(\.9{7})+}", + php_regex!(r"{(\.9{7})+}"), ".x", version_data.version.as_deref().unwrap_or(""), )); @@ -185,12 +188,12 @@ impl VersionGuesser { None, ) && Preg::is_match( - r"{\.9{7}}", + php_regex!(r"{\.9{7}}"), version_data.feature_version.as_deref().unwrap_or(""), ) { version_data.feature_pretty_version = Some(Preg::replace( - r"{(\.9{7})+}", + php_regex!(r"{(\.9{7})+}"), ".x", version_data.feature_version.as_deref().unwrap_or(""), )); @@ -237,7 +240,9 @@ impl VersionGuesser { if !branch.is_empty() { let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - r"{^(?:\* ) *(\(no branch\)|\(detached from \S+\)|\(HEAD detached at \S+\)|\S+) *([a-f0-9]+) .*$}", + php_regex!( + r"{^(?:\* ) *(\(no branch\)|\(detached from \S+\)|\(HEAD detached at \S+\)|\S+) *([a-f0-9]+) .*$}" + ), &branch, Some(&mut m), ) { @@ -263,11 +268,13 @@ impl VersionGuesser { if !branch.is_empty() && { let mut tmp: IndexMap<CaptureKey, String> = IndexMap::new(); - !Preg::is_match3(r"{^ *.+/HEAD }", &branch, Some(&mut tmp)) + !Preg::is_match3(php_regex!(r"{^ *.+/HEAD }"), &branch, Some(&mut tmp)) } { let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - r"{^(?:\* )? *((?:remotes/(?:origin|upstream)/)?[^\s/]+) *([a-f0-9]+) .*$}", + php_regex!( + r"{^(?:\* )? *((?:remotes/(?:origin|upstream)/)?[^\s/]+) *([a-f0-9]+) .*$}" + ), &branch, Some(&mut m), ) { @@ -516,7 +523,8 @@ impl VersionGuesser { ) .is_some(); if !has_branch_alias || has_self_version { - let branch = Preg::replace(r"{^dev-}", "", version.as_deref().unwrap_or("")); + let branch = + Preg::replace(php_regex!(r"{^dev-}"), "", version.as_deref().unwrap_or("")); let mut length: i64 = PHP_INT_MAX; // return directly, if branch is configured to be non-feature branch @@ -549,7 +557,8 @@ impl VersionGuesser { let mut last_index: i64 = -1; for (index, candidate) in branches.iter().enumerate() { let index = index as i64; - let candidate_version = Preg::replace(r"{^remotes/\S+/}", "", candidate); + let candidate_version = + Preg::replace(php_regex!(r"{^remotes/\S+/}"), "", candidate); // do not compare against itself or other feature branches if candidate == &branch @@ -625,7 +634,7 @@ impl VersionGuesser { } !Preg::is_match( - &format!( + format!( r"{{^({}|master|main|latest|next|current|support|tip|trunk|default|develop|\d+\..+)$}}", non_feature_branches, ), @@ -772,7 +781,11 @@ impl VersionGuesser { } }; let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::is_match3(r"{^(\d+(?:\.\d+)*)-dev$}i", &version, Some(&mut m)) { + if Preg::is_match3( + php_regex!(r"{^(\d+(?:\.\d+)*)-dev$}i"), + &version, + Some(&mut m), + ) { return Ok(format!( "{}.x-dev", m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default() diff --git a/crates/shirabe/src/package/version/version_parser.rs b/crates/shirabe/src/package/version/version_parser.rs index 3527722c..8cf3aa72 100644 --- a/crates/shirabe/src/package/version/version_parser.rs +++ b/crates/shirabe/src/package/version/version_parser.rs @@ -3,6 +3,7 @@ use crate::repository::PlatformRepository; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::Preg; +use shirabe_php_shim::php_regex; use shirabe_semver::Semver; use shirabe_semver::VersionParser as SemverVersionParser; use shirabe_semver::constraint::AnyConstraint; @@ -49,11 +50,18 @@ impl VersionParser { let count = pairs.len(); let mut i = 0_usize; while i < count { - let mut pair = Preg::replace(r"{^([^=: ]+)[=: ](.*)$}", "$1 $2", pairs[i].trim()); + let mut pair = Preg::replace( + php_regex!(r"{^([^=: ]+)[=: ](.*)$}"), + "$1 $2", + pairs[i].trim(), + ); if !pair.contains(' ') && i + 1 < count && !pairs[i + 1].contains('/') - && !Preg::is_match(r"{(?<=[a-z0-9_/-])\*|\*(?=[a-z0-9_/-])}i", &pairs[i + 1]) + && !Preg::is_match( + php_regex!(r"{(?<=[a-z0-9_/-])\*|\*(?=[a-z0-9_/-])}i"), + &pairs[i + 1], + ) && !PlatformRepository::is_platform_package(&pairs[i + 1]) { pair += &format!(" {}", pairs[i + 1]); diff --git a/crates/shirabe/src/package/version/version_selector.rs b/crates/shirabe/src/package/version/version_selector.rs index 48b045eb..ff5e7586 100644 --- a/crates/shirabe/src/package/version/version_selector.rs +++ b/crates/shirabe/src/package/version/version_selector.rs @@ -18,7 +18,8 @@ use crate::repository::RepositorySetInterface; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::Preg; use shirabe_php_shim::{ - PHP_MAJOR_VERSION, PHP_MINOR_VERSION, PHP_RELEASE_VERSION, strtolower, version_compare, + PHP_MAJOR_VERSION, PHP_MINOR_VERSION, PHP_RELEASE_VERSION, php_regex, strtolower, + version_compare, }; use shirabe_semver::constraint::AnyConstraint; use shirabe_semver::constraint::SimpleConstraint; @@ -280,7 +281,11 @@ impl VersionSelector { if let Some(extra) = extra && extra != VersionParser::DEFAULT_BRANCH_ALIAS { - let new_extra = Preg::replace(r"{^(\d+\.\d+\.\d+)(\.9999999)-dev$}", "$1.0", &extra); + let new_extra = Preg::replace( + php_regex!(r"{^(\d+\.\d+\.\d+)(\.9999999)-dev$}"), + "$1.0", + &extra, + ); if new_extra != extra { let new_extra = new_extra.replace(".9999999", ".0"); return self.transform_version(&new_extra, &new_extra, "dev"); @@ -299,7 +304,7 @@ impl VersionSelector { let semantic_version_parts: Vec<&str> = version.split('.').collect(); if semantic_version_parts.len() == 4 - && Preg::is_match(r"{^\d+\D?}", semantic_version_parts[3]) + && Preg::is_match(php_regex!(r"{^\d+\D?}"), semantic_version_parts[3]) { let mut parts: Vec<String> = semantic_version_parts .iter() diff --git a/crates/shirabe/src/platform/runtime.rs b/crates/shirabe/src/platform/runtime.rs index 40297907..28cfa095 100644 --- a/crates/shirabe/src/platform/runtime.rs +++ b/crates/shirabe/src/platform/runtime.rs @@ -4,7 +4,7 @@ use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ PhpMixed, class_exists, function_exists, html_entity_decode, implode, instantiate_class, ltrim, - strip_tags, trim, + php_regex, strip_tags, trim, }; /// Seam over the PHP runtime so PlatformRepository can be tested against mocked @@ -96,7 +96,7 @@ impl Runtime { let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::match3( - r"~<h2>\s*<a[^>]*>([^<]+)</a>\s*</h2>~i", + php_regex!(r"~<h2>\s*<a[^>]*>([^<]+)</a>\s*</h2>~i"), html, Some(&mut matches), ) { @@ -114,7 +114,9 @@ impl Runtime { let mut matches: IndexMap<CaptureKey, Vec<String>> = IndexMap::new(); if Preg::match_all3( - r#"~<tr>\s*<td class="e">\s*(.*?)\s*</td>\s*<td class="v">\s*(.*?)\s*</td>\s*</tr>~is"#, + php_regex!( + r#"~<tr>\s*<td class="e">\s*(.*?)\s*</td>\s*<td class="v">\s*(.*?)\s*</td>\s*</tr>~is"# + ), html, Some(&mut matches), ) > 0 diff --git a/crates/shirabe/src/platform/version.rs b/crates/shirabe/src/platform/version.rs index cbbbe44e..feed1b85 100644 --- a/crates/shirabe/src/platform/version.rs +++ b/crates/shirabe/src/platform/version.rs @@ -2,7 +2,7 @@ use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; -use shirabe_php_shim::version_compare; +use shirabe_php_shim::{php_regex, version_compare}; pub struct Version; @@ -12,7 +12,9 @@ impl Version { let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if !Preg::match3( - r"/^(?P<version>[0-9.]+)(?P<patch>[a-z]{0,2})(?P<suffix>(?:-?(?:dev|pre|alpha|beta|rc|fips)[\d]*)*)(?:-\w+)?(?: \(.+?\))?$/", + 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), ) { @@ -56,7 +58,7 @@ impl Version { pub fn parse_libjpeg(libjpeg_version: &str) -> Option<String> { let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if !Preg::match3( - r"/^(?P<major>\d+)(?P<minor>[a-z]*)$/", + php_regex!(r"/^(?P<major>\d+)(?P<minor>[a-z]*)$/"), libjpeg_version, Some(&mut matches), ) { @@ -81,7 +83,7 @@ impl Version { pub fn parse_zoneinfo_version(zoneinfo_version: &str) -> Option<String> { let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if !Preg::match3( - r"/^(?P<year>\d{4})(?P<revision>[a-z]*)$/", + php_regex!(r"/^(?P<year>\d{4})(?P<revision>[a-z]*)$/"), zoneinfo_version, Some(&mut matches), ) { diff --git a/crates/shirabe/src/plugin/plugin_manager.rs b/crates/shirabe/src/plugin/plugin_manager.rs index dd68d1ed..aa3f0a7d 100644 --- a/crates/shirabe/src/plugin/plugin_manager.rs +++ b/crates/shirabe/src/plugin/plugin_manager.rs @@ -26,7 +26,7 @@ use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::Preg; use shirabe_php_shim::{ E_USER_DEPRECATED, PhpMixed, RuntimeException, UnexpectedValueException, array_key_exists, - get_class_obj, implode, ksort, trigger_error, trim, var_export_str, version_compare, + get_class_obj, implode, ksort, php_regex, trigger_error, trim, var_export_str, version_compare, }; use shirabe_semver::constraint::SimpleConstraint; @@ -250,7 +250,7 @@ impl PluginManager { } if package.get_name() == "symfony/flex" - && Preg::is_match3("{^[0-9.]+$}", &package.get_version(), None) + && Preg::is_match3(php_regex!("{^[0-9.]+$}"), &package.get_version(), None) && version_compare(&package.get_version(), "1.9.8", "<") { 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>", diff --git a/crates/shirabe/src/repository/array_repository.rs b/crates/shirabe/src/repository/array_repository.rs index 6f5e4194..ba085020 100644 --- a/crates/shirabe/src/repository/array_repository.rs +++ b/crates/shirabe/src/repository/array_repository.rs @@ -13,7 +13,7 @@ use crate::repository::{ }; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::Preg; -use shirabe_php_shim::{implode, preg_quote, strtolower}; +use shirabe_php_shim::{implode, php_regex, preg_quote, strtolower}; use shirabe_semver::constraint::AnyConstraint; use shirabe_semver::constraint::SimpleConstraint; use std::rc::Weak; @@ -329,11 +329,11 @@ impl RepositoryInterface for ArrayRepository { r#type: Option<String>, ) -> anyhow::Result<Vec<SearchResult>> { let regex = if mode == crate::repository::SEARCH_FULLTEXT { - let parts = Preg::split("{\\s+}", &preg_quote(&query, None)); + let parts = Preg::split(php_regex!("{\\s+}"), &preg_quote(&query, None)); format!("{{(?:{})}}i", implode("|", &parts)) } else { // vendor/name searches expect the caller to have preg_quoted the query - let parts = Preg::split("{\\s+}", &query); + let parts = Preg::split(php_regex!("{\\s+}"), &query); format!("{{(?:{})}}i", implode("|", &parts)) }; diff --git a/crates/shirabe/src/repository/composer_repository.rs b/crates/shirabe/src/repository/composer_repository.rs index fc576189..54edc39a 100644 --- a/crates/shirabe/src/repository/composer_repository.rs +++ b/crates/shirabe/src/repository/composer_repository.rs @@ -41,7 +41,7 @@ use shirabe_metadata_minifier::MetadataMinifier; use shirabe_php_shim::{ InvalidArgumentException, LogicException, PHP_EOL, PhpMixed, RuntimeException, UnexpectedValueException, extension_loaded, hash, http_build_query, in_array, json_decode, - parse_url_all, realpath, strtolower, strtr, urlencode, var_export, + parse_url_all, php_regex, realpath, strtolower, strtr, urlencode, var_export, }; use shirabe_semver::CompilingMatcher; use shirabe_semver::constraint::AnyConstraint; @@ -160,7 +160,7 @@ impl ComposerRepository { .and_then(|v| v.as_string()) .unwrap_or("") .to_string(); - if !Preg::is_match(r"{^[\w.]+\??://}", &url_str) { + if !Preg::is_match(php_regex!(r"{^[\w.]+\??://}"), &url_str) { if let Some(local_file_path) = realpath(&url_str) { // it is a local path, add file scheme repo_config.insert( @@ -247,7 +247,7 @@ impl ComposerRepository { // force url for packagist.org to repo.packagist.org let mut match_packagist: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - r"{^(?P<proto>https?)://packagist\.org/?$}i", + php_regex!(r"{^(?P<proto>https?)://packagist\.org/?$}i"), &url, Some(&mut match_packagist), ) { @@ -258,7 +258,8 @@ impl ComposerRepository { url = format!("{}://repo.packagist.org", proto); } - let base_url_trimmed = Preg::replace(r"{(?:/[^/\\]+\.json)?(?:[?#].*)?$}", "", &url); + let base_url_trimmed = + Preg::replace(php_regex!(r"{(?:/[^/\\]+\.json)?(?:[?#].*)?$}"), "", &url); let base_url = base_url_trimmed.trim_end_matches('/').to_string(); assert!(!base_url.is_empty()); @@ -772,7 +773,7 @@ impl ComposerRepository { if mode == SEARCH_VENDOR { let mut results: Vec<IndexMap<String, PhpMixed>> = Vec::new(); - let parts = Preg::split(r"{\s+}", &query); + let parts = Preg::split(php_regex!(r"{\s+}"), &query); let regex = format!("{{(?:{})}}i", parts.join("|")); let vendor_names = self.get_vendor_names()?; @@ -791,7 +792,7 @@ impl ComposerRepository { // optimize search for "^foo/bar" where at least "^foo/" is present by loading this directly from the listUrl if present let mut match_groups: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - r"{^\^(?P<query>(?P<vendor>[a-z0-9_.-]+)/[a-z0-9_.-]*)\*?$}i", + 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() @@ -837,7 +838,7 @@ impl ComposerRepository { } let mut results: Vec<IndexMap<String, PhpMixed>> = Vec::new(); - let parts = Preg::split(r"{\s+}", &query); + let parts = Preg::split(php_regex!(r"{\s+}"), &query); let regex = format!("{{(?:{})}}i", parts.join("|")); let package_names = self.get_package_names(None)?; @@ -1747,7 +1748,7 @@ impl ComposerRepository { .into_iter() .filter_map(|(name, constraint)| { let name = strtolower(&name); - let real_name = Preg::replace(r"{~dev$}", "", &name); + let real_name = Preg::replace(php_regex!(r"{~dev$}"), "", &name); // skip platform packages, root package and composer-plugin-api if PlatformRepository::is_platform_package(&real_name) || real_name == "__root__" { None @@ -2435,7 +2436,11 @@ impl ComposerRepository { if url.starts_with('/') { let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::is_match3(r"{^[^:]++://[^/]*+}", &self.url, Some(&mut matches)) { + if Preg::is_match3( + php_regex!(r"{^[^:]++://[^/]*+}"), + &self.url, + Some(&mut matches), + ) { return Ok(format!( "{}{}", matches @@ -2732,7 +2737,7 @@ impl ComposerRepository { // url-encode $ signs in URLs as bad proxies choke on them if let Some(pos) = filename.find('$') && pos > 0 - && Preg::is_match(r"{^https?://}i", &filename) + && Preg::is_match(php_regex!(r"{^https?://}i"), &filename) { filename = format!("{}%24{}", &filename[..pos], &filename[pos + 1..]); } diff --git a/crates/shirabe/src/repository/filesystem_repository.rs b/crates/shirabe/src/repository/filesystem_repository.rs index 7d59bb0e..c2b23b52 100644 --- a/crates/shirabe/src/repository/filesystem_repository.rs +++ b/crates/shirabe/src/repository/filesystem_repository.rs @@ -23,7 +23,7 @@ use shirabe_external_packages::composer::pcre::Preg; use shirabe_php_shim::{ Exception, InvalidArgumentException, LogicException, PhpMixed, UnexpectedValueException, array_flip, dirname, r#eval, file_get_contents, get_class_err, get_debug_type, in_array, - is_array, is_null, is_string, ksort, realpath, str_repeat, trim, usort, var_export, + is_array, is_null, is_string, ksort, php_regex, realpath, str_repeat, trim, usort, var_export, }; use shirabe_semver::constraint::AnyConstraint; @@ -356,7 +356,7 @@ impl FilesystemRepository { let mixed = PhpMixed::String(data.clone()); if is_string(&mixed) && Preg::is_match(pattern, &trim(&data, None)) { let replaced = Preg::replace( - r#"{=>\s*+__DIR__\s*+\.\s*+(['\"])}"#, + php_regex!(r#"{=>\s*+__DIR__\s*+\.\s*+(['\"])}"#), &format!( "=> {} . $1", var_export(&PhpMixed::String(dirname(path)), true), diff --git a/crates/shirabe/src/repository/package_repository.rs b/crates/shirabe/src/repository/package_repository.rs index 0973332d..7f61bc9e 100644 --- a/crates/shirabe/src/repository/package_repository.rs +++ b/crates/shirabe/src/repository/package_repository.rs @@ -16,7 +16,7 @@ use crate::repository::{ }; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::Preg; -use shirabe_php_shim::{Exception, PhpMixed, RuntimeException, var_export}; +use shirabe_php_shim::{Exception, PhpMixed, RuntimeException, php_regex, var_export}; use shirabe_semver::constraint::AnyConstraint; #[derive(Debug)] @@ -85,7 +85,11 @@ impl PackageRepository { pub fn get_repo_name(&self) -> String { use crate::repository::RepositoryInterface; - Preg::replace(r"{^array }", "package ", &self.inner.get_repo_name()) + Preg::replace( + php_regex!(r"{^array }"), + "package ", + &self.inner.get_repo_name(), + ) } // In PHP the inherited ArrayRepository methods lazily call the overridden initialize() to load diff --git a/crates/shirabe/src/repository/path_repository.rs b/crates/shirabe/src/repository/path_repository.rs index 8249bb90..d7f24fa7 100644 --- a/crates/shirabe/src/repository/path_repository.rs +++ b/crates/shirabe/src/repository/path_repository.rs @@ -26,7 +26,7 @@ use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::Preg; use shirabe_php_shim::{ DIRECTORY_SEPARATOR, GLOB_BRACE, GLOB_MARK, GLOB_ONLYDIR, PhpMixed, RuntimeException, defined, - file_exists, file_get_contents, glob_with_flags, hash, realpath, serialize, + file_exists, file_get_contents, glob_with_flags, hash, php_regex, realpath, serialize, }; #[derive(Debug)] @@ -161,9 +161,9 @@ impl PathRepository { let url_matches = self.get_url_matches()?; if url_matches.is_empty() { - if Preg::is_match(r"{[*{}]}", &self.url) { + if Preg::is_match(php_regex!(r"{[*{}]}"), &self.url) { let mut url = self.url.clone(); - while Preg::is_match(r"{[*{}]}", &url) { + while Preg::is_match(php_regex!(r"{[*{}]}"), &url) { url = shirabe_php_shim::dirname(&url); } // the parent directory before any wildcard exists, so we assume it is correctly configured but simply empty diff --git a/crates/shirabe/src/repository/platform_repository.rs b/crates/shirabe/src/repository/platform_repository.rs index 73c4dbea..0d63940c 100644 --- a/crates/shirabe/src/repository/platform_repository.rs +++ b/crates/shirabe/src/repository/platform_repository.rs @@ -23,7 +23,7 @@ use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; use shirabe_external_packages::composer::xdebug_handler::XdebugHandler; use shirabe_php_shim::{ InvalidArgumentException, PhpMixed, UnexpectedValueException, array_map_str_fn, - array_slice_strs, explode, get_class, implode, in_array, is_string, str_replace, + array_slice_strs, explode, get_class, implode, in_array, is_string, php_regex, str_replace, str_starts_with, strpos, strtolower, var_export, }; use shirabe_semver::constraint::SimpleConstraint; @@ -223,7 +223,8 @@ impl PlatformRepository { version = v; } Err(_) => { - pretty_version = Preg::replace("#^([^~+-]+).*$#", "$1", &php_version_str); + pretty_version = + Preg::replace(php_regex!("#^([^~+-]+).*$#"), "$1", &php_version_str); version = self .version_parser .as_ref() @@ -344,7 +345,7 @@ impl PlatformRepository { // librabbitmq version => 0.9.0 let mut librabbitmq_matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^librabbitmq version => (?<version>.+)$/im", + php_regex!("/^librabbitmq version => (?<version>.+)$/im"), &info, Some(&mut librabbitmq_matches), ) { @@ -363,7 +364,7 @@ impl PlatformRepository { // AMQP protocol version => 0-9-1 let mut protocol_matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^AMQP protocol version => (?<version>.+)$/im", + php_regex!("/^AMQP protocol version => (?<version>.+)$/im"), &info, Some(&mut protocol_matches), ) { @@ -388,7 +389,7 @@ impl PlatformRepository { // BZip2 Version => 1.0.6, 6-Sept-2010 let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^BZip2 Version => (?<version>.*),/im", + php_regex!("/^BZip2 Version => (?<version>.*),/im"), &info, Some(&mut matches), ) { @@ -423,7 +424,7 @@ impl PlatformRepository { // SSL Version => OpenSSL/1.0.1t let mut ssl_matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "{^SSL Version => (?<library>[^/]+)/(?<version>.+)$}im", + php_regex!("{^SSL Version => (?<library>[^/]+)/(?<version>.+)$}im"), &info, Some(&mut ssl_matches), ) { @@ -459,7 +460,7 @@ impl PlatformRepository { let mut securetransport_matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "{^\\(securetransport\\) ([a-z0-9]+)}", + php_regex!("{^\\(securetransport\\) ([a-z0-9]+)}"), &library, Some(&mut securetransport_matches), ) { @@ -491,7 +492,9 @@ impl PlatformRepository { // libSSH Version => libssh2/1.4.3 let mut ssh_matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "{^libSSH Version => (?<library>[^/]+)/(?<version>.+?)(?:/.*)?$}im", + php_regex!( + "{^libSSH Version => (?<library>[^/]+)/(?<version>.+?)(?:/.*)?$}im" + ), &info, Some(&mut ssh_matches), ) { @@ -516,7 +519,7 @@ impl PlatformRepository { // ZLib Version => 1.2.8 let mut zlib_matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "{^ZLib Version => (?<version>.+)$}im", + php_regex!("{^ZLib Version => (?<version>.+)$}im"), &info, Some(&mut zlib_matches), ) { @@ -539,7 +542,7 @@ impl PlatformRepository { // timelib version => 2018.03 let mut timelib_matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^timelib version => (?<version>.+)$/im", + php_regex!("/^timelib version => (?<version>.+)$/im"), &info, Some(&mut timelib_matches), ) { @@ -558,7 +561,7 @@ impl PlatformRepository { // Timezone Database => internal let mut zoneinfo_source_matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^Timezone Database => (?<source>internal|external)$/im", + php_regex!("/^Timezone Database => (?<source>internal|external)$/im"), &info, Some(&mut zoneinfo_source_matches), ) { @@ -568,7 +571,9 @@ impl PlatformRepository { .unwrap_or(false); let mut zoneinfo_matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^\"Olson\" Timezone Database Version => (?<version>.+?)(?:\\.system)?$/im", + php_regex!( + "/^\"Olson\" Timezone Database Version => (?<version>.+?)(?:\\.system)?$/im" + ), &info, Some(&mut zoneinfo_matches), ) { @@ -608,7 +613,7 @@ impl PlatformRepository { // libmagic => 537 let mut magic_matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^libmagic => (?<version>.+)$/im", + php_regex!("/^libmagic => (?<version>.+)$/im"), &info, Some(&mut magic_matches), ) { @@ -644,7 +649,7 @@ impl PlatformRepository { let mut libjpeg_matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^libJPEG Version => (?<version>.+?)(?: compatible)?$/im", + php_regex!("/^libJPEG Version => (?<version>.+?)(?: compatible)?$/im"), &info, Some(&mut libjpeg_matches), ) { @@ -665,7 +670,7 @@ impl PlatformRepository { let mut libpng_matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^libPNG Version => (?<version>.+)$/im", + php_regex!("/^libPNG Version => (?<version>.+)$/im"), &info, Some(&mut libpng_matches), ) { @@ -683,7 +688,7 @@ impl PlatformRepository { let mut freetype_matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^FreeType Version => (?<version>.+)$/im", + php_regex!("/^FreeType Version => (?<version>.+)$/im"), &info, Some(&mut freetype_matches), ) { @@ -701,7 +706,7 @@ impl PlatformRepository { let mut libxpm_matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^libXpm Version => (?<versionId>\\d+)$/im", + php_regex!("/^libXpm Version => (?<versionId>\\d+)$/im"), &info, Some(&mut libxpm_matches), ) { @@ -775,7 +780,7 @@ impl PlatformRepository { } else { let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^ICU version => (?<version>.+)$/im", + php_regex!("/^ICU version => (?<version>.+)$/im"), &info, Some(&mut matches), ) { @@ -795,7 +800,7 @@ impl PlatformRepository { // ICU TZData version => 2019c let mut zoneinfo_matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^ICU TZData version => (?<version>.*)$/im", + php_regex!("/^ICU TZData version => (?<version>.*)$/im"), &info, Some(&mut zoneinfo_matches), ) { @@ -878,7 +883,7 @@ impl PlatformRepository { // 7.x: ImageMagick 7.0.8-34 Q16 x86_64 2019-03-23 https://imagemagick.org let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^ImageMagick (?<version>[\\d.]+)(?:-(?<patch>\\d+))?/", + php_regex!("/^ImageMagick (?<version>[\\d.]+)(?:-(?<patch>\\d+))?/"), &image_magick_version_str, Some(&mut matches), ) { @@ -907,11 +912,11 @@ impl PlatformRepository { let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); let mut vendor_matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^Vendor Version => (?<versionId>\\d+)$/im", + php_regex!("/^Vendor Version => (?<versionId>\\d+)$/im"), &info, Some(&mut matches), ) && Preg::is_match3( - "/^Vendor Name => (?<vendor>.+)$/im", + php_regex!("/^Vendor Name => (?<vendor>.+)$/im"), &info, Some(&mut vendor_matches), ) { @@ -966,7 +971,7 @@ impl PlatformRepository { // libmbfl version => 1.3.2 let mut libmbfl_matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^libmbfl version => (?<version>.+)$/im", + php_regex!("/^libmbfl version => (?<version>.+)$/im"), &info, Some(&mut libmbfl_matches), ) { @@ -1002,7 +1007,9 @@ impl PlatformRepository { } else { let mut oniguruma_matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^(?:oniguruma|Multibyte regex \\(oniguruma\\)) version => (?<version>.+)$/im", + php_regex!( + "/^(?:oniguruma|Multibyte regex \\(oniguruma\\)) version => (?<version>.+)$/im" + ), &info, Some(&mut oniguruma_matches), ) { @@ -1026,7 +1033,7 @@ impl PlatformRepository { // libmemcached version => 1.0.18 let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^libmemcached version => (?<version>.+)$/im", + php_regex!("/^libmemcached version => (?<version>.+)$/im"), &info, Some(&mut matches), ) { @@ -1052,7 +1059,7 @@ impl PlatformRepository { // OpenSSL 1.1.1g 21 Apr 2020 let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "{^(?:OpenSSL|LibreSSL)?\\s*(?<version>\\S+)}i", + php_regex!("{^(?:OpenSSL|LibreSSL)?\\s*(?<version>\\S+)}i"), &openssl_text_str, Some(&mut matches), ) { @@ -1084,7 +1091,8 @@ impl PlatformRepository { PhpMixed::String(s) => s.clone(), _ => "".to_string(), }; - let stripped = Preg::replace("{^(\\S+).*}", "$1", &pcre_version_str); + let stripped = + Preg::replace(php_regex!("{^(\\S+).*}"), "$1", &pcre_version_str); self.add_library(&mut libraries, name, Some(&stripped), None, &[], &[])?; let info = self.runtime.get_extension_info(name)?; @@ -1092,7 +1100,7 @@ impl PlatformRepository { // PCRE Unicode Version => 12.1.0 let mut pcre_unicode_matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^PCRE Unicode Version => (?<version>.+)$/im", + php_regex!("/^PCRE Unicode Version => (?<version>.+)$/im"), &info, Some(&mut pcre_unicode_matches), ) { @@ -1114,7 +1122,9 @@ impl PlatformRepository { let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^(?:Client API version|Version) => mysqlnd (?<version>.+?) /mi", + php_regex!( + "/^(?:Client API version|Version) => mysqlnd (?<version>.+?) /mi" + ), &info, Some(&mut matches), ) { @@ -1136,7 +1146,7 @@ impl PlatformRepository { let mut libmongoc_matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^libmongoc bundled version => (?<version>.+)$/im", + php_regex!("/^libmongoc bundled version => (?<version>.+)$/im"), &info, Some(&mut libmongoc_matches), ) { @@ -1154,7 +1164,7 @@ impl PlatformRepository { let mut libbson_matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^libbson bundled version => (?<version>.+)$/im", + php_regex!("/^libbson bundled version => (?<version>.+)$/im"), &info, Some(&mut libbson_matches), ) { @@ -1192,7 +1202,7 @@ impl PlatformRepository { let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^PostgreSQL\\(libpq\\) Version => (?<version>.*)$/im", + php_regex!("/^PostgreSQL\\(libpq\\) Version => (?<version>.*)$/im"), &info, Some(&mut matches), ) { @@ -1215,7 +1225,7 @@ impl PlatformRepository { let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^PostgreSQL\\(libpq\\) Version => (?<version>.*)$/im", + php_regex!("/^PostgreSQL\\(libpq\\) Version => (?<version>.*)$/im"), &info, Some(&mut matches), ) { @@ -1239,7 +1249,7 @@ impl PlatformRepository { // libpq => 14.3 (Ubuntu 14.3-1.pgdg22.04+1) => 15.0.2 let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^libpq => (?<compiled>.+) => (?<linked>.+)$/im", + php_regex!("/^libpq => (?<compiled>.+) => (?<linked>.+)$/im"), &info, Some(&mut matches), ) { @@ -1318,7 +1328,7 @@ impl PlatformRepository { let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^SQLite Library => (?<version>.+)$/im", + php_regex!("/^SQLite Library => (?<version>.+)$/im"), &info, Some(&mut matches), ) { @@ -1340,7 +1350,7 @@ impl PlatformRepository { let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^libssh2 version => (?<version>.+)$/im", + php_regex!("/^libssh2 version => (?<version>.+)$/im"), &info, Some(&mut matches), ) { @@ -1375,7 +1385,9 @@ impl PlatformRepository { let info = self.runtime.get_extension_info("xsl")?; let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^libxslt compiled against libxml Version => (?<version>.+)$/im", + php_regex!( + "/^libxslt compiled against libxml Version => (?<version>.+)$/im" + ), &info, Some(&mut matches), ) { @@ -1397,7 +1409,7 @@ impl PlatformRepository { let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^LibYAML Version => (?<version>.+)$/im", + php_regex!("/^LibYAML Version => (?<version>.+)$/im"), &info, Some(&mut matches), ) { @@ -1458,7 +1470,7 @@ impl PlatformRepository { let info = self.runtime.get_extension_info(name)?; let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "/^Linked Version => (?<version>.+)$/im", + php_regex!("/^Linked Version => (?<version>.+)$/im"), &info, Some(&mut matches), ) { @@ -1494,7 +1506,8 @@ impl PlatformRepository { version = v; } Err(_) => { - pretty_version = Preg::replace("#^([^~+-]+).*$#", "$1", &hhvm_version); + pretty_version = + Preg::replace(php_regex!("#^([^~+-]+).*$#"), "$1", &hhvm_version); version = self .version_parser .as_ref() @@ -1655,7 +1668,7 @@ impl PlatformRepository { extra_description = Some(format!(" (actual version: {})", pretty_version)); let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - "{^(\\d+\\.\\d+\\.\\d+(?:\\.\\d+)?)}", + php_regex!("{^(\\d+\\.\\d+\\.\\d+(?:\\.\\d+)?)}"), &pretty_version, Some(&mut m), ) { diff --git a/crates/shirabe/src/repository/repository_factory.rs b/crates/shirabe/src/repository/repository_factory.rs index 23766bf1..972a5161 100644 --- a/crates/shirabe/src/repository/repository_factory.rs +++ b/crates/shirabe/src/repository/repository_factory.rs @@ -15,7 +15,7 @@ use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::Preg; use shirabe_php_shim::{ InvalidArgumentException, PhpMixed, UnexpectedValueException, get_debug_type, json_encode, - php_to_string, + php_regex, php_to_string, }; pub struct RepositoryFactory; @@ -320,7 +320,7 @@ impl RepositoryFactory { ) -> String { let mut name = if matches!(index, PhpMixed::Int(_)) && repo.contains_key("url") { let url = repo.get("url").and_then(|v| v.as_string()).unwrap_or(""); - Preg::replace("{^https?://}i", "", url) + Preg::replace(php_regex!("{^https?://}i"), "", url) } else { php_to_string(index) }; @@ -336,7 +336,7 @@ impl RepositoryFactory { existing_repos: &IndexMap<String, RepositoryInterfaceHandle>, ) -> String { let mut name = if let Some(url) = repo.get("url").and_then(|v| v.as_string()) { - Preg::replace("{^https?://}i", "", url) + Preg::replace(php_regex!("{^https?://}i"), "", url) } else { index.to_string() }; diff --git a/crates/shirabe/src/repository/vcs/forgejo_driver.rs b/crates/shirabe/src/repository/vcs/forgejo_driver.rs index 0c7e201f..49d0dcf1 100644 --- a/crates/shirabe/src/repository/vcs/forgejo_driver.rs +++ b/crates/shirabe/src/repository/vcs/forgejo_driver.rs @@ -17,7 +17,7 @@ use crate::util::http::Response; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ - PhpMixed, RuntimeException, base64_decode, explode, extension_loaded, urlencode, + PhpMixed, RuntimeException, base64_decode, explode, extension_loaded, php_regex, urlencode, }; #[derive(Debug)] @@ -585,7 +585,7 @@ impl ForgejoDriver { let links = explode(",", &header); for link in links { let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::match3(r#"{<(.+?)>; *rel="next"}"#, &link, Some(&mut m)) + if Preg::match3(php_regex!(r#"{<(.+?)>; *rel="next"}"#), &link, Some(&mut m)) && let Some(url) = m.get(&CaptureKey::ByIndex(1)) { return Some(url.clone()); diff --git a/crates/shirabe/src/repository/vcs/fossil_driver.rs b/crates/shirabe/src/repository/vcs/fossil_driver.rs index cf9a2ea0..a75f6874 100644 --- a/crates/shirabe/src/repository/vcs/fossil_driver.rs +++ b/crates/shirabe/src/repository/vcs/fossil_driver.rs @@ -12,7 +12,9 @@ use crate::util::ProcessExecutor; use chrono::{DateTime, FixedOffset, Utc}; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::Preg; -use shirabe_php_shim::{PhpMixed, RuntimeException, dirname, is_dir, is_file, is_writable}; +use shirabe_php_shim::{ + PhpMixed, RuntimeException, dirname, is_dir, is_file, is_writable, php_regex, +}; #[derive(Debug)] pub struct FossilDriver { @@ -82,7 +84,7 @@ impl FossilDriver { .into()); } - let local_name = Preg::replace(r"{[^a-z0-9]}i", "-", &self.inner.url); + let local_name = Preg::replace(php_regex!(r"{[^a-z0-9]}i"), "-", &self.inner.url); self.repo_file = Some(format!("{}/{}.fossil", cache_repo_dir, local_name)); self.checkout_dir = format!("{}/{}/", cache_vcs_dir, local_name); @@ -301,7 +303,7 @@ impl FossilDriver { Some(&self.checkout_dir), ); for branch in self.inner.process.borrow().split_lines(&output) { - let branch = Preg::replace(r"/^\*/", "", branch.trim()); + let branch = Preg::replace(php_regex!(r"/^\*/"), "", branch.trim()); let branch = branch.trim().to_string(); branches.insert(branch.clone(), branch); } @@ -317,13 +319,13 @@ impl FossilDriver { deep: bool, ) -> anyhow::Result<bool> { if Preg::is_match( - r"#(^(?:https?|ssh)://(?:[^@]@)?(?:chiselapp\.com|fossil\.))#i", + php_regex!(r"#(^(?:https?|ssh)://(?:[^@]@)?(?:chiselapp\.com|fossil\.))#i"), url, ) { return Ok(true); } - if Preg::is_match(r"!/fossil/|\.fossil!", url) { + if Preg::is_match(php_regex!(r"!/fossil/|\.fossil!"), url) { return Ok(true); } diff --git a/crates/shirabe/src/repository/vcs/git_bitbucket_driver.rs b/crates/shirabe/src/repository/vcs/git_bitbucket_driver.rs index 875945af..546dc72d 100644 --- a/crates/shirabe/src/repository/vcs/git_bitbucket_driver.rs +++ b/crates/shirabe/src/repository/vcs/git_bitbucket_driver.rs @@ -19,7 +19,7 @@ use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ InvalidArgumentException, LogicException, PhpMixed, RuntimeException, array_key_exists, array_search_mixed, extension_loaded, http_build_query_mixed, implode, in_array, is_array, - strpos, + php_regex, strpos, }; #[derive(Debug)] @@ -86,7 +86,7 @@ impl GitBitbucketDriver { pub fn initialize(&mut self) -> anyhow::Result<()> { let mut m: indexmap::IndexMap<CaptureKey, String> = indexmap::IndexMap::new(); if !Preg::is_match3( - r"#^https?://bitbucket\.org/([^/]+)/([^/]+?)(?:\.git|/?)?$#i", + php_regex!(r"#^https?://bitbucket\.org/([^/]+)/([^/]+?)(?:\.git|/?)?$#i"), &self.inner.url, Some(&mut m), ) { @@ -788,7 +788,7 @@ impl GitBitbucketDriver { // Format: https://(user@)bitbucket.org/{user}/{repo} // Strip username from URL (only present in clone URL's for private repositories) self.clone_https_url = Preg::replace( - r"/https:\/\/([^@]+@)?/", + php_regex!(r"/https:\/\/([^@]+@)?/"), "https://", m.get("href").and_then(|v| v.as_string()).unwrap_or(""), ); @@ -850,7 +850,7 @@ impl GitBitbucketDriver { _deep: bool, ) -> anyhow::Result<bool> { if !Preg::is_match( - r"#^https?://bitbucket\.org/([^/]+)/([^/]+?)(\.git|/?)?$#i", + php_regex!(r"#^https?://bitbucket\.org/([^/]+)/([^/]+?)(\.git|/?)?$#i"), url, ) { return Ok(false); diff --git a/crates/shirabe/src/repository/vcs/git_driver.rs b/crates/shirabe/src/repository/vcs/git_driver.rs index 81110335..22691b0c 100644 --- a/crates/shirabe/src/repository/vcs/git_driver.rs +++ b/crates/shirabe/src/repository/vcs/git_driver.rs @@ -15,11 +15,11 @@ use chrono::TimeZone; use chrono::{DateTime, FixedOffset, Utc}; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; -use shirabe_php_shim::PhpMixed; use shirabe_php_shim::{ InvalidArgumentException, RuntimeException, dirname, is_dir, is_writable, realpath, sys_get_temp_dir, }; +use shirabe_php_shim::{PhpMixed, php_regex}; #[derive(Debug)] pub struct GitDriver { @@ -50,7 +50,7 @@ impl GitDriver { pub fn initialize(&mut self) -> anyhow::Result<()> { let cache_url; if Filesystem::is_local_path(&self.inner.url) { - self.inner.url = Preg::replace(r"{[\\/]\.git/?$}", "", &self.inner.url); + self.inner.url = Preg::replace(php_regex!(r"{[\\/]\.git/?$}"), "", &self.inner.url); if !is_dir(&self.inner.url) { return Err(RuntimeException { message: format!( @@ -107,7 +107,7 @@ impl GitDriver { .into()); } - if Preg::is_match(r"{^ssh://[^@]+@[^:]+:[^0-9]+}", &self.inner.url) { + if Preg::is_match(php_regex!(r"{^ssh://[^@]+@[^:]+:[^0-9]+}"), &self.inner.url) { return Err(InvalidArgumentException { message: format!( "The source URL {} is invalid, ssh URLs should have a port number after \":\".\nUse ssh://git@example.com:22/path or just git@example.com:path if you do not want to provide a password or custom port.", @@ -214,7 +214,7 @@ impl GitDriver { for branch in &branches { if !branch.is_empty() { let mut caps: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::match3(r"{^\* +(\S+)}", branch, Some(&mut caps)) + 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()); @@ -333,7 +333,7 @@ impl GitDriver { if !tag.is_empty() { let mut caps: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::match3( - r"{^([a-f0-9]{40}) refs/tags/(\S+?)(\^\{\})?$}", + php_regex!(r"{^([a-f0-9]{40}) refs/tags/(\S+?)(\^\{\})?$}"), &tag, Some(&mut caps), ) && let (Some(hash), Some(name)) = ( @@ -369,10 +369,10 @@ impl GitDriver { Some(&self.repo_dir), ); for branch in self.inner.process.borrow().split_lines(&output) { - if !branch.is_empty() && !Preg::is_match(r"{^ *[^/]+/HEAD }", &branch) { + if !branch.is_empty() && !Preg::is_match(php_regex!(r"{^ *[^/]+/HEAD }"), &branch) { let mut caps: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::match3( - r"{^(?:\* )? *(\S+) *([a-f0-9]+)(?: .*)?$}", + php_regex!(r"{^(?:\* )? *(\S+) *([a-f0-9]+)(?: .*)?$}"), &branch, Some(&mut caps), ) && let (Some(name), Some(hash)) = ( @@ -398,7 +398,7 @@ impl GitDriver { deep: bool, ) -> anyhow::Result<bool> { if Preg::is_match( - r"#(^git://|\.git/?$|git(?:olite)?@|//git\.|//github.com/)#i", + php_regex!(r"#(^git://|\.git/?$|git(?:olite)?@|//git\.|//github.com/)#i"), url, ) { return Ok(true); diff --git a/crates/shirabe/src/repository/vcs/github_driver.rs b/crates/shirabe/src/repository/vcs/github_driver.rs index 3ee38f27..37bba1c7 100644 --- a/crates/shirabe/src/repository/vcs/github_driver.rs +++ b/crates/shirabe/src/repository/vcs/github_driver.rs @@ -18,7 +18,7 @@ use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ InvalidArgumentException, PhpMixed, RuntimeException, array_diff, array_key_exists, array_map, array_search_mixed, base64_decode, basename, empty, explode, extension_loaded, in_array, - parse_url_all, strpos, strtolower, substr, trim, urlencode, + parse_url_all, php_regex, strpos, strtolower, substr, trim, urlencode, }; #[derive(Debug)] @@ -71,7 +71,9 @@ impl GitHubDriver { pub fn initialize(&mut self) -> anyhow::Result<()> { let mut match_: IndexMap<CaptureKey, String> = IndexMap::new(); if !Preg::is_match3( - r"#^(?:(?:https?|git)://([^/]+)/|git@([^:]+):/?)([^/]+)/([^/]+?)(?:\.git|/)?$#", + php_regex!( + r"#^(?:(?:https?|git)://([^/]+)/|git@([^:]+):/?)([^/]+)/([^/]+?)(?:\.git|/)?$#" + ), &self.inner.url, Some(&mut match_), ) { @@ -494,10 +496,10 @@ impl GitHubDriver { let mut result: Vec<IndexMap<String, PhpMixed>> = vec![]; let mut key: Option<String> = None; - for line in Preg::split(r"{\r?\n}", &funding) { + for line in Preg::split(php_regex!(r"{\r?\n}"), &funding) { let line = trim(&line, None); let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::is_match3(r"{^(\w+)\s*:\s*(.+)$}", &line, Some(&mut m)) { + if Preg::is_match3(php_regex!(r"{^(\w+)\s*:\s*(.+)$}"), &line, 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 g2 == "[" { @@ -505,11 +507,11 @@ impl GitHubDriver { continue; } let mut m2: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::is_match3(r"{^\[(.*?)\](?:\s*#.*)?$}", &g2, Some(&mut m2)) { + if Preg::is_match3(php_regex!(r"{^\[(.*?)\](?:\s*#.*)?$}"), &g2, Some(&mut m2)) { let inner = m2.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); for item in array_map( |s: &String| trim(s, None), - &Preg::split(r#"{[\'\"]?\s*,\s*[\'\"]?}"#, &inner), + &Preg::split(php_regex!(r#"{[\'\"]?\s*,\s*[\'\"]?}"#), &inner), ) { let mut entry = IndexMap::new(); entry.insert("type".to_string(), PhpMixed::String(g1.clone())); @@ -519,7 +521,11 @@ impl GitHubDriver { ); result.push(entry); } - } else if Preg::is_match3(r"{^([^#].*?)(?:\s+#.*)?$}", &g2, Some(&mut m2)) { + } else if Preg::is_match3( + php_regex!(r"{^([^#].*?)(?:\s+#.*)?$}"), + &g2, + Some(&mut m2), + ) { let mut entry = IndexMap::new(); entry.insert("type".to_string(), PhpMixed::String(g1.clone())); entry.insert( @@ -532,15 +538,16 @@ impl GitHubDriver { result.push(entry); } key = None; - } else if Preg::is_match3(r"{^(\w+)\s*:\s*#\s*$}", &line, Some(&mut m)) { + } else if Preg::is_match3(php_regex!(r"{^(\w+)\s*:\s*#\s*$}"), &line, Some(&mut m)) { key = Some(m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default()); } else if key.is_some() && { let mut tmp: IndexMap<CaptureKey, String> = IndexMap::new(); - Preg::is_match3(r"{^-\s*(.+)(?:\s+#.*)?$}", &line, Some(&mut m)) - || Preg::is_match3(r"{^(.+),(?:\s*#.*)?$}", &line, Some(&mut tmp)) && { - m = tmp; - true - } + 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 + } } { let mut entry = IndexMap::new(); entry.insert( @@ -675,7 +682,7 @@ impl GitHubDriver { if !array_key_exists("scheme", &bits_map) && !array_key_exists("host", &bits_map) { - if Preg::is_match(r"{^[a-z0-9-]++\.[a-z]{2,3}$}", &item_url) { + if Preg::is_match(php_regex!(r"{^[a-z0-9-]++\.[a-z]{2,3}$}"), &item_url) { result[key_idx].insert( "url".to_string(), PhpMixed::String(format!("https://{}", item_url)), @@ -941,7 +948,9 @@ impl GitHubDriver { ) -> anyhow::Result<bool> { let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if !Preg::is_match3( - r"#^((?:https?|git)://([^/]+)/|git@([^:]+):/?)([^/]+)/([^/]+?)(?:\.git|/)?$#", + php_regex!( + r"#^((?:https?|git)://([^/]+)/|git@([^:]+):/?)([^/]+)/([^/]+?)(?:\.git|/)?$#" + ), url, Some(&mut matches), ) { @@ -959,7 +968,11 @@ impl GitHubDriver { .unwrap_or_default() }); if !in_array( - PhpMixed::String(strtolower(&Preg::replace(r"{^www\.}i", "", &origin_url))), + PhpMixed::String(strtolower(&Preg::replace( + php_regex!(r"{^www\.}i"), + "", + &origin_url, + ))), &config.borrow().get("github-domains"), false, ) { @@ -1294,7 +1307,7 @@ impl GitHubDriver { let links = explode(",", &header); for link in &links { let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::is_match3(r#"{<(.+?)>; *rel="next"}"#, link, Some(&mut m)) { + if Preg::is_match3(php_regex!(r#"{<(.+?)>; *rel="next"}"#), link, Some(&mut m)) { 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 4ad75b64..b1cfd004 100644 --- a/crates/shirabe/src/repository/vcs/gitlab_driver.rs +++ b/crates/shirabe/src/repository/vcs/gitlab_driver.rs @@ -19,7 +19,7 @@ use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ InvalidArgumentException, LogicException, PhpMixed, RuntimeException, array_search_mixed, array_shift, ctype_alnum, empty, explode, extension_loaded, implode, in_array, is_array, - is_string, ord, strpos, strtolower, + is_string, ord, php_regex, strpos, strtolower, }; /// Driver for GitLab API, use the Git driver for local checkouts. @@ -193,7 +193,7 @@ impl GitLabDriver { self.namespace = implode("/", &url_parts); self.repository = Preg::replace( - r"#(\.git)$#", + php_regex!(r"#(\.git)$#"), "", &match_ .get(&CaptureKey::ByName("repo".to_string())) @@ -426,7 +426,7 @@ impl GitLabDriver { // Convert the root identifier to a cacheable commit id let mut identifier = identifier.to_string(); - if !Preg::is_match(r"{[a-f0-9]{40}}i", &identifier) { + if !Preg::is_match(php_regex!(r"{[a-f0-9]{40}}i"), &identifier) { let branches = self.get_branches()?; if let Some(sha) = branches.get(&identifier) { identifier = sha.clone(); @@ -1048,7 +1048,11 @@ impl GitLabDriver { let links = explode(",", &header); for link in &links { let mut match_: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::is_match3(r#"{<(.+?)>; *rel="next"}"#, link, Some(&mut match_)) { + if Preg::is_match3( + php_regex!(r#"{<(.+?)>; *rel="next"}"#), + link, + Some(&mut match_), + ) { return Some( match_ .get(&CaptureKey::ByIndex(1)) @@ -1108,7 +1112,7 @@ impl GitLabDriver { false, ) || (port_number.is_some() && in_array( - PhpMixed::String(Preg::replace(r"{:\d+}", "", &guessed_domain)), + PhpMixed::String(Preg::replace(php_regex!(r"{:\d+}"), "", &guessed_domain)), configured_domains, false, )) diff --git a/crates/shirabe/src/repository/vcs/hg_driver.rs b/crates/shirabe/src/repository/vcs/hg_driver.rs index f987eb4b..a346094c 100644 --- a/crates/shirabe/src/repository/vcs/hg_driver.rs +++ b/crates/shirabe/src/repository/vcs/hg_driver.rs @@ -12,7 +12,7 @@ use crate::util::Url; use chrono::{DateTime, FixedOffset, Utc}; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; -use shirabe_php_shim::{PhpMixed, RuntimeException, dirname, is_dir, is_writable}; +use shirabe_php_shim::{PhpMixed, RuntimeException, dirname, is_dir, is_writable, php_regex}; #[derive(Debug)] pub struct HgDriver { @@ -59,8 +59,11 @@ impl HgDriver { }.into()); } - let sanitized = - Preg::replace(r"{[^a-z0-9]}i", "-", &Url::sanitize(self.inner.url.clone())); + let sanitized = Preg::replace( + php_regex!(r"{[^a-z0-9]}i"), + "-", + &Url::sanitize(self.inner.url.clone()), + ); self.repo_dir = format!("{}/{}/", cache_vcs_dir, sanitized); let mut fs = Filesystem::new(None); @@ -242,7 +245,7 @@ impl HgDriver { for tag in self.inner.process.borrow().split_lines(&output) { if !tag.is_empty() { let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::match3(r"(^([^\s]+)\s+\d+:(.*)$)", &tag, Some(&mut m)) { + 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(), @@ -272,7 +275,11 @@ impl HgDriver { for branch in self.inner.process.borrow().split_lines(&output) { if !branch.is_empty() { let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::match3(r"(^([^\s]+)\s+\d+:([a-f0-9]+))", &branch, Some(&mut m)) { + 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( @@ -293,7 +300,11 @@ impl HgDriver { for branch in self.inner.process.borrow().split_lines(&output) { if !branch.is_empty() { let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::match3(r"(^(?:[\s*]*)([^\s]+)\s+\d+:(.*)$)", &branch, Some(&mut m)) { + 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( @@ -320,7 +331,9 @@ impl HgDriver { deep: bool, ) -> anyhow::Result<bool> { if Preg::is_match( - r"#(^(?:https?|ssh)://(?:[^@]+@)?bitbucket.org|https://(?:.*?)\.kilnhg.com)#i", + php_regex!( + r"#(^(?:https?|ssh)://(?:[^@]+@)?bitbucket.org|https://(?:.*?)\.kilnhg.com)#i" + ), url, ) { return Ok(true); diff --git a/crates/shirabe/src/repository/vcs/perforce_driver.rs b/crates/shirabe/src/repository/vcs/perforce_driver.rs index 9a98f4d3..452ac5a2 100644 --- a/crates/shirabe/src/repository/vcs/perforce_driver.rs +++ b/crates/shirabe/src/repository/vcs/perforce_driver.rs @@ -10,7 +10,7 @@ use crate::util::ProcessExecutor; use crate::util::http::Response; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::Preg; -use shirabe_php_shim::{BadMethodCallException, PhpMixed, RuntimeException}; +use shirabe_php_shim::{BadMethodCallException, PhpMixed, RuntimeException, php_regex}; #[derive(Debug)] pub struct PerforceDriver { @@ -193,7 +193,7 @@ impl PerforceDriver { url: &str, deep: bool, ) -> anyhow::Result<bool> { - if deep || Preg::is_match(r"#\b(perforce|p4)\b#i", url) { + if deep || Preg::is_match(php_regex!(r"#\b(perforce|p4)\b#i"), url) { return Ok(Perforce::check_server_exists( url, &mut ProcessExecutor::new(Some(io)), diff --git a/crates/shirabe/src/repository/vcs/svn_driver.rs b/crates/shirabe/src/repository/vcs/svn_driver.rs index 50852aef..5f1faa65 100644 --- a/crates/shirabe/src/repository/vcs/svn_driver.rs +++ b/crates/shirabe/src/repository/vcs/svn_driver.rs @@ -15,7 +15,7 @@ use chrono::{DateTime, FixedOffset, Utc}; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ - PhpMixed, RuntimeException, array_key_exists, stripos, strrpos, strtr, substr, trim, + PhpMixed, RuntimeException, array_key_exists, php_regex, stripos, strrpos, strtr, substr, trim, }; #[derive(Debug)] @@ -157,7 +157,7 @@ impl SvnDriver { } pub(crate) fn should_cache(&self, identifier: &str) -> bool { - self.inner.cache.is_some() && Preg::is_match(r"{@\d+$}", identifier) + self.inner.cache.is_some() && Preg::is_match(php_regex!(r"{@\d+$}"), identifier) } pub fn get_composer_information( @@ -262,7 +262,7 @@ impl SvnDriver { let identifier = format!("/{}/", trim(identifier, Some("/"))); let (path, rev) = if let Some(m) = - Preg::is_match_with_indexed_captures(r"{^(.+?)(@\d+)?/$}", &identifier) + Preg::is_match_with_indexed_captures(php_regex!(r"{^(.+?)(@\d+)?/$}"), &identifier) { if m.get(2).is_some() { ( @@ -302,7 +302,7 @@ impl SvnDriver { let identifier = format!("/{}/", trim(identifier, Some("/"))); let (path, rev) = if let Some(m) = - Preg::is_match_with_indexed_captures(r"{^(.+?)(@\d+)?/$}", &identifier) + Preg::is_match_with_indexed_captures(php_regex!(r"{^(.+?)(@\d+)?/$}"), &identifier) { if m.get(2).is_some() { ( @@ -323,7 +323,11 @@ impl SvnDriver { for line in self.inner.process.borrow().split_lines(&output) { if !line.is_empty() { let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::is_match3(r"{^Last Changed Date: ([^(]+)}", &line, Some(&mut m)) { + 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() @@ -351,7 +355,11 @@ impl SvnDriver { let line = trim(&line, None); if !line.is_empty() { let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::is_match3(r"{^\s*(\S+).*?(\S+)\s*$}", &line, Some(&mut m)) { + 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()) @@ -398,7 +406,11 @@ impl SvnDriver { let line = trim(&line, None); if !line.is_empty() { let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::is_match3(r"{^\s*(\S+).*?(\S+)\s*$}", &line, Some(&mut m)) { + 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()) @@ -436,7 +448,11 @@ impl SvnDriver { let line = trim(&line, None); if !line.is_empty() { let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::is_match3(r"{^\s*(\S+).*?(\S+)\s*$}", &line, Some(&mut m)) { + 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()) @@ -472,7 +488,7 @@ impl SvnDriver { deep: bool, ) -> anyhow::Result<bool> { let url = Self::normalize_url(url); - if Preg::is_match(r"#(^svn://|^svn\+ssh://|svn\.)#i", &url) { + if Preg::is_match(php_regex!(r"#(^svn://|^svn\+ssh://|svn\.)#i"), &url) { return Ok(true); } diff --git a/crates/shirabe/src/repository/vcs/vcs_driver.rs b/crates/shirabe/src/repository/vcs/vcs_driver.rs index 1dce8567..5aa74959 100644 --- a/crates/shirabe/src/repository/vcs/vcs_driver.rs +++ b/crates/shirabe/src/repository/vcs/vcs_driver.rs @@ -13,7 +13,7 @@ use crate::util::http::Response; use chrono::{DateTime, FixedOffset}; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::Preg; -use shirabe_php_shim::{DATE_RFC3339, PhpMixed, extension_loaded}; +use shirabe_php_shim::{DATE_RFC3339, PhpMixed, extension_loaded, php_regex}; #[derive(Debug)] pub struct VcsDriverBase { @@ -56,7 +56,7 @@ impl VcsDriverBase { } pub fn should_cache(&self, identifier: &str) -> bool { - self.cache.is_some() && Preg::is_match("{^[a-f0-9]{40}$}iD", identifier) + self.cache.is_some() && Preg::is_match(php_regex!("{^[a-f0-9]{40}$}iD"), identifier) } pub fn get_scheme(&self) -> &str { @@ -199,7 +199,7 @@ pub trait VcsDriver: VcsDriverInterface { fn cache_mut(&mut self) -> Option<&mut Cache>; fn should_cache(&self, identifier: &str) -> bool { - self.cache().is_some() && Preg::is_match("{^[a-f0-9]{40}$}iD", identifier) + self.cache().is_some() && Preg::is_match(php_regex!("{^[a-f0-9]{40}$}iD"), identifier) } fn get_composer_information( diff --git a/crates/shirabe/src/repository/vcs_repository.rs b/crates/shirabe/src/repository/vcs_repository.rs index 29702db3..c04b1b67 100644 --- a/crates/shirabe/src/repository/vcs_repository.rs +++ b/crates/shirabe/src/repository/vcs_repository.rs @@ -28,7 +28,9 @@ use crate::util::ProcessExecutor; use crate::util::Url; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::Preg; -use shirabe_php_shim::{InvalidArgumentException, PhpMixed, in_array, str_replace, strpos}; +use shirabe_php_shim::{ + InvalidArgumentException, PhpMixed, in_array, php_regex, str_replace, strpos, +}; use shirabe_semver::constraint::SimpleConstraint; // TODO(phase-c): the driver registration should be refactored later. @@ -479,7 +481,7 @@ impl VcsRepository { data.insert( "version".to_string(), PhpMixed::String(Preg::replace( - r"{[.-]?dev$}i", + php_regex!(r"{[.-]?dev$}i"), "", data.get("version") .and_then(|v| v.as_string()) @@ -489,7 +491,7 @@ impl VcsRepository { data.insert( "version_normalized".to_string(), PhpMixed::String(Preg::replace( - r"{(^dev-|[.-]?dev$)}i", + php_regex!(r"{(^dev-|[.-]?dev$)}i"), "", data.get("version_normalized") .and_then(|v| v.as_string()) @@ -509,7 +511,7 @@ impl VcsRepository { // broken package, version doesn't match tag if version_normalized != parsed_tag { if is_very_verbose { - if Preg::is_match(r"{(^dev-|[.-]?dev$)}i", &parsed_tag) { + if Preg::is_match(php_regex!(r"{(^dev-|[.-]?dev$)}i"), &parsed_tag) { self.io.write_error(&format!( "<warning>Skipped tag {}, invalid tag name, tags can not use dev prefixes or suffixes</warning>", tag diff --git a/crates/shirabe/src/self_update/versions.rs b/crates/shirabe/src/self_update/versions.rs index 856d16f4..3f8c2a8b 100644 --- a/crates/shirabe/src/self_update/versions.rs +++ b/crates/shirabe/src/self_update/versions.rs @@ -8,7 +8,7 @@ use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::Preg; use shirabe_php_shim::{ InvalidArgumentException, PHP_EOL, PHP_VERSION, PHP_VERSION_ID, PhpMixed, - UnexpectedValueException, + UnexpectedValueException, php_regex, }; pub struct Versions { @@ -94,7 +94,7 @@ impl Versions { self.channel = Some(channel.clone()); // rewrite '2' and '1' channels to stable for future self-updates, but LTS ones like '2.2' remain pinned - let stored_channel = if Preg::is_match(r"{^\d+$}D", &channel) { + let stored_channel = if Preg::is_match(php_regex!(r"{^\d+$}D"), &channel) { "stable".to_string() } else { channel.clone() diff --git a/crates/shirabe/src/util/auth_helper.rs b/crates/shirabe/src/util/auth_helper.rs index 1e997fd9..0a2dbf86 100644 --- a/crates/shirabe/src/util/auth_helper.rs +++ b/crates/shirabe/src/util/auth_helper.rs @@ -12,8 +12,8 @@ use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::Preg; use shirabe_php_shim::{ PHP_URL_HOST, PHP_URL_PATH, PHP_URL_SCHEME, PhpMixed, RuntimeException, base64_encode, explode, - in_array, is_array, is_string, json_decode, parse_url, str_replace, strpos, strtolower, substr, - trim, + in_array, is_array, is_string, json_decode, parse_url, php_regex, str_replace, strpos, + strtolower, substr, trim, }; #[derive(Debug)] @@ -516,7 +516,7 @@ impl AuthHelper { } } else if origin == "github.com" && password == "x-oauth-basic" { // only add the access_token if it is actually a github API URL - if Preg::is_match(r"{^https?://api\.github\.com/}", url) { + if Preg::is_match(php_regex!(r"{^https?://api\.github\.com/}"), url) { headers.push(PhpMixed::String(format!( "Authorization: token {}", username, diff --git a/crates/shirabe/src/util/composer_mirror.rs b/crates/shirabe/src/util/composer_mirror.rs index 31f71279..a6f60621 100644 --- a/crates/shirabe/src/util/composer_mirror.rs +++ b/crates/shirabe/src/util/composer_mirror.rs @@ -1,7 +1,7 @@ //! ref: composer/src/Composer/Util/ComposerMirror.php use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; -use shirabe_php_shim::hash; +use shirabe_php_shim::{hash, php_regex}; pub struct ComposerMirror; @@ -15,7 +15,7 @@ impl ComposerMirror { pretty_version: Option<&str>, ) -> String { let reference = reference.map(|r| { - if Preg::is_match(r"{^([a-f0-9]*|%reference%)$}", r) { + if Preg::is_match(php_regex!(r"{^([a-f0-9]*|%reference%)$}"), r) { r.to_string() } else { hash("md5", r) @@ -56,7 +56,9 @@ impl ComposerMirror { let mut gh_matches: indexmap::IndexMap<CaptureKey, String> = indexmap::IndexMap::new(); let mut bb_matches: indexmap::IndexMap<CaptureKey, String> = indexmap::IndexMap::new(); let normalized_url = if Preg::match3( - r"#^(?:(?:https?|git)://github\.com/|git@github\.com:)([^/]+)/(.+?)(?:\.git)?$#", + php_regex!( + r"#^(?:(?:https?|git)://github\.com/|git@github\.com:)([^/]+)/(.+?)(?:\.git)?$#" + ), url, Some(&mut gh_matches), ) { @@ -72,7 +74,7 @@ impl ComposerMirror { .unwrap_or_default(), ) } else if Preg::match3( - r"#^https://bitbucket\.org/([^/]+)/(.+?)(?:\.git)?/?$#", + php_regex!(r"#^https://bitbucket\.org/([^/]+)/(.+?)(?:\.git)?/?$#"), url, Some(&mut bb_matches), ) { @@ -88,7 +90,7 @@ impl ComposerMirror { .unwrap_or_default(), ) } else { - Preg::replace(r"{[^a-z0-9_.-]}i", "-", url.trim_matches('/')) + Preg::replace(php_regex!(r"{[^a-z0-9_.-]}i"), "-", url.trim_matches('/')) }; ["%package%", "%normalizedUrl%", "%type%"] diff --git a/crates/shirabe/src/util/config_validator.rs b/crates/shirabe/src/util/config_validator.rs index 4137a2d9..a9b89fd6 100644 --- a/crates/shirabe/src/util/config_validator.rs +++ b/crates/shirabe/src/util/config_validator.rs @@ -10,7 +10,7 @@ use crate::package::loader::ValidatingArrayLoader; use indexmap::IndexMap; use serde::de::Error as _; use shirabe_external_packages::composer::pcre::Preg; -use shirabe_php_shim::PhpMixed; +use shirabe_php_shim::{PhpMixed, php_regex}; use shirabe_spdx_licenses::SpdxLicenses; #[derive(Debug)] @@ -123,13 +123,16 @@ impl ConfigValidator { _ => false, }; if is_deprecated { - if Preg::is_match(r"{^[AL]?GPL-[123](\.[01])?\+$}i", license) { + if Preg::is_match(php_regex!(r"{^[AL]?GPL-[123](\.[01])?\+$}i"), license) { warnings.push(format!( "License \"{}\" is a deprecated SPDX license identifier, use \"{}-or-later\" instead", license, license.replace('+', "") )); - } else if Preg::is_match(r"{^[AL]?GPL-[123](\.[01])?$}i", license) { + } else if Preg::is_match( + php_regex!(r"{^[AL]?GPL-[123](\.[01])?$}i"), + license, + ) { warnings.push(format!( "License \"{}\" is a deprecated SPDX license identifier, use \"{}-only\" or \"{}-or-later\" instead", license, license, license @@ -151,10 +154,10 @@ impl ConfigValidator { if let Some(PhpMixed::String(name)) = manifest.get("name") && !name.is_empty() - && Preg::is_match(r"{[A-Z]}", name) + && Preg::is_match(php_regex!(r"{[A-Z]}"), name) { let suggest_name = Preg::replace( - r"{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}", + php_regex!(r"{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}"), r"\1\3-\2\4", name, ); @@ -228,7 +231,7 @@ impl ConfigValidator { packages.extend(require_dev); for (package, version) in &packages { if let PhpMixed::String(version_str) = version - && Preg::is_match(r"{#}", version_str) + && Preg::is_match(php_regex!(r"{#}"), version_str) { warnings.push(format!( "The package \"{}\" is pointing to a commit-ref, this is bad practice and can cause unforeseen issues.", diff --git a/crates/shirabe/src/util/filesystem.rs b/crates/shirabe/src/util/filesystem.rs index d21a0e7d..b92bee94 100644 --- a/crates/shirabe/src/util/filesystem.rs +++ b/crates/shirabe/src/util/filesystem.rs @@ -11,9 +11,9 @@ use shirabe_php_shim::{ basename, chdir, clearstatcache, clearstatcache2, copy, dirname, error_get_last, explode, fclose, feof, file_exists, file_get_contents, file_put_contents, fileatime, filemtime, filesize, fopen, fread, function_exists, fwrite, implode, is_dir, is_file, is_link, - is_readable, lstat, mkdir, rename, rmdir, rtrim, str_contains, str_repeat, str_replace, - str_starts_with, strlen, strpos, strtoupper, strtr, substr, substr_count, symlink, touch, - unlink, usleep, var_export, + is_readable, lstat, mkdir, php_regex, rename, rmdir, rtrim, str_contains, str_repeat, + str_replace, str_starts_with, strlen, strpos, strtoupper, strtr, substr, substr_count, symlink, + touch, unlink, usleep, var_export, }; use std::path::Path; @@ -227,7 +227,7 @@ impl Filesystem { return Ok(Some(true)); } - if Preg::is_match3("{^(?:[a-z]:)?[/\\\\]+$}i", directory, None) { + if Preg::is_match3(php_regex!("{^(?:[a-z]:)?[/\\\\]+$}i"), directory, None) { return Err(RuntimeException { message: format!("Aborting an attempted deletion of {}, this was probably not intended, if it is a real use case please report it.", directory), code: 0, @@ -592,7 +592,7 @@ impl Filesystem { let mut common_path = to.clone(); while strpos(&format!("{}/", from), &format!("{}/", common_path)) != Some(0) && "/" != common_path - && !Preg::is_match3("{^[A-Z]:/?$}i", &common_path, None) + && !Preg::is_match3(php_regex!("{^[A-Z]:/?$}i"), &common_path, None) { common_path = strtr(&dirname(&common_path), "\\", "/"); } @@ -649,7 +649,7 @@ impl Filesystem { let mut common_path = to.clone(); while strpos(&format!("{}/", from), &format!("{}/", common_path)) != Some(0) && "/" != common_path - && !Preg::is_match3("{^[A-Z]:/?$}i", &common_path, None) + && !Preg::is_match3(php_regex!("{^[A-Z]:/?$}i"), &common_path, None) && "." != common_path { common_path = strtr(&dirname(&common_path), "\\", "/"); @@ -756,7 +756,7 @@ impl Filesystem { String, > = indexmap::IndexMap::new(); if Preg::is_match3( - "{^( [0-9a-z]{2,}+: (?: // (?: [a-z]: )? )? | [a-z]: )}ix", + php_regex!("{^( [0-9a-z]{2,}+: (?: // (?: [a-z]: )? )? | [a-z]: )}ix"), &path, Some(&mut prefix_match), ) { @@ -785,7 +785,7 @@ impl Filesystem { // ensure c: is normalized to C: prefix = Preg::replace_callback( - "{(^|://)[a-z]:$}i", + php_regex!("{(^|://)[a-z]:$}i"), |m: &indexmap::IndexMap< shirabe_external_packages::composer::pcre::CaptureKey, String, @@ -808,7 +808,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("{^[/\\\\]+$}", &path, None) { + if !Preg::is_match3(php_regex!("{^[/\\\\]+$}"), &path, None) { path = rtrim(&path, Some("/\\")); } @@ -821,14 +821,16 @@ impl Filesystem { // on linux as file:////foo (which would be a network path \\foo on windows) will resolve to /foo which could be a local path if Platform::is_windows() { return Preg::is_match3( - "{^(file://(?!//)|/(?!/)|/?[a-z]:[\\\\/]|\\.\\.[\\\\/]|[a-z0-9_.-]+[\\\\/])}i", + php_regex!( + "{^(file://(?!//)|/(?!/)|/?[a-z]:[\\\\/]|\\.\\.[\\\\/]|[a-z0-9_.-]+[\\\\/])}i" + ), path, None, ); } Preg::is_match3( - "{^(file://|/|/?[a-z]:[\\\\/]|\\.\\.[\\\\/]|[a-z0-9_.-]+[\\\\/])}i", + php_regex!("{^(file://|/|/?[a-z]:[\\\\/]|\\.\\.[\\\\/]|[a-z0-9_.-]+[\\\\/])}i"), path, None, ) @@ -837,10 +839,14 @@ impl Filesystem { pub fn get_platform_path(path: &str) -> String { let mut path = path.to_string(); if Platform::is_windows() { - path = Preg::replace("{^(?:file:///([a-z]):?/)}i", "file://$1:/", &path); + path = Preg::replace( + php_regex!("{^(?:file:///([a-z]):?/)}i"), + "file://$1:/", + &path, + ); } - Preg::replace("{^file://}i", "", &path) + Preg::replace(php_regex!("{^file://}i"), "", &path) } /// Cross-platform safe version of is_readable() diff --git a/crates/shirabe/src/util/git.rs b/crates/shirabe/src/util/git.rs index 4520759f..1e6768b1 100644 --- a/crates/shirabe/src/util/git.rs +++ b/crates/shirabe/src/util/git.rs @@ -17,8 +17,8 @@ use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ InvalidArgumentException, PHP_EOL, PhpMixed, RuntimeException, array_map, clearstatcache, - explode, implode, in_array, is_dir, preg_quote, rawurldecode, rawurlencode, str_contains, - str_ends_with, str_replace_array, strlen, strpos, substr, trim, version_compare, + explode, implode, in_array, is_dir, php_regex, preg_quote, rawurldecode, rawurlencode, + str_contains, str_ends_with, str_replace_array, strlen, strpos, substr, trim, version_compare, }; use std::sync::Mutex; @@ -114,7 +114,7 @@ impl Git { map.insert("%url%".to_string(), url.to_string()); map.insert( "%sanitizedUrl%".to_string(), - Preg::replace(r"{://([^@]+?):(.+?)@}", "://", url), + Preg::replace(php_regex!(r"{://([^@]+?):(.+?)@}"), "://", url), ); array_map( @@ -215,7 +215,7 @@ impl Git { status }; - if Preg::is_match(r"{^ssh://[^@]+@[^:]+:[^0-9]+}", url) { + if Preg::is_match(php_regex!(r"{^ssh://[^@]+@[^:]+:[^0-9]+}"), url) { return Err(InvalidArgumentException { message: format!( "The source URL {} is invalid, ssh URLs should have a port number after \":\".\nUse ssh://git@example.com:22/path or just git@example.com:path if you do not want to provide a password or custom port.", @@ -236,7 +236,7 @@ impl Git { ); let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - r"{^(?:composer|origin)\s+https?://(.+):(.+)@([^/]+)}im", + php_regex!(r"{^(?:composer|origin)\s+https?://(.+):(.+)@([^/]+)}im"), &output, Some(&mut m), ) { @@ -258,7 +258,7 @@ impl Git { // @phpstan-ignore composerPcre.maybeUnsafeStrictGroups let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - &format!( + format!( "{{^(?:https?|git)://{}/(.*)}}", Self::get_github_domains_regex(&self.config.borrow()) ), @@ -326,7 +326,7 @@ impl Git { _ => vec![], }; let bypass_ssh_for_github = Preg::is_match( - &format!( + format!( "{{^git@{}:(.+?)\\.git$}}i", Self::get_github_domains_regex(&self.config.borrow()) ), @@ -357,14 +357,14 @@ impl Git { // @phpstan-ignore composerPcre.maybeUnsafeStrictGroups let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); let github_matched = Preg::is_match3( - &format!( + format!( "{{^git@{}:(.+?)\\.git$}}i", Self::get_github_domains_regex(&self.config.borrow()) ), url, Some(&mut m), ) || Preg::is_match3( - &format!( + format!( "{{^https?://{}/(.*?)(?:\\.git)?$}}i", Self::get_github_domains_regex(&self.config.borrow()) ), @@ -422,11 +422,11 @@ impl Git { error_msg = self.process.borrow().get_error_output().to_string(); } } else if Preg::is_match3( - r"{^(https?)://(bitbucket\.org)/(.*?)(?:\.git)?$}i", + php_regex!(r"{^(https?)://(bitbucket\.org)/(.*?)(?:\.git)?$}i"), url, Some(&mut m), ) || Preg::is_match3( - r"{^(git)@(bitbucket\.org):(.+?\.git)$}i", + php_regex!(r"{^(git)@(bitbucket\.org):(.+?\.git)$}i"), url, Some(&mut m), ) { @@ -568,14 +568,14 @@ impl Git { error_msg = self.process.borrow().get_error_output().to_string(); } else if Preg::is_match3( - &format!( + format!( "{{^(git)@{}:(.+?\\.git)$}}i", Self::get_gitlab_domains_regex(&self.config.borrow()) ), url, Some(&mut m), ) || Preg::is_match3( - &format!( + format!( "{{^(https?)://{}/(.*)}}i", Self::get_gitlab_domains_regex(&self.config.borrow()) ), @@ -924,10 +924,14 @@ impl Git { pretty_version: Option<&str>, ) -> anyhow::Result<bool> { if self.check_ref_is_in_mirror(dir, r#ref)? { - if Preg::is_match(r"{^[a-f0-9]{40}$}", r#ref) + if Preg::is_match(php_regex!(r"{^[a-f0-9]{40}$}"), r#ref) && let Some(pretty_version) = pretty_version { - let branch = Preg::replace(r"{(?:^dev-|(?:\.x)?-dev$)}i", "", pretty_version); + let branch = Preg::replace( + php_regex!(r"{(?:^dev-|(?:\.x)?-dev$)}i"), + "", + pretty_version, + ); let mut branches: Option<String> = None; let mut tags: Option<String> = None; let mut output = String::new(); @@ -955,12 +959,12 @@ impl Git { // see https://github.com/composer/composer/discussions/11002 if branches.is_some() && !Preg::is_match( - &format!(r"{{^[\s*]*v?{}$}}m", preg_quote(&branch, None)), + format!(r"{{^[\s*]*v?{}$}}m", preg_quote(&branch, None)), branches.as_deref().unwrap_or(""), ) && tags.is_some() && !Preg::is_match( - &format!(r"{{^[\s*]*{}$}}m", preg_quote(&branch, None)), + format!(r"{{^[\s*]*{}$}}m", preg_quote(&branch, None)), tags.as_deref().unwrap_or(""), ) { @@ -1050,7 +1054,7 @@ impl Git { } // Filter out "commit <hash>" lines for older git versions - Preg::replace(r"{^commit [a-f0-9]{40}\n?}m", "", output) + Preg::replace(php_regex!(r"{^commit [a-f0-9]{40}\n?}m"), "", output) } fn check_ref_is_in_mirror(&mut self, dir: &str, r#ref: &str) -> anyhow::Result<bool> { @@ -1091,7 +1095,11 @@ impl Git { /// @return array<int, string>|null fn get_authentication_failure(&self, url: &str) -> Option<IndexMap<CaptureKey, String>> { let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); - if !Preg::is_match3(r"{^(https?://)([^/]+)(.*)$}i", url, Some(&mut m)) { + if !Preg::is_match3( + php_regex!(r"{^(https?://)([^/]+)(.*)$}i"), + url, + Some(&mut m), + ) { return None; } @@ -1176,7 +1184,11 @@ impl Git { .split_lines(output_mixed.as_string().unwrap_or("")); for line in lines { let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::is_match3(r"{^\s*HEAD branch:\s(.+)\s*$}m", &line, Some(&mut matches)) { + if Preg::is_match3( + php_regex!(r"{^\s*HEAD branch:\s(.+)\s*$}m"), + &line, + Some(&mut matches), + ) { return Ok(Some( matches .get(&CaptureKey::ByIndex(1)) @@ -1314,7 +1326,7 @@ impl Git { if exit_code == 0 { let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::is_match3( - r"/^git version (\d+(?:\.\d+)+)/m", + php_regex!(r"/^git version (\d+(?:\.\d+)+)/m"), &output, Some(&mut matches), ) { diff --git a/crates/shirabe/src/util/github.rs b/crates/shirabe/src/util/github.rs index 905026a6..e8e83ddd 100644 --- a/crates/shirabe/src/util/github.rs +++ b/crates/shirabe/src/util/github.rs @@ -9,7 +9,7 @@ use crate::util::HttpDownloader; use crate::util::ProcessExecutor; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; -use shirabe_php_shim::{PhpMixed, date, stripos, strtolower}; +use shirabe_php_shim::{PhpMixed, date, php_regex, stripos, strtolower}; #[derive(Debug)] pub struct GitHub { @@ -331,7 +331,11 @@ impl GitHub { continue; } let mut caps: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::match3(r"{\burl=(?P<url>[^\s;]+)}", header, Some(&mut caps)) { + if Preg::match3( + php_regex!(r"{\burl=(?P<url>[^\s;]+)}"), + header, + Some(&mut caps), + ) { return caps.get(&CaptureKey::ByName("url".to_string())).cloned(); } } @@ -341,7 +345,7 @@ impl GitHub { pub fn is_rate_limited(&self, headers: &[String]) -> bool { for header in headers { - if Preg::is_match(r"{^x-ratelimit-remaining: *0$}i", header.trim()) { + if Preg::is_match(php_regex!(r"{^x-ratelimit-remaining: *0$}i"), header.trim()) { return true; } } @@ -351,7 +355,7 @@ impl GitHub { pub fn requires_sso(&self, headers: &[String]) -> bool { for header in headers { - if Preg::is_match(r"{^x-github-sso: required}i", header.trim()) { + if Preg::is_match(php_regex!(r"{^x-github-sso: required}i"), header.trim()) { return true; } } diff --git a/crates/shirabe/src/util/gitlab.rs b/crates/shirabe/src/util/gitlab.rs index eae26f0e..4a636efa 100644 --- a/crates/shirabe/src/util/gitlab.rs +++ b/crates/shirabe/src/util/gitlab.rs @@ -10,7 +10,9 @@ use crate::util::HttpDownloader; use crate::util::ProcessExecutor; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::Preg; -use shirabe_php_shim::{PhpMixed, RuntimeException, http_build_query, json_decode, time}; +use shirabe_php_shim::{ + PhpMixed, RuntimeException, http_build_query, json_decode, php_regex, time, +}; #[derive(Debug)] pub struct GitLab { @@ -50,7 +52,7 @@ impl GitLab { pub fn authorize_oauth(&mut self, origin_url: &str) -> bool { // before composer 1.9, origin URLs had no port number in them - let bc_origin_url = Preg::replace("{:\\d+}", "", origin_url); + let bc_origin_url = Preg::replace(php_regex!("{:\\d+}"), "", origin_url); let gitlab_domains = self.config.borrow_mut().get("gitlab-domains"); let domains = match gitlab_domains.as_array() { diff --git a/crates/shirabe/src/util/hg.rs b/crates/shirabe/src/util/hg.rs index 56e5044f..9f5ea3b5 100644 --- a/crates/shirabe/src/util/hg.rs +++ b/crates/shirabe/src/util/hg.rs @@ -6,7 +6,7 @@ use crate::io::IOInterfaceImmutable; use crate::util::ProcessExecutor; use crate::util::Url; use shirabe_external_packages::composer::pcre::Preg; -use shirabe_php_shim::rawurlencode; +use shirabe_php_shim::{php_regex, rawurlencode}; use std::sync::OnceLock; static VERSION: OnceLock<Option<String>> = OnceLock::new(); @@ -58,7 +58,9 @@ impl Hg { // Try with the authentication information available let mut matches: indexmap::IndexMap<String, String> = indexmap::IndexMap::new(); let matched = Preg::is_match_named( - r"{^(?P<proto>ssh|https?)://(?:(?P<user>[^:@]+)(?::(?P<pass>[^:@]+))?@)?(?P<host>[^/]+)(?P<path>/.*)?}mi", + php_regex!( + r"{^(?P<proto>ssh|https?)://(?:(?P<user>[^:@]+)(?::(?P<pass>[^:@]+))?@)?(?P<host>[^/]+)(?P<path>/.*)?}mi" + ), &url, &mut matches, ); @@ -152,7 +154,7 @@ impl Hg { None, ) == 0 && let Some(matches) = Preg::is_match_with_indexed_captures( - r"/^.+? (\d+(?:\.\d+)+)(?:\+.*?)?\)?\r?\n/", + php_regex!(r"/^.+? (\d+(?:\.\d+)+)(?:\+.*?)?\)?\r?\n/"), &output, ) { diff --git a/crates/shirabe/src/util/http/curl_downloader.rs b/crates/shirabe/src/util/http/curl_downloader.rs index 47260a85..508aa56e 100644 --- a/crates/shirabe/src/util/http/curl_downloader.rs +++ b/crates/shirabe/src/util/http/curl_downloader.rs @@ -33,7 +33,7 @@ use crate::util::{AuthHelper, PromptAuthResult, StoreAuth}; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::Preg; use shirabe_php_shim::{ - PhpMixed, in_array, parse_url, preg_quote, rename, strpos, substr, unlink_silent, + PhpMixed, in_array, parse_url, php_regex, preg_quote, rename, strpos, substr, unlink_silent, }; use std::sync::atomic::{AtomicBool, Ordering}; @@ -150,7 +150,7 @@ impl CurlDownloader { // check URL can be accessed (i.e. is not insecure), but allow insecure Packagist calls to // $hashed providers as file integrity is verified with sha256 - if !Preg::is_match(r"{^http://(repo\.)?packagist\.org/p/}", url) + if !Preg::is_match(php_regex!(r"{^http://(repo\.)?packagist\.org/p/}"), url) || (strpos(url, "$").is_none() && strpos(url, "%24").is_none()) { self.config.borrow_mut().prohibit_url_by_config( @@ -659,7 +659,7 @@ impl CurlDownloader { let url_host = parse_url(url, shirabe_php_shim::PHP_URL_HOST); let url_host_str = url_host.as_string().unwrap_or(""); target_url = Preg::replace( - &format!( + format!( r"{{^(.+(?://|@){}(?::\d+)?)(?:[/\?].*)?$}}", preg_quote(url_host_str, None) ), @@ -669,7 +669,7 @@ impl CurlDownloader { } else { // Relative path; e.g. foo target_url = Preg::replace( - r"{^(.+/)[^/?]*(?:\?.*)?$}", + php_regex!(r"{^(.+/)[^/?]*(?:\?.*)?$}"), &format!("\\1{}", location_header), url, ); @@ -754,7 +754,7 @@ impl CurlDownloader { && (location_header.is_none() || substr(location_header.as_deref().unwrap_or(""), -4, None) != ".zip") && Preg::is_match( - r"{^text/html\b}i", + php_regex!(r"{^text/html\b}i"), &response .inner .get_header("content-type") diff --git a/crates/shirabe/src/util/http/response.rs b/crates/shirabe/src/util/http/response.rs index 5398fe25..3ee538d5 100644 --- a/crates/shirabe/src/util/http/response.rs +++ b/crates/shirabe/src/util/http/response.rs @@ -2,7 +2,7 @@ use crate::json::JsonFile; use shirabe_external_packages::composer::pcre::Preg; -use shirabe_php_shim::{PhpMixed, preg_quote}; +use shirabe_php_shim::{PhpMixed, php_regex, preg_quote}; #[derive(Debug)] pub struct Response { @@ -29,7 +29,7 @@ impl Response { pub fn get_status_message(&self) -> Option<String> { let mut value = None; for header in &self.headers { - if Preg::is_match(r"{^HTTP/\S+ \d+}i", header) { + if Preg::is_match(php_regex!(r"{^HTTP/\S+ \d+}i"), header) { // In case of redirects, headers contain the headers of all responses // so we can not return directly and need to keep iterating value = Some(header.clone()); diff --git a/crates/shirabe/src/util/http_downloader.rs b/crates/shirabe/src/util/http_downloader.rs index 98678ad2..b055a515 100644 --- a/crates/shirabe/src/util/http_downloader.rs +++ b/crates/shirabe/src/util/http_downloader.rs @@ -19,8 +19,8 @@ use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ InvalidArgumentException, LogicException, PhpMixed, array_replace_recursive, chr, - extension_loaded, file_get_contents, function_exists, implode, is_numeric, rawurldecode, - stream_context_create, stripos, strpos, substr, ucfirst, + extension_loaded, file_get_contents, function_exists, implode, is_numeric, php_regex, + rawurldecode, stream_context_create, stripos, strpos, substr, ucfirst, }; use shirabe_semver::constraint::SimpleConstraint; @@ -253,7 +253,11 @@ impl HttpDownloader { // capture username/password from URL if there is one let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::is_match3(r"{^https?://([^:/]+):([^@/]+)@([^/]+)}i", url, Some(&mut m)) { + if Preg::is_match3( + php_regex!(r"{^https?://([^:/]+):([^@/]+)@([^/]+)}i"), + url, + Some(&mut m), + ) { self.io.borrow_mut().set_authentication( origin.clone(), rawurldecode( @@ -378,7 +382,7 @@ impl HttpDownloader { let clean_message = |msg: &str| -> anyhow::Result<String> { if !io.is_decorated() { return Ok(Preg::replace( - &format!("{{{}{}}}u", chr(27), "\\[[;\\d]*m"), + format!("{{{}{}}}u", chr(27), "\\[[;\\d]*m"), "", msg, )); @@ -515,7 +519,7 @@ impl HttpDownloader { return false; } - if !Preg::is_match(r"{^https?://}i", url) { + if !Preg::is_match(php_regex!(r"{^https?://}i"), url) { return false; } diff --git a/crates/shirabe/src/util/no_proxy_pattern.rs b/crates/shirabe/src/util/no_proxy_pattern.rs index 0a3d5640..dc91a256 100644 --- a/crates/shirabe/src/util/no_proxy_pattern.rs +++ b/crates/shirabe/src/util/no_proxy_pattern.rs @@ -4,8 +4,8 @@ use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::Preg; use shirabe_php_shim::{ PHP_URL_HOST, PHP_URL_PORT, PHP_URL_SCHEME, PhpMixed, RuntimeException, array_key_exists, chr, - empty, explode, filter_var_int_with_range, filter_var_ip, inet_pton, ltrim, parse_url, str_pad, - str_repeat, stripos, strlen, strpbrk, strpos, substr, substr_count, unpack, + empty, explode, filter_var_int_with_range, filter_var_ip, inet_pton, ltrim, parse_url, + php_regex, str_pad, str_repeat, stripos, strlen, strpbrk, strpos, substr, substr_count, unpack, }; /// Tests URLs against NO_PROXY patterns @@ -38,7 +38,7 @@ impl NoProxyPattern { /// @param string $pattern NO_PROXY pattern pub fn new(pattern: &str) -> Self { // PHP: Preg::split('{[\s,]+}', $pattern, -1, PREG_SPLIT_NO_EMPTY) - let host_names = Preg::split(r"{[\s,]+}", pattern); + let host_names = Preg::split(php_regex!(r"{[\s,]+}"), pattern); let noproxy = host_names.is_empty() || host_names[0] == "*"; Self { host_names, diff --git a/crates/shirabe/src/util/perforce.rs b/crates/shirabe/src/util/perforce.rs index 389618ed..e39ed3c2 100644 --- a/crates/shirabe/src/util/perforce.rs +++ b/crates/shirabe/src/util/perforce.rs @@ -11,8 +11,8 @@ use shirabe_external_packages::symfony::process::ExecutableFinder; use shirabe_external_packages::symfony::process::Process; use shirabe_php_shim::{ Exception, PHP_EOL, PhpMixed, PhpResource, chdir, date, explode, fclose, feof, fgets, - file_get_contents, fopen, fwrite, gethostname, json_decode, str_replace_array, strcmp, strlen, - strpos, strrpos, substr, time, trim, + file_get_contents, fopen, fwrite, gethostname, json_decode, php_regex, str_replace_array, + strcmp, strlen, strpos, strrpos, substr, time, trim, }; /// @phpstan-type RepoConfig array{unique_perforce_client_name?: string, depot?: string, branch?: string, p4user?: string, p4password?: string} @@ -690,7 +690,7 @@ impl Perforce { let res_bits = explode(" ", line); if res_bits.len() > 4 { let branch = Preg::replace( - r"/[^A-Za-z0-9 ]/", + php_regex!(r"/[^A-Za-z0-9 ]/"), "", &res_bits.get(4).cloned().unwrap_or_default(), ); diff --git a/crates/shirabe/src/util/platform.rs b/crates/shirabe/src/util/platform.rs index 45ddb306..81f2adbb 100644 --- a/crates/shirabe/src/util/platform.rs +++ b/crates/shirabe/src/util/platform.rs @@ -6,7 +6,7 @@ use shirabe_external_packages::composer::pcre::Preg; use shirabe_php_shim::{ PHP_ENV, PHP_SERVER, PhpMixed, PhpResource, RuntimeException, defined, file_exists, file_get_contents, fstat, function_exists, getcwd, getenv, in_array, ini_get, is_array, - is_readable, mb_strlen, php_os_family, posix_geteuid, posix_getpwuid, posix_getuid, + is_readable, mb_strlen, php_os_family, php_regex, posix_geteuid, posix_getpwuid, posix_getuid, posix_isatty, putenv, putenv_clear, realpath, stream_isatty, stripos, strlen, strtoupper, substr, usleep, }; @@ -90,7 +90,7 @@ impl Platform { /// Parses tildes and environment variables in paths. pub fn expand_path(path: &str) -> String { use shirabe_external_packages::composer::pcre::CaptureKey; - if Preg::is_match(r"#^~[\\/]#", path) { + if Preg::is_match(php_regex!(r"#^~[\\/]#"), path) { return format!( "{}{}", Self::get_user_directory().unwrap(), @@ -103,7 +103,7 @@ impl Platform { // only for the `%VAR%` form. The Rust regex crate does not support conditionals, so the // two forms are written as an explicit alternation: `$VAR` or `%VAR%`. Preg::replace_callback( - r"#^(?:\$(?P<dvar>\w+)|%(?P<pvar>\w+)%)(?P<path>.*)#", + php_regex!(r"#^(?:\$(?P<dvar>\w+)|%(?P<pvar>\w+)%)(?P<path>.*)#"), |matches: &indexmap::IndexMap<CaptureKey, String>| -> String { let var = matches .get(&CaptureKey::ByName("dvar".to_string())) diff --git a/crates/shirabe/src/util/process_executor.rs b/crates/shirabe/src/util/process_executor.rs index 463e5115..e2b1422d 100644 --- a/crates/shirabe/src/util/process_executor.rs +++ b/crates/shirabe/src/util/process_executor.rs @@ -14,7 +14,7 @@ use shirabe_external_packages::symfony::process::exception::ProcessSignaledExcep use shirabe_external_packages::symfony::process::exception::RuntimeException as SymfonyProcessRuntimeException; use shirabe_php_shim::{ LogicException, PHP_EOL, PhpMixed, array_intersect, array_map, call_user_func, escapeshellarg, - explode, implode, in_array, is_array, is_dir, is_numeric, is_string, rtrim, sprintf, + explode, implode, in_array, is_array, is_dir, is_numeric, is_string, php_regex, rtrim, sprintf, str_replace, strcspn, strlen, strpbrk, strtolower, strtr_array, substr_replace, trim, usleep, }; use std::sync::{LazyLock, Mutex}; @@ -236,7 +236,7 @@ impl ProcessExecutor { let mut command_str = command.as_string().unwrap_or("").to_string(); if Platform::is_windows() { let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::is_match3(r"{^([^:/\\]++) }", &command_str, Some(&mut m)) { + 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, @@ -870,7 +870,7 @@ impl ProcessExecutor { if output.is_empty() { vec![] } else { - Preg::split(r"{\r?\n}", &output) + Preg::split(php_regex!(r"{\r?\n}"), &output) } } @@ -912,7 +912,7 @@ impl ProcessExecutor { String::new() }; let safe_command = Preg::replace_callback( - r"{://(?P<user>[^:/\s]+):(?P<password>[^@\s/]+)@}i", + php_regex!(r"{://(?P<user>[^:/\s]+):(?P<password>[^@\s/]+)@}i"), |m: &IndexMap<CaptureKey, String>| -> String { let user_key = CaptureKey::ByName("user".to_string()); // if the username looks like a long (12char+) hex string, or a modern github token (e.g. ghp_xxx, github_pat_xxx) we obfuscate that @@ -934,7 +934,7 @@ impl ProcessExecutor { &command_string, ); let safe_command = Preg::replace( - r"{--password (.*[^\\]') }", + php_regex!(r"{--password (.*[^\\]') }"), "--password '***' ", &safe_command, ); @@ -980,8 +980,14 @@ impl ProcessExecutor { let mut quote = strpbrk(&argument, " \t,").is_some(); let mut dquotes: usize = 0; // PHP: Preg::replace('/(\\\\*)"/', '$1$1\\"', $argument, -1, $dquotes) - argument = Preg::replace5(r#"/(\\*)"/"#, r#"$1$1\""#, &argument, -1, &mut dquotes); - let meta = dquotes > 0 || Preg::is_match(r"/%[^%]+%|![^!]+!/", &argument); + argument = Preg::replace5( + php_regex!(r#"/(\\*)"/"#), + r#"$1$1\""#, + &argument, + -1, + &mut dquotes, + ); + let meta = dquotes > 0 || Preg::is_match(php_regex!(r"/%[^%]+%|![^!]+!/"), &argument); if !meta && !quote { quote = strpbrk(&argument, "^&|<>()").is_some(); @@ -992,8 +998,8 @@ impl ProcessExecutor { } if meta { - argument = Preg::replace(r#"/(["^&|<>()%])/"#, "^$1", &argument); - argument = Preg::replace(r"/(!)/", "^^$1", &argument); + argument = Preg::replace(php_regex!(r#"/(["^&|<>()%])/"#), "^$1", &argument); + argument = Preg::replace(php_regex!(r"/(!)/"), "^^$1", &argument); } argument diff --git a/crates/shirabe/src/util/remote_filesystem.rs b/crates/shirabe/src/util/remote_filesystem.rs index df47be20..9eaf8229 100644 --- a/crates/shirabe/src/util/remote_filesystem.rs +++ b/crates/shirabe/src/util/remote_filesystem.rs @@ -20,7 +20,7 @@ use shirabe_php_shim::{ array_replace_recursive, base64_encode, explode, extension_loaded, file_get_contents, file_get_contents5, file_put_contents, filter_var_boolean, gethostbyname, http_clear_last_response_headers, http_get_last_response_headers, ini_get, json_decode, - parse_url, preg_quote, strpos, strtolower, strtr, substr, trim, zlib_decode, + parse_url, php_regex, preg_quote, strpos, strtolower, strtr, substr, trim, zlib_decode, }; /// Result of `RemoteFilesystem::get` — string content, `true` (for copy), or `false`. @@ -149,7 +149,7 @@ impl RemoteFilesystem { let mut value: Option<i64> = None; for header in headers { let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::is_match3("{^HTTP/\\S+ (\\d+)}i", header, Some(&mut m)) { + if Preg::is_match3(php_regex!("{^HTTP/\\S+ (\\d+)}i"), header, Some(&mut m)) { value = m .get(&CaptureKey::ByIndex(1)) .and_then(|s| s.parse().ok()) @@ -163,7 +163,7 @@ impl RemoteFilesystem { pub fn find_status_message(&self, headers: &[String]) -> Option<String> { let mut value: Option<String> = None; for header in headers { - if Preg::is_match("{^HTTP/\\S+ \\d+}i", header) { + if Preg::is_match(php_regex!("{^HTTP/\\S+ \\d+}i"), header) { value = Some(header.clone()); } } @@ -287,8 +287,10 @@ impl RemoteFilesystem { crate::io::DEBUG, ); - if (!Preg::is_match("{^http://(repo\\.)?packagist\\.org/p/}", &file_url) - || (strpos(&file_url, "$").is_none() && strpos(&file_url, "%24").is_none())) + if (!Preg::is_match( + php_regex!("{^http://(repo\\.)?packagist\\.org/p/}"), + &file_url, + ) || (strpos(&file_url, "$").is_none() && strpos(&file_url, "%24").is_none())) && !degraded_packagist { let _ = self.config.borrow_mut().prohibit_url_by_config( @@ -472,7 +474,10 @@ impl RemoteFilesystem { None, ) != ".zip") && content_type.is_some() - && Preg::is_match("{^text/html\\b}i", content_type.as_deref().unwrap_or("")); + && Preg::is_match( + php_regex!("{^text/html\\b}i"), + content_type.as_deref().unwrap_or(""), + ); if bitbucket_login_match { result = None; if retry_auth_failure { @@ -940,7 +945,7 @@ impl RemoteFilesystem { .to_string(); target_url = Some(Preg::replace( - &format!( + format!( "{{^(.+(?://|@){}(?::\\d+)?)(?:[/\\?].*)?$}}", preg_quote(&url_host, None) ), @@ -949,7 +954,7 @@ impl RemoteFilesystem { )); } else { target_url = Some(Preg::replace( - "{^(.+/)[^/?]*(?:\\?.*)?$}", + php_regex!("{^(.+/)[^/?]*(?:\\?.*)?$}"), &format!("\\1{}", location_header), &self.file_url, )); diff --git a/crates/shirabe/src/util/svn.rs b/crates/shirabe/src/util/svn.rs index 4c01a3ae..f761ac05 100644 --- a/crates/shirabe/src/util/svn.rs +++ b/crates/shirabe/src/util/svn.rs @@ -10,7 +10,7 @@ use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ LogicException, PHP_URL_HOST, PhpMixed, RuntimeException, empty, implode, parse_url, - parse_url_all, stripos, strpos, trim, + parse_url_all, php_regex, stripos, strpos, trim, }; use std::sync::Mutex; @@ -444,7 +444,11 @@ impl Svn { None, ) { let mut matches: IndexMap<CaptureKey, String> = IndexMap::new(); - if Preg::is_match3(r"{(\d+(?:\.\d+)+)}", &output, Some(&mut matches)) { + if Preg::is_match3( + php_regex!(r"{(\d+(?:\.\d+)+)}"), + &output, + Some(&mut matches), + ) { *cached = Some( matches .get(&CaptureKey::ByIndex(1)) diff --git a/crates/shirabe/src/util/tls_helper.rs b/crates/shirabe/src/util/tls_helper.rs index 6422be3e..5121bd06 100644 --- a/crates/shirabe/src/util/tls_helper.rs +++ b/crates/shirabe/src/util/tls_helper.rs @@ -3,7 +3,7 @@ use shirabe_external_packages::composer::ca_bundle::ca_bundle::CaBundle; use shirabe_external_packages::composer::pcre::Preg; use shirabe_php_shim::{ - PhpMixed, ltrim, preg_quote, str_replace, strtolower, substr, substr_count, + PhpMixed, ltrim, php_regex, preg_quote, str_replace, strtolower, substr, substr_count, }; /// Extracted certificate names. Mirrors PHP's `array{cn: string, san: string[]}`. @@ -81,7 +81,7 @@ impl TlsHelper { .and_then(|e| e.get("subjectAltName")) .and_then(|s| s.as_string()) { - let split = Preg::split("{\\s*,\\s*}", san); + let split = Preg::split(php_regex!("{\\s*,\\s*}"), san); subject_alt_names = split .into_iter() .filter_map(|name| { diff --git a/crates/shirabe/src/util/url.rs b/crates/shirabe/src/util/url.rs index b1f17fb1..77649308 100644 --- a/crates/shirabe/src/util/url.rs +++ b/crates/shirabe/src/util/url.rs @@ -4,7 +4,7 @@ use crate::config::Config; use crate::util::GitHub; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; -use shirabe_php_shim::{PHP_URL_HOST, PHP_URL_PORT, PhpMixed, in_array, parse_url}; +use shirabe_php_shim::{PHP_URL_HOST, PHP_URL_PORT, PhpMixed, in_array, parse_url, php_regex}; pub struct Url; @@ -18,7 +18,9 @@ impl Url { if host == "api.github.com" || host == "github.com" || host == "www.github.com" { let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::match3( - r"{^https?://(?:www\.)?github\.com/([^/]+)/([^/]+)/(zip|tar)ball/(.+)$}i", + php_regex!( + r"{^https?://(?:www\.)?github\.com/([^/]+)/([^/]+)/(zip|tar)ball/(.+)$}i" + ), &url, Some(&mut m), ) { @@ -30,7 +32,9 @@ impl Url { r#ref ); } else if Preg::match3( - r"{^https?://(?:www\.)?github\.com/([^/]+)/([^/]+)/archive/.+\.(zip|tar)(?:\.gz)?$}i", + php_regex!( + r"{^https?://(?:www\.)?github\.com/([^/]+)/([^/]+)/archive/.+\.(zip|tar)(?:\.gz)?$}i" + ), &url, Some(&mut m), ) { @@ -42,7 +46,9 @@ impl Url { r#ref ); } else if Preg::match3( - r"{^https?://api\.github\.com/repos/([^/]+)/([^/]+)/(zip|tar)ball(?:/.+)?$}i", + php_regex!( + r"{^https?://api\.github\.com/repos/([^/]+)/([^/]+)/(zip|tar)ball(?:/.+)?$}i" + ), &url, Some(&mut m), ) { @@ -57,7 +63,9 @@ impl Url { } else if host == "bitbucket.org" || host == "www.bitbucket.org" { let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::match3( - r"{^https?://(?:www\.)?bitbucket\.org/([^/]+)/([^/]+)/get/(.+)\.(zip|tar\.gz|tar\.bz2)$}i", + php_regex!( + r"{^https?://(?:www\.)?bitbucket\.org/([^/]+)/([^/]+)/get/(.+)\.(zip|tar\.gz|tar\.bz2)$}i" + ), &url, Some(&mut m), ) { @@ -72,7 +80,9 @@ impl Url { } else if host == "gitlab.com" || host == "www.gitlab.com" { let mut m: IndexMap<CaptureKey, String> = IndexMap::new(); if Preg::match3( - r"{^https?://(?:www\.)?gitlab\.com/api/v[34]/projects/([^/]+)/repository/archive\.(zip|tar\.gz|tar\.bz2|tar)\?sha=.+$}i", + 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), ) { @@ -89,7 +99,7 @@ impl Url { true, ) { url = Preg::replace( - r"{(/repos/[^/]+/[^/]+/(zip|tar)ball)(?:/.+)?$}i", + php_regex!(r"{(/repos/[^/]+/[^/]+/(zip|tar)ball)(?:/.+)?$}i"), &format!("$1/{}", r#ref), &url, ); @@ -99,7 +109,9 @@ impl Url { true, ) { url = Preg::replace( - r"{(/api/v[34]/projects/[^/]+/repository/archive\.(?:zip|tar\.gz|tar\.bz2|tar)\?sha=).+$}i", + php_regex!( + r"{(/api/v[34]/projects/[^/]+/repository/archive\.(?:zip|tar\.gz|tar\.bz2|tar)\?sha=).+$}i" + ), &format!("${{1}}{}", r#ref), &url, ); @@ -164,10 +176,10 @@ impl Url { pub fn sanitize(url: String) -> String { // GitHub repository rename result in redirect locations containing the access_token as GET parameter // e.g. https://api.github.com/repositories/9999999999?access_token=github_token - let url = Preg::replace(r"{([&?]access_token=)[^&]+}", "$1***", &url); + let url = Preg::replace(php_regex!(r"{([&?]access_token=)[^&]+}"), "$1***", &url); Preg::replace_callback( - r"{^(?P<prefix>[a-z0-9]+://)?(?P<user>[^:/\s@]+):(?P<password>[^@\s/]+)@}i", + php_regex!(r"{^(?P<prefix>[a-z0-9]+://)?(?P<user>[^:/\s@]+):(?P<password>[^@\s/]+)@}i"), |m| { let user = m .get(&CaptureKey::ByName("user".to_string())) |
