From 530d085d4f3e19f94ac3cf8f8ac3b17000214b2e Mon Sep 17 00:00:00 2001 From: nsfisis Date: Tue, 18 Aug 2026 01:57:02 +0900 Subject: refactor(pcre): inline Preg into its call sites and drop the crate Preg had shed everything it owned: after the last few rounds its methods were one-line forwards to the shim's preg_*(), differing only in a default argument or a wrapper the caller unwrapped anyway. The 460 call sites now name the shim function, and shirabe-pcre is gone from the workspace along with its LICENSE entry. The forwards expand as they read: isMatch becomes preg_match2(.., 0).is_some() (is_none() where PHP negates it), isMatch3 and match3 drop the .is_some(), matchAll counts through preg_match_all2(..).occurrence_count(), and replace4/replace5 spell out the limit and count arguments preg_replace2 takes. Callbacks are the one place the shapes differ: preg_replace_callback carries an error out of the callback, so the fourteen infallible closures wrap their result in Ok() and expect() it back. Config::process() is the fifteenth, and it drops the `error` cell it captured to smuggle a failure past a closure that could only return a String. The `?` in the closure now carries it, which is what the PHP does -- a throw from the callback leaves preg_replace_callback at the failing match rather than running the remaining replacements and reporting the last error. The module doc that explained why composer/pcre's exceptions and *StrictGroups() variants have no counterpart moves to the shim's preg module, where the functions it describes live. Co-Authored-By: Claude Opus 5 (1M context) --- crates/shirabe-class-map-generator/Cargo.toml | 1 - .../shirabe-class-map-generator/src/class_map.rs | 5 +- .../src/class_map_generator.rs | 29 ++-- .../src/php_file_cleaner.rs | 6 +- .../src/php_file_parser.rs | 10 +- crates/shirabe-pcre/Cargo.toml | 16 --- crates/shirabe-pcre/LICENSE | 19 --- crates/shirabe-pcre/src/lib.rs | 3 - crates/shirabe-pcre/src/preg.rs | 117 ---------------- crates/shirabe-php-shim/src/preg.rs | 15 +++ crates/shirabe-symfony-console/Cargo.toml | 1 - .../src/descriptor/json_descriptor.rs | 7 +- .../src/descriptor/markdown_descriptor.rs | 7 +- .../src/descriptor/text_descriptor.rs | 7 +- crates/shirabe-symfony-console/src/helper/table.rs | 9 +- crates/shirabe-symfony-finder/Cargo.toml | 1 - crates/shirabe-symfony-finder/src/finder.rs | 17 ++- crates/shirabe/Cargo.toml | 1 - crates/shirabe/src/advisory/auditor.rs | 6 +- .../src/advisory/partial_security_advisory.rs | 5 +- crates/shirabe/src/autoload/autoload_generator.rs | 43 +++--- crates/shirabe/src/cache.rs | 27 ++-- crates/shirabe/src/command/archive_command.rs | 10 +- crates/shirabe/src/command/bump_command.rs | 7 +- crates/shirabe/src/command/completion_trait.rs | 12 +- crates/shirabe/src/command/config_command.rs | 38 +++--- .../shirabe/src/command/create_project_command.rs | 6 +- crates/shirabe/src/command/diagnose_command.rs | 14 +- crates/shirabe/src/command/fund_command.rs | 5 +- crates/shirabe/src/command/global_command.rs | 6 +- crates/shirabe/src/command/init_command.rs | 36 ++--- .../shirabe/src/command/package_discovery_trait.rs | 10 +- crates/shirabe/src/command/reinstall_command.rs | 5 +- crates/shirabe/src/command/remove_command.rs | 7 +- crates/shirabe/src/command/repository_command.rs | 7 +- crates/shirabe/src/command/script_alias_command.rs | 5 +- crates/shirabe/src/command/show_command.rs | 17 ++- crates/shirabe/src/command/update_command.rs | 13 +- crates/shirabe/src/composer.rs | 7 +- crates/shirabe/src/config.rs | 42 +++--- .../shirabe/src/console/html_output_formatter.rs | 15 ++- .../src/dependency_resolver/lock_transaction.rs | 21 ++- .../src/dependency_resolver/pool_builder.rs | 9 +- crates/shirabe/src/dependency_resolver/problem.rs | 24 ++-- crates/shirabe/src/downloader/download_manager.rs | 7 +- crates/shirabe/src/downloader/fossil_downloader.rs | 7 +- crates/shirabe/src/downloader/git_downloader.rs | 47 ++++--- crates/shirabe/src/downloader/svn_downloader.rs | 27 ++-- crates/shirabe/src/downloader/zip_downloader.rs | 12 +- .../src/event_dispatcher/event_dispatcher.rs | 37 ++--- .../ignore_list_platform_requirement_filter.rs | 12 +- crates/shirabe/src/installer/binary_installer.rs | 11 +- crates/shirabe/src/installer/library_installer.rs | 5 +- .../src/installer/suggested_packages_reporter.rs | 5 +- crates/shirabe/src/io/base_io.rs | 5 +- crates/shirabe/src/io/buffer_io.rs | 16 +-- crates/shirabe/src/io/console_io.rs | 7 +- crates/shirabe/src/json/json_file.rs | 27 ++-- crates/shirabe/src/json/json_manipulator.rs | 64 ++++----- .../package/archiver/archivable_files_finder.rs | 5 +- .../src/package/archiver/archive_manager.rs | 9 +- .../src/package/archiver/base_exclude_filter.rs | 4 +- crates/shirabe/src/package/loader/array_loader.rs | 11 +- .../src/package/loader/root_package_loader.rs | 17 +-- .../src/package/loader/validating_array_loader.rs | 29 ++-- crates/shirabe/src/package/locker.rs | 8 +- crates/shirabe/src/package/package.rs | 29 ++-- .../shirabe/src/package/version/version_bumper.rs | 13 +- .../shirabe/src/package/version/version_guesser.rs | 45 ++++--- .../shirabe/src/package/version/version_parser.rs | 9 +- .../src/package/version/version_selector.rs | 7 +- crates/shirabe/src/platform/version.rs | 12 +- crates/shirabe/src/plugin/plugin_manager.rs | 14 +- .../src/question/strict_confirmation_question.rs | 7 +- crates/shirabe/src/repository/array_repository.rs | 11 +- .../shirabe/src/repository/composer_repository.rs | 29 ++-- crates/shirabe/src/repository/filter_repository.rs | 7 +- .../shirabe/src/repository/package_repository.rs | 5 +- crates/shirabe/src/repository/path_repository.rs | 7 +- .../shirabe/src/repository/platform_repository.rs | 150 +++++++++++++-------- .../shirabe/src/repository/repository_factory.rs | 7 +- .../shirabe/src/repository/vcs/forgejo_driver.rs | 6 +- crates/shirabe/src/repository/vcs/fossil_driver.rs | 17 ++- .../src/repository/vcs/git_bitbucket_driver.rs | 16 ++- crates/shirabe/src/repository/vcs/git_driver.rs | 36 +++-- crates/shirabe/src/repository/vcs/github_driver.rs | 30 +++-- crates/shirabe/src/repository/vcs/gitlab_driver.rs | 15 +-- crates/shirabe/src/repository/vcs/hg_driver.rs | 20 +-- .../shirabe/src/repository/vcs/perforce_driver.rs | 7 +- crates/shirabe/src/repository/vcs/svn_driver.rs | 23 ++-- crates/shirabe/src/repository/vcs/vcs_driver.rs | 9 +- crates/shirabe/src/repository/vcs_repository.rs | 14 +- crates/shirabe/src/self_update/versions.rs | 5 +- crates/shirabe/src/util/auth_helper.rs | 7 +- crates/shirabe/src/util/composer_mirror.rs | 13 +- crates/shirabe/src/util/config_validator.rs | 17 ++- crates/shirabe/src/util/filesystem.rs | 40 +++--- crates/shirabe/src/util/forgejo_url.rs | 5 +- crates/shirabe/src/util/git.rs | 84 +++++++----- crates/shirabe/src/util/github.rs | 17 ++- crates/shirabe/src/util/gitlab.rs | 5 +- crates/shirabe/src/util/hg.rs | 9 +- crates/shirabe/src/util/http/curl_downloader.rs | 15 ++- crates/shirabe/src/util/http/response.rs | 7 +- crates/shirabe/src/util/http_downloader.rs | 16 ++- crates/shirabe/src/util/perforce.rs | 7 +- crates/shirabe/src/util/platform.rs | 27 ++-- crates/shirabe/src/util/process_executor.rs | 48 ++++--- crates/shirabe/src/util/remote_filesystem.rs | 25 ++-- crates/shirabe/src/util/svn.rs | 7 +- crates/shirabe/src/util/url.rs | 42 +++--- crates/shirabe/tests/all_functional_test.rs | 15 ++- crates/shirabe/tests/common/io_mock.rs | 5 +- .../tests/dependency_resolver/pool_builder_test.rs | 5 +- .../dependency_resolver/pool_optimizer_test.rs | 5 +- crates/shirabe/tests/installer_test.rs | 11 +- .../archiver/archivable_files_finder_test.rs | 9 +- 117 files changed, 1024 insertions(+), 1007 deletions(-) delete mode 100644 crates/shirabe-pcre/Cargo.toml delete mode 100644 crates/shirabe-pcre/LICENSE delete mode 100644 crates/shirabe-pcre/src/lib.rs delete mode 100644 crates/shirabe-pcre/src/preg.rs (limited to 'crates') diff --git a/crates/shirabe-class-map-generator/Cargo.toml b/crates/shirabe-class-map-generator/Cargo.toml index 4d66ac00..73ad1901 100644 --- a/crates/shirabe-class-map-generator/Cargo.toml +++ b/crates/shirabe-class-map-generator/Cargo.toml @@ -8,7 +8,6 @@ repository.workspace = true license.workspace = true [dependencies] -shirabe-pcre.workspace = true shirabe-php-rpc.workspace = true shirabe-php-shim.workspace = true shirabe-symfony-finder.workspace = true diff --git a/crates/shirabe-class-map-generator/src/class_map.rs b/crates/shirabe-class-map-generator/src/class_map.rs index 4eb6ae48..982d8494 100644 --- a/crates/shirabe-class-map-generator/src/class_map.rs +++ b/crates/shirabe-class-map-generator/src/class_map.rs @@ -1,8 +1,7 @@ //! ref: composer/vendor/composer/class-map-generator/src/ClassMap.php use indexmap::IndexMap; -use shirabe_pcre::Preg; -use shirabe_php_shim::{OutOfBoundsException, rtrim, strpos, strtr}; +use shirabe_php_shim::{OutOfBoundsException, preg_match2, rtrim, strpos, strtr}; #[derive(Debug, Clone)] pub struct PsrViolationEntry { @@ -67,7 +66,7 @@ impl ClassMap { for (class, paths) in &self.ambiguous_classes { let paths: Vec = paths .iter() - .filter(|path| !Preg::is_match(duplicates_filter, &strtr(path, "\\", "/"))) + .filter(|path| preg_match2(duplicates_filter, &strtr(path, "\\", "/"), 0).is_none()) .cloned() .collect(); if !paths.is_empty() { diff --git a/crates/shirabe-class-map-generator/src/class_map_generator.rs b/crates/shirabe-class-map-generator/src/class_map_generator.rs index 0ee9d992..c4130cff 100644 --- a/crates/shirabe-class-map-generator/src/class_map_generator.rs +++ b/crates/shirabe-class-map-generator/src/class_map_generator.rs @@ -3,11 +3,11 @@ use crate::class_map::ClassMap; use crate::file_list::FileList; use crate::php_file_parser::PhpFileParser; -use shirabe_pcre::Preg; use shirabe_php_shim::{ InvalidArgumentException, LogicException, PATHINFO_EXTENSION, RuntimeException, explode, - getcwd, implode, is_dir, is_file, pathinfo, php_regex, preg_quote, realpath, str_replace, - stream_get_wrappers, strlen, strpos, strrpos, strtr, substr, + getcwd, implode, is_dir, is_file, pathinfo, php_regex, preg_match2, preg_quote, preg_replace, + preg_replace_callback, realpath, str_replace, stream_get_wrappers, strlen, strpos, strrpos, + strtr, substr, }; use shirabe_symfony_finder::Finder; use std::path::PathBuf; @@ -134,7 +134,8 @@ impl ClassMapGenerator { continue; } - let is_stream_wrapper_path = Preg::is_match(&self.stream_wrappers_regex, &file_path); + let is_stream_wrapper_path = + preg_match2(&self.stream_wrappers_regex, &file_path, 0).is_some(); if !Self::is_absolute_path(&file_path) && !is_stream_wrapper_path { file_path = format!("{}/{}", cwd, file_path); file_path = Self::normalize_path(&file_path); @@ -146,7 +147,7 @@ impl ClassMapGenerator { // optional leading group `(^|[^:])` that is re-emitted in the replacement. Slash runs // are always separated by path-segment characters, so consuming the single preceding // char never prevents an adjacent run from matching. - file_path = Preg::replace(php_regex!(r"{(^|[^:])[\\/]{2,}}"), "${1}/", &file_path); + file_path = preg_replace(php_regex!(r"{(^|[^:])[\\/]{2,}}"), "${1}/", &file_path); } if file_path.is_empty() { @@ -182,11 +183,11 @@ impl ClassMapGenerator { // check the realpath of the file against the excluded paths as the path might be a symlink and the excluded path is realpath'd so symlink are resolved if let Some(ref excluded) = excluded { - if Preg::is_match(excluded, &strtr(&real_path, "\\", "/")) { + if preg_match2(excluded, &strtr(&real_path, "\\", "/"), 0).is_some() { continue; } // check non-realpath of file for directories symlink in project dir - if Preg::is_match(excluded, &strtr(&file_path, "\\", "/")) { + if preg_match2(excluded, &strtr(&file_path, "\\", "/"), 0).is_some() { continue; } } @@ -297,12 +298,12 @@ impl ClassMapGenerator { None => cwd_str, }; let cwd = Self::normalize_path(&cwd); - let short_path = Preg::replace( + let short_path = preg_replace( format!("{{^{}}}", preg_quote(&cwd, None)), ".", &Self::normalize_path(file_path), ); - let short_base_path = Preg::replace( + let short_base_path = preg_replace( format!("{{^{}}}", preg_quote(&cwd, None)), ".", &Self::normalize_path(base_path), @@ -347,9 +348,10 @@ impl ClassMapGenerator { } // extract a prefix being a protocol://, protocol:, protocol://drive: or simply drive: - if let Some(r#match) = Preg::is_match3( + if let Some(r#match) = preg_match2( php_regex!(r"{^( [0-9a-z]{2,}+: (?: // (?: [a-z]: )? )? | [a-z]: )}ix"), &path, + 0, ) { prefix = r#match.get(1).unwrap_or_default().to_string(); path = substr(&path, strlen(&prefix), None); @@ -372,11 +374,12 @@ impl ClassMapGenerator { } // ensure c: is normalized to C: - let prefix = Preg::replace_callback( + let prefix = preg_replace_callback( php_regex!(r"{(?:^|://)[a-z]:$}i"), - |m| m.get(0).unwrap_or_default().to_string().to_uppercase(), + |m| Ok(m.get(0).unwrap_or_default().to_string().to_uppercase()), &prefix, - ); + ) + .expect("the replacement callback cannot fail"); format!("{}{}{}", prefix, absolute, parts.join("/")) } diff --git a/crates/shirabe-class-map-generator/src/php_file_cleaner.rs b/crates/shirabe-class-map-generator/src/php_file_cleaner.rs index 18b051c9..78cee261 100644 --- a/crates/shirabe-class-map-generator/src/php_file_cleaner.rs +++ b/crates/shirabe-class-map-generator/src/php_file_cleaner.rs @@ -1,7 +1,7 @@ //! ref: composer/vendor/composer/class-map-generator/src/PhpFileCleaner.php use indexmap::IndexMap; -use shirabe_pcre::{Preg, PregMatches}; +use shirabe_php_shim::{PregMatches, preg_match2}; use std::sync::Mutex; #[derive(Debug, Clone)] @@ -147,7 +147,7 @@ impl PhpFileCleaner { if end <= self.len && self.contents[self.index..end] == entry.name { let offset = if self.index > 0 { self.index - 1 } else { 0 }; if let Some(r#match) = - Preg::is_match4(&entry.pattern, &self.contents, offset) + preg_match2(&entry.pattern, &self.contents, offset) { return clean + r#match.get(0).unwrap_or(""); } @@ -283,6 +283,6 @@ impl PhpFileCleaner { } fn r#match(&self, regex: &str) -> Option> { - Preg::is_match4(regex, &self.contents, self.index) + preg_match2(regex, &self.contents, self.index) } } diff --git a/crates/shirabe-class-map-generator/src/php_file_parser.rs b/crates/shirabe-class-map-generator/src/php_file_parser.rs index e05f4f1a..0ed78c7f 100644 --- a/crates/shirabe-class-map-generator/src/php_file_parser.rs +++ b/crates/shirabe-class-map-generator/src/php_file_parser.rs @@ -1,10 +1,10 @@ //! ref: composer/vendor/composer/class-map-generator/src/PhpFileParser.php use crate::php_file_cleaner::PhpFileCleaner; -use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ - PHP_EOL, RuntimeException, file_exists, file_get_contents, function_exists, is_file, - is_readable, ltrim, php_strip_whitespace, str_replace_array, strrpos, substr, trim, + CaptureKey, PHP_EOL, RuntimeException, file_exists, file_get_contents, function_exists, + is_file, is_readable, ltrim, php_strip_whitespace, preg_match_all2, str_replace_array, strrpos, + substr, trim, }; use std::sync::OnceLock; @@ -58,7 +58,7 @@ impl PhpFileParser { // return early if there is no chance of matching anything in this file let pattern = format!("{{\\b(?:class|interface|trait{})\\s}}i", extra_types); - let max_matches = Preg::match_all(&pattern, &contents); + let max_matches = preg_match_all2(&pattern, &contents).occurrence_count(); if max_matches == 0 { return Ok(vec![]); } @@ -84,7 +84,7 @@ impl PhpFileParser { }}ix", et = extra_types ); - let matches = Preg::match_all2(&pattern2, &contents); + let matches = preg_match_all2(&pattern2, &contents); let mut classes = vec![]; let mut namespace = String::new(); diff --git a/crates/shirabe-pcre/Cargo.toml b/crates/shirabe-pcre/Cargo.toml deleted file mode 100644 index 4c884440..00000000 --- a/crates/shirabe-pcre/Cargo.toml +++ /dev/null @@ -1,16 +0,0 @@ -[package] -name = "shirabe-pcre" -version.workspace = true -edition.workspace = true -rust-version.workspace = true -description = "A Rust port of composer/pcre" -repository.workspace = true -license.workspace = true - -[dependencies] -shirabe-php-shim.workspace = true -indexmap.workspace = true -regex.workspace = true - -[lints] -workspace = true diff --git a/crates/shirabe-pcre/LICENSE b/crates/shirabe-pcre/LICENSE deleted file mode 100644 index c5a282ff..00000000 --- a/crates/shirabe-pcre/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (C) 2021 Composer - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/crates/shirabe-pcre/src/lib.rs b/crates/shirabe-pcre/src/lib.rs deleted file mode 100644 index 20c37d02..00000000 --- a/crates/shirabe-pcre/src/lib.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub mod preg; - -pub use preg::*; diff --git a/crates/shirabe-pcre/src/preg.rs b/crates/shirabe-pcre/src/preg.rs deleted file mode 100644 index 753a4678..00000000 --- a/crates/shirabe-pcre/src/preg.rs +++ /dev/null @@ -1,117 +0,0 @@ -//! ref: composer/vendor/composer/pcre/src/Preg.php -//! -//! The following two exception classes are intentionally not ported: -//! -//! - `PcreException`: thrown when a `preg_*()` call returns false. Composer never feeds a pattern -//! that fails to compile at runtime, so such a failure would be a programming error rather than -//! a recoverable condition; they panic instead. -//! - `UnexpectedNullMatchException`: thrown by the `Preg::*StrictGroups()` variants when a capture -//! group did not participate. Those variants were dropped because Rust's `Option` already -//! distinguishes participating from non-participating groups. -//! -//! See docs/dev/regex-porting.md for more detailed regex porting rules. - -pub use shirabe_php_shim::{CaptureKey, PregMatches, PregMatchesAll, PregMatchesAllWithOffsets}; -use shirabe_php_shim::{ - PregPattern, preg_grep, preg_match_all_offset_capture, preg_match_all2, preg_match2, - preg_replace_callback, preg_replace2, -}; - -#[derive(Debug)] -pub struct Preg; - -impl Preg { - pub fn match3<'h>(pattern: impl PregPattern, subject: &'h str) -> Option> { - Self::match4(pattern, subject, 0) - } - - pub fn match4<'h>( - pattern: impl PregPattern, - subject: &'h str, - offset: usize, - ) -> Option> { - preg_match2(pattern, subject, offset) - } - - pub fn match_all(pattern: impl PregPattern, subject: &str) -> usize { - Self::match_all2(pattern, subject).occurrence_count() - } - - pub fn match_all2(pattern: impl PregPattern, subject: &str) -> PregMatchesAll { - preg_match_all2(pattern, subject) - } - - fn match_all_with_offsets5( - pattern: impl PregPattern, - subject: &str, - ) -> PregMatchesAllWithOffsets { - preg_match_all_offset_capture(pattern, subject) - } - - pub fn replace(pattern: impl PregPattern, replacement: &str, subject: &str) -> String { - preg_replace2(pattern, replacement, subject, -1, None) - } - - pub fn replace4( - pattern: impl PregPattern, - replacement: &str, - subject: &str, - limit: i64, - ) -> String { - preg_replace2(pattern, replacement, subject, limit, None) - } - - pub fn replace5( - pattern: impl PregPattern, - replacement: &str, - subject: &str, - limit: i64, - count: &mut usize, - ) -> String { - preg_replace2(pattern, replacement, subject, limit, Some(count)) - } - - pub fn replace_callback<'h, F: FnMut(&PregMatches<'h>) -> String>( - pattern: impl PregPattern, - mut replacement: F, - subject: &'h str, - ) -> String { - let adapter = |matches: &PregMatches<'h>| Ok(replacement(matches)); - - preg_replace_callback(pattern, adapter, subject).expect("$replacement cannot fail") - } - - pub fn grep>( - pattern: impl PregPattern, - array: impl IntoIterator, - ) -> impl Iterator { - preg_grep(pattern, array) - } - - pub fn is_match(pattern: impl PregPattern, subject: &str) -> bool { - Self::match4(pattern, subject, 0).is_some() - } - - pub fn is_match3<'h>(pattern: impl PregPattern, subject: &'h str) -> Option> { - Self::match4(pattern, subject, 0) - } - - pub fn is_match4<'h>( - pattern: impl PregPattern, - subject: &'h str, - offset: usize, - ) -> Option> { - Self::match4(pattern, subject, offset) - } - - pub fn is_match_all(pattern: impl PregPattern, subject: &str) -> PregMatchesAll { - Self::match_all2(pattern, subject) - } - - pub fn is_match_all_with_offsets3( - pattern: impl PregPattern, - subject: &str, - ) -> PregMatchesAllWithOffsets { - Self::match_all_with_offsets5(pattern, subject) - } -} diff --git a/crates/shirabe-php-shim/src/preg.rs b/crates/shirabe-php-shim/src/preg.rs index 1e3e9726..202510e9 100644 --- a/crates/shirabe-php-shim/src/preg.rs +++ b/crates/shirabe-php-shim/src/preg.rs @@ -1,3 +1,18 @@ +//! PHP's `preg_*` functions. Composer reaches PCRE through the `Composer\Pcre\Preg` wrapper; its +//! call sites are ported straight onto these functions. `Preg`'s `*StrictGroups()` variants have no +//! counterpart here because `Option` already tells a non-participating capture group from an empty +//! one, and a pattern that fails to compile panics instead of raising `PcreException`: Composer +//! never assembles a pattern that PCRE rejects, so such a failure is a programming error. +//! +//! This module's functions do not mirror the PHP signatures for two reasons. +//! +//! * Typing: the shape of the `$matches` out parameter of `preg_*()` functions depends on the +//! `PREG_*` flags, which is hard to represent in a type-safe way. +//! * Performance: pattern matching is performed in Composer's hot loops such as dependency +//! resolution. Allocating a PHP-compatible `$matches` array is expensive. +//! +//! See docs/dev/regex-porting.md for the regex porting rules. + use indexmap::IndexMap; use std::sync::{Arc, LazyLock, Mutex}; diff --git a/crates/shirabe-symfony-console/Cargo.toml b/crates/shirabe-symfony-console/Cargo.toml index 43768b50..06f6fe5b 100644 --- a/crates/shirabe-symfony-console/Cargo.toml +++ b/crates/shirabe-symfony-console/Cargo.toml @@ -8,7 +8,6 @@ repository.workspace = true license.workspace = true [dependencies] -shirabe-pcre.workspace = true shirabe-php-shim.workspace = true shirabe-symfony-process.workspace = true shirabe-symfony-string.workspace = true diff --git a/crates/shirabe-symfony-console/src/descriptor/json_descriptor.rs b/crates/shirabe-symfony-console/src/descriptor/json_descriptor.rs index a195dc01..53941663 100644 --- a/crates/shirabe-symfony-console/src/descriptor/json_descriptor.rs +++ b/crates/shirabe-symfony-console/src/descriptor/json_descriptor.rs @@ -10,8 +10,7 @@ use crate::input::InputDefinition; use crate::input::InputOption; use crate::output::OutputInterface; use indexmap::IndexMap; -use shirabe_pcre::preg::Preg; -use shirabe_php_shim::{PhpMixed, php_regex}; +use shirabe_php_shim::{PhpMixed, php_regex, preg_replace}; /// JSON descriptor. /// @@ -160,7 +159,7 @@ impl JsonDescriptor { data.insert("is_array".to_string(), PhpMixed::Bool(argument.is_array())); data.insert( "description".to_string(), - PhpMixed::String(Preg::replace( + PhpMixed::String(preg_replace( php_regex!("/\\s*[\\r\\n]\\s*/"), " ", argument.get_description(), @@ -221,7 +220,7 @@ impl JsonDescriptor { data.insert("is_multiple".to_string(), PhpMixed::Bool(option.is_array())); data.insert( "description".to_string(), - PhpMixed::String(Preg::replace( + PhpMixed::String(preg_replace( php_regex!("/\\s*[\\r\\n]\\s*/"), " ", option.get_description(), diff --git a/crates/shirabe-symfony-console/src/descriptor/markdown_descriptor.rs b/crates/shirabe-symfony-console/src/descriptor/markdown_descriptor.rs index 8c814bb5..d6285468 100644 --- a/crates/shirabe-symfony-console/src/descriptor/markdown_descriptor.rs +++ b/crates/shirabe-symfony-console/src/descriptor/markdown_descriptor.rs @@ -11,8 +11,7 @@ use crate::input::InputDefinition; use crate::input::InputOption; use crate::output::OutputInterface; use indexmap::IndexMap; -use shirabe_pcre::preg::Preg; -use shirabe_php_shim::PhpMixed; +use shirabe_php_shim::{PhpMixed, preg_replace}; /// Markdown descriptor. /// @@ -55,7 +54,7 @@ impl MarkdownDescriptor { if !argument.get_description().is_empty() { format!( "{}\n\n", - Preg::replace("/\\s*[\\r\\n]\\s*/", "\n", argument.get_description()) + preg_replace("/\\s*[\\r\\n]\\s*/", "\n", argument.get_description()) ) } else { String::new() @@ -93,7 +92,7 @@ impl MarkdownDescriptor { if !option.get_description().is_empty() { format!( "{}\n\n", - Preg::replace("/\\s*[\\r\\n]\\s*/", "\n", option.get_description()) + preg_replace("/\\s*[\\r\\n]\\s*/", "\n", option.get_description()) ) } else { String::new() diff --git a/crates/shirabe-symfony-console/src/descriptor/text_descriptor.rs b/crates/shirabe-symfony-console/src/descriptor/text_descriptor.rs index 0308415f..8783ef5e 100644 --- a/crates/shirabe-symfony-console/src/descriptor/text_descriptor.rs +++ b/crates/shirabe-symfony-console/src/descriptor/text_descriptor.rs @@ -12,8 +12,7 @@ use crate::input::InputDefinition; use crate::input::InputOption; use crate::output::OutputInterface; use indexmap::IndexMap; -use shirabe_pcre::preg::Preg; -use shirabe_php_shim::PhpMixed; +use shirabe_php_shim::{PhpMixed, preg_replace}; /// Text descriptor. /// @@ -63,7 +62,7 @@ impl TextDescriptor { argument.get_name(), shirabe_php_shim::str_repeat(" ", spacing_width as usize), // + 4 = 2 spaces before , 2 spaces after - Preg::replace( + preg_replace( "/\\s*[\\r\\n]\\s*/", &format!( "\n{}", @@ -131,7 +130,7 @@ impl TextDescriptor { synopsis, shirabe_php_shim::str_repeat(" ", spacing_width as usize), // + 4 = 2 spaces before , 2 spaces after - Preg::replace( + preg_replace( "/\\s*[\\r\\n]\\s*/", &format!( "\n{}", diff --git a/crates/shirabe-symfony-console/src/helper/table.rs b/crates/shirabe-symfony-console/src/helper/table.rs index 06743dbf..acfcbfef 100644 --- a/crates/shirabe-symfony-console/src/helper/table.rs +++ b/crates/shirabe-symfony-console/src/helper/table.rs @@ -8,8 +8,7 @@ use crate::helper::{ }; use crate::output::OutputInterface; use indexmap::IndexMap; -use shirabe_pcre::preg::Preg; -use shirabe_php_shim::{PhpMixed, php_regex}; +use shirabe_php_shim::{PhpMixed, php_regex, preg_match2}; /// A single cell within a table row. /// @@ -656,10 +655,12 @@ impl Table { let mut cell_format = cell_format; let mut pad_type = style.get_pad_type(); if cell.is_table_cell() && cell.style().is_some() { - let is_not_styled_by_tag = !Preg::is_match( + let is_not_styled_by_tag = preg_match2( php_regex!("/^<(\\w+|(\\w+=[\\w,]+;?)*)>.+<\\/(\\w+|(\\w+=\\w+;?)*)?>$/"), &cell_str, - ); + 0, + ) + .is_none(); if is_not_styled_by_tag { let cell_style = cell.style().unwrap(); match cell_style.get_cell_format() { diff --git a/crates/shirabe-symfony-finder/Cargo.toml b/crates/shirabe-symfony-finder/Cargo.toml index 0823bfaf..6dd01987 100644 --- a/crates/shirabe-symfony-finder/Cargo.toml +++ b/crates/shirabe-symfony-finder/Cargo.toml @@ -8,7 +8,6 @@ repository.workspace = true license.workspace = true [dependencies] -shirabe-pcre.workspace = true shirabe-php-shim.workspace = true anyhow.workspace = true chrono.workspace = true diff --git a/crates/shirabe-symfony-finder/src/finder.rs b/crates/shirabe-symfony-finder/src/finder.rs index f25b144e..5befed2d 100644 --- a/crates/shirabe-symfony-finder/src/finder.rs +++ b/crates/shirabe-symfony-finder/src/finder.rs @@ -9,8 +9,7 @@ use crate::glob::Glob; use chrono::{NaiveDate, NaiveDateTime}; use indexmap::IndexSet; -use shirabe_pcre::Preg; -use shirabe_php_shim::{file_exists, glob, is_dir, php_regex, preg_quote, rtrim}; +use shirabe_php_shim::{file_exists, glob, is_dir, php_regex, preg_match2, preg_quote, rtrim}; use std::path::{Path, PathBuf}; use std::time::UNIX_EPOCH; @@ -311,7 +310,7 @@ impl Finder { let dir = rtrim(dir, Some("/")); - if Preg::is_match(php_regex!("#^(ssh2\\.)?s?ftp://#"), &dir) { + if preg_match2(php_regex!("#^(ssh2\\.)?s?ftp://#"), &dir, 0).is_some() { format!("{dir}/") } else { dir @@ -592,7 +591,7 @@ fn exclude_accept( }; let path = path.replace('\\', "/"); - return !Preg::is_match(pattern, &path); + return preg_match2(pattern, &path, 0).is_none(); } true @@ -619,14 +618,14 @@ fn to_regex_path(pattern: &str) -> String { /// `MultiplePcreFilterIterator::isAccepted`. fn is_accepted(string: &str, match_regexps: &[String], nomatch_regexps: &[String]) -> bool { for regex in nomatch_regexps { - if Preg::is_match(regex, string) { + if preg_match2(regex, string, 0).is_some() { return false; } } if !match_regexps.is_empty() { for regex in match_regexps { - if Preg::is_match(regex, string) { + if preg_match2(regex, string, 0).is_some() { return true; } } @@ -643,7 +642,7 @@ fn is_regex(str: &str) -> bool { let available_modifiers = "imsxuADUn"; let pattern = format!("/^(.{{3,}}?)[{available_modifiers}]*$/"); - if let Some(matches) = Preg::is_match3(&pattern, str) { + if let Some(matches) = preg_match2(&pattern, str, 0) { let group = matches.get(1).unwrap_or_default().to_string(); let bytes = group.as_bytes(); let start = bytes @@ -656,7 +655,7 @@ fn is_regex(str: &str) -> bool { .unwrap_or_default(); if start == end { - return !Preg::is_match(php_regex!("/[*?[:alnum:] \\\\]/"), &start); + return preg_match2(php_regex!("/[*?[:alnum:] \\\\]/"), &start, 0).is_none(); } for (open, close) in [("{", "}"), ("(", ")"), ("[", "]"), ("<", ">")] { @@ -684,7 +683,7 @@ fn comparator_test(operator: &str, test: i64, target: i64) -> bool { /// `DateComparator::__construct`, returning `(operator, target unix timestamp)`. fn parse_date_comparator(test: &str) -> (String, i64) { let pattern = "#^\\s*(==|!=|[<>]=?|after|since|before|until)?\\s*(.+?)\\s*$#i"; - let Some(matches) = Preg::is_match3(pattern, test) else { + let Some(matches) = preg_match2(pattern, test, 0) else { panic!("Don't understand \"{test}\" as a date test."); }; diff --git a/crates/shirabe/Cargo.toml b/crates/shirabe/Cargo.toml index 0790d937..fb58f859 100644 --- a/crates/shirabe/Cargo.toml +++ b/crates/shirabe/Cargo.toml @@ -11,7 +11,6 @@ license.workspace = true shirabe-ca-bundle.workspace = true shirabe-class-map-generator.workspace = true shirabe-metadata-minifier.workspace = true -shirabe-pcre.workspace = true shirabe-php-rpc.workspace = true shirabe-php-shim.workspace = true shirabe-seld-json-lint.workspace = true diff --git a/crates/shirabe/src/advisory/auditor.rs b/crates/shirabe/src/advisory/auditor.rs index c85871fc..563da5b3 100644 --- a/crates/shirabe/src/advisory/auditor.rs +++ b/crates/shirabe/src/advisory/auditor.rs @@ -12,10 +12,9 @@ use crate::package::base_package; use crate::repository::RepositorySet; use crate::util::PackageInfo; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::{ DATE_ATOM, InvalidArgumentException, PhpMixed, array_all, array_any, array_key_exists, - array_keys, array_reduce, get_class, + array_keys, array_reduce, get_class, preg_match2, }; use shirabe_symfony_console::formatter::OutputFormatter; use shirabe_symfony_console::helper::Cell; @@ -290,7 +289,8 @@ impl Auditor { continue; }; if pkg.is_abandoned() - && (filter.is_none() || !Preg::is_match(filter.as_ref().unwrap(), &pkg.get_name())) + && (filter.is_none() + || preg_match2(filter.as_ref().unwrap(), &pkg.get_name(), 0).is_none()) { result.push(pkg); } diff --git a/crates/shirabe/src/advisory/partial_security_advisory.rs b/crates/shirabe/src/advisory/partial_security_advisory.rs index 677425ba..086d921d 100644 --- a/crates/shirabe/src/advisory/partial_security_advisory.rs +++ b/crates/shirabe/src/advisory/partial_security_advisory.rs @@ -5,8 +5,7 @@ use crate::advisory::SecurityAdvisory; use crate::package::version::VersionParser; use chrono::{DateTime, Utc}; use indexmap::IndexMap; -use shirabe_pcre::Preg; -use shirabe_php_shim::{PhpMixed, php_regex}; +use shirabe_php_shim::{PhpMixed, php_regex, preg_replace}; use shirabe_semver::constraint::AnyConstraint; use shirabe_semver::constraint::SimpleConstraint; @@ -37,7 +36,7 @@ impl PartialSecurityAdvisory { let constraint: AnyConstraint = match parser.parse_constraints(affected_versions_str) { Ok(c) => c, Err(_) => { - let affected_version = Preg::replace( + let affected_version = preg_replace( php_regex!(r"{(^[>=<^~]*[\d.]+).*}"), "$1", affected_versions_str, diff --git a/crates/shirabe/src/autoload/autoload_generator.rs b/crates/shirabe/src/autoload/autoload_generator.rs index 48f94263..05115123 100644 --- a/crates/shirabe/src/autoload/autoload_generator.rs +++ b/crates/shirabe/src/autoload/autoload_generator.rs @@ -23,13 +23,12 @@ use crate::util::Platform; use indexmap::IndexMap; use shirabe_class_map_generator::class_map::ClassMap; use shirabe_class_map_generator::class_map_generator::ClassMapGenerator; -use shirabe_pcre::{Preg, PregMatches}; use shirabe_php_shim::{ - InvalidArgumentException, PhpMixed, array_keys, array_map, array_merge_map, + InvalidArgumentException, PhpMixed, PregMatches, 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, php_regex, preg_quote, - random_bytes, realpath, str_replace, strlen, strpos, strtr, substr, substr_count, trim, unlink, - var_export, + file_exists, file_get_contents, hash, implode, is_array, ksort, ltrim, php_regex, preg_match2, + preg_quote, preg_replace, preg_replace_callback, random_bytes, realpath, str_replace, strlen, + strpos, strtr, substr, substr_count, trim, unlink, var_export, }; use shirabe_semver::constraint::Bound; use shirabe_symfony_console::formatter::OutputFormatter; @@ -559,9 +558,11 @@ return array( { let content = file_get_contents(format!("{}/autoload.php", vendor_path)).unwrap_or_default(); - if let Some(matches) = - Preg::match3(php_regex!("{ComposerAutoloaderInit([^:\\s]+)::}"), &content) - { + if let Some(matches) = preg_match2( + php_regex!("{ComposerAutoloaderInit([^:\\s]+)::}"), + &content, + 0, + ) { suffix = matches.get(1).map(str::to_string); } } @@ -745,7 +746,7 @@ return array( let mut new_excluded: Vec = vec![]; 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( + let pattern_processed = preg_replace( php_regex!( "{^(([^.+*?\\[^\\]$(){}=!<>|:\\\\#-]+|\\\\[.+*?\\[^\\]$(){}=!<>|:#-])*).*}" ), @@ -1127,7 +1128,7 @@ return array( } } - if Preg::is_match(php_regex!("{\\.phar([\\\\/]|$)}"), &path) { + if preg_match2(php_regex!("{\\.phar([\\\\/]|$)}"), &path, 0).is_some() { base_dir = format!("'phar://' . {}", base_dir); } @@ -1152,7 +1153,8 @@ return array( let package = &item.0; let links = array_merge_map(package.get_replaces(), package.get_provides()); for (_k, link) in &links { - if let Some(matches) = Preg::match3(php_regex!("{^ext-(.+)$}iD"), link.get_target()) + if let Some(matches) = + preg_match2(php_regex!("{^ext-(.+)$}iD"), link.get_target(), 0) && let Some(ext) = matches.get(1).map(str::to_string) { extension_providers @@ -1196,7 +1198,7 @@ return array( if check_platform.as_bool() == Some(true) && let Some(matches) = - Preg::match3(php_regex!("{^ext-(.+)$}iD"), link.get_target()) + preg_match2(php_regex!("{^ext-(.+)$}iD"), link.get_target(), 0) { let ext_key = matches.get(1).unwrap_or_default().to_string(); // skip extension checks if they have a valid provider/replacer @@ -1770,10 +1772,10 @@ class ComposerStaticInit{} m }); let value = shirabe_php_shim::ltrim( - &Preg::replace(php_regex!("/^ */m"), " $0$0", &value), + &preg_replace(php_regex!("/^ */m"), " $0$0", &value), None, ); - let value = Preg::replace(php_regex!("/ +$/m"), "", &value); + let value = preg_replace(php_regex!("/ +$/m"), "", &value); file.push_str(&format!( " public static ${} = {};\n\n", @@ -1898,7 +1900,7 @@ class ComposerStaticInit{} .collect::>() .join("[\\\\/]"); path_str = ltrim( - &Preg::replace( + &preg_replace( format!("{{^{}}}", target_dir), "", <rim(&path_str, Some("\\/")), @@ -1917,7 +1919,7 @@ class ComposerStaticInit{} if r#type == "exclude-from-classmap" { // first escape user input - let p = Preg::replace( + let p = preg_replace( php_regex!("{/+}"), "/", &preg_quote(&trim(&strtr(&path_str, "\\", "/"), Some("/")), None), @@ -1934,17 +1936,18 @@ class ComposerStaticInit{} // add support for up-level relative paths let updir_cell: std::cell::RefCell> = std::cell::RefCell::new(None); - let p = Preg::replace_callback( + let p = preg_replace_callback( php_regex!("{^((?:(?:\\\\\\.){1,2}+/)+)}"), - |matches: &PregMatches| -> String { + |matches: &PregMatches| -> anyhow::Result { // undo preg_quote for the matched string *updir_cell.borrow_mut() = Some(str_replace("\\.", ".", matches.get(1).unwrap_or(""))); - String::new() + Ok(String::new()) }, &p, - ); + ) + .expect("the replacement callback cannot fail"); let updir: Option = updir_cell.into_inner(); let install_path_for_resolve = if install_path.is_empty() { strtr(&Platform::get_cwd(false).unwrap_or_default(), "\\", "/") diff --git a/crates/shirabe/src/cache.rs b/crates/shirabe/src/cache.rs index 47f3219c..80085ff9 100644 --- a/crates/shirabe/src/cache.rs +++ b/crates/shirabe/src/cache.rs @@ -6,11 +6,11 @@ use crate::util::Filesystem; use crate::util::Platform; use crate::util::Silencer; use chrono::Utc; -use shirabe_pcre::Preg; use shirabe_php_shim::{ ErrorException, bin2hex, clearstatcache, date_format_to_strftime, dirname, disk_free_space, file_exists, file_get_contents, file_put_contents, filemtime, function_exists, hash_file, - is_dir, is_writable, mkdir, php_regex, random_bytes, random_int, rename, time, unlink, + is_dir, is_writable, mkdir, php_regex, preg_match2, preg_replace, random_bytes, random_int, + rename, time, unlink, }; use shirabe_symfony_finder::Finder; use std::sync::Mutex; @@ -94,10 +94,12 @@ impl Cache { } pub fn is_usable(path: &str) -> bool { - !Preg::is_match( + preg_match2( php_regex!(r"{(^|[\\\\/])(\$null|nul|NUL|/dev/null)([\\\\/]|$)}"), path, + 0, ) + .is_none() } pub fn is_enabled(&mut self) -> bool { @@ -127,7 +129,7 @@ impl Cache { pub fn read(&mut self, file: &str) -> Option { 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( @@ -147,7 +149,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), @@ -186,11 +188,12 @@ impl Cache { true, crate::io::DEBUG, ); - if let Some(m) = Preg::match3( + if let Some(m) = preg_match2( php_regex!( r"{^file_put_contents\(\): Only ([0-9]+) of ([0-9]+) bytes written}" ), e.get_message(), + 0, ) { // Remove partial file. unlink(&temp_file_name); @@ -226,7 +229,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() @@ -255,7 +258,7 @@ impl Cache { /// Copy a file out of the cache pub fn copy_to(&mut self, file: &str, target: &str) -> anyhow::Result { 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(|| { @@ -315,7 +318,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 @@ -344,7 +347,7 @@ impl Cache { pub fn get_age(&mut self, file: &str) -> Option { 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 +464,7 @@ impl Cache { pub fn sha1(&mut self, file: &str) -> Option { 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); @@ -473,7 +476,7 @@ impl Cache { pub fn sha256(&mut self, file: &str) -> Option { 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 31d25b3b..f2f26702 100644 --- a/crates/shirabe/src/command/archive_command.rs +++ b/crates/shirabe/src/command/archive_command.rs @@ -26,8 +26,7 @@ use crate::util::Platform; use crate::util::ProcessExecutor; use crate::util::r#loop::Loop; use indexmap::IndexMap; -use shirabe_pcre::Preg; -use shirabe_php_shim::{LogicException, get_debug_type, impl_php_class, php_regex}; +use shirabe_php_shim::{LogicException, get_debug_type, impl_php_class, php_regex, preg_match2}; use shirabe_symfony_console::command::Command; use shirabe_symfony_console::input::InputInterface; use shirabe_symfony_console::output::OutputInterface; @@ -229,8 +228,11 @@ impl ArchiveCommand { } if let Some(version_str) = &version - && let Some(matches) = - Preg::match3(php_regex!(r"{@(stable|RC|beta|alpha|dev)$}i"), version_str) + && let Some(matches) = preg_match2( + php_regex!(r"{@(stable|RC|beta|alpha|dev)$}i"), + version_str, + 0, + ) { let m1 = matches.get(1).unwrap_or_default().to_string(); let m0 = matches.get(0).unwrap_or_default().to_string(); diff --git a/crates/shirabe/src/command/bump_command.rs b/crates/shirabe/src/command/bump_command.rs index 87109d20..db4888c7 100644 --- a/crates/shirabe/src/command/bump_command.rs +++ b/crates/shirabe/src/command/bump_command.rs @@ -16,10 +16,9 @@ use crate::package::version::VersionBumper; use crate::repository::PlatformRepository; use crate::util::Filesystem; use crate::util::Silencer; -use shirabe_pcre::Preg; use shirabe_php_shim::{ PhpMixed, file_get_contents, file_put_contents, impl_php_class, is_writable, php_regex, - strtolower, + preg_match2, preg_replace, strtolower, }; use shirabe_symfony_console::command::Command; use shirabe_symfony_console::input::InputInterface; @@ -177,7 +176,7 @@ impl BumpCommand { let packages_filter = if !packages_filter.is_empty() { let packages_filter: Vec = packages_filter .iter() - .map(|constraint| Preg::replace(php_regex!(r"{[:= ].+}"), "", constraint)) + .map(|constraint| preg_replace(php_regex!(r"{[:= ].+}"), "", constraint)) .collect(); let unique_lower: Vec = packages_filter .iter() @@ -187,7 +186,7 @@ impl BumpCommand { .collect(); let pattern = base_package::package_names_to_regexp(&unique_lower, "{^(?:%s)$}iD"); for (key, reqs) in tasks.iter_mut() { - reqs.retain(|pkg_name, _| Preg::is_match(&pattern, pkg_name)); + reqs.retain(|pkg_name, _| preg_match2(&pattern, pkg_name, 0).is_some()); } packages_filter } else { diff --git a/crates/shirabe/src/command/completion_trait.rs b/crates/shirabe/src/command/completion_trait.rs index 491c5d07..ce0aef58 100644 --- a/crates/shirabe/src/command/completion_trait.rs +++ b/crates/shirabe/src/command/completion_trait.rs @@ -11,8 +11,7 @@ use crate::repository::RepositoryInterfaceHandle; use crate::repository::RootPackageRepository; use crate::repository::repository_interface::{SEARCH_NAME, SEARCH_VENDOR, SearchResult}; use indexmap::IndexMap; -use shirabe_pcre::Preg; -use shirabe_php_shim::{PhpMixed, php_regex, preg_quote}; +use shirabe_php_shim::{PhpMixed, php_regex, preg_match2, preg_quote}; /// Adds completion to arguments and options. /// @@ -257,10 +256,13 @@ pub trait CompletionTrait: BaseCommand { /// platform packages from the ones available on the currently-running PHP fn suggest_available_package_incl_platform(&self) -> SuggestedValues { SuggestedValues::Closure(Box::new(|this, input, suggestions| { - let matches = if Preg::is_match( + let matches = if preg_match2( php_regex!(r"{^(ext|lib|php)(-|$)|^com}"), &input.get_completion_value(), - ) { + 0, + ) + .is_some() + { this.suggest_platform_package() .call(this, input, suggestions)? } else { @@ -295,7 +297,7 @@ pub trait CompletionTrait: BaseCommand { let mut names: Vec = vec![]; for package in repos.get_packages()? { let name = package.get_name(); - if Preg::is_match(pattern.clone(), &name) { + if preg_match2(pattern.clone(), &name, 0).is_some() { names.push(name); } } diff --git a/crates/shirabe/src/command/config_command.rs b/crates/shirabe/src/command/config_command.rs index 8f0cbc51..7bf091a1 100644 --- a/crates/shirabe/src/command/config_command.rs +++ b/crates/shirabe/src/command/config_command.rs @@ -18,12 +18,12 @@ use crate::util::Filesystem; use crate::util::Platform; use crate::util::Silencer; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::{ InvalidArgumentException, PhpMixed, RuntimeException, array_is_list, array_merge, escapeshellcmd, exec, explode, file_exists, impl_php_class, implode, in_array_loose, in_array_strict, is_array, is_bool, is_dir, is_numeric, is_object, is_string, json_encode, - php_regex, str_replace, strpos, strtolower, system, touch, var_export, + php_regex, preg_match2, preg_replace, str_replace, strpos, strtolower, system, touch, + var_export, }; use shirabe_semver::VersionParser; use shirabe_symfony_console::command::Command; @@ -206,7 +206,7 @@ impl ConfigCommand { || (key == "repositories" && k.is_none())) { let mut new_k = k.clone().unwrap_or_default(); - new_k.push_str(&Preg::replace( + new_k.push_str(&preg_replace( php_regex!("{^config\\.}"), "", &format!("{}.", key), @@ -269,13 +269,13 @@ impl ConfigCommand { } else { k.clone().unwrap() }; - let id = Preg::replace(php_regex!("{\\..*$}"), "", &id_source); - let id = Preg::replace( + let id = preg_replace(php_regex!("{\\..*$}"), "", &id_source); + let id = preg_replace( php_regex!("{[^a-z0-9]}i"), "-", &strtolower(&shirabe_php_shim::trim(&id, Some(" \t\n\r\0\u{0B}"))), ); - let id = Preg::replace(php_regex!("{-+}"), "-", &id); + let id = preg_replace(php_regex!("{-+}"), "-", &id); format!("https://getcomposer.org/doc/06-config.md#{}", id) }; if is_string(&raw_val) @@ -701,9 +701,10 @@ impl Command for ConfigCommand { let mut source = config.borrow_mut().get_source_of_value(&setting_key); let mut value: PhpMixed; - if let Some(matches) = Preg::is_match3( + if let Some(matches) = preg_match2( php_regex!("/^repos?(?:itories)?(?:\\.(.+))?/"), &setting_key, + 0, ) { if matches.get(1).is_none() { value = data @@ -925,7 +926,7 @@ impl Command for ConfigCommand { } // handle preferred-install per-package config if let Some(matches) = - Preg::is_match3(php_regex!("/^preferred-install\\.(.+)/"), &setting_key) + preg_match2(php_regex!("/^preferred-install\\.(.+)/"), &setting_key, 0) { if input.borrow().get_option("unset")?.as_bool() == Some(true) { self.config_source @@ -959,9 +960,10 @@ impl Command for ConfigCommand { } // handle allow-plugins config setting elements true or false to add/remove - if let Some(matches) = Preg::is_match3( + if let Some(matches) = preg_match2( php_regex!("{^allow-plugins\\.([a-zA-Z0-9/*-]+)}"), &setting_key, + 0, ) { if input.borrow().get_option("unset")?.as_bool() == Some(true) { self.config_source @@ -1028,7 +1030,7 @@ impl Command for ConfigCommand { // handle repositories if let Some(matches) = - Preg::is_match3(php_regex!("/^repos?(?:itories)?\\.(.+)/"), &setting_key) + preg_match2(php_regex!("/^repos?(?:itories)?\\.(.+)/"), &setting_key, 0) { if input.borrow().get_option("unset")?.as_bool() == Some(true) { self.config_source @@ -1097,7 +1099,7 @@ impl Command for ConfigCommand { } // handle extra - if let Some(matches) = Preg::is_match3(php_regex!("/^extra\\.(.+)/"), &setting_key) { + if let Some(matches) = preg_match2(php_regex!("/^extra\\.(.+)/"), &setting_key, 0) { if input.borrow().get_option("unset")?.as_bool() == Some(true) { self.config_source .borrow_mut() @@ -1169,7 +1171,7 @@ impl Command for ConfigCommand { } // handle suggest - if let Some(matches) = Preg::is_match3(php_regex!("/^suggest\\.(.+)/"), &setting_key) { + if let Some(matches) = preg_match2(php_regex!("/^suggest\\.(.+)/"), &setting_key, 0) { if input.borrow().get_option("unset")?.as_bool() == Some(true) { self.config_source .borrow_mut() @@ -1203,7 +1205,7 @@ impl Command for ConfigCommand { } // handle platform - if let Some(matches) = Preg::is_match3(php_regex!("/^platform\\.(.+)/"), &setting_key) { + if let Some(matches) = preg_match2(php_regex!("/^platform\\.(.+)/"), &setting_key, 0) { if input.borrow().get_option("unset")?.as_bool() == Some(true) { self.config_source .borrow_mut() @@ -1320,11 +1322,12 @@ impl Command for ConfigCommand { } // handle auth - if let Some(matches) = Preg::is_match3( + if let Some(matches) = preg_match2( php_regex!( "/^(bitbucket-oauth|github-oauth|gitlab-oauth|gitlab-token|http-basic|custom-headers|bearer|forgejo-token)\\.(.+)/" ), &setting_key, + 0, ) { if input.borrow().get_option("unset")?.as_bool() == Some(true) { self.auth_config_source @@ -1452,7 +1455,7 @@ impl Command for ConfigCommand { } // Check if the header is in correct "Name: Value" format - if Preg::is_match3(php_regex!("/^[^:]+:\\s*.+$/"), header).is_none() { + if preg_match2(php_regex!("/^[^:]+:\\s*.+$/"), header, 0).is_none() { return Err(RuntimeException::new(format!( "Header \"{}\" is not in \"Header-Name: Header-Value\" format", header @@ -1500,7 +1503,7 @@ impl Command for ConfigCommand { } // handle script - if let Some(matches) = Preg::is_match3(php_regex!("/^scripts\\.(.+)/"), &setting_key) { + if let Some(matches) = preg_match2(php_regex!("/^scripts\\.(.+)/"), &setting_key, 0) { if input.borrow().get_option("unset")?.as_bool() == Some(true) { self.config_source .borrow_mut() @@ -1739,9 +1742,10 @@ fn build_unique_config_values() -> IndexMap ( Box::new(|val| { PhpMixed::Bool( - Preg::is_match3( + preg_match2( php_regex!("/^\\s*([0-9.]+)\\s*(?:([kmg])(?:i?b)?)?\\s*$/i"), val.as_string().unwrap_or(""), + 0, ) .is_some(), ) diff --git a/crates/shirabe/src/command/create_project_command.rs b/crates/shirabe/src/command/create_project_command.rs index f1b899d3..fbdcfabb 100644 --- a/crates/shirabe/src/command/create_project_command.rs +++ b/crates/shirabe/src/command/create_project_command.rs @@ -37,12 +37,11 @@ use crate::util::Filesystem; use crate::util::Platform; use crate::util::ProcessExecutor; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ InvalidArgumentException, PhpMixed, RuntimeException, UnexpectedValueException, array_pop, chdir, explode_with_limit, file_exists, getcwd, impl_php_class, implode, is_dir, is_file, - mkdir, realpath, rtrim, strtolower, unlink, + mkdir, preg_match2, realpath, rtrim, strtolower, unlink, }; use shirabe_symfony_console::command::Command; use shirabe_symfony_console::input::InputInterface; @@ -526,7 +525,7 @@ impl CreateProjectCommand { if package_version.is_none() { stability = Some("stable".to_string()); } else { - let matched = Preg::is_match3( + let matched = preg_match2( format!( "{{^[^,\\s]*?@({})$}}i", implode( @@ -538,6 +537,7 @@ impl CreateProjectCommand { ) ), package_version.as_deref().unwrap_or(""), + 0, ); if let Some(matched) = matched { stability = Some(matched.get(1).unwrap_or_default().to_string()); diff --git a/crates/shirabe/src/command/diagnose_command.rs b/crates/shirabe/src/command/diagnose_command.rs index 820b026c..f7f84575 100644 --- a/crates/shirabe/src/command/diagnose_command.rs +++ b/crates/shirabe/src/command/diagnose_command.rs @@ -33,13 +33,12 @@ use crate::util::ProcessExecutor; use crate::util::http::ProxyManager; use crate::util::http::RequestProxy; use indexmap::IndexMap; -use shirabe_pcre::Preg; -use shirabe_php_shim::Catch as _; +use shirabe_php_shim::PhpClass as _; use shirabe_php_shim::{ - AnyThrowable, CmpOp, InvalidArgumentException, PHP_EOL, PhpClass as _, PhpMixed, - RuntimeException, disk_free_space, file_exists, filter_var_boolean, hash, impl_php_class, - implode, is_array, is_string, php_regex, rtrim, str_replace, strpos, strstr, strstr3, - strtolower, trim, version_compare, + AnyThrowable, Catch as _, CmpOp, InvalidArgumentException, PHP_EOL, PhpMixed, RuntimeException, + disk_free_space, file_exists, filter_var_boolean, hash, impl_php_class, implode, is_array, + is_string, php_regex, preg_match2, rtrim, str_replace, strpos, strstr, strstr3, strtolower, + trim, version_compare, }; use shirabe_symfony_console::command::Command; use shirabe_symfony_console::input::InputInterface; @@ -862,9 +861,10 @@ impl DiagnoseCommand { warnings.insert("zlib".to_string(), PhpMixed::Bool(true)); } - if let Some(phpinfo_match) = Preg::is_match3( + if let Some(phpinfo_match) = preg_match2( php_regex!("{Configure Command(?: *| *=> *)(.*?)(?:|$)}m"), &diagnostics.phpinfo_general, + 0, ) { let configure = phpinfo_match.get(1).unwrap_or_default().to_string(); let configure = configure.as_str(); diff --git a/crates/shirabe/src/command/fund_command.rs b/crates/shirabe/src/command/fund_command.rs index f900bce0..ea077ef5 100644 --- a/crates/shirabe/src/command/fund_command.rs +++ b/crates/shirabe/src/command/fund_command.rs @@ -10,8 +10,7 @@ use crate::package::base_package::{self}; use crate::repository::CompositeRepository; use crate::repository::RepositoryInterface; use indexmap::IndexMap; -use shirabe_pcre::Preg; -use shirabe_php_shim::{PhpMixed, impl_php_class, php_regex}; +use shirabe_php_shim::{PhpMixed, impl_php_class, php_regex, preg_match2}; use shirabe_semver::constraint::AnyConstraint; use shirabe_semver::constraint::MatchAllConstraint; use shirabe_symfony_console::command::Command; @@ -64,7 +63,7 @@ impl FundCommand { .unwrap_or(""); if r#type == "github" && let Some(matches) = - Preg::is_match3(php_regex!(r"{^https://github.com/([^/]+)$}"), &url) + preg_match2(php_regex!(r"{^https://github.com/([^/]+)$}"), &url, 0) && let Some(sponsor) = matches.get(1).map(str::to_string) { 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 21375141..f31d29c4 100644 --- a/crates/shirabe/src/command/global_command.rs +++ b/crates/shirabe/src/command/global_command.rs @@ -8,9 +8,8 @@ use crate::console::input::InputArgument; use crate::factory::Factory; use crate::util::Filesystem; use crate::util::Platform; -use shirabe_pcre::Preg; use shirabe_php_shim::{ - LogicException, RuntimeException, chdir, impl_php_class, php_regex, preg_split, + LogicException, RuntimeException, chdir, impl_php_class, php_regex, preg_replace2, preg_split, }; use shirabe_symfony_console::command::Command; use shirabe_symfony_console::completion::CompletionInput; @@ -105,11 +104,12 @@ impl GlobalCommand { )); } - let new_input_str = Preg::replace4( + let new_input_str = preg_replace2( php_regex!(r"{\bg(?:l(?:o(?:b(?:a(?:l)?)?)?)?)?\b}"), "", &Self::input_to_string(&*input.borrow())?, 1, + None, ); self.reset_composer()?; diff --git a/crates/shirabe/src/command/init_command.rs b/crates/shirabe/src/command/init_command.rs index 030a8657..96bdc58d 100644 --- a/crates/shirabe/src/command/init_command.rs +++ b/crates/shirabe/src/command/init_command.rs @@ -19,14 +19,13 @@ use crate::util::Filesystem; use crate::util::ProcessExecutor; use crate::util::Silencer; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ - FILE_IGNORE_NEW_LINES, InvalidArgumentException, PHP_EOL, PHP_SERVER, PhpMixed, + CaptureKey, 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, impl_php_class, implode, - is_dir, is_string, php_regex, preg_quote, realpath, str_replace, strpos, strtolower, trim, - ucwords, + is_dir, is_string, php_regex, preg_match_all2, preg_match2, preg_quote, preg_replace, realpath, + str_replace, strpos, strtolower, trim, ucwords, }; use shirabe_spdx_licenses::SpdxLicenses; use shirabe_symfony_console::command::Command; @@ -90,9 +89,10 @@ impl InitCommand { &self, author: &str, ) -> anyhow::Result>> { - if let Some(m) = Preg::is_match3( + if let Some(m) = preg_match2( php_regex!(r#"/^(?P[- .,\p{L}\p{N}\p{Mn}\'’\"()]+)(?:\s+<(?P.+?)>)?$/u"#), author, + 0, ) { let email = m.name("email").map(str::to_string); if let Some(ref email) = email @@ -143,7 +143,7 @@ impl InitCommand { let namespace: Vec = array_map( |part: &String| { - let part = Preg::replace(php_regex!(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) }, @@ -168,7 +168,7 @@ impl InitCommand { ) == 0 { *self.git_config.borrow_mut() = Some(IndexMap::new()); - let m = Preg::is_match_all(php_regex!(r"{^([^=]+)=(.*)$}m"), &output); + let m = preg_match_all2(php_regex!(r"{^([^=]+)=(.*)$}m"), &output); if m.occurrence_count() > 0 { let keys: Vec> = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default(); @@ -210,7 +210,7 @@ impl InitCommand { let lines = file(ignore_file, FILE_IGNORE_NEW_LINES).unwrap_or_default(); for line in &lines { - if Preg::is_match(&pattern, line) { + if preg_match2(&pattern, line, 0).is_some() { return true; } } @@ -329,15 +329,15 @@ impl InitCommand { } fn sanitize_package_name_component(&self, name: &str) -> String { - let name = Preg::replace( + let name = preg_replace( 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(php_regex!(r"{^[_.-]+|[_.-]+$|[^a-z0-9_.-]}u"), "", &name); + let name = preg_replace(php_regex!(r"{^[_.-]+|[_.-]+$|[^a-z0-9_.-]}u"), "", &name); - Preg::replace(php_regex!(r"{([_.-]){2,}}u"), "$1", &name) + preg_replace(php_regex!(r"{([_.-]){2,}}u"), "$1", &name) } fn get_default_package_name(&self) -> String { @@ -498,13 +498,15 @@ impl Command for InitCommand { }); if options.contains_key("name") - && !Preg::is_match( + && preg_match2( 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()) .unwrap_or(""), + 0, ) + .is_none() { return Err(InvalidArgumentException::new(format!( "The package name {} is invalid, it should be lowercase and have a vendor name, a forward slash, and a package name, matching: [a-z0-9_.-]+/[a-z0-9_.-]+", @@ -908,10 +910,13 @@ impl Command for InitCommand { return Ok(PhpMixed::String(name_for_validate.clone())); } - if !Preg::is_match( + if preg_match2( php_regex!(r"{^[a-z0-9]([_.-]?[a-z0-9]+)*\/[a-z0-9](([_.]|-{1,2})?[a-z0-9]+)*$}D"), value.as_string().unwrap_or(""), - ) { + 0, + ) + .is_none() + { return Err(InvalidArgumentException::new(format!( "The package name {} is invalid, it should be lowercase and have a vendor name, a forward slash, and a package name, matching: [a-z0-9_.-]+/[a-z0-9_.-]+", value.as_string().unwrap_or("") @@ -1221,7 +1226,8 @@ impl Command for InitCommand { value_str }; - if !Preg::is_match(php_regex!(r"{^[^/][A-Za-z0-9\-_/]+/$}"), &value_or_default) + if preg_match2(php_regex!(r"{^[^/][A-Za-z0-9\-_/]+/$}"), &value_or_default, 0) + .is_none() { return Err(InvalidArgumentException::new(format!( "The src folder name \"{}\" is invalid. Please add a relative path with tailing forward slash. [A-Za-z0-9_-/]+/", diff --git a/crates/shirabe/src/command/package_discovery_trait.rs b/crates/shirabe/src/command/package_discovery_trait.rs index d31b5894..a5b606a8 100644 --- a/crates/shirabe/src/command/package_discovery_trait.rs +++ b/crates/shirabe/src/command/package_discovery_trait.rs @@ -19,12 +19,11 @@ use crate::repository::RepositorySet; use crate::repository::{RepositoryInterface, SearchResult}; use crate::util::Filesystem; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ Exception, InvalidArgumentException, LogicException, PHP_EOL, PhpMixed, array_keys, array_slice, asort, explode, file_get_contents, implode, in_array_strict, is_array, is_file, - is_numeric, json_decode_assoc, levenshtein, php_regex, strlen, strpos, trim, + is_numeric, json_decode_assoc, levenshtein, php_regex, preg_match2, strlen, strpos, trim, }; use shirabe_symfony_console::input::InputInterface; use shirabe_symfony_console::output::OutputInterface; @@ -144,10 +143,12 @@ pub trait PackageDiscoveryTrait: BaseCommand { for mut requirement in requires_norm { if requirement.contains_key("version") - && Preg::is_match( + && preg_match2( php_regex!(r"{^\d+(\.\d+)?$}"), requirement.get("version").map(|s| s.as_str()).unwrap_or(""), + 0, ) + .is_some() { io.write_error3( &format!( @@ -330,9 +331,10 @@ pub trait PackageDiscoveryTrait: BaseCommand { } } - if let Some(m) = Preg::is_match3( + if let Some(m) = preg_match2( php_regex!(r"{^\s*(?P[\S/]+)(?:\s+(?P\S+))?\s*$}"), &selection, + 0, ) { if let Some(v) = m.name("version").map(str::to_string) { // parsing `acme/example ~2.3` diff --git a/crates/shirabe/src/command/reinstall_command.rs b/crates/shirabe/src/command/reinstall_command.rs index 9ef45fbf..05c277d5 100644 --- a/crates/shirabe/src/command/reinstall_command.rs +++ b/crates/shirabe/src/command/reinstall_command.rs @@ -15,8 +15,7 @@ use crate::plugin::CommandEvent; use crate::plugin::PluginEvents; use crate::script::ScriptEvents; use crate::util::Platform; -use shirabe_pcre::Preg; -use shirabe_php_shim::{InvalidArgumentException, impl_php_class}; +use shirabe_php_shim::{InvalidArgumentException, impl_php_class, preg_match2}; use shirabe_symfony_console::command::Command; use shirabe_symfony_console::input::InputInterface; use shirabe_symfony_console::output::OutputInterface; @@ -137,7 +136,7 @@ impl Command for ReinstallCommand { let pattern_regexp = base_package::package_name_to_regexp(pattern); let mut matched = false; for package in local_repo.get_canonical_packages()? { - if Preg::is_match(&pattern_regexp, &package.get_name()) { + if preg_match2(&pattern_regexp, &package.get_name(), 0).is_some() { matched = true; package_names_to_reinstall.push(package.get_name()); packages_to_reinstall.push(package); diff --git a/crates/shirabe/src/command/remove_command.rs b/crates/shirabe/src/command/remove_command.rs index bba0285f..7eb88f2b 100644 --- a/crates/shirabe/src/command/remove_command.rs +++ b/crates/shirabe/src/command/remove_command.rs @@ -17,8 +17,7 @@ use crate::json::JsonFile; use crate::package::base_package; use crate::repository::RepositoryInterface; use indexmap::IndexMap; -use shirabe_pcre::Preg; -use shirabe_php_shim::{PhpMixed, UnexpectedValueException, impl_php_class, strtolower}; +use shirabe_php_shim::{PhpMixed, UnexpectedValueException, impl_php_class, preg_grep, strtolower}; use shirabe_symfony_console::command::Command; use shirabe_symfony_console::exception::InvalidArgumentException; use shirabe_symfony_console::input::InputInterface; @@ -393,7 +392,7 @@ impl Command for RemoveCommand { .and_then(|v| v.as_array()) .map(|m| m.keys().cloned().collect()) .unwrap_or_default(); - let matches_in_type: Vec<&String> = Preg::grep( + let matches_in_type: Vec<&String> = preg_grep( base_package::package_name_to_regexp(package), type_keys.iter(), ) @@ -405,7 +404,7 @@ impl Command for RemoveCommand { .and_then(|v| v.as_array()) .map(|m| m.keys().cloned().collect()) .unwrap_or_default(); - let matches_in_alt_type: Vec<&String> = Preg::grep( + let matches_in_alt_type: Vec<&String> = preg_grep( base_package::package_name_to_regexp(package), alt_type_keys.iter(), ) diff --git a/crates/shirabe/src/command/repository_command.rs b/crates/shirabe/src/command/repository_command.rs index 4853d3d3..bbd1eace 100644 --- a/crates/shirabe/src/command/repository_command.rs +++ b/crates/shirabe/src/command/repository_command.rs @@ -10,10 +10,9 @@ use crate::console::input::InputOption; use crate::io::IOInterfaceImmutable; use crate::json::JsonFile; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::{ InvalidArgumentException, PhpMixed, RuntimeException, impl_php_class, parse_url, php_regex, - strtolower, + preg_match2, strtolower, }; use shirabe_symfony_console::command::Command; use shirabe_symfony_console::input::InputInterface; @@ -369,7 +368,9 @@ impl Command for RepositoryCommand { .into()); } let arg1_str = arg1.as_deref().unwrap(); - let repo_config: PhpMixed = if Preg::is_match(php_regex!(r"{^\s*\{}"), arg1_str) { + let repo_config: PhpMixed = if preg_match2(php_regex!(r"{^\s*\{}"), arg1_str, 0) + .is_some() + { 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 30d82779..713947f4 100644 --- a/crates/shirabe/src/command/script_alias_command.rs +++ b/crates/shirabe/src/command/script_alias_command.rs @@ -6,9 +6,9 @@ use crate::command::base_command::base_command_initialize; use crate::console::input::InputArgument; use crate::console::input::InputOption; use crate::util::Platform; -use shirabe_pcre::Preg; use shirabe_php_shim::{ InvalidArgumentException, LogicException, PhpMixed, impl_php_class, is_string, php_regex, + preg_replace2, }; use shirabe_symfony_console::command::Command; use shirabe_symfony_console::input::InputInterface; @@ -134,7 +134,8 @@ impl Command for ScriptAliasCommand { // TODO(symfony): 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(php_regex!(r"{^\S+ ?}"), "", &input_as_string, 1); + let script_alias_input = + preg_replace2(php_regex!(r"{^\S+ ?}"), "", &input_as_string, 1, None); 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 4be7873c..e8072ca8 100644 --- a/crates/shirabe/src/command/show_command.rs +++ b/crates/shirabe/src/command/show_command.rs @@ -36,11 +36,11 @@ use crate::repository::RepositoryUtils; use crate::repository::RootPackageRepository; use crate::util::PackageInfo; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::{ CmpOp, DATE_ATOM, InvalidArgumentException, LogicException, PhpMixed, UnexpectedValueException, array_search, date_format_to_strftime, date_local, extension_loaded, impl_php_class, - in_array_loose, in_array_strict, php_regex, preg_quote, realpath, strtolower, version_compare, + in_array_loose, in_array_strict, php_regex, preg_match2, preg_quote, preg_replace, realpath, + strtolower, version_compare, }; use shirabe_semver::Semver; use shirabe_semver::constraint::AnyConstraint; @@ -1373,9 +1373,10 @@ impl ShowCommand { if target_version.is_none() { if major_only - && let Some(groups) = Preg::is_match3( + && let Some(groups) = preg_match2( php_regex!(r"{^(?P(?:0\.)+)?(?P\d+)\.}"), &package.get_version(), + 0, ) { let zero_major = groups.name("zero_major").unwrap_or_default().to_string(); @@ -1398,7 +1399,7 @@ impl ShowCommand { if patch_only { let trimmed_version = - Preg::replace(php_regex!(r"{(\.0)+$}D"), "", &package.get_version()); + preg_replace(php_regex!(r"{(\.0)+$}D"), "", &package.get_version()); let parts_needed = if trimmed_version.starts_with('0') { 4 } else { @@ -2341,7 +2342,7 @@ impl Command for ShowCommand { } let matches_filter = match &package_filter_regex { None => true, - Some(r) => Preg::is_match(r, &p.get_name()), + Some(r) => preg_match2(r, &p.get_name(), 0).is_some(), }; if matches_filter { let matches_list = match &package_list_filter { @@ -2420,7 +2421,8 @@ impl Command for ShowCommand { if show_latest && *show_version { for package_or_name in type_packages.values() { if let PackageOrName::Pkg(package) = package_or_name - && !Preg::is_match(&ignored_packages_regex, &package.get_pretty_name()) + && preg_match2(&ignored_packages_regex, &package.get_pretty_name(), 0) + .is_none() { let latest = self.find_latest_package( package.clone(), @@ -2491,7 +2493,8 @@ impl Command for ShowCommand { package_is_up_to_date = package_is_up_to_date || (latest_package.is_none() && show_major_only); let package_is_ignored = - Preg::is_match(&ignored_packages_regex, &package.get_pretty_name()); + preg_match2(&ignored_packages_regex, &package.get_pretty_name(), 0) + .is_some(); if input.borrow().get_option("outdated")?.as_bool() == Some(true) && (package_is_up_to_date || package_is_ignored) { diff --git a/crates/shirabe/src/command/update_command.rs b/crates/shirabe/src/command/update_command.rs index e9f0e3ce..72d97315 100644 --- a/crates/shirabe/src/command/update_command.rs +++ b/crates/shirabe/src/command/update_command.rs @@ -27,10 +27,10 @@ use crate::repository::PlatformRepository; use crate::repository::RepositorySet; use crate::util::HttpDownloader; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::{ InvalidArgumentException, PhpMixed, RuntimeException, array_filter, array_intersect, - array_keys, array_merge_map, array_search_in_vec, impl_php_class, php_regex, strtolower, + array_keys, array_merge_map, array_search_in_vec, impl_php_class, php_regex, preg_match2, + preg_replace, strtolower, }; use shirabe_semver::Intervals; use shirabe_semver::constraint::MultiConstraint; @@ -115,7 +115,7 @@ impl UpdateCommand { let mut version_selector = self.create_version_selector(composer)?; for package in &installed_packages { if let Some(filter) = &filter - && !Preg::is_match(filter, &package.get_name()) + && preg_match2(filter, &package.get_name(), 0).is_none() { continue; } @@ -378,7 +378,7 @@ impl Command for UpdateCommand { if !packages.is_empty() { let allowlist_packages_with_requirements: Vec = array_filter(&packages, |pkg: &String| -> bool { - Preg::is_match(php_regex!(r"{\S+[ =:]\S+}"), pkg) + preg_match2(php_regex!(r"{\S+[ =:]\S+}"), pkg, 0).is_some() }); for (package, constraint) in self.format_requirements(allowlist_packages_with_requirements.clone())? @@ -388,8 +388,7 @@ 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(php_regex!(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; } @@ -460,7 +459,7 @@ impl Command for UpdateCommand { continue; } let version = package.get_version(); - let matches = Preg::is_match3(php_regex!(r"{^(\d+\.\d+\.\d+)}"), &version); + let matches = preg_match2(php_regex!(r"{^(\d+\.\d+\.\d+)}"), &version, 0); let Some(matches) = matches else { continue; }; diff --git a/crates/shirabe/src/composer.rs b/crates/shirabe/src/composer.rs index 1c6bbaed..6d3c6e26 100644 --- a/crates/shirabe/src/composer.rs +++ b/crates/shirabe/src/composer.rs @@ -11,8 +11,7 @@ use crate::package::{LockerInterface, RootPackageInterfaceHandle}; use crate::plugin::PluginManager; use crate::repository::RepositoryManagerInterface; use crate::util::r#loop::Loop; -use shirabe_pcre::Preg; -use shirabe_php_shim::php_regex; +use shirabe_php_shim::{php_regex, preg_match2}; /// The Composer version this port tracks. Kept as-is so `Composer::VERSION`, the `composer` /// platform package and the HTTP User-Agent keep reporting a value plugins and servers can @@ -43,7 +42,9 @@ pub fn get_version() -> String { if VERSION == "@package_version@" { return SOURCE_VERSION.to_string(); } - if !BRANCH_ALIAS_VERSION.is_empty() && Preg::is_match(php_regex!("{^[a-f0-9]{40}$}"), VERSION) { + if !BRANCH_ALIAS_VERSION.is_empty() + && preg_match2(php_regex!("{^[a-f0-9]{40}$}"), VERSION, 0).is_some() + { return format!("{}+{}", BRANCH_ALIAS_VERSION, VERSION); } VERSION.to_string() diff --git a/crates/shirabe/src/config.rs b/crates/shirabe/src/config.rs index 92b13fb8..1a14f67f 100644 --- a/crates/shirabe/src/config.rs +++ b/crates/shirabe/src/config.rs @@ -8,12 +8,11 @@ pub use json_config_source::*; use crate::io::io_interface; use indexmap::IndexMap; -use shirabe_pcre::{Preg, PregMatches}; use shirabe_php_shim::{ - E_USER_DEPRECATED, PhpMixed, RuntimeException, array_key_exists, array_merge, + E_USER_DEPRECATED, PhpMixed, PregMatches, RuntimeException, array_key_exists, array_merge, array_search_mixed, array_unique, empty, filter_var_url, implode, in_array_loose, - in_array_strict, intval, is_array, is_string, parse_url, php_regex, php_to_string, rtrim, - strtolower, strtoupper, strtr, substr, trigger_error, + in_array_strict, intval, is_array, is_string, parse_url, php_regex, php_to_string, preg_match2, + preg_replace_callback, rtrim, strtolower, strtoupper, strtr, substr, trigger_error, }; use crate::advisory::Auditor; @@ -482,10 +481,12 @@ impl Config { .unwrap_or("") .to_string(); if is_composer - && Preg::is_match( + && preg_match2( php_regex!(r"{^https?://(?:[a-z0-9-.]+\.)?packagist.org(/|$)}"), &repo_url, + 0, ) + .is_some() { self.disable_repo_by_name("packagist.org"); } @@ -647,9 +648,10 @@ impl Config { // numbers with kb/mb/gb support, without env var support "cache-files-maxsize" => { let raw = self.config.get(key).map(php_to_string).unwrap_or_default(); - let Some(matches) = Preg::is_match3( + let Some(matches) = preg_match2( php_regex!(r"/^\s*([0-9.]+)\s*(?:([kmg])(?:i?b)?)?\s*$/i"), &raw, + 0, ) else { return Err(RuntimeException::new(format!( "Could not parse the value of '{}': {}", @@ -956,24 +958,14 @@ impl Config { } let value_str = value.as_string().unwrap_or("").to_string(); - let mut error = None; - let result = Preg::replace_callback( + let result = preg_replace_callback( php_regex!(r"#\{\$(.+)\}#"), - |m: &PregMatches| -> String { + |m: &PregMatches| -> anyhow::Result { let key_match = m.get(1).unwrap_or_default().to_string(); - match self.get_with_flags(&key_match, flags) { - Ok(v) => php_to_string(&v), - Err(e) => { - error = Some(e); - String::new() - } - } + Ok(php_to_string(&self.get_with_flags(&key_match, flags)?)) }, &value_str, - ); - if let Some(e) = error { - return Err(e); - } + )?; Ok(PhpMixed::String(result)) } @@ -981,7 +973,13 @@ 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(php_regex!(r"{^(?:/|[a-z]:|[a-z0-9.]+://|\\\\\\\\)}i"), path) { + if preg_match2( + php_regex!(r"{^(?:/|[a-z]:|[a-z0-9.]+://|\\\\\\\\)}i"), + path, + 0, + ) + .is_some() + { return path.to_string(); } @@ -1023,7 +1021,7 @@ impl Config { repo_options: &IndexMap, ) -> 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(php_regex!(r"{^https?://}"), url) { + if !filter_var_url(url) && preg_match2(php_regex!(r"{^https?://}"), url, 0).is_none() { return Ok(()); } diff --git a/crates/shirabe/src/console/html_output_formatter.rs b/crates/shirabe/src/console/html_output_formatter.rs index 694f8de6..bcc7c045 100644 --- a/crates/shirabe/src/console/html_output_formatter.rs +++ b/crates/shirabe/src/console/html_output_formatter.rs @@ -1,7 +1,7 @@ //! ref: composer/src/Composer/Console/HtmlOutputFormatter.php use indexmap::IndexMap; -use shirabe_pcre::{Preg, PregMatches}; +use shirabe_php_shim::{PregMatches, preg_replace_callback}; use shirabe_symfony_console::formatter::OutputFormatter; use shirabe_symfony_console::formatter::OutputFormatterInterface; use shirabe_symfony_console::formatter::OutputFormatterStyleInterface; @@ -65,11 +65,14 @@ impl HtmlOutputFormatter { clear_escape_codes, clear_escape_codes ); - Ok(Some(Preg::replace_callback( - &pattern, - |matches| self.format_html(matches), - &formatted, - ))) + Ok(Some( + preg_replace_callback( + &pattern, + |matches| Ok(self.format_html(matches)), + &formatted, + ) + .expect("the replacement callback cannot fail"), + )) } fn format_html(&self, matches: &PregMatches) -> String { diff --git a/crates/shirabe/src/dependency_resolver/lock_transaction.rs b/crates/shirabe/src/dependency_resolver/lock_transaction.rs index a238f2d6..df9a737d 100644 --- a/crates/shirabe/src/dependency_resolver/lock_transaction.rs +++ b/crates/shirabe/src/dependency_resolver/lock_transaction.rs @@ -5,8 +5,7 @@ use crate::dependency_resolver::Pool; use crate::dependency_resolver::Transaction; use crate::package::PackageInterfaceHandle; use indexmap::IndexMap; -use shirabe_pcre::Preg; -use shirabe_php_shim::php_regex; +use shirabe_php_shim::{PregMatches, php_regex, preg_match2, preg_replace_callback}; #[derive(Debug)] pub struct LockTransaction { @@ -159,12 +158,9 @@ impl LockTransaction { if package.get_dist_url().is_some() && present_package.get_dist_reference().is_some() - && Preg::is_match( - php_regex!( - r"{^https?://(?:(?:www\.)?bitbucket\.org|(api\.)?github\.com|(?:www\.)?gitlab\.com)/}i" - ), - &package.get_dist_url().unwrap(), - ) + && preg_match2(php_regex!( + r"{^https?://(?:(?:www\.)?bitbucket\.org|(api\.)?github\.com|(?:www\.)?gitlab\.com)/}i" + ), &package.get_dist_url().unwrap(), 0).is_some() { // Regex pattern compatibility: // The `regex` crate has no look-around, so `(?<=/|sha=)[a-f0-9]{40}(?=/|$)` is @@ -174,14 +170,15 @@ impl LockTransaction { // 40-hex SHAs sharing a single `/` between them would not both match; harmless // here since a dist URL never carries more than one SHA reference. let dist_reference = present_package.get_dist_reference().unwrap(); - let new_dist_url = Preg::replace_callback( + let new_dist_url = preg_replace_callback( php_regex!(r"{(/|sha=)[a-f0-9]{40}(/|$)}i"), - |m: &shirabe_pcre::PregMatches| -> String { + |m: &PregMatches| -> anyhow::Result { let get = |i: usize| -> String { m.get(i).unwrap_or_default().to_string() }; - format!("{}{}{}", get(1), dist_reference, get(2)) + Ok(format!("{}{}{}", get(1), dist_reference, get(2))) }, &package.get_dist_url().unwrap(), - ); + ) + .expect("the replacement callback cannot fail"); present_package.set_dist_url(Some(new_dist_url)); } present_package.set_dist_mirrors(package.get_dist_mirrors()); diff --git a/crates/shirabe/src/dependency_resolver/pool_builder.rs b/crates/shirabe/src/dependency_resolver/pool_builder.rs index 9e2e18ea..8c5064c5 100644 --- a/crates/shirabe/src/dependency_resolver/pool_builder.rs +++ b/crates/shirabe/src/dependency_resolver/pool_builder.rs @@ -19,10 +19,9 @@ use crate::repository::RepositoryInterface; use crate::repository::RepositoryInterfaceHandle; use crate::repository::RootPackageRepository; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::{ CmpOp, LogicException, PhpMixed, array_flip_strings, array_map, in_array_strict, microtime, - number_format, round, strpos, + number_format, preg_match2, round, strpos, }; use shirabe_semver::CompilingMatcher; use shirabe_semver::Intervals; @@ -786,7 +785,7 @@ impl PoolBuilder { fn is_update_allowed(&self, package: PackageInterfaceHandle) -> bool { for pattern in &self.update_allow_list { let pattern_regexp = base_package::package_name_to_regexp(pattern); - if Preg::is_match3(&pattern_regexp, &package.get_name()).is_some() { + if preg_match2(&pattern_regexp, &package.get_name(), 0).is_some() { return true; } } @@ -813,13 +812,13 @@ impl PoolBuilder { .borrow_mut() .get_packages()? { - if Preg::is_match3(&pattern_regexp, &package.get_name()).is_some() { + if preg_match2(&pattern_regexp, &package.get_name(), 0).is_some() { continue 'outer; } } // update pattern matches a root require? => all good, probably a new package for (package_name, _constraint) in request.get_requires() { - if Preg::is_match3(&pattern_regexp, package_name).is_some() { + if preg_match2(&pattern_regexp, package_name, 0).is_some() { if PlatformRepository::is_platform_package(package_name) { matched_platform_package = true; continue; diff --git a/crates/shirabe/src/dependency_resolver/problem.rs b/crates/shirabe/src/dependency_resolver/problem.rs index c42caa35..867dc3fe 100644 --- a/crates/shirabe/src/dependency_resolver/problem.rs +++ b/crates/shirabe/src/dependency_resolver/problem.rs @@ -10,11 +10,10 @@ use crate::repository::LockArrayRepository; use crate::repository::PlatformRepository; use crate::repository::RepositorySet; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::{ CmpOp, LogicException, PhpMixed, extension_loaded, implode, loosely_compare, php_regex, - spl_object_hash, sprintf, str_replace, stripos, strpos, strtolower, substr, substr_count, - version_compare, + preg_match2, preg_replace, spl_object_hash, sprintf, str_replace, stripos, strpos, strtolower, + substr, substr_count, version_compare, }; use shirabe_semver::constraint::AnyConstraint; use shirabe_semver::constraint::MultiConstraint; @@ -224,11 +223,12 @@ impl Problem { rule_ref.get_reason(), rule::RULE_PACKAGE_REQUIRES | rule::RULE_PACKAGE_CONFLICT ) { - Preg::is_match3( + preg_match2( php_regex!( r"{^(?P\S+) (?P\S+) (?Prequires|conflicts)}" ), &message, + 0, ) } else { None @@ -237,7 +237,7 @@ impl Problem { let pkg_key = m.get(1).unwrap_or_default().to_string(); let m2 = m.get(2).unwrap_or_default().to_string(); message = str_replace("%", "%%", &message); - let template = Preg::replace(php_regex!(r"{^\S+ \S+ }"), "%s%s ", &message); + let template = preg_replace(php_regex!(r"{^\S+ \S+ }"), "%s%s ", &message); messages.push(template.clone()); let version_key = parser.normalize(&m2, Some("")).unwrap_or_default(); templates @@ -302,7 +302,7 @@ impl Problem { }; if versions_list.len() > 1 { // remove the s from requires/conflicts to correct grammar - let message_var = Preg::replace( + let message_var = preg_replace( php_regex!(r"{^(%s%s (?:require|conflict))s}"), "$1", message, @@ -557,9 +557,9 @@ impl Problem { if let Some(c) = constraint && c.is_constraint() && c.get_operator() == Some(CmpOp::Eq) - && Preg::is_match3(php_regex!(r"{^dev-.*#.*}"), &c.get_pretty_string()).is_some() + && preg_match2(php_regex!(r"{^dev-.*#.*}"), &c.get_pretty_string(), 0).is_some() { - let new_constraint = Preg::replace( + let new_constraint = preg_replace( php_regex!(r"{ +as +([^,\s|]+)$}"), "", &c.get_pretty_string(), @@ -991,8 +991,8 @@ impl Problem { )); } - if Preg::is_match3(php_regex!(r"{^[A-Za-z0-9_./-]+$}"), package_name).is_none() { - let illegal_chars = Preg::replace(php_regex!(r"{[A-Za-z0-9_./-]+}"), "", package_name); + if preg_match2(php_regex!(r"{^[A-Za-z0-9_./-]+$}"), package_name, 0).is_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), @@ -1203,7 +1203,7 @@ impl Problem { .or_default() .push(pretty.clone()); } else { - let key = Preg::replace(php_regex!(r"{^(\d+)\..*}"), "$1", version); + let key = preg_replace(php_regex!(r"{^(\d+)\..*}"), "$1", version); by_major.entry(key).or_default().push(pretty.clone()); } } @@ -1381,7 +1381,7 @@ impl Problem { && c.get_operator() == Some(CmpOp::Eq) && !c.get_version().starts_with("dev-") { - if Preg::is_match3(php_regex!(r"{^\d+(?:\.\d+)*$}"), &c.get_pretty_string()).is_none() { + if preg_match2(php_regex!(r"{^\d+(?:\.\d+)*$}"), &c.get_pretty_string(), 0).is_none() { return format!(" {} (exact version match)", c.get_pretty_string()); } diff --git a/crates/shirabe/src/downloader/download_manager.rs b/crates/shirabe/src/downloader/download_manager.rs index 15b009e6..f2360f9d 100644 --- a/crates/shirabe/src/downloader/download_manager.rs +++ b/crates/shirabe/src/downloader/download_manager.rs @@ -8,12 +8,11 @@ use crate::io::io_interface; use crate::package::PackageInterfaceHandle; use crate::util::Filesystem; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ InvalidArgumentException, LogicException, PhpMixed, RuntimeException, array_keys, - array_reverse, array_shift, dirname, implode, in_array_strict, preg_quote, rtrim, str_replace, - strtolower, usort, + array_reverse, array_shift, dirname, implode, in_array_strict, preg_match2, preg_quote, rtrim, + str_replace, strtolower, usort, }; /// Downloaders manager. @@ -431,7 +430,7 @@ impl DownloadManager { "{{^{}$}}i", str_replace("\\*", ".*", &preg_quote(pattern, None)), ); - if Preg::is_match(&pattern_regex, &package.get_name()) { + if preg_match2(&pattern_regex, &package.get_name(), 0).is_some() { if "dist" == preference || (!package.is_dev() && "auto" == preference) { return "dist".to_string(); } diff --git a/crates/shirabe/src/downloader/fossil_downloader.rs b/crates/shirabe/src/downloader/fossil_downloader.rs index cdc5f268..e7b3a20d 100644 --- a/crates/shirabe/src/downloader/fossil_downloader.rs +++ b/crates/shirabe/src/downloader/fossil_downloader.rs @@ -12,8 +12,9 @@ use crate::package::PackageInterfaceHandle; use crate::util::Filesystem; use crate::util::ProcessExecutor; use indexmap::IndexMap; -use shirabe_pcre::Preg; -use shirabe_php_shim::{PhpMixed, RuntimeException, impl_php_class, php_regex, preg_split}; +use shirabe_php_shim::{ + PhpMixed, RuntimeException, impl_php_class, php_regex, preg_match2, preg_split, +}; #[derive(Debug)] pub struct FossilDownloader { @@ -227,7 +228,7 @@ impl VcsDownloader for FossilDownloader { }; for line in lines { - if Preg::is_match(&match_pattern, &line) { + if preg_match2(&match_pattern, &line, 0).is_some() { break; } log.push_str(&line); diff --git a/crates/shirabe/src/downloader/git_downloader.rs b/crates/shirabe/src/downloader/git_downloader.rs index b816aa18..d3dea453 100644 --- a/crates/shirabe/src/downloader/git_downloader.rs +++ b/crates/shirabe/src/downloader/git_downloader.rs @@ -17,11 +17,10 @@ use crate::util::Platform; use crate::util::ProcessExecutor; use crate::util::Url; use indexmap::IndexMap; -use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ - CmpOp, PhpMixed, RuntimeException, array_map, basename, dirname, impl_php_class, implode, - in_array_strict, is_dir, php_regex, preg_quote, preg_split, realpath, rtrim, strlen, strpos, - substr, trim, version_compare, + CaptureKey, CmpOp, PhpMixed, RuntimeException, array_map, basename, dirname, impl_php_class, + implode, in_array_strict, is_dir, php_regex, preg_match_all2, preg_match2, preg_quote, + preg_replace, preg_split, realpath, rtrim, strlen, strpos, substr, trim, version_compare, }; #[derive(Debug)] @@ -95,13 +94,13 @@ impl GitDownloader { } let mut refs = trim(&output, None); - let Some(head_match) = Preg::is_match3(php_regex!(r"{^([a-f0-9]+) HEAD$}mi"), &refs) else { + let Some(head_match) = preg_match2(php_regex!(r"{^([a-f0-9]+) HEAD$}mi"), &refs, 0) else { // could not match the HEAD for some reason return Ok(None); }; let head_ref = head_match.get(1).unwrap_or_default().to_string(); - let branches_match = Preg::is_match_all( + let branches_match = preg_match_all2( format!("{{^{} refs/heads/(.+)$}}mi", preg_quote(&head_ref, None)), &refs, ); @@ -128,7 +127,7 @@ impl GitDownloader { // try to find matching branch names in remote repos for candidate in &candidate_branches { - let m = Preg::is_match_all( + let m = preg_match_all2( format!( "{{^[a-f0-9]+ refs/remotes/((?:[^/]+)/{})$}}mi", preg_quote(candidate, None) @@ -275,7 +274,7 @@ impl GitDownloader { // If the non-existent branch is actually the name of a file, the file // is checked out. - let mut branch = Preg::replace( + let mut branch = preg_replace( php_regex!(r"{(?:^dev-|(?:\.x)?-dev$)}i"), "", pretty_version, @@ -299,12 +298,14 @@ 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(php_regex!(r"{^[a-f0-9]{40}$}"), reference) + if preg_match2(php_regex!(r"{^[a-f0-9]{40}$}"), reference, 0).is_none() && branches.is_some() - && Preg::is_match( + && preg_match2( format!("{{^\\s+composer/{}$}}m", preg_quote(reference, None)), branches.as_deref().unwrap_or(""), + 0, ) + .is_some() { let mut command1: Vec = vec!["git".to_string(), "checkout".to_string()]; command1.extend(force.clone()); @@ -345,17 +346,21 @@ impl GitDownloader { } // try to checkout branch by name and then reset it so it's on the proper branch name - if Preg::is_match(php_regex!(r"{^[a-f0-9]{40}$}"), reference) { + if preg_match2(php_regex!(r"{^[a-f0-9]{40}$}"), reference, 0).is_some() { // add 'v' in front of the branch if it was stripped when generating the pretty name if branches.is_some() - && !Preg::is_match( + && preg_match2( format!("{{^\\s+composer/{}$}}m", preg_quote(&branch, None)), branches.as_deref().unwrap_or(""), + 0, ) - && Preg::is_match( + .is_none() + && preg_match2( format!("{{^\\s+composer/v{}$}}m", preg_quote(&branch, None)), branches.as_deref().unwrap_or(""), + 0, ) + .is_some() { branch = format!("v{}", branch); } @@ -500,12 +505,13 @@ impl GitDownloader { fn set_push_url(&self, path: &str, url: &str) { // set push url for github projects - if let Some(match_) = Preg::is_match3( + if let Some(match_) = preg_match2( format!( "{{^(?:https?|git)://{}/([^/]+)/([^/]+?)(?:\\.git)?$}}", GitUtil::get_github_domains_regex(&self.inner.config.borrow()) ), url, + 0, ) { let protocols = self.inner.config.borrow_mut().get("github-protocols"); let m1 = match_.get(1).unwrap_or_default().to_string(); @@ -640,7 +646,8 @@ impl GitDownloader { } fn get_short_hash(&self, reference: &str) -> String { - if !self.inner.io.is_verbose() && Preg::is_match(php_regex!(r"{^[0-9a-f]{40}$}"), reference) + if !self.inner.io.is_verbose() + && preg_match2(php_regex!(r"{^[0-9a-f]{40}$}"), reference, 0).is_some() { return substr(reference, 0, Some(10)); } @@ -769,7 +776,7 @@ impl VcsDownloader for GitDownloader { .get("cache-vcs-dir") .as_string() .unwrap_or(""), - Preg::replace(r"{[^a-z0-9.]}i", "-", &Url::sanitize(url.to_string())), + preg_replace(r"{[^a-z0-9.]}i", "-", &Url::sanitize(url.to_string())), ); let git_version = GitUtil::get_version(&self.inner.process); @@ -834,7 +841,7 @@ impl VcsDownloader for GitDownloader { .get("cache-vcs-dir") .as_string() .unwrap_or(""), - Preg::replace(r"{[^a-z0-9.]}i", "-", &Url::sanitize(url.to_string())), + preg_replace(r"{[^a-z0-9.]}i", "-", &Url::sanitize(url.to_string())), ); let r#ref = package.get_source_reference().unwrap_or_default(); @@ -994,7 +1001,7 @@ impl VcsDownloader for GitDownloader { .get("cache-vcs-dir") .as_string() .unwrap_or(""), - Preg::replace(r"{[^a-z0-9.]}i", "-", &Url::sanitize(url.to_string())), + preg_replace(r"{[^a-z0-9.]}i", "-", &Url::sanitize(url.to_string())), ); let r#ref = target.get_source_reference().unwrap_or_default(); @@ -1094,9 +1101,9 @@ impl VcsDownloader for GitDownloader { Some(&path), ) == 0 && let Some(origin_match) = - Preg::is_match3(php_regex!(r"{^origin\s+(?P\S+)}m"), &output) + preg_match2(php_regex!(r"{^origin\s+(?P\S+)}m"), &output, 0) && let Some(composer_match) = - Preg::is_match3(php_regex!(r"{^composer\s+(?P\S+)}m"), &output) + preg_match2(php_regex!(r"{^composer\s+(?P\S+)}m"), &output, 0) { let origin_url = origin_match.name("url").unwrap_or_default().to_string(); let composer_url = composer_match.name("url").unwrap_or_default().to_string(); diff --git a/crates/shirabe/src/downloader/svn_downloader.rs b/crates/shirabe/src/downloader/svn_downloader.rs index 4931e539..a31e89c9 100644 --- a/crates/shirabe/src/downloader/svn_downloader.rs +++ b/crates/shirabe/src/downloader/svn_downloader.rs @@ -15,10 +15,9 @@ use crate::util::Filesystem; use crate::util::ProcessExecutor; use crate::util::Svn as SvnUtil; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::{ - CmpOp, PhpMixed, RuntimeException, impl_php_class, is_dir, php_regex, preg_split, - version_compare, + CmpOp, PhpMixed, RuntimeException, impl_php_class, is_dir, php_regex, preg_match2, + preg_replace, preg_split, version_compare, }; #[derive(Debug)] @@ -354,8 +353,8 @@ impl VcsDownloader for SvnDownloader { to_reference: &str, path: &str, ) -> anyhow::Result { - if Preg::is_match(php_regex!(r"{@(\d+)$}"), from_reference) - && Preg::is_match(php_regex!(r"{@(\d+)$}"), to_reference) + if preg_match2(php_regex!(r"{@(\d+)$}"), from_reference, 0).is_some() + && preg_match2(php_regex!(r"{@(\d+)$}"), to_reference, 0).is_some() { // retrieve the svn base url from the checkout folder let command = vec![ @@ -383,7 +382,7 @@ impl VcsDownloader for SvnDownloader { } let url_pattern = "#(.*)#"; - let base_url = if let Some(matches) = Preg::match3(url_pattern, &output) { + let base_url = if let Some(matches) = preg_match2(url_pattern, &output, 0) { matches.get(1).unwrap_or_default().to_string() } else { return Err(RuntimeException::new(format!( @@ -394,8 +393,8 @@ impl VcsDownloader for SvnDownloader { }; // strip paths from references and only keep the actual revision - 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 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(), @@ -453,11 +452,13 @@ impl ChangeReportInterface for SvnDownloader { Some(path), ); - Ok(if Preg::is_match(php_regex!("{^ *[^X ] +}m"), &output) { - Some(output) - } else { - None - }) + Ok( + if preg_match2(php_regex!("{^ *[^X ] +}m"), &output, 0).is_some() { + Some(output) + } else { + None + }, + ) } } diff --git a/crates/shirabe/src/downloader/zip_downloader.rs b/crates/shirabe/src/downloader/zip_downloader.rs index b4802066..7b0ad050 100644 --- a/crates/shirabe/src/downloader/zip_downloader.rs +++ b/crates/shirabe/src/downloader/zip_downloader.rs @@ -8,13 +8,12 @@ use crate::package::PackageInterfaceHandle; use crate::util::IniHelper; use crate::util::Platform; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ CmpOp, ErrorException, PhpMixed, RuntimeException, UnexpectedValueException, ZipArchive, bin2hex, class_exists, file_exists, file_get_contents, filesize, function_exists, hash_file, - impl_php_class, is_file, json_encode, php_regex, random_int, str_replace, strlen, substr, - version_compare, + impl_php_class, is_file, json_encode, php_regex, preg_match2, random_int, str_replace, strlen, + substr, version_compare, }; use shirabe_symfony_process::ExecutableFinder; use std::sync::Mutex; @@ -113,8 +112,11 @@ impl ZipDownloader { .execute(&[command_spec[1].as_str()], &mut output, None::<&str>) .unwrap_or(1) == 0 - && let Some(m) = - Preg::is_match3(php_regex!(r"{^\s*7-Zip(?:\s\[64\])?\s([0-9.]+)}"), &output) + && let Some(m) = preg_match2( + php_regex!(r"{^\s*7-Zip(?:\s\[64\])?\s([0-9.]+)}"), + &output, + 0, + ) { let m1 = m.get(1).unwrap_or_default().to_string(); if version_compare(&m1, "21.01", CmpOp::Lt) { diff --git a/crates/shirabe/src/event_dispatcher/event_dispatcher.rs b/crates/shirabe/src/event_dispatcher/event_dispatcher.rs index fd4b4663..06ce21cc 100644 --- a/crates/shirabe/src/event_dispatcher/event_dispatcher.rs +++ b/crates/shirabe/src/event_dispatcher/event_dispatcher.rs @@ -21,7 +21,6 @@ use crate::script::Event as ScriptEvent; use crate::util::Platform; use crate::util::ProcessExecutor; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_rpc::{ PhpThrow, PluginValue, RustMethodDispatcher, RustObjHandle, call_function, call_function_with_dispatcher, call_php_method, call_static_method, @@ -30,9 +29,10 @@ use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ InvalidArgumentException, PhpMixed, RuntimeException, array_pop, array_push, array_search_in_vec, array_splice, file_exists, get_class, hash, implode, ini_get, 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_replace, strlen, strpos, strtoupper, substr, trim, + is_callable, is_object, is_string, krsort, php_regex, preg_match2, preg_quote, preg_replace, + preg_replace_callback, realpath, spl_autoload_functions, spl_autoload_register, + spl_autoload_unregister, spl_object_hash, str_replace, strlen, strpos, strtoupper, substr, + trim, }; use shirabe_symfony_console::output::output_interface; use shirabe_symfony_process::ExecutableFinder; @@ -372,7 +372,7 @@ impl EventDispatcher { if let Callable::String(ref s) = callable && s.contains("@no_additional_args") { - let replaced = Preg::replace(php_regex!("{ ?@no_additional_args}"), "", s); + let replaced = preg_replace(php_regex!("{ ?@no_additional_args}"), "", s); callable = Callable::String(replaced); additional_args = Vec::new(); } @@ -922,13 +922,16 @@ try {{ .get_binaries(); if !possible_local_binaries.is_empty() { for local_exec in &possible_local_binaries { - if Preg::is_match( + if preg_match2( format!("{{\\b{}$}}", preg_quote(&callable_str, None)), local_exec, - ) { + 0, + ) + .is_some() + { let caller = BinaryInstaller::determine_binary_caller(local_exec); - exec = Preg::replace( + exec = preg_replace( format!("{{^{}}}", preg_quote(&callable_str, None)), &format!("{} {}", caller, local_exec), &exec, @@ -954,16 +957,17 @@ try {{ if strpos(&exec, "@php ") == Some(0) { let mut path_and_args = substr(&exec, 5, None); if Platform::is_windows() { - path_and_args = Preg::replace_callback( + path_and_args = preg_replace_callback( php_regex!("{^\\S+}"), - |m| str_replace("/", "\\", m.get(0).unwrap()), + |m| Ok(str_replace("/", "\\", m.get(0).unwrap())), &path_and_args, - ); + ) + .expect("the replacement callback cannot fail"); } // 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 if let Some(m) = - Preg::is_match3(php_regex!("{^[^\\'\"\\s/\\\\]+}"), &path_and_args) + preg_match2(php_regex!("{^[^\\'\"\\s/\\\\]+}"), &path_and_args, 0) { let m0 = m.get(0).unwrap_or_default().to_string(); if !file_exists(&m0) { @@ -971,7 +975,7 @@ try {{ if let Some(path_to_exec) = finder.find(&m0, None, &[]) { let mut path_to_exec = path_to_exec; if Platform::is_windows() { - let exec_without_ext = Preg::replace( + let exec_without_ext = preg_replace( php_regex!("{\\.(exe|bat|cmd|com)$}i"), "", &path_to_exec, @@ -998,11 +1002,12 @@ try {{ } if Platform::is_windows() { - exec = Preg::replace_callback( + exec = preg_replace_callback( php_regex!("{^\\S+}"), - |m| str_replace("/", "\\", m.get(0).unwrap()), + |m| Ok(str_replace("/", "\\", m.get(0).unwrap())), &exec, - ); + ) + .expect("the replacement callback cannot fail"); } } diff --git a/crates/shirabe/src/filter/platform_requirement_filter/ignore_list_platform_requirement_filter.rs b/crates/shirabe/src/filter/platform_requirement_filter/ignore_list_platform_requirement_filter.rs index 54557fb2..5fcdc629 100644 --- a/crates/shirabe/src/filter/platform_requirement_filter/ignore_list_platform_requirement_filter.rs +++ b/crates/shirabe/src/filter/platform_requirement_filter/ignore_list_platform_requirement_filter.rs @@ -3,7 +3,7 @@ use crate::filter::platform_requirement_filter::PlatformRequirementFilterInterface; use crate::package::base_package::{self}; use crate::repository::PlatformRepository; -use shirabe_pcre::Preg; +use shirabe_php_shim::preg_match2; use shirabe_semver::Interval; use shirabe_semver::Intervals; use shirabe_semver::constraint::AnyConstraint; @@ -47,11 +47,13 @@ impl IgnoreListPlatformRequirementFilter { return Ok(constraint); } - if !allow_upper_bound_override || !Preg::is_match(&self.ignore_upper_bound_regex, req) { + if !allow_upper_bound_override + || preg_match2(&self.ignore_upper_bound_regex, req, 0).is_none() + { return Ok(constraint); } - if Preg::is_match(&self.ignore_regex, req) { + if preg_match2(&self.ignore_regex, req, 0).is_some() { return Ok(MatchAllConstraint::new(None).into()); } @@ -85,14 +87,14 @@ impl PlatformRequirementFilterInterface for IgnoreListPlatformRequirementFilter if !PlatformRepository::is_platform_package(req) { return false; } - Preg::is_match(&self.ignore_regex, req) + preg_match2(&self.ignore_regex, req, 0).is_some() } fn is_upper_bound_ignored(&self, req: &str) -> bool { if !PlatformRepository::is_platform_package(req) { return false; } - self.is_ignored(req) || Preg::is_match(&self.ignore_upper_bound_regex, req) + self.is_ignored(req) || preg_match2(&self.ignore_upper_bound_regex, req, 0).is_some() } fn as_any(&self) -> &dyn std::any::Any { diff --git a/crates/shirabe/src/installer/binary_installer.rs b/crates/shirabe/src/installer/binary_installer.rs index 4bcb6865..4e3b5e4c 100644 --- a/crates/shirabe/src/installer/binary_installer.rs +++ b/crates/shirabe/src/installer/binary_installer.rs @@ -8,11 +8,10 @@ use crate::util::Filesystem; use crate::util::Platform; use crate::util::ProcessExecutor; use crate::util::Silencer; -use shirabe_pcre::Preg; use shirabe_php_shim::{ PhpMixed, basename, basename_with_suffix, chmod, dirname, fclose, fgets, file_exists, - file_get_contents5, file_put_contents, fopen, is_dir, is_file, is_link, php_regex, realpath, - rmdir, substr, trim, umask, + file_get_contents5, file_put_contents, fopen, is_dir, is_file, is_link, php_regex, preg_match2, + realpath, rmdir, substr, trim, umask, }; /// Seam over the BinaryInstaller methods reached through LibraryInstaller, so tests can inject a @@ -201,9 +200,10 @@ impl BinaryInstaller { } Err(_) => String::new(), }; - if let Some(m) = Preg::is_match3( + if let Some(m) = preg_match2( php_regex!(r"{^#!/(?:usr/bin/env )?(?:[^/]+/)*(.+)$}m"), &line, + 0, ) { return trim(m.get(1).unwrap_or(""), None); } @@ -316,9 +316,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_match3( + if let Some(m) = preg_match2( php_regex!(r"{^(#!.*\r?\n)?[\r\n\t ]*<\?php}"), &bin_contents, + 0, ) { // carry over the existing shebang if present, otherwise add our own let proxy_code = match m.get(1) { diff --git a/crates/shirabe/src/installer/library_installer.rs b/crates/shirabe/src/installer/library_installer.rs index 5f3b2054..d3bf4643 100644 --- a/crates/shirabe/src/installer/library_installer.rs +++ b/crates/shirabe/src/installer/library_installer.rs @@ -12,10 +12,9 @@ use crate::repository::InstalledRepositoryInterfaceHandle; use crate::util::Filesystem; use crate::util::Platform; use crate::util::Silencer; -use shirabe_pcre::Preg; use shirabe_php_shim::{ InvalidArgumentException, LogicException, PhpMixed, dirname, is_dir, is_link, preg_quote, - realpath, rmdir, rtrim, strpos, + preg_replace, realpath, rmdir, rtrim, strpos, }; /// Package installation manager. @@ -127,7 +126,7 @@ impl LibraryInstaller { if let Some(target_dir) = target_dir && !target_dir.is_empty() { - let replaced = Preg::replace( + let replaced = preg_replace( 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 916f647d..a450c869 100644 --- a/crates/shirabe/src/installer/suggested_packages_reporter.rs +++ b/crates/shirabe/src/installer/suggested_packages_reporter.rs @@ -6,8 +6,7 @@ use crate::package::PackageInterfaceHandle; use crate::repository::InstalledRepository; use crate::repository::RepositoryInterface; use indexmap::IndexMap; -use shirabe_pcre::Preg; -use shirabe_php_shim::php_regex; +use shirabe_php_shim::{php_regex, preg_replace}; use shirabe_symfony_console::formatter::OutputFormatter; #[derive(Debug)] @@ -207,6 +206,6 @@ impl SuggestedPackagesReporter { } fn remove_control_characters(&self, string: &str) -> String { - Preg::replace(php_regex!("/[[: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 4d0d9309..08a9fd7e 100644 --- a/crates/shirabe/src/io/base_io.rs +++ b/crates/shirabe/src/io/base_io.rs @@ -6,10 +6,9 @@ use crate::io::io_interface; use crate::util::ProcessExecutor; use crate::util::Silencer; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::{ JSON_INVALID_UTF8_IGNORE, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE, PhpMixed, - UnexpectedValueException, array_merge, in_array_strict, json_encode_ex, php_regex, + UnexpectedValueException, array_merge, in_array_strict, json_encode_ex, php_regex, preg_match2, }; /// ref: composer/vendor/psr/log/Psr/Log/LogLevel.php @@ -157,7 +156,7 @@ pub trait BaseIO: IOInterface { config.merge(&config_outer, "implicit-due-to-auth"); } - if !Preg::is_match(php_regex!(r"{^[.A-Za-z0-9_]+$}"), &token_str) { + if preg_match2(php_regex!(r"{^[.A-Za-z0-9_]+$}"), &token_str, 0).is_none() { return Err(UnexpectedValueException::new(format!( "Your github oauth token for {} contains invalid characters: \"{}\"", domain, token_str diff --git a/crates/shirabe/src/io/buffer_io.rs b/crates/shirabe/src/io/buffer_io.rs index 466efe0b..3b1afdf8 100644 --- a/crates/shirabe/src/io/buffer_io.rs +++ b/crates/shirabe/src/io/buffer_io.rs @@ -1,10 +1,9 @@ //! ref: composer/src/Composer/IO/BufferIO.php use crate::io::ConsoleIO; -use shirabe_pcre::Preg; use shirabe_php_shim::{ - PHP_EOL, PhpMixed, PhpResource, RuntimeException, SEEK_SET, fopen, fseek, fwrite, php_regex, - rewind, stream_get_contents, strip_tags, + PHP_EOL, PhpMixed, PhpResource, PregMatches, RuntimeException, SEEK_SET, fopen, fseek, fwrite, + php_regex, preg_replace_callback, rewind, stream_get_contents, strip_tags, }; use shirabe_symfony_console::formatter::OutputFormatterInterface; use shirabe_symfony_console::helper::QuestionHelper; @@ -74,23 +73,24 @@ impl BufferIO { // pass, so the replacement is applied to a fixpoint (each pass strictly shrinks the string). let mut output = output; loop { - let next = Preg::replace_callback( + let next = preg_replace_callback( php_regex!(r"{(^|\n|\x08)(.+?)(\x08+)}"), - |matches: &shirabe_pcre::PregMatches| -> String { + |matches: &PregMatches| -> anyhow::Result { let g1 = matches.get(1).unwrap_or(""); let g2 = matches.get(2).unwrap_or(""); let g3 = matches.get(3).unwrap_or(""); let pre = strip_tags(g2); if pre.len() == g3.len() { - return g1.to_string(); + return Ok(g1.to_string()); } // TODO reverse parse the string, skipping span tags and \033\[([0-9;]+)m(.*?)\033\[0m style blobs - format!("{}{}\n", g1, g2.trim_end()) + Ok(format!("{}{}\n", g1, g2.trim_end())) }, &output, - ); + ) + .expect("the replacement callback cannot fail"); if next == output { break; } diff --git a/crates/shirabe/src/io/console_io.rs b/crates/shirabe/src/io/console_io.rs index e9ca2048..e3ba68b3 100644 --- a/crates/shirabe/src/io/console_io.rs +++ b/crates/shirabe/src/io/console_io.rs @@ -9,10 +9,9 @@ use crate::io::io_interface; use crate::question::StrictConfirmationQuestion; use indexmap::IndexMap; use indexmap::indexmap; -use shirabe_pcre::Preg; use shirabe_php_shim::{ - PhpMixed, array_search, in_array_strict, is_array, is_string, microtime, str_repeat, - strip_tags, strlen, + PhpMixed, array_search, in_array_strict, is_array, is_string, microtime, preg_replace, + str_repeat, strip_tags, strlen, }; use shirabe_symfony_console::helper::ProgressBar; use shirabe_symfony_console::helper::QuestionHelper; @@ -237,7 +236,7 @@ impl ConsoleIO { }; let messages = Self::ensure_valid_utf8(messages); - Preg::replace(&pattern, replacement, &messages) + preg_replace(&pattern, replacement, &messages) } /// Ensures a string is valid UTF-8, replacing invalid byte sequences with '?' diff --git a/crates/shirabe/src/json/json_file.rs b/crates/shirabe/src/json/json_file.rs index 004645c5..3bfff4d3 100644 --- a/crates/shirabe/src/json/json_file.rs +++ b/crates/shirabe/src/json/json_file.rs @@ -8,13 +8,13 @@ use crate::json::JsonValidationException; use crate::util::Filesystem; use crate::util::HttpDownloader; use crate::util::Silencer; -use shirabe_pcre::Preg; use shirabe_php_shim::Catch as _; 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_assoc, json_decode_obj, json_encode_ex, mkdir, - php_regex, realpath, str_repeat, strlen, strpos, usleep, + PhpMixed, PregMatches, RuntimeException, UnexpectedValueException, dirname, file_exists, + file_get_contents, file_put_contents, is_dir, is_file, json_decode_assoc, json_decode_obj, + json_encode_ex, mkdir, php_regex, preg_match2, preg_replace_callback, preg_replace2, realpath, + str_repeat, strlen, strpos, usleep, }; use shirabe_seld_json_lint::{ParsingException, ParsingExceptionDetails}; @@ -107,7 +107,9 @@ impl JsonFile { http_downloader: Option>>, io: Option>>, ) -> anyhow::Result { - if http_downloader.is_none() && Preg::is_match(php_regex!(r"{^https?://}i"), &path) { + if http_downloader.is_none() + && preg_match2(php_regex!(r"{^https?://}i"), &path, 0).is_some() + { return Err(InvalidArgumentException::new( "http urls require a HttpDownloader instance to be passed".to_string(), ) @@ -448,14 +450,15 @@ impl JsonFile { if options.pretty_print && options.indent != Self::INDENT_DEFAULT { // Pretty printing and not using default indentation let indent_owned = options.indent; - return Ok(Preg::replace_callback( + return Ok(preg_replace_callback( php_regex!(r"#^ {4,}#m"), - move |m: &shirabe_pcre::PregMatches| -> String { + move |m: &PregMatches| -> anyhow::Result { let whole = m.get(0).unwrap_or(""); - str_repeat(&indent_owned, (strlen(whole) / 4) as usize) + Ok(str_repeat(&indent_owned, (strlen(whole) / 4) as usize)) }, &json, - )); + ) + .expect("the replacement callback cannot fail")); } Ok(json) @@ -485,14 +488,14 @@ impl JsonFile { && json.contains("\"content-hash\"") { let mut count: usize = 0; - let replaced = Preg::replace5( + let replaced = preg_replace2( 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, - &mut count, + Some(&mut count), ); if count == 1 { data = json_decode_assoc(&replaced)?; @@ -551,7 +554,7 @@ impl JsonFile { } pub fn detect_indenting(json: Option<&str>) -> String { - if let Some(m) = Preg::is_match3(php_regex!(r##"#^([ \t]+)"#m"##), json.unwrap_or("")) { + if let Some(m) = preg_match2(php_regex!(r##"#^([ \t]+)"#m"##), json.unwrap_or(""), 0) { return m.get(1).unwrap_or_default().to_string(); } diff --git a/crates/shirabe/src/json/json_manipulator.rs b/crates/shirabe/src/json/json_manipulator.rs index 9fa8e1e0..f0cb8790 100644 --- a/crates/shirabe/src/json/json_manipulator.rs +++ b/crates/shirabe/src/json/json_manipulator.rs @@ -4,12 +4,12 @@ use crate::json::JsonFile; use crate::json::json_grammar::{self, ValueKind}; use crate::repository::PlatformRepository; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::{ InvalidArgumentException, LogicException, PhpMixed, addcslashes, array_key_exists, array_keys, array_reverse, empty, explode, implode, in_array_loose, is_array, is_int, is_numeric, - json_decode_assoc, json_decode_obj, php_regex, php_truthy, preg_quote, rtrim, str_repeat, - str_replace, strlen, strnatcmp, strpos, substr, trim, uksort, + json_decode_assoc, json_decode_obj, php_regex, php_truthy, preg_match2, preg_quote, + preg_replace, preg_replace2, rtrim, 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(php_regex!("#^\\{(.*)\\}$#s"), &contents).is_none() { + if preg_match2(php_regex!("#^\\{(.*)\\}$#s"), &contents, 0).is_none() { return Err(InvalidArgumentException::new( "The json file must be an object ({})".to_string(), ) @@ -112,14 +112,15 @@ impl JsonManipulator { &links[value_end..] ); } else { - if let Some(groups) = - Preg::is_match3(php_regex!("#^\\s*\\{\\s*\\S+.*?(\\s*\\}\\s*)$#s"), &links) - { + if let Some(groups) = preg_match2( + php_regex!("#^\\s*\\{\\s*\\S+.*?(\\s*\\}\\s*)$#s"), + &links, + 0, + ) { let groups_1 = groups.get(1).unwrap_or_default().to_string(); // link missing but non empty links - links = Preg::replace( + links = preg_replace( 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!( ",{}{}{}{}: {}{}", @@ -168,7 +169,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 { @@ -734,11 +735,12 @@ impl JsonManipulator { &children[cm.value_end..] ); } else { - if let Some(leading_match) = Preg::is_match3( + if let Some(leading_match) = preg_match2( php_regex!( "#^\\{(?P\\s*?)(?P\\S+.*?)?(?P\\s*)\\}$#s" ), &children, + 0, ) { let mut whitespace = leading_match .name("trailingspace") @@ -759,7 +761,7 @@ impl JsonManipulator { // child missing but non empty children if append { - children = Preg::replace( + children = preg_replace( format!("#{}}}$#", whitespace), &addcslashes( &format!( @@ -777,7 +779,7 @@ impl JsonManipulator { ); } else { whitespace = leading_space; - children = Preg::replace( + children = preg_replace( format!("#^{{{}#", whitespace), &addcslashes( &format!( @@ -891,7 +893,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 = None; - if Preg::is_match3(format!("{{\"{}\"\\s*:}}i", key_regex), &children).is_some() { + if preg_match2(format!("{{\"{}\"\\s*:}}i", key_regex), &children, 0).is_some() { // find best match for the value of "name". The PHP pattern `"name"\s*:\s*(?&json)` is // not anchored, so it can match the key at several nesting levels; collect every such // occurrence and keep the longest, reproducing PHP's behaviour. @@ -904,20 +906,20 @@ impl JsonManipulator { } } let mut count_out: usize = 0; - let cleaned = Preg::replace5( + let cleaned = preg_replace2( format!("{{,\\s*{}}}i", preg_quote(&best_match, None)), "", &children, -1, - &mut count_out, + Some(&mut count_out), ); if 1 != count_out { - let cleaned2 = Preg::replace5( + let cleaned2 = preg_replace2( format!("{{{}\\s*,?\\s*}}i", preg_quote(&best_match, None)), "", &cleaned, -1, - &mut count_out, + Some(&mut count_out), ); if 1 != count_out { return Ok(false); @@ -934,9 +936,10 @@ impl JsonManipulator { let children_clean = children_clean.ok_or_else(|| InvalidArgumentException::new("JsonManipulator: $childrenClean is not defined. Please report at https://github.com/nsfisis/php-shirabe/issues/new.".to_string()))?; // no child data left, $name was the only key in - if let Some(empty_match) = Preg::is_match3( + if let Some(empty_match) = preg_match2( php_regex!("#^\\{\\s*?(?P\\S+.*?)?(?P\\s*)\\}$#s"), &children_clean, + 0, ) && empty_match.name("content").is_none() { self.contents = format!( @@ -1029,11 +1032,12 @@ impl JsonManipulator { return Ok(false); } - if let Some(leading_match) = Preg::is_match3( + if let Some(leading_match) = preg_match2( php_regex!( "#^\\[(?P\\s*?)(?P\\S+.*?)?(?P\\s*)\\]$#s" ), &children, + 0, ) { let leading_whitespace = leading_match .name("leadingspace") @@ -1058,7 +1062,7 @@ impl JsonManipulator { if leading_match.name("content").is_some() { // child missing but non empty children if append { - children = Preg::replace( + children = preg_replace( format!("#{}\\]$#", whitespace), &addcslashes( &format!( @@ -1073,7 +1077,7 @@ impl JsonManipulator { ); } else { whitespace = leading_whitespace; - children = Preg::replace( + children = preg_replace( format!("#^\\[{}#", whitespace), &addcslashes( &format!( @@ -1318,10 +1322,10 @@ impl JsonManipulator { } // append at the end of the file and keep whitespace - if let Some(tail_match) = Preg::is_match3(php_regex!("#[^{\\s](\\s*)\\}$#"), &self.contents) + if let Some(tail_match) = preg_match2(php_regex!("#[^{\\s](\\s*)\\}$#"), &self.contents, 0) { let tail_match_1 = tail_match.get(1).unwrap_or_default().to_string(); - self.contents = Preg::replace( + self.contents = preg_replace( format!("#{}\\}}$#", tail_match_1), &addcslashes( &format!( @@ -1341,7 +1345,7 @@ impl JsonManipulator { } // append at the end of the file - self.contents = Preg::replace( + self.contents = preg_replace( php_regex!("#\\}$#"), &addcslashes( &format!( @@ -1392,17 +1396,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(php_regex!("#,\\s*$#"), &start).is_some() - && Preg::is_match3(php_regex!("#^\\}$#"), &end).is_some() + if preg_match2(php_regex!("#,\\s*$#"), &start, 0).is_some() + && preg_match2(php_regex!("#^\\}$#"), &end, 0).is_some() { start = rtrim( - &Preg::replace(php_regex!("#,(\\s*)$#"), "$1", &start), + &preg_replace(php_regex!("#,(\\s*)$#"), "$1", &start), Some(&self.indent), ); } self.contents = format!("{}{}", start, end); - if Preg::is_match3(php_regex!("#^\\{\\s*\\}\\s*$#"), &self.contents).is_some() { + if preg_match2(php_regex!("#^\\{\\s*\\}\\s*$#"), &self.contents, 0).is_some() { self.contents = "{\n}".to_string(); } @@ -1639,7 +1643,7 @@ fn match_pkg_name(b: &[u8], start: usize, name: &[u8]) -> Option { Some(p + 1) } -// Lightweight clone of JsonManipulator's formatting logic, used inside Preg::replace_callback closures. +// Lightweight clone of JsonManipulator's formatting logic, used inside preg_replace_callback closures. struct ManipulatorFormatter { newline: String, indent: String, diff --git a/crates/shirabe/src/package/archiver/archivable_files_finder.rs b/crates/shirabe/src/package/archiver/archivable_files_finder.rs index 8fba18cb..7a1797bf 100644 --- a/crates/shirabe/src/package/archiver/archivable_files_finder.rs +++ b/crates/shirabe/src/package/archiver/archivable_files_finder.rs @@ -4,8 +4,7 @@ use crate::package::archiver::BaseExcludeFilter; use crate::package::archiver::ComposerExcludeFilter; use crate::package::archiver::GitExcludeFilter; use crate::util::Filesystem; -use shirabe_pcre::Preg; -use shirabe_php_shim::{RuntimeException, preg_quote, realpath}; +use shirabe_php_shim::{RuntimeException, preg_quote, preg_replace, realpath}; use shirabe_symfony_finder::Finder; use std::path::{Path, PathBuf}; @@ -56,7 +55,7 @@ impl ArchivableFilesFinder { return false; } - let relative_path = Preg::replace( + let relative_path = preg_replace( 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 a0216d88..4f9e2ddc 100644 --- a/crates/shirabe/src/package/archiver/archive_manager.rs +++ b/crates/shirabe/src/package/archiver/archive_manager.rs @@ -10,10 +10,9 @@ use crate::util::Filesystem; use crate::util::SyncHelper; use crate::util::r#loop::Loop; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::{ - InvalidArgumentException, RuntimeException, bin2hex, file_exists, php_regex, random_bytes, - realpath, sys_get_temp_dir, + InvalidArgumentException, RuntimeException, bin2hex, file_exists, php_regex, preg_match2, + preg_replace, random_bytes, realpath, sys_get_temp_dir, }; pub struct ArchiveManager { @@ -58,7 +57,7 @@ impl ArchiveManager { ) -> anyhow::Result> { let base_name = match package.get_archive_name() { Some(name) => name, - None => Preg::replace(php_regex!("#[^a-z0-9-_]#i"), "-", &package.get_name()), + None => preg_replace(php_regex!("#[^a-z0-9-_]#i"), "-", &package.get_name()), }; let mut parts: IndexMap = IndexMap::new(); @@ -66,7 +65,7 @@ impl ArchiveManager { let dist_reference = package.get_dist_reference(); if let Some(ref dist_ref) = dist_reference { - if Preg::is_match(php_regex!("{^[a-f0-9]{40}$}"), dist_ref) { + if preg_match2(php_regex!("{^[a-f0-9]{40}$}"), dist_ref, 0).is_some() { 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); diff --git a/crates/shirabe/src/package/archiver/base_exclude_filter.rs b/crates/shirabe/src/package/archiver/base_exclude_filter.rs index e5487038..16a189a8 100644 --- a/crates/shirabe/src/package/archiver/base_exclude_filter.rs +++ b/crates/shirabe/src/package/archiver/base_exclude_filter.rs @@ -1,6 +1,6 @@ //! ref: composer/src/Composer/Package/Archiver/BaseExcludeFilter.php -use shirabe_pcre::Preg; +use shirabe_php_shim::preg_match2; use shirabe_symfony_finder::Glob; #[derive(Debug)] @@ -86,7 +86,7 @@ pub trait BaseExcludeFilter { relative_path }; - if Preg::is_match(pattern, path) { + if preg_match2(pattern, path, 0).is_some() { exclude = !negate; } } diff --git a/crates/shirabe/src/package/loader/array_loader.rs b/crates/shirabe/src/package/loader/array_loader.rs index 21811f14..b6b5ac1e 100644 --- a/crates/shirabe/src/package/loader/array_loader.rs +++ b/crates/shirabe/src/package/loader/array_loader.rs @@ -17,11 +17,10 @@ use crate::package::loader::LoaderInterface; use crate::package::version::VersionParser; use chrono::Utc; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::{ AnyThrowable, E_USER_DEPRECATED, PhpMixed, UnexpectedValueException, is_scalar, is_string, - json_encode, ltrim, php_regex, stripos, strpos, strtolower, strval, substr, trigger_error, - trim, + json_encode, ltrim, php_regex, preg_match2, preg_replace, stripos, strpos, strtolower, strval, + substr, trigger_error, trim, }; #[derive(Debug)] @@ -340,7 +339,7 @@ impl ArrayLoader { && !shirabe_php_shim::empty(time_value) { let time_str = time_value.as_string().unwrap_or(""); - let time = if Preg::is_match(php_regex!(r"/^\d++$/D"), time_str) { + let time = if preg_match2(php_regex!(r"/^\d++$/D"), time_str, 0).is_some() { format!("@{}", time_str) } else { time_str.to_string() @@ -510,7 +509,7 @@ impl ArrayLoader { if let Some(alias_normalized) = alias_normalized && !alias_normalized.is_empty() { - let pretty_alias = Preg::replace(php_regex!(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( @@ -771,7 +770,7 @@ impl ArrayLoader { && default_branch_is_true && self .version_parser - .parse_numeric_alias_prefix(&Preg::replace(php_regex!(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 012c30fd..bc49ffc0 100644 --- a/crates/shirabe/src/package/loader/root_package_loader.rs +++ b/crates/shirabe/src/package/loader/root_package_loader.rs @@ -15,9 +15,9 @@ use crate::repository::RepositoryManager; use crate::util::Platform; use crate::util::ProcessExecutor; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::{ - PhpMixed, RuntimeException, UnexpectedValueException, php_regex, preg_split, strtolower, + PhpMixed, RuntimeException, UnexpectedValueException, php_regex, preg_match2, preg_replace, + preg_split, strtolower, }; #[derive(Debug)] @@ -252,9 +252,10 @@ impl RootPackageLoader { mut aliases: Vec>, ) -> Vec> { for (req_name, req_version) in requires { - if let Some(m) = Preg::is_match3( + if let Some(m) = preg_match2( php_regex!(r"{(?:^|\| *|, *)([^,\s#|]+)(?:#[^ ]+)? +as +([^,\s|]+)(?:$| *\|| *,)}"), req_version, + 0, ) { let m1 = m.get(1).unwrap_or_default().to_string(); let m2 = m.get(2).unwrap_or_default().to_string(); @@ -316,7 +317,7 @@ impl RootPackageLoader { let mut matched = false; for constraint in &constraints { - if let Some(m) = Preg::is_match3(&pattern, constraint) { + if let Some(m) = preg_match2(&pattern, constraint, 0) { let name = strtolower(req_name); let m1 = m.get(1).unwrap_or_default().to_string(); let normalized_m1 = VersionParser::normalize_stability(&m1).unwrap_or_default(); @@ -336,8 +337,8 @@ impl RootPackageLoader { for constraint in &constraints { let req_version_stripped = - Preg::replace(php_regex!(r"{^([^,\s@]+) as .+$}"), "$1", constraint); - if Preg::is_match(php_regex!(r"{^[^,\s@]+$}"), &req_version_stripped) { + preg_replace(php_regex!(r"{^([^,\s@]+) as .+$}"), "$1", constraint); + if preg_match2(php_regex!(r"{^[^,\s@]+$}"), &req_version_stripped, 0).is_some() { let stability_name = VersionParser::parse_stability(&req_version_stripped); if stability_name != "stable" { let name = strtolower(req_name); @@ -361,8 +362,8 @@ impl RootPackageLoader { mut references: IndexMap, ) -> IndexMap { for (req_name, req_version) in requires { - let req_version = Preg::replace(php_regex!(r"{^([^,\s@]+) as .+$}"), "$1", req_version); - if let Some(m) = Preg::is_match3(php_regex!(r"{^[^,\s@]+?#([a-f0-9]+)$}"), &req_version) + let req_version = preg_replace(php_regex!(r"{^([^,\s@]+) as .+$}"), "$1", req_version); + if let Some(m) = preg_match2(php_regex!(r"{^[^,\s@]+?#([a-f0-9]+)$}"), &req_version, 0) && VersionParser::parse_stability(&req_version) == "dev" { let name = strtolower(req_name); diff --git a/crates/shirabe/src/package/loader/validating_array_loader.rs b/crates/shirabe/src/package/loader/validating_array_loader.rs index 6b9bea91..5ac1a929 100644 --- a/crates/shirabe/src/package/loader/validating_array_loader.rs +++ b/crates/shirabe/src/package/loader/validating_array_loader.rs @@ -7,12 +7,11 @@ use crate::package::version::VersionParser; use crate::package::{STABILITIES, SUPPORTED_LINK_TYPES}; use crate::repository::PlatformRepository; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::{ CmpOp, E_USER_DEPRECATED, PHP_EOL, PhpMixed, array_intersect_key, array_values, filter_var_email, get_debug_type, is_array, is_bool, is_int, is_numeric, is_scalar, is_string, - json_encode, parse_url, php_regex, php_to_string, str_replace, strcasecmp, strtolower, - strtotime, substr, trigger_error, trim, var_export, + json_encode, parse_url, php_regex, php_to_string, preg_match2, preg_replace, str_replace, + strcasecmp, strtolower, strtotime, substr, trigger_error, trim, var_export, }; use shirabe_semver::Intervals; use shirabe_semver::constraint::AnyConstraint; @@ -74,12 +73,15 @@ impl ValidatingArrayLoader { return None; } - if !Preg::is_match( + if preg_match2( php_regex!( "{^[a-z0-9](?:[_.-]?[a-z0-9]++)*+/[a-z0-9](?:(?:[_.]|-{1,2})?[a-z0-9]++)*+$}iD" ), name, - ) { + 0, + ) + .is_none() + { return Some(format!( "{} is invalid, it should have a vendor name, a forward slash, and a package name. The vendor and package name can be words separated by -, . or _. The complete name should match \"^[a-z0-9]([_.-]?[a-z0-9]+)*/[a-z0-9](([_.]?|-{{0,2}})[a-z0-9]+)*$\".", name @@ -100,14 +102,14 @@ impl ValidatingArrayLoader { )); } - if Preg::is_match(php_regex!("{\\.json$}"), name) { + if preg_match2(php_regex!("{\\.json$}"), name, 0).is_some() { 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(php_regex!("{[A-Z]}"), name) { + if preg_match2(php_regex!("{[A-Z]}"), name, 0).is_some() { if is_link { return Some(format!( "{} is invalid, it should not contain uppercase characters. Please use {} instead.", @@ -116,7 +118,7 @@ impl ValidatingArrayLoader { )); } - let suggest_name = Preg::replace( + let suggest_name = preg_replace( php_regex!("{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}"), "\\1\\3-\\2\\4", name, @@ -141,7 +143,7 @@ impl ValidatingArrayLoader { .as_string() .unwrap_or("") .to_string(); - if !Preg::is_match(format!("{{^{}$}}u", regex), &value) { + if preg_match2(format!("{{^{}$}}u", regex), &value, 0).is_none() { let message = format!( "{} : invalid value ({}), must match {}", property, value, regex @@ -256,7 +258,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_match2(format!("{{^{}$}}u", regex_str), &value_str, 0).is_none() { self.warnings.borrow_mut().push(format!( "{}.{} : invalid value ({}), must match {}", property, key, value_str, regex_str @@ -1185,7 +1187,8 @@ impl LoaderInterface for ValidatingArrayLoader { self.warnings .borrow_mut() .push(format!("{}.{}", link_type, err)); - } else if !Preg::is_match(php_regex!("{^[A-Za-z0-9_./-]+$}"), &package) { + } else if preg_match2(php_regex!("{^[A-Za-z0-9_./-]+$}"), &package, 0).is_none() + { self.errors.borrow_mut().push(format!( "{}.{} : invalid key, package names must be strings containing only [A-Za-z0-9_./-]", link_type, package @@ -1448,7 +1451,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(php_regex!("{^\\s*-}"), &ref_str) { + if preg_match2(php_regex!("{^\\s*-}"), &ref_str, 0).is_some() { self.errors.borrow_mut().push(format!( "{}.reference : must not start with a \"-\", \"{}\" given", src_type, ref_str @@ -1457,7 +1460,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(php_regex!("{^\\s*-}"), &url_str) { + if preg_match2(php_regex!("{^\\s*-}"), &url_str, 0).is_some() { self.errors.borrow_mut().push(format!( "{}.url : must not start with a \"-\", \"{}\" given", src_type, url_str diff --git a/crates/shirabe/src/package/locker.rs b/crates/shirabe/src/package/locker.rs index 7d45e573..fee45fef 100644 --- a/crates/shirabe/src/package/locker.rs +++ b/crates/shirabe/src/package/locker.rs @@ -24,12 +24,11 @@ use crate::repository::RootPackageRepository; use crate::util::Git as GitUtil; use crate::util::ProcessExecutor; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::Catch as _; 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_loose, - is_int, ksort, php_regex, realpath, strcmp, strtolower, touch2, trim, usort, + is_int, ksort, php_regex, preg_match2, realpath, strcmp, strtolower, touch2, trim, usort, }; use shirabe_seld_json_lint::ParsingException; @@ -824,7 +823,7 @@ impl Locker { ), None, ); - if Preg::is_match(php_regex!(r"{^\s*\d+\s*$}"), &output_str) { + if preg_match2(php_regex!(r"{^\s*\d+\s*$}"), &output_str, 0).is_some() { let ts = trim(&output_str, None).parse::().unwrap_or(0); datetime = chrono::DateTime::from_timestamp(ts, 0); } @@ -843,9 +842,10 @@ impl Locker { ]), &mut output, path.as_deref(), - )? && let Some(m) = Preg::is_match3( + )? && let Some(m) = preg_match2( php_regex!(r"{^\s*(\d+)\s*}"), output.as_string().unwrap_or(""), + 0, ) { let ts = m .get(1) diff --git a/crates/shirabe/src/package/package.rs b/crates/shirabe/src/package/package.rs index 2e2d5feb..ddeb2932 100644 --- a/crates/shirabe/src/package/package.rs +++ b/crates/shirabe/src/package/package.rs @@ -10,9 +10,9 @@ use crate::repository::RepositoryInterfaceWeakHandle; use crate::util::ComposerMirror; use chrono::{DateTime, Utc}; use indexmap::{IndexMap, IndexSet}; -use shirabe_pcre::Preg; use shirabe_php_shim::{ - E_USER_DEPRECATED, LogicException, PhpMixed, php_regex, strpos, trigger_error, + E_USER_DEPRECATED, LogicException, PhpMixed, PregMatches, php_regex, preg_match2, preg_replace, + preg_replace_callback, strpos, trigger_error, }; /// Mirror entry, e.g. `['url' => 'https://...', 'preferred' => true]`. @@ -139,7 +139,7 @@ impl Package { pub fn get_target_dir(&self) -> Option { let target_dir = self.target_dir.as_ref()?; - let replaced = Preg::replace( + let replaced = preg_replace( php_regex!("{ (?:^|[\\\\/]+) \\.\\.? (?:[\\\\/]+|$) (?:\\.\\.? (?:[\\\\/]+|$) )*}x"), "/", target_dir, @@ -416,12 +416,14 @@ impl Package { // only bitbucket, github and gitlab have auto generated dist URLs that easily allow replacing the reference in the dist URL // 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( + && preg_match2( php_regex!( "{^https?://(?:(?:www\\.)?bitbucket\\.org|(api\\.)?github\\.com|(?:www\\.)?gitlab\\.com)/}i" ), &self.get_dist_url().unwrap_or_default(), + 0, ) + .is_some() { self.set_dist_reference(Some(reference.clone())); // Regex pattern compatibility: @@ -431,14 +433,17 @@ impl Package { // lookaround, the capturing version consumes its boundary delimiter, so two 40-hex // SHAs sharing a single `/` between them would not both match; harmless here since a // dist URL never carries more than one SHA reference. - self.set_dist_url(Some(Preg::replace_callback( - php_regex!("{(/|sha=)[a-f0-9]{40}(/|$)}i"), - |m: &shirabe_pcre::PregMatches| -> String { - let get = |i: usize| -> String { m.get(i).unwrap_or_default().to_string() }; - format!("{}{}{}", get(1), reference, get(2)) - }, - &self.get_dist_url().unwrap_or_default(), - ))); + self.set_dist_url(Some( + preg_replace_callback( + php_regex!("{(/|sha=)[a-f0-9]{40}(/|$)}i"), + |m: &PregMatches| -> anyhow::Result { + let get = |i: usize| -> String { m.get(i).unwrap_or_default().to_string() }; + Ok(format!("{}{}{}", get(1), reference, get(2))) + }, + &self.get_dist_url().unwrap_or_default(), + ) + .expect("the replacement callback cannot fail"), + )); } else if self.get_dist_reference().is_some() { // update the dist reference if there was one, but if none was provided ignore it self.set_dist_reference(Some(reference)); diff --git a/crates/shirabe/src/package/version/version_bumper.rs b/crates/shirabe/src/package/version/version_bumper.rs index 6911fb14..50808916 100644 --- a/crates/shirabe/src/package/version/version_bumper.rs +++ b/crates/shirabe/src/package/version/version_bumper.rs @@ -5,8 +5,9 @@ use crate::package::dumper::ArrayDumper; use crate::package::loader::ArrayLoader; use crate::package::version::VersionParser; use crate::util::Platform; -use shirabe_pcre::{CaptureKey, Preg}; -use shirabe_php_shim::php_regex; +use shirabe_php_shim::{ + CaptureKey, php_regex, preg_match_all_offset_capture, preg_match2, preg_replace, +}; use shirabe_semver::Intervals; use shirabe_semver::constraint::AnyConstraint; @@ -45,12 +46,12 @@ impl VersionBumper { return Ok(pretty_constraint); } - let major = Preg::replace(php_regex!(r"{^([1-9][0-9]*|0\.\d+).*}"), "$1", &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); + preg_replace(php_regex!(r"{(?:\.(?:0|9999999))+(-dev)?$}"), "", &version); let new_pretty_constraint = format!("^{}", version_without_suffix); - if !Preg::is_match(php_regex!(r"{^\^\d+(\.\d+)*$}"), &new_pretty_constraint) { + if preg_match2(php_regex!(r"{^\^\d+(\.\d+)*$}"), &new_pretty_constraint, 0).is_none() { return Ok(pretty_constraint); } @@ -77,7 +78,7 @@ impl VersionBumper { major = major ); - let matches = Preg::is_match_all_with_offsets3(&pattern, &pretty_constraint); + let matches = preg_match_all_offset_capture(&pattern, &pretty_constraint); if matches.occurrence_count() > 0 { let mut modified = pretty_constraint.clone(); let constraint_matches = matches diff --git a/crates/shirabe/src/package/version/version_guesser.rs b/crates/shirabe/src/package/version/version_guesser.rs index c85000e7..fd7fe389 100644 --- a/crates/shirabe/src/package/version/version_guesser.rs +++ b/crates/shirabe/src/package/version/version_guesser.rs @@ -12,11 +12,10 @@ use crate::util::ProcessExecutor; use crate::util::Svn as SvnUtil; use crate::util::sync_executor; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::{ PhpMixed, RuntimeException, array_keys, array_map, array_merge, empty, function_exists, - implode, is_string, json_encode, php_regex, preg_quote, str_replace, strlen, strnatcasecmp, - strpos, substr, trim, usort, + implode, is_string, json_encode, php_regex, preg_match2, preg_quote, preg_replace, str_replace, + strlen, strnatcasecmp, strpos, substr, trim, usort, }; /// Seam over the parts of [`VersionGuesser`] that consumers depend on, so they can be exercised @@ -157,12 +156,14 @@ impl VersionGuesser { } if "-dev" == substr(version_data.version.as_deref().unwrap_or(""), -4, None) - && Preg::is_match( + && preg_match2( php_regex!(r"{\.9{7}}"), version_data.version.as_deref().unwrap_or(""), + 0, ) + .is_some() { - version_data.pretty_version = Some(Preg::replace( + version_data.pretty_version = Some(preg_replace( php_regex!(r"{(\.9{7})+}"), ".x", version_data.version.as_deref().unwrap_or(""), @@ -181,12 +182,14 @@ impl VersionGuesser { -4, None, ) - && Preg::is_match( + && preg_match2( php_regex!(r"{\.9{7}}"), version_data.feature_version.as_deref().unwrap_or(""), + 0, ) + .is_some() { - version_data.feature_pretty_version = Some(Preg::replace( + version_data.feature_pretty_version = Some(preg_replace( php_regex!(r"{(\.9{7})+}"), ".x", version_data.feature_version.as_deref().unwrap_or(""), @@ -229,11 +232,12 @@ impl VersionGuesser { // find current branch and collect all branch names for branch in self.process.borrow().split_lines(&output) { if !branch.is_empty() - && let Some(m) = Preg::is_match3( + && let Some(m) = preg_match2( php_regex!( r"{^(?:\* ) *(\(no branch\)|\(detached from \S+\)|\(HEAD detached at \S+\)|\S+) *([a-f0-9]+) .*$}" ), &branch, + 0, ) { let g1 = m.get(1).unwrap_or_default().to_string(); @@ -256,12 +260,13 @@ impl VersionGuesser { } if !branch.is_empty() - && Preg::is_match3(php_regex!(r"{^ *.+/HEAD }"), &branch).is_none() - && let Some(m) = Preg::is_match3( + && preg_match2(php_regex!(r"{^ *.+/HEAD }"), &branch, 0).is_none() + && let Some(m) = preg_match2( php_regex!( r"{^(?:\* )? *((?:remotes/(?:origin|upstream)/)?[^\s/]+) *([a-f0-9]+) .*$}" ), &branch, + 0, ) { branches.push(m.get(1).unwrap_or_default().to_string()); @@ -499,8 +504,7 @@ impl VersionGuesser { ) .is_some(); if !has_branch_alias || has_self_version { - let branch = - Preg::replace(php_regex!(r"{^dev-}"), "", version.as_deref().unwrap_or("")); + let branch = preg_replace(php_regex!(r"{^dev-}"), "", version.as_deref().unwrap_or("")); let mut length = i64::MAX; // return directly, if branch is configured to be non-feature branch @@ -534,7 +538,7 @@ impl VersionGuesser { for (index, candidate) in branches.iter().enumerate() { let index = index as i64; let candidate_version = - Preg::replace(php_regex!(r"{^remotes/\S+/}"), "", candidate); + preg_replace(php_regex!(r"{^remotes/\S+/}"), "", candidate); // do not compare against itself or other feature branches if candidate == &branch @@ -608,13 +612,10 @@ impl VersionGuesser { non_feature_branches = implode("|", &names); } - !Preg::is_match( - format!( - r"{{^({}|master|main|latest|next|current|support|tip|trunk|default|develop|\d+\..+)$}}", - non_feature_branches, - ), - branch_name.unwrap_or(""), - ) + preg_match2(format!( + r"{{^({}|master|main|latest|next|current|support|tip|trunk|default|develop|\d+\..+)$}}", + non_feature_branches, + ), branch_name.unwrap_or(""), 0).is_none() } fn guess_fossil_version(&mut self, path: &str) -> anyhow::Result { @@ -697,7 +698,7 @@ impl VersionGuesser { trunk_path, branches_path, tags_path, ); - if let Some(matches) = Preg::is_match3(&url_pattern, &output) { + if let Some(matches) = preg_match2(&url_pattern, &output, 0) { let m1 = matches.get(1).unwrap_or_default(); let m2 = matches.get(2); let m3 = matches.get(3); @@ -750,7 +751,7 @@ impl VersionGuesser { .into()); } }; - if let Some(m) = Preg::is_match3(php_regex!(r"{^(\d+(?:\.\d+)*)-dev$}i"), &version) { + if let Some(m) = preg_match2(php_regex!(r"{^(\d+(?:\.\d+)*)-dev$}i"), &version, 0) { return Ok(format!("{}.x-dev", m.get(1).unwrap_or_default())); } diff --git a/crates/shirabe/src/package/version/version_parser.rs b/crates/shirabe/src/package/version/version_parser.rs index c16583e0..ad1a05cf 100644 --- a/crates/shirabe/src/package/version/version_parser.rs +++ b/crates/shirabe/src/package/version/version_parser.rs @@ -2,8 +2,7 @@ use crate::repository::PlatformRepository; use indexmap::IndexMap; -use shirabe_pcre::Preg; -use shirabe_php_shim::php_regex; +use shirabe_php_shim::{php_regex, preg_match2, preg_replace}; use shirabe_semver::Semver; use shirabe_semver::VersionParser as SemverVersionParser; use shirabe_semver::constraint::AnyConstraint; @@ -50,7 +49,7 @@ impl VersionParser { let count = pairs.len(); let mut i = 0_usize; while i < count { - let mut pair = Preg::replace( + let mut pair = preg_replace( php_regex!(r"{^([^=: ]+)[=: ](.*)$}"), "$1 $2", pairs[i].trim(), @@ -58,10 +57,12 @@ impl VersionParser { if !pair.contains(' ') && i + 1 < count && !pairs[i + 1].contains('/') - && !Preg::is_match( + && preg_match2( php_regex!(r"{(?<=[a-z0-9_/-])\*|\*(?=[a-z0-9_/-])}i"), &pairs[i + 1], + 0, ) + .is_none() && !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 1661c749..c7b7b31e 100644 --- a/crates/shirabe/src/package/version/version_selector.rs +++ b/crates/shirabe/src/package/version/version_selector.rs @@ -16,8 +16,7 @@ use crate::repository::PlatformRepository; use crate::repository::RepositoryInterface; use crate::repository::RepositorySetInterface; use indexmap::IndexMap; -use shirabe_pcre::Preg; -use shirabe_php_shim::{CmpOp, php_regex, strtolower, version_compare}; +use shirabe_php_shim::{CmpOp, php_regex, preg_match2, preg_replace, strtolower, version_compare}; use shirabe_semver::constraint::AnyConstraint; use shirabe_semver::constraint::SimpleConstraint; @@ -280,7 +279,7 @@ impl VersionSelector { if let Some(extra) = extra && extra != VersionParser::DEFAULT_BRANCH_ALIAS { - let new_extra = Preg::replace( + let new_extra = preg_replace( php_regex!(r"{^(\d+\.\d+\.\d+)(\.9999999)-dev$}"), "$1.0", &extra, @@ -303,7 +302,7 @@ impl VersionSelector { let semantic_version_parts: Vec<&str> = version.split('.').collect(); if semantic_version_parts.len() == 4 - && Preg::is_match(php_regex!(r"{^\d+\D?}"), semantic_version_parts[3]) + && preg_match2(php_regex!(r"{^\d+\D?}"), semantic_version_parts[3], 0).is_some() { let mut parts: Vec = semantic_version_parts .iter() diff --git a/crates/shirabe/src/platform/version.rs b/crates/shirabe/src/platform/version.rs index 00ff3097..baa029ef 100644 --- a/crates/shirabe/src/platform/version.rs +++ b/crates/shirabe/src/platform/version.rs @@ -1,7 +1,6 @@ //! ref: composer/src/Composer/Platform/Version.php -use shirabe_pcre::Preg; -use shirabe_php_shim::{CmpOp, php_regex, version_compare}; +use shirabe_php_shim::{CmpOp, php_regex, preg_match2, version_compare}; pub struct Version; @@ -9,11 +8,12 @@ impl Version { pub fn parse_openssl(openssl_version: &str, is_fips: &mut bool) -> Option { *is_fips = false; - let matches = Preg::match3( + let matches = preg_match2( php_regex!( r"/^(?P[0-9.]+)(?P[a-z]{0,2})(?P(?:-?(?:dev|pre|alpha|beta|rc|fips)[\d]*)*)(?:-\w+)?(?: \(.+?\))?$/" ), openssl_version, + 0, )?; let version = matches.name("version").unwrap_or_default().to_string(); @@ -42,9 +42,10 @@ impl Version { } pub fn parse_libjpeg(libjpeg_version: &str) -> Option { - let matches = Preg::match3( + let matches = preg_match2( php_regex!(r"/^(?P\d+)(?P[a-z]*)$/"), libjpeg_version, + 0, )?; let major = matches.name("major").unwrap_or_default().to_string(); @@ -57,9 +58,10 @@ impl Version { } pub fn parse_zoneinfo_version(zoneinfo_version: &str) -> Option { - let matches = Preg::match3( + let matches = preg_match2( php_regex!(r"/^(?P\d{4})(?P[a-z]*)$/"), zoneinfo_version, + 0, )?; let year = matches.name("year").unwrap_or_default().to_string(); diff --git a/crates/shirabe/src/plugin/plugin_manager.rs b/crates/shirabe/src/plugin/plugin_manager.rs index 0ebc56e6..5c2c5bff 100644 --- a/crates/shirabe/src/plugin/plugin_manager.rs +++ b/crates/shirabe/src/plugin/plugin_manager.rs @@ -25,12 +25,11 @@ use crate::repository::RepositoryUtils; use crate::repository::RootPackageRepository; use crate::util::PackageSorter; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_rpc::{PluginValue, call_function_with_dispatcher}; use shirabe_php_shim::{ CmpOp, E_USER_DEPRECATED, PhpMixed, RuntimeException, UnexpectedValueException, dirname, empty, - file_get_contents, implode, ksort, php_regex, preg_quote, strrpos, strtr_array, substr, - trigger_error, trim, var_export, var_export_str, version_compare, + file_get_contents, implode, ksort, php_regex, preg_match2, preg_quote, preg_replace2, strrpos, + strtr_array, substr, trigger_error, trim, var_export, var_export_str, version_compare, }; use shirabe_semver::constraint::SimpleConstraint; @@ -260,7 +259,7 @@ impl PluginManager { } if package.get_name() == "symfony/flex" - && Preg::is_match3(php_regex!("{^[0-9.]+$}"), &package.get_version()).is_some() + && preg_match2(php_regex!("{^[0-9.]+$}"), &package.get_version(), 0).is_some() && version_compare(&package.get_version(), "1.9.8", CmpOp::Lt) { self.io.write_error(&format!("The \"{}\" plugin {}was skipped because it is not compatible with Composer 2+. Make sure to update it to version 1.9.8 or greater.", @@ -448,7 +447,7 @@ impl PluginManager { { class_name = substr(&class, (separator_pos + 1) as i64, None); } - let code = Preg::replace4( + let code = preg_replace2( format!( "{{^((?:(?:final|readonly)\\s+)*(?:\\s*))class\\s+({})}}mi", preg_quote(&class_name, None) @@ -456,13 +455,14 @@ impl PluginManager { &format!("$1class $2_composer_tmp{}", class_counter), &code, 1, + None, ); let mut replacements: IndexMap = IndexMap::new(); replacements.insert("__FILE__".to_string(), var_export_str(&path, true)); replacements.insert("__DIR__".to_string(), var_export_str(&dirname(&path), true)); replacements.insert("__CLASS__".to_string(), var_export_str(&class, true)); let code = strtr_array(&code, &replacements); - let code = Preg::replace4(r"/^\s*<\?(php)?/i", "", &code, 1); + let code = preg_replace2(r"/^\s*<\?(php)?/i", "", &code, 1, None); self.php_runtime_eval(&code)?; class = format!("{}_composer_tmp{}", class, class_counter); CLASS_COUNTER.store(class_counter + 1, std::sync::atomic::Ordering::Relaxed); @@ -1242,7 +1242,7 @@ impl PluginManager { .map(|(k, v)| (k.clone(), *v)) .collect(); for (pattern, allow) in &rules_snapshot { - if Preg::is_match3(pattern, package).is_some() { + if preg_match2(pattern, package, 0).is_some() { return Ok(*allow); } } diff --git a/crates/shirabe/src/question/strict_confirmation_question.rs b/crates/shirabe/src/question/strict_confirmation_question.rs index 107b9c25..f1240336 100644 --- a/crates/shirabe/src/question/strict_confirmation_question.rs +++ b/crates/shirabe/src/question/strict_confirmation_question.rs @@ -1,7 +1,6 @@ //! ref: composer/src/Composer/Question/StrictConfirmationQuestion.php -use shirabe_pcre::Preg; -use shirabe_php_shim::{PhpMixed, empty, is_bool}; +use shirabe_php_shim::{PhpMixed, empty, is_bool, preg_match2}; use shirabe_symfony_console::exception::InvalidArgumentException; use shirabe_symfony_console::question::Question; use shirabe_symfony_console::question::QuestionInterface; @@ -54,10 +53,10 @@ impl StrictConfirmationQuestion { return default.clone(); } if let PhpMixed::String(s) = &answer { - if Preg::is_match(&true_regex, s) { + if preg_match2(&true_regex, s, 0).is_some() { return PhpMixed::Bool(true); } - if Preg::is_match(&false_regex, s) { + if preg_match2(&false_regex, s, 0).is_some() { return PhpMixed::Bool(false); } } diff --git a/crates/shirabe/src/repository/array_repository.rs b/crates/shirabe/src/repository/array_repository.rs index 0f3dc237..2e364d0e 100644 --- a/crates/shirabe/src/repository/array_repository.rs +++ b/crates/shirabe/src/repository/array_repository.rs @@ -12,8 +12,7 @@ use crate::repository::{ RepositoryInterfaceHandle, RepositoryInterfaceWeakHandle, SearchResult, }; use indexmap::IndexMap; -use shirabe_pcre::Preg; -use shirabe_php_shim::{implode, php_regex, preg_quote, preg_split, strtolower}; +use shirabe_php_shim::{implode, php_regex, preg_match2, preg_quote, preg_split, strtolower}; use shirabe_semver::constraint::AnyConstraint; use shirabe_semver::constraint::SimpleConstraint; use std::rc::Weak; @@ -358,7 +357,7 @@ impl RepositoryInterface for ArrayRepository { let fulltext_match = mode == crate::repository::SEARCH_FULLTEXT && complete.is_some() - && Preg::is_match( + && preg_match2( ®ex, &format!( "{} {}", @@ -369,9 +368,11 @@ impl RepositoryInterface for ArrayRepository { .get_description() .unwrap_or_default() ), - ); + 0, + ) + .is_some(); - if Preg::is_match(®ex, &name) || fulltext_match { + if preg_match2(®ex, &name, 0).is_some() || fulltext_match { if mode == crate::repository::SEARCH_VENDOR { matches.insert( name.clone(), diff --git a/crates/shirabe/src/repository/composer_repository.rs b/crates/shirabe/src/repository/composer_repository.rs index 8970a227..9f6e6bf8 100644 --- a/crates/shirabe/src/repository/composer_repository.rs +++ b/crates/shirabe/src/repository/composer_repository.rs @@ -37,14 +37,13 @@ use futures::StreamExt; use futures::stream::FuturesOrdered; use indexmap::IndexMap; use shirabe_metadata_minifier::MetadataMinifier; -use shirabe_pcre::Preg; -use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ AnyThrowable, CmpOp, InvalidArgumentException, LogicException, PHP_EOL, PhpMixed, RuntimeException, UnexpectedValueException, extension_loaded, hash, http_build_query_mixed, json_decode_assoc, parse_url, php_regex, preg_split, realpath, strtolower, strtr, urlencode, var_export, }; +use shirabe_php_shim::{Catch as _, preg_grep, preg_match2, preg_replace}; use shirabe_semver::CompilingMatcher; use shirabe_semver::constraint::AnyConstraint; use shirabe_semver::constraint::MatchAllConstraint; @@ -162,7 +161,7 @@ impl ComposerRepository { .and_then(|v| v.as_string()) .unwrap_or("") .to_string(); - if !Preg::is_match(php_regex!(r"{^[\w.]+\??://}"), &url_str) { + if preg_match2(php_regex!(r"{^[\w.]+\??://}"), &url_str, 0).is_none() { if let Some(local_file_path) = realpath(&url_str) { // it is a local path, add file scheme repo_config.insert( @@ -245,9 +244,10 @@ impl ComposerRepository { .to_string(); // force url for packagist.org to repo.packagist.org - if let Some(match_packagist) = Preg::is_match3( + if let Some(match_packagist) = preg_match2( php_regex!(r"{^(?Phttps?)://packagist\.org/?$}i"), &url, + 0, ) { let proto = match_packagist .name("proto") @@ -257,14 +257,14 @@ impl ComposerRepository { } let base_url_trimmed = - Preg::replace(php_regex!(r"{(?:/[^/\\]+\.json)?(?:[?#].*)?$}"), "", &url); + preg_replace(php_regex!(r"{(?:/[^/\\]+\.json)?(?:[?#].*)?$}"), "", &url); let base_url = base_url_trimmed.trim_end_matches('/').to_string(); assert!(!base_url.is_empty()); let cache_dir = format!( "{}/{}", config.get("cache-repo-dir").as_string().unwrap_or(""), - Preg::replace(r"{[^a-z0-9.]}i", "-", &Url::sanitize(url.clone())), + preg_replace(r"{[^a-z0-9.]}i", "-", &Url::sanitize(url.clone())), ); let cache = Cache::new(io.clone(), &cache_dir, Some("a-z0-9.$~"), None, false); let version_parser = VersionParser::new(); @@ -429,7 +429,7 @@ impl ComposerRepository { }; let filter_results = |results: Vec| -> anyhow::Result> { match &package_filter_regex { - Some(regex) => Ok(Preg::grep(regex, results).collect()), + Some(regex) => Ok(preg_grep(regex, results).collect()), None => Ok(results), } }; @@ -767,7 +767,7 @@ impl ComposerRepository { let regex = format!("{{(?:{})}}i", parts.join("|")); let vendor_names = self.get_vendor_names()?; - for name in Preg::grep(®ex, vendor_names) { + for name in preg_grep(®ex, vendor_names) { let mut entry = IndexMap::new(); entry.insert("name".to_string(), PhpMixed::String(name)); entry.insert("description".to_string(), PhpMixed::String(String::new())); @@ -779,9 +779,10 @@ impl ComposerRepository { if self.has_providers()? || self.lazy_providers_url.is_some() { // optimize search for "^foo/bar" where at least "^foo/" is present by loading this directly from the listUrl if present - if let Some(match_groups) = Preg::is_match3( + if let Some(match_groups) = preg_match2( php_regex!(r"{^\^(?P(?P[a-z0-9_.-]+)/[a-z0-9_.-]*)\*?$}i"), &query, + 0, ) && let Some(list_url) = self.list_url.as_ref() { let q = match_groups.name("query").unwrap_or_default().to_string(); @@ -823,7 +824,7 @@ impl ComposerRepository { let regex = format!("{{(?:{})}}i", parts.join("|")); let package_names = self.get_package_names(None)?; - for name in Preg::grep(®ex, package_names) { + for name in preg_grep(®ex, package_names) { let mut entry = IndexMap::new(); entry.insert("name".to_string(), PhpMixed::String(name)); entry.insert("description".to_string(), PhpMixed::String(String::new())); @@ -1735,7 +1736,7 @@ impl ComposerRepository { .into_iter() .filter_map(|(name, constraint)| { let name = strtolower(&name); - let real_name = Preg::replace(php_regex!(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 @@ -2420,7 +2421,7 @@ impl ComposerRepository { } if url.starts_with('/') { - if let Some(matches) = Preg::is_match3(php_regex!(r"{^[^:]++://[^/]*+}"), &self.url) { + if let Some(matches) = preg_match2(php_regex!(r"{^[^:]++://[^/]*+}"), &self.url, 0) { return Ok(format!("{}{}", matches.get(0).unwrap_or_default(), url)); } @@ -2709,7 +2710,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(php_regex!(r"{^https?://}i"), &filename) + && preg_match2(php_regex!(r"{^https?://}i"), &filename, 0).is_some() { filename = format!("{}%24{}", &filename[..pos], &filename[pos + 1..]); } @@ -3308,7 +3309,7 @@ impl ComposerRepository { if let Some(ref patterns) = self.available_package_patterns { for provider_regex in patterns.iter() { - if Preg::is_match(provider_regex, name) { + if preg_match2(provider_regex, name, 0).is_some() { return Ok(true); } } diff --git a/crates/shirabe/src/repository/filter_repository.rs b/crates/shirabe/src/repository/filter_repository.rs index 0f6f7526..3b36a969 100644 --- a/crates/shirabe/src/repository/filter_repository.rs +++ b/crates/shirabe/src/repository/filter_repository.rs @@ -9,8 +9,7 @@ use crate::repository::{ RepositoryInterfaceHandle, SearchResult, }; use indexmap::IndexMap; -use shirabe_pcre::Preg; -use shirabe_php_shim::{InvalidArgumentException, PhpMixed}; +use shirabe_php_shim::{InvalidArgumentException, PhpMixed, preg_match2}; use shirabe_semver::constraint::AnyConstraint; #[derive(Debug)] @@ -124,14 +123,14 @@ impl FilterRepository { } if let Some(only) = &self.only { - return Preg::is_match(only, name); + return preg_match2(only, name, 0).is_some(); } if self.exclude.is_none() { return true; } - !Preg::is_match(self.exclude.as_ref().unwrap(), name) + preg_match2(self.exclude.as_ref().unwrap(), name, 0).is_none() } } diff --git a/crates/shirabe/src/repository/package_repository.rs b/crates/shirabe/src/repository/package_repository.rs index 1016ee7f..ef1eb59f 100644 --- a/crates/shirabe/src/repository/package_repository.rs +++ b/crates/shirabe/src/repository/package_repository.rs @@ -15,8 +15,7 @@ use crate::repository::{ RepositoryInterface, SearchResult, SecurityAdvisoryResult, }; use indexmap::IndexMap; -use shirabe_pcre::Preg; -use shirabe_php_shim::{PhpMixed, RuntimeException, php_regex, var_export}; +use shirabe_php_shim::{PhpMixed, RuntimeException, php_regex, preg_replace, var_export}; use shirabe_semver::constraint::AnyConstraint; #[derive(Debug)] @@ -85,7 +84,7 @@ impl PackageRepository { // PHP: parent::getRepoName() counts through the late-bound $this->initialize(), // which resolves to PackageRepository::initialize (loading the config packages). self.ensure_initialized()?; - Ok(Preg::replace( + Ok(preg_replace( php_regex!(r"{^array }"), "package ", &self.inner.get_repo_name()?, diff --git a/crates/shirabe/src/repository/path_repository.rs b/crates/shirabe/src/repository/path_repository.rs index 680911eb..77cc0222 100644 --- a/crates/shirabe/src/repository/path_repository.rs +++ b/crates/shirabe/src/repository/path_repository.rs @@ -23,10 +23,9 @@ use crate::util::Platform; use crate::util::ProcessExecutor; use crate::util::Url; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::{ GLOB_BRACE, GLOB_MARK, GLOB_ONLYDIR, PhpMixed, RuntimeException, defined, file_exists, - file_get_contents, glob_with_flags, hash, php_regex, realpath, serialize, + file_get_contents, glob_with_flags, hash, php_regex, preg_match2, realpath, serialize, }; #[derive(Debug)] @@ -159,9 +158,9 @@ impl PathRepository { let url_matches = self.get_url_matches()?; if url_matches.is_empty() { - if Preg::is_match(php_regex!(r"{[*{}]}"), &self.url) { + if preg_match2(php_regex!(r"{[*{}]}"), &self.url, 0).is_some() { let mut url = self.url.clone(); - while Preg::is_match(php_regex!(r"{[*{}]}"), &url) { + while preg_match2(php_regex!(r"{[*{}]}"), &url, 0).is_some() { 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 3df346de..4ded0163 100644 --- a/crates/shirabe/src/repository/platform_repository.rs +++ b/crates/shirabe/src/repository/platform_repository.rs @@ -16,12 +16,11 @@ use crate::plugin::plugin_interface::{self}; use crate::repository::ArrayRepository; use crate::repository::RepositoryInterface; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_rpc::PlatformInfo; use shirabe_php_shim::{ InvalidArgumentException, PhpMixed, UnexpectedValueException, array_map_str_fn, - array_slice_strs, explode, get_class, implode, is_string, php_regex, str_replace, strpos, - strtolower, var_export, + array_slice_strs, explode, get_class, implode, is_string, php_regex, preg_match2, preg_replace, + str_replace, strpos, strtolower, var_export, }; use shirabe_semver::constraint::SimpleConstraint; use std::sync::{LazyLock, Mutex}; @@ -221,7 +220,7 @@ impl PlatformRepository { } Err(_) => { pretty_version = - Preg::replace(php_regex!("#^([^~+-]+).*$#"), "$1", &php_version_str); + preg_replace(php_regex!("#^([^~+-]+).*$#"), "$1", &php_version_str); version = self .version_parser .as_ref() @@ -316,9 +315,10 @@ impl PlatformRepository { let info = platform_info.get_extension_info(name); // librabbitmq version => 0.9.0 - if let Some(librabbitmq_matches) = Preg::is_match3( + if let Some(librabbitmq_matches) = preg_match2( php_regex!("/^librabbitmq version => (?.+)$/im"), info, + 0, ) { self.add_library( &mut libraries, @@ -331,9 +331,10 @@ impl PlatformRepository { } // AMQP protocol version => 0-9-1 - if let Some(protocol_matches) = Preg::is_match3( + if let Some(protocol_matches) = preg_match2( php_regex!("/^AMQP protocol version => (?.+)$/im"), info, + 0, ) { let version_str = protocol_matches .name("version") @@ -355,7 +356,7 @@ impl PlatformRepository { // BZip2 Version => 1.0.6, 6-Sept-2010 if let Some(matches) = - Preg::is_match3(php_regex!("/^BZip2 Version => (?.*),/im"), info) + preg_match2(php_regex!("/^BZip2 Version => (?.*),/im"), info, 0) { self.add_library( &mut libraries, @@ -382,9 +383,10 @@ impl PlatformRepository { let info = platform_info.get_extension_info(name); // SSL Version => OpenSSL/1.0.1t - if let Some(ssl_matches) = Preg::is_match3( + if let Some(ssl_matches) = preg_match2( php_regex!("{^SSL Version => (?[^/]+)/(?.+)$}im"), info, + 0, ) { let ssl_library_raw = ssl_matches.name("library").unwrap_or_default().to_string(); @@ -411,9 +413,10 @@ impl PlatformRepository { } else { let (shortlib, ssl_lib); if library.starts_with("(securetransport)") { - if let Some(securetransport_matches) = Preg::is_match3( + if let Some(securetransport_matches) = preg_match2( php_regex!("{^\\(securetransport\\) ([a-z0-9]+)}"), &library, + 0, ) { shortlib = "securetransport".to_string(); let m1 = securetransport_matches @@ -441,11 +444,12 @@ impl PlatformRepository { } // libSSH Version => libssh2/1.4.3 - if let Some(ssh_matches) = Preg::is_match3( + if let Some(ssh_matches) = preg_match2( php_regex!( "{^libSSH Version => (?[^/]+)/(?.+?)(?:/.*)?$}im" ), info, + 0, ) { let ssh_library = ssh_matches.name("library").unwrap_or_default().to_string(); @@ -463,7 +467,7 @@ impl PlatformRepository { // ZLib Version => 1.2.8 if let Some(zlib_matches) = - Preg::is_match3(php_regex!("{^ZLib Version => (?.+)$}im"), info) + preg_match2(php_regex!("{^ZLib Version => (?.+)$}im"), info, 0) { self.add_library( &mut libraries, @@ -480,9 +484,11 @@ impl PlatformRepository { let info = platform_info.get_extension_info(name); // timelib version => 2018.03 - if let Some(timelib_matches) = - Preg::is_match3(php_regex!("/^timelib version => (?.+)$/im"), info) - { + if let Some(timelib_matches) = preg_match2( + php_regex!("/^timelib version => (?.+)$/im"), + info, + 0, + ) { self.add_library( &mut libraries, &format!("{}-timelib", name), @@ -494,19 +500,21 @@ impl PlatformRepository { } // Timezone Database => internal - if let Some(zoneinfo_source_matches) = Preg::is_match3( + if let Some(zoneinfo_source_matches) = preg_match2( php_regex!("/^Timezone Database => (?internal|external)$/im"), info, + 0, ) { let external = zoneinfo_source_matches .name("source") .map(|s| s == "external") .unwrap_or(false); - if let Some(zoneinfo_matches) = Preg::is_match3( + if let Some(zoneinfo_matches) = preg_match2( php_regex!( "/^\"Olson\" Timezone Database Version => (?.+?)(?:\\.system)?$/im" ), info, + 0, ) { let zoneinfo_version = zoneinfo_matches .name("version") @@ -543,7 +551,7 @@ impl PlatformRepository { // libmagic => 537 if let Some(magic_matches) = - Preg::is_match3(php_regex!("/^libmagic => (?.+)$/im"), info) + preg_match2(php_regex!("/^libmagic => (?.+)$/im"), info, 0) { self.add_library( &mut libraries, @@ -573,9 +581,10 @@ impl PlatformRepository { let info = platform_info.get_extension_info(name); - if let Some(libjpeg_matches) = Preg::is_match3( + if let Some(libjpeg_matches) = preg_match2( php_regex!("/^libJPEG Version => (?.+?)(?: compatible)?$/im"), info, + 0, ) { let libjpeg_version = libjpeg_matches .name("version") @@ -592,9 +601,11 @@ impl PlatformRepository { )?; } - if let Some(libpng_matches) = - Preg::is_match3(php_regex!("/^libPNG Version => (?.+)$/im"), info) - { + if let Some(libpng_matches) = preg_match2( + php_regex!("/^libPNG Version => (?.+)$/im"), + info, + 0, + ) { self.add_library( &mut libraries, &format!("{}-libpng", name), @@ -605,9 +616,10 @@ impl PlatformRepository { )?; } - if let Some(freetype_matches) = Preg::is_match3( + if let Some(freetype_matches) = preg_match2( php_regex!("/^FreeType Version => (?.+)$/im"), info, + 0, ) { self.add_library( &mut libraries, @@ -619,9 +631,10 @@ impl PlatformRepository { )?; } - if let Some(libxpm_matches) = Preg::is_match3( + if let Some(libxpm_matches) = preg_match2( php_regex!("/^libXpm Version => (?\\d+)$/im"), info, + 0, ) { let version_id: i64 = libxpm_matches .name("versionId") @@ -692,7 +705,7 @@ impl PlatformRepository { )?; } else { if let Some(matches) = - Preg::is_match3(php_regex!("/^ICU version => (?.+)$/im"), info) + preg_match2(php_regex!("/^ICU version => (?.+)$/im"), info, 0) { self.add_library( &mut libraries, @@ -706,9 +719,10 @@ impl PlatformRepository { } // ICU TZData version => 2019c - if let Some(zoneinfo_matches) = Preg::is_match3( + if let Some(zoneinfo_matches) = preg_match2( php_regex!("/^ICU TZData version => (?.*)$/im"), info, + 0, ) { let zi_version = zoneinfo_matches .name("version") @@ -769,9 +783,10 @@ impl PlatformRepository { Self::imagick_get_version_string(image_magick_version); // 6.x: ImageMagick 6.2.9 08/24/06 Q16 http://www.imagemagick.org // 7.x: ImageMagick 7.0.8-34 Q16 x86_64 2019-03-23 https://imagemagick.org - if let Some(matches) = Preg::is_match3( + if let Some(matches) = preg_match2( php_regex!("/^ImageMagick (?[\\d.]+)(?:-(?\\d+))?/"), &image_magick_version_str, + 0, ) { let mut version_built = matches.name("version").unwrap_or_default().to_string(); @@ -793,11 +808,12 @@ impl PlatformRepository { "ldap" => { let info = platform_info.get_extension_info(name); - if let Some(matches) = Preg::is_match3( + if let Some(matches) = preg_match2( php_regex!("/^Vendor Version => (?\\d+)$/im"), info, + 0, ) && let Some(vendor_matches) = - Preg::is_match3(php_regex!("/^Vendor Name => (?.+)$/im"), info) + preg_match2(php_regex!("/^Vendor Name => (?.+)$/im"), info, 0) { let version_id: i64 = matches .name("versionId") @@ -848,9 +864,11 @@ impl PlatformRepository { let info = platform_info.get_extension_info(name); // libmbfl version => 1.3.2 - if let Some(libmbfl_matches) = - Preg::is_match3(php_regex!("/^libmbfl version => (?.+)$/im"), info) - { + if let Some(libmbfl_matches) = preg_match2( + php_regex!("/^libmbfl version => (?.+)$/im"), + info, + 0, + ) { self.add_library( &mut libraries, &format!("{}-libmbfl", name), @@ -879,11 +897,12 @@ impl PlatformRepository { // Multibyte regex (oniguruma) version => 5.9.5 // oniguruma version => 6.9.0 } else { - if let Some(oniguruma_matches) = Preg::is_match3( + if let Some(oniguruma_matches) = preg_match2( php_regex!( "/^(?:oniguruma|Multibyte regex \\(oniguruma\\)) version => (?.+)$/im" ), info, + 0, ) { self.add_library( &mut libraries, @@ -901,9 +920,10 @@ impl PlatformRepository { let info = platform_info.get_extension_info(name); // libmemcached version => 1.0.18 - if let Some(matches) = Preg::is_match3( + if let Some(matches) = preg_match2( php_regex!("/^libmemcached version => (?.+)$/im"), info, + 0, ) { self.add_library( &mut libraries, @@ -923,9 +943,10 @@ impl PlatformRepository { _ => "".to_string(), }; // OpenSSL 1.1.1g 21 Apr 2020 - if let Some(matches) = Preg::is_match3( + if let Some(matches) = preg_match2( php_regex!("{^(?:OpenSSL|LibreSSL)?\\s*(?\\S+)}i"), &openssl_text_str, + 0, ) { let version = matches.name("version").unwrap_or_default().to_string(); let mut is_fips = false; @@ -952,16 +973,16 @@ impl PlatformRepository { PhpMixed::String(s) => s.clone(), _ => "".to_string(), }; - let stripped = - Preg::replace(php_regex!("{^(\\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 = platform_info.get_extension_info(name); // PCRE Unicode Version => 12.1.0 - if let Some(pcre_unicode_matches) = Preg::is_match3( + if let Some(pcre_unicode_matches) = preg_match2( php_regex!("/^PCRE Unicode Version => (?.+)$/im"), info, + 0, ) { self.add_library( &mut libraries, @@ -977,11 +998,12 @@ impl PlatformRepository { "mysqlnd" | "pdo_mysql" => { let info = platform_info.get_extension_info(name); - if let Some(matches) = Preg::is_match3( + if let Some(matches) = preg_match2( php_regex!( "/^(?:Client API version|Version) => mysqlnd (?.+?) /mi" ), info, + 0, ) { self.add_library( &mut libraries, @@ -997,9 +1019,10 @@ impl PlatformRepository { "mongodb" => { let info = platform_info.get_extension_info(name); - if let Some(libmongoc_matches) = Preg::is_match3( + if let Some(libmongoc_matches) = preg_match2( php_regex!("/^libmongoc bundled version => (?.+)$/im"), info, + 0, ) { self.add_library( &mut libraries, @@ -1011,9 +1034,10 @@ impl PlatformRepository { )?; } - if let Some(libbson_matches) = Preg::is_match3( + if let Some(libbson_matches) = preg_match2( php_regex!("/^libbson bundled version => (?.+)$/im"), info, + 0, ) { self.add_library( &mut libraries, @@ -1045,9 +1069,10 @@ impl PlatformRepository { // intentional fall-through to next case... let info = platform_info.get_extension_info(name); - if let Some(matches) = Preg::is_match3( + if let Some(matches) = preg_match2( php_regex!("/^PostgreSQL\\(libpq\\) Version => (?.*)$/im"), info, + 0, ) { self.add_library( &mut libraries, @@ -1064,9 +1089,10 @@ impl PlatformRepository { "pdo_pgsql" => { let info = platform_info.get_extension_info(name); - if let Some(matches) = Preg::is_match3( + if let Some(matches) = preg_match2( php_regex!("/^PostgreSQL\\(libpq\\) Version => (?.*)$/im"), info, + 0, ) { self.add_library( &mut libraries, @@ -1084,9 +1110,10 @@ impl PlatformRepository { // Used Library => Compiled => Linked // libpq => 14.3 (Ubuntu 14.3-1.pgdg22.04+1) => 15.0.2 - if let Some(matches) = Preg::is_match3( + if let Some(matches) = preg_match2( php_regex!("/^libpq => (?.+) => (?.+)$/im"), info, + 0, ) { self.add_library( &mut libraries, @@ -1158,9 +1185,11 @@ impl PlatformRepository { "sqlite3" | "pdo_sqlite" => { let info = platform_info.get_extension_info(name); - if let Some(matches) = - Preg::is_match3(php_regex!("/^SQLite Library => (?.+)$/im"), info) - { + if let Some(matches) = preg_match2( + php_regex!("/^SQLite Library => (?.+)$/im"), + info, + 0, + ) { self.add_library( &mut libraries, &format!("{}-sqlite", name), @@ -1175,9 +1204,11 @@ impl PlatformRepository { "ssh2" => { let info = platform_info.get_extension_info(name); - if let Some(matches) = - Preg::is_match3(php_regex!("/^libssh2 version => (?.+)$/im"), info) - { + if let Some(matches) = preg_match2( + php_regex!("/^libssh2 version => (?.+)$/im"), + info, + 0, + ) { self.add_library( &mut libraries, &format!("{}-libssh2", name), @@ -1206,11 +1237,12 @@ impl PlatformRepository { )?; let info = platform_info.get_extension_info("xsl"); - if let Some(matches) = Preg::is_match3( + if let Some(matches) = preg_match2( php_regex!( "/^libxslt compiled against libxml Version => (?.+)$/im" ), info, + 0, ) { self.add_library( &mut libraries, @@ -1226,9 +1258,11 @@ impl PlatformRepository { "yaml" => { let info = platform_info.get_extension_info("yaml"); - if let Some(matches) = - Preg::is_match3(php_regex!("/^LibYAML Version => (?.+)$/im"), info) - { + if let Some(matches) = preg_match2( + php_regex!("/^LibYAML Version => (?.+)$/im"), + info, + 0, + ) { self.add_library( &mut libraries, &format!("{}-libyaml", name), @@ -1278,9 +1312,10 @@ impl PlatformRepository { // Linked Version => 1.2.8 } else { let info = platform_info.get_extension_info(name); - if let Some(matches) = Preg::is_match3( + if let Some(matches) = preg_match2( php_regex!("/^Linked Version => (?.+)$/im"), info, + 0, ) { self.add_library( &mut libraries, @@ -1313,7 +1348,7 @@ impl PlatformRepository { } Err(_) => { pretty_version = - Preg::replace(php_regex!("#^([^~+-]+).*$#"), "$1", &hhvm_version); + preg_replace(php_regex!("#^([^~+-]+).*$#"), "$1", &hhvm_version); version = self .version_parser .as_ref() @@ -1477,9 +1512,10 @@ impl PlatformRepository { Ok(v) => v, Err(_) => { extra_description = Some(format!(" (actual version: {})", pretty_version)); - if let Some(m) = Preg::is_match3( + if let Some(m) = preg_match2( php_regex!("{^(\\d+\\.\\d+\\.\\d+(?:\\.\\d+)?)}"), &pretty_version, + 0, ) { pretty_version = m.get(1).unwrap_or_default().to_string(); } else { @@ -1608,7 +1644,7 @@ impl PlatformRepository { return cached; } - let result = Preg::is_match(Self::PLATFORM_PACKAGE_REGEX, name); + let result = preg_match2(Self::PLATFORM_PACKAGE_REGEX, name, 0).is_some(); cache.insert(name.to_string(), result); result } diff --git a/crates/shirabe/src/repository/repository_factory.rs b/crates/shirabe/src/repository/repository_factory.rs index 279fafc5..cd492628 100644 --- a/crates/shirabe/src/repository/repository_factory.rs +++ b/crates/shirabe/src/repository/repository_factory.rs @@ -12,10 +12,9 @@ use crate::repository::RepositoryManagerInterface; use crate::util::HttpDownloader; use crate::util::ProcessExecutor; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::{ InvalidArgumentException, PhpMixed, UnexpectedValueException, get_debug_type, json_encode, - php_regex, php_to_string, + php_regex, php_to_string, preg_replace, }; pub struct RepositoryFactory; @@ -302,7 +301,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(php_regex!("{^https?://}i"), "", url) + preg_replace(php_regex!("{^https?://}i"), "", url) } else { php_to_string(index) }; @@ -318,7 +317,7 @@ impl RepositoryFactory { existing_repos: &IndexMap, ) -> String { let mut name = if let Some(url) = repo.get("url").and_then(|v| v.as_string()) { - Preg::replace(php_regex!("{^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 8047602a..90480add 100644 --- a/crates/shirabe/src/repository/vcs/forgejo_driver.rs +++ b/crates/shirabe/src/repository/vcs/forgejo_driver.rs @@ -15,10 +15,10 @@ use crate::util::ForgejoRepositoryData; use crate::util::ForgejoUrl; use crate::util::http::Response; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ - PhpMixed, RuntimeException, base64_decode, explode, extension_loaded, php_regex, urlencode, + PhpMixed, RuntimeException, base64_decode, explode, extension_loaded, php_regex, preg_match2, + urlencode, }; #[derive(Debug)] @@ -584,7 +584,7 @@ impl ForgejoDriver { let links = explode(",", &header); for link in links { - if let Some(m) = Preg::match3(php_regex!(r#"{<(.+?)>; *rel="next"}"#), &link) + if let Some(m) = preg_match2(php_regex!(r#"{<(.+?)>; *rel="next"}"#), &link, 0) && let Some(url) = m.get(1) { return Some(url.to_string()); diff --git a/crates/shirabe/src/repository/vcs/fossil_driver.rs b/crates/shirabe/src/repository/vcs/fossil_driver.rs index 8ce479fd..c42ca271 100644 --- a/crates/shirabe/src/repository/vcs/fossil_driver.rs +++ b/crates/shirabe/src/repository/vcs/fossil_driver.rs @@ -11,10 +11,10 @@ use crate::util::Filesystem; use crate::util::ProcessExecutor; use chrono::{DateTime, FixedOffset, Utc}; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ - PhpMixed, RuntimeException, dirname, is_dir, is_file, is_writable, php_regex, + PhpMixed, RuntimeException, dirname, is_dir, is_file, is_writable, php_regex, preg_match2, + preg_replace, }; #[derive(Debug)] @@ -82,7 +82,7 @@ impl FossilDriver { .into()); } - let local_name = Preg::replace(php_regex!(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); @@ -286,7 +286,7 @@ impl FossilDriver { Some(&self.checkout_dir), ); for branch in self.inner.process.borrow().split_lines(&output) { - let branch = Preg::replace(php_regex!(r"/^\*/"), "", branch.trim()); + let branch = preg_replace(php_regex!(r"/^\*/"), "", branch.trim()); let branch = branch.trim().to_string(); branches.insert(branch.clone(), branch); } @@ -301,14 +301,17 @@ impl FossilDriver { url: &str, deep: bool, ) -> anyhow::Result { - if Preg::is_match( + if preg_match2( php_regex!(r"#(^(?:https?|ssh)://(?:[^@]@)?(?:chiselapp\.com|fossil\.))#i"), url, - ) { + 0, + ) + .is_some() + { return Ok(true); } - if Preg::is_match(php_regex!(r"!/fossil/|\.fossil!"), url) { + if preg_match2(php_regex!(r"!/fossil/|\.fossil!"), url, 0).is_some() { 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 5f83b4e1..9f8e7a80 100644 --- a/crates/shirabe/src/repository/vcs/git_bitbucket_driver.rs +++ b/crates/shirabe/src/repository/vcs/git_bitbucket_driver.rs @@ -15,11 +15,11 @@ use crate::util::Bitbucket; use crate::util::http::Response; use chrono::{DateTime, FixedOffset}; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ InvalidArgumentException, LogicException, PhpMixed, RuntimeException, array_key_exists, - array_search_mixed, extension_loaded, http_build_query, implode, is_array, php_regex, strpos, + array_search_mixed, extension_loaded, http_build_query, implode, is_array, php_regex, + preg_match2, preg_replace, strpos, }; #[derive(Debug)] @@ -84,9 +84,10 @@ impl GitBitbucketDriver { /// @inheritDoc pub fn initialize(&mut self) -> anyhow::Result<()> { - let Some(m) = Preg::is_match3( + let Some(m) = preg_match2( php_regex!(r"#^https?://bitbucket\.org/([^/]+)/([^/]+?)(?:\.git|/?)?$#i"), &self.inner.url, + 0, ) else { return Err(InvalidArgumentException::new(format!( "The Bitbucket repository URL {} is invalid. It must be the HTTPS URL of a Bitbucket repository.", @@ -739,7 +740,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( + self.clone_https_url = preg_replace( php_regex!(r"/https:\/\/([^@]+@)?/"), "https://", m.get("href").and_then(|v| v.as_string()).unwrap_or(""), @@ -797,10 +798,13 @@ impl GitBitbucketDriver { url: &str, _deep: bool, ) -> anyhow::Result { - if !Preg::is_match( + if preg_match2( php_regex!(r"#^https?://bitbucket\.org/([^/]+)/([^/]+?)(\.git|/?)?$#i"), url, - ) { + 0, + ) + .is_none() + { return Ok(false); } diff --git a/crates/shirabe/src/repository/vcs/git_driver.rs b/crates/shirabe/src/repository/vcs/git_driver.rs index c224e8e6..62cca379 100644 --- a/crates/shirabe/src/repository/vcs/git_driver.rs +++ b/crates/shirabe/src/repository/vcs/git_driver.rs @@ -14,11 +14,10 @@ use crate::util::Url; use chrono::TimeZone; use chrono::{DateTime, FixedOffset, Utc}; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ - InvalidArgumentException, RuntimeException, dirname, is_dir, is_writable, realpath, - sys_get_temp_dir, + InvalidArgumentException, RuntimeException, dirname, is_dir, is_writable, preg_match2, + preg_replace, realpath, sys_get_temp_dir, }; use shirabe_php_shim::{PhpMixed, php_regex}; @@ -51,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(php_regex!(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::new(format!( "Failed to read package information from {} as the path does not exist", @@ -78,7 +77,7 @@ impl GitDriver { self.repo_dir = format!( "{}/{}/", cache_vcs_dir, - Preg::replace( + preg_replace( r"{[^a-z0-9.]}i", "-", &Url::sanitize(self.inner.url.clone()) @@ -99,7 +98,13 @@ impl GitDriver { .into()); } - if Preg::is_match(php_regex!(r"{^ssh://[^@]+@[^:]+:[^0-9]+}"), &self.inner.url) { + if preg_match2( + php_regex!(r"{^ssh://[^@]+@[^:]+:[^0-9]+}"), + &self.inner.url, + 0, + ) + .is_some() + { return Err(InvalidArgumentException::new(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.", self.inner.url @@ -146,7 +151,7 @@ impl GitDriver { &format!( "{}/{}", cache_repo_dir, - Preg::replace(r"{[^a-z0-9.]}i", "-", &Url::sanitize(cache_url)) + preg_replace(r"{[^a-z0-9.]}i", "-", &Url::sanitize(cache_url)) ), None, None, @@ -199,7 +204,7 @@ impl GitDriver { if !branches.contains(&"* master".to_string()) { for branch in &branches { if !branch.is_empty() - && let Some(caps) = Preg::match3(php_regex!(r"{^\* +(\S+)}"), branch) + && let Some(caps) = preg_match2(php_regex!(r"{^\* +(\S+)}"), branch, 0) && let Some(name) = caps.get(1) { self.root_identifier = Some(name.to_string()); @@ -309,9 +314,10 @@ impl GitDriver { ); for tag in self.inner.process.borrow().split_lines(&output) { if !tag.is_empty() - && let Some(caps) = Preg::match3( + && let Some(caps) = preg_match2( php_regex!(r"{^([a-f0-9]{40}) refs/tags/(\S+?)(\^\{\})?$}"), &tag, + 0, ) && let (Some(hash), Some(name)) = (caps.get(1), caps.get(2)) { @@ -344,10 +350,11 @@ impl GitDriver { ); for branch in self.inner.process.borrow().split_lines(&output) { if !branch.is_empty() - && !Preg::is_match(php_regex!(r"{^ *[^/]+/HEAD }"), &branch) - && let Some(caps) = Preg::match3( + && preg_match2(php_regex!(r"{^ *[^/]+/HEAD }"), &branch, 0).is_none() + && let Some(caps) = preg_match2( php_regex!(r"{^(?:\* )? *(\S+) *([a-f0-9]+)(?: .*)?$}"), &branch, + 0, ) && let (Some(name), Some(hash)) = (caps.get(1), caps.get(2)) && !name.starts_with('-') @@ -368,10 +375,13 @@ impl GitDriver { url: &str, deep: bool, ) -> anyhow::Result { - if Preg::is_match( + if preg_match2( php_regex!(r"#(^git://|\.git/?$|git(?:olite)?@|//git\.|//github.com/)#i"), url, - ) { + 0, + ) + .is_some() + { return Ok(true); } diff --git a/crates/shirabe/src/repository/vcs/github_driver.rs b/crates/shirabe/src/repository/vcs/github_driver.rs index 11bb9503..e9c17d30 100644 --- a/crates/shirabe/src/repository/vcs/github_driver.rs +++ b/crates/shirabe/src/repository/vcs/github_driver.rs @@ -14,12 +14,12 @@ use crate::util::GitHub; use crate::util::http::Response; use chrono::{DateTime, FixedOffset}; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ InvalidArgumentException, PhpMixed, RuntimeException, array_diff, array_map, array_search_mixed, base64_decode, basename, empty, explode, extension_loaded, in_array_loose, - parse_url, php_regex, preg_split, strpos, strtolower, substr, trim, urlencode, + parse_url, php_regex, preg_match2, preg_replace, preg_split, strpos, strtolower, substr, trim, + urlencode, }; #[derive(Debug)] @@ -70,11 +70,12 @@ impl GitHubDriver { } pub fn initialize(&mut self) -> anyhow::Result<()> { - let Some(match_) = Preg::is_match3( + let Some(match_) = preg_match2( php_regex!( r"#^(?:(?:https?|git)://([^/]+)/|git@([^:]+):/?)([^/]+)/([^/]+?)(?:\.git|/)?$#" ), &self.inner.url, + 0, ) else { return Err(InvalidArgumentException::new(format!( "The GitHub repository URL {} is invalid.", @@ -482,14 +483,14 @@ impl GitHubDriver { let mut key: Option = None; for line in preg_split(php_regex!(r"{\r?\n}"), &funding) { let line = trim(&line, None); - if let Some(m) = Preg::is_match3(php_regex!(r"{^(\w+)\s*:\s*(.+)$}"), &line) { + if let Some(m) = preg_match2(php_regex!(r"{^(\w+)\s*:\s*(.+)$}"), &line, 0) { let g1 = m.get(1).unwrap_or_default().to_string(); let g2 = m.get(2).unwrap_or_default().to_string(); if g2 == "[" { key = Some(g1); continue; } - if let Some(m2) = Preg::is_match3(php_regex!(r"{^\[(.*?)\](?:\s*#.*)?$}"), &g2) { + if let Some(m2) = preg_match2(php_regex!(r"{^\[(.*?)\](?:\s*#.*)?$}"), &g2, 0) { let inner = m2.get(1).unwrap_or_default().to_string(); for item in array_map( |s: &String| trim(s, None), @@ -504,7 +505,7 @@ impl GitHubDriver { result.push(entry); } } else if let Some(m2) = - Preg::is_match3(php_regex!(r"{^([^#].*?)(?:\s+#.*)?$}"), &g2) + preg_match2(php_regex!(r"{^([^#].*?)(?:\s+#.*)?$}"), &g2, 0) { let mut entry = IndexMap::new(); entry.insert("type".to_string(), PhpMixed::String(g1.clone())); @@ -515,11 +516,11 @@ impl GitHubDriver { result.push(entry); } key = None; - } else if let Some(m) = Preg::is_match3(php_regex!(r"{^(\w+)\s*:\s*#\s*$}"), &line) { + } else if let Some(m) = preg_match2(php_regex!(r"{^(\w+)\s*:\s*#\s*$}"), &line, 0) { key = Some(m.get(1).unwrap_or_default().to_string()); } else if key.is_some() - && let Some(m) = Preg::is_match3(php_regex!(r"{^-\s*(.+)(?:\s+#.*)?$}"), &line) - .or_else(|| Preg::is_match3(php_regex!(r"{^(.+),(?:\s*#.*)?$}"), &line)) + && let Some(m) = preg_match2(php_regex!(r"{^-\s*(.+)(?:\s+#.*)?$}"), &line, 0) + .or_else(|| preg_match2(php_regex!(r"{^(.+),(?:\s*#.*)?$}"), &line, 0)) { let mut entry = IndexMap::new(); entry.insert( @@ -644,7 +645,9 @@ impl GitHubDriver { }; if bits.scheme.is_none() && bits.host.is_none() { - if Preg::is_match(php_regex!(r"{^[a-z0-9-]++\.[a-z]{2,3}$}"), &item_url) { + if preg_match2(php_regex!(r"{^[a-z0-9-]++\.[a-z]{2,3}$}"), &item_url, 0) + .is_some() + { result[key_idx].insert( "url".to_string(), PhpMixed::String(format!("https://{}", item_url)), @@ -908,11 +911,12 @@ impl GitHubDriver { url: &str, _deep: bool, ) -> anyhow::Result { - let Some(matches) = Preg::is_match3( + let Some(matches) = preg_match2( php_regex!( r"#^((?:https?|git)://([^/]+)/|git@([^:]+):/?)([^/]+)/([^/]+?)(?:\.git|/)?$#" ), url, + 0, ) else { return Ok(false); }; @@ -923,7 +927,7 @@ impl GitHubDriver { .map(str::to_string) .unwrap_or_else(|| matches.get(3).unwrap_or_default().to_string()); if !in_array_loose( - strtolower(&Preg::replace(php_regex!(r"{^www\.}i"), "", &origin_url)), + strtolower(&preg_replace(php_regex!(r"{^www\.}i"), "", &origin_url)), config.borrow().get("github-domains").values(), ) { return Ok(false); @@ -1249,7 +1253,7 @@ impl GitHubDriver { let links = explode(",", &header); for link in &links { - if let Some(m) = Preg::is_match3(php_regex!(r#"{<(.+?)>; *rel="next"}"#), link) { + if let Some(m) = preg_match2(php_regex!(r#"{<(.+?)>; *rel="next"}"#), link, 0) { return Some(m.get(1).unwrap_or_default().to_string()); } } diff --git a/crates/shirabe/src/repository/vcs/gitlab_driver.rs b/crates/shirabe/src/repository/vcs/gitlab_driver.rs index 30c3f7ae..6054d941 100644 --- a/crates/shirabe/src/repository/vcs/gitlab_driver.rs +++ b/crates/shirabe/src/repository/vcs/gitlab_driver.rs @@ -15,12 +15,11 @@ use crate::util::HttpDownloader; use crate::util::http::Response; use chrono::{DateTime, FixedOffset}; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ InvalidArgumentException, LogicException, PhpMixed, RuntimeException, array_search_mixed, array_shift, ctype_alnum, empty, explode, extension_loaded, implode, in_array_loose, is_array, - is_string, ord, php_regex, strpos, strtolower, + is_string, ord, php_regex, preg_match2, preg_replace, strpos, strtolower, }; /// Driver for GitLab API, use the Git driver for local checkouts. @@ -81,7 +80,7 @@ impl GitLabDriver { /// /// SSH urls use https by default. Set "secure-http": false on the repository config to use http instead. pub fn initialize(&mut self) -> anyhow::Result<()> { - let Some(match_) = Preg::is_match3(Self::URL_REGEX, &self.inner.url) else { + let Some(match_) = preg_match2(Self::URL_REGEX, &self.inner.url, 0) else { return Err(InvalidArgumentException::new(format!( "The GitLab repository URL {} is invalid. It must be the HTTP URL of a GitLab project.", self.inner.url.clone(), @@ -152,7 +151,7 @@ impl GitLabDriver { } self.namespace = implode("/", &url_parts); - self.repository = Preg::replace( + self.repository = preg_replace( php_regex!(r"#(\.git)$#"), "", match_.name("repo").unwrap_or_default(), @@ -383,7 +382,7 @@ impl GitLabDriver { // Convert the root identifier to a cacheable commit id let mut identifier = identifier.to_string(); - if !Preg::is_match(php_regex!(r"{[a-f0-9]{40}}i"), &identifier) { + if preg_match2(php_regex!(r"{[a-f0-9]{40}}i"), &identifier, 0).is_none() { let branches = self.get_branches()?; if let Some(sha) = branches.get(&identifier) { identifier = sha.clone(); @@ -927,7 +926,7 @@ impl GitLabDriver { url: &str, _deep: bool, ) -> anyhow::Result { - let Some(match_) = Preg::is_match3(Self::URL_REGEX, url) else { + let Some(match_) = preg_match2(Self::URL_REGEX, url, 0) else { return Ok(false); }; @@ -978,7 +977,7 @@ impl GitLabDriver { let links = explode(",", &header); for link in &links { - if let Some(match_) = Preg::is_match3(php_regex!(r#"{<(.+?)>; *rel="next"}"#), link) { + if let Some(match_) = preg_match2(php_regex!(r#"{<(.+?)>; *rel="next"}"#), link, 0) { return Some(match_.get(1).unwrap_or_default().to_string()); } } @@ -1022,7 +1021,7 @@ impl GitLabDriver { if in_array_loose(guessed_domain.clone(), configured_domains.values()) || (port_number.is_some() && in_array_loose( - Preg::replace(php_regex!(r"{:\d+}"), "", &guessed_domain), + preg_replace(php_regex!(r"{:\d+}"), "", &guessed_domain), configured_domains.values(), )) { diff --git a/crates/shirabe/src/repository/vcs/hg_driver.rs b/crates/shirabe/src/repository/vcs/hg_driver.rs index 120b8ea8..ada1063e 100644 --- a/crates/shirabe/src/repository/vcs/hg_driver.rs +++ b/crates/shirabe/src/repository/vcs/hg_driver.rs @@ -11,9 +11,10 @@ use crate::util::Hg as HgUtils; use crate::util::Url; use chrono::{DateTime, FixedOffset, Utc}; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::Catch as _; -use shirabe_php_shim::{PhpMixed, RuntimeException, dirname, is_dir, is_writable, php_regex}; +use shirabe_php_shim::{ + PhpMixed, RuntimeException, dirname, is_dir, is_writable, php_regex, preg_match2, preg_replace, +}; #[derive(Debug)] pub struct HgDriver { @@ -57,7 +58,7 @@ impl HgDriver { return Err(RuntimeException::new("HgDriver requires a usable cache directory, and it looks like you set it to be disabled".to_string()).into()); } - let sanitized = Preg::replace( + let sanitized = preg_replace( php_regex!(r"{[^a-z0-9]}i"), "-", &Url::sanitize(self.inner.url.clone()), @@ -233,7 +234,7 @@ impl HgDriver { ); for tag in self.inner.process.borrow().split_lines(&output) { if !tag.is_empty() - && let Some(m) = Preg::match3(php_regex!(r"(^([^\s]+)\s+\d+:(.*)$)"), &tag) + && let Some(m) = preg_match2(php_regex!(r"(^([^\s]+)\s+\d+:(.*)$)"), &tag, 0) { tags.insert( m.get(1).unwrap_or_default().to_string(), @@ -263,7 +264,7 @@ impl HgDriver { for branch in self.inner.process.borrow().split_lines(&output) { if !branch.is_empty() && let Some(m) = - Preg::match3(php_regex!(r"(^([^\s]+)\s+\d+:([a-f0-9]+))"), &branch) + preg_match2(php_regex!(r"(^([^\s]+)\s+\d+:([a-f0-9]+))"), &branch, 0) { let name = m.get(1).unwrap_or_default().to_string(); if !name.starts_with('-') { @@ -281,7 +282,7 @@ impl HgDriver { for branch in self.inner.process.borrow().split_lines(&output) { if !branch.is_empty() && let Some(m) = - Preg::match3(php_regex!(r"(^(?:[\s*]*)([^\s]+)\s+\d+:(.*)$)"), &branch) + preg_match2(php_regex!(r"(^(?:[\s*]*)([^\s]+)\s+\d+:(.*)$)"), &branch, 0) { let name = m.get(1).unwrap_or_default().to_string(); if !name.starts_with('-') { @@ -304,12 +305,15 @@ impl HgDriver { url: &str, deep: bool, ) -> anyhow::Result { - if Preg::is_match( + if preg_match2( php_regex!( r"#(^(?:https?|ssh)://(?:[^@]+@)?bitbucket.org|https://(?:.*?)\.kilnhg.com)#i" ), url, - ) { + 0, + ) + .is_some() + { return Ok(true); } diff --git a/crates/shirabe/src/repository/vcs/perforce_driver.rs b/crates/shirabe/src/repository/vcs/perforce_driver.rs index ce9ffb49..50aed379 100644 --- a/crates/shirabe/src/repository/vcs/perforce_driver.rs +++ b/crates/shirabe/src/repository/vcs/perforce_driver.rs @@ -9,8 +9,9 @@ use crate::util::PerforceInterface; use crate::util::ProcessExecutor; use crate::util::http::Response; use indexmap::IndexMap; -use shirabe_pcre::Preg; -use shirabe_php_shim::{BadMethodCallException, PhpMixed, RuntimeException, php_regex}; +use shirabe_php_shim::{ + BadMethodCallException, PhpMixed, RuntimeException, php_regex, preg_match2, +}; #[derive(Debug)] pub struct PerforceDriver { @@ -189,7 +190,7 @@ impl PerforceDriver { url: &str, deep: bool, ) -> anyhow::Result { - if deep || Preg::is_match(php_regex!(r"#\b(perforce|p4)\b#i"), url) { + if deep || preg_match2(php_regex!(r"#\b(perforce|p4)\b#i"), url, 0).is_some() { 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 6fb987a4..3398eb59 100644 --- a/crates/shirabe/src/repository/vcs/svn_driver.rs +++ b/crates/shirabe/src/repository/vcs/svn_driver.rs @@ -13,10 +13,10 @@ use crate::util::Svn as SvnUtil; use crate::util::Url; use chrono::{DateTime, FixedOffset, Utc}; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ - PhpMixed, RuntimeException, php_regex, stripos, strrpos, strtr, substr, trim, + PhpMixed, RuntimeException, php_regex, preg_match2, preg_replace, stripos, strrpos, strtr, + substr, trim, }; #[derive(Debug)] @@ -110,7 +110,7 @@ impl SvnDriver { .get("cache-repo-dir") .as_string() .unwrap_or(""), - Preg::replace(r"{[^a-z0-9.]}i", "-", &Url::sanitize(self.base_url.clone())), + preg_replace(r"{[^a-z0-9.]}i", "-", &Url::sanitize(self.base_url.clone())), ), None, None, @@ -153,7 +153,7 @@ impl SvnDriver { } fn should_cache(&self, identifier: &str) -> bool { - self.inner.cache.is_some() && Preg::is_match(php_regex!(r"{@\d+$}"), identifier) + self.inner.cache.is_some() && preg_match2(php_regex!(r"{@\d+$}"), identifier, 0).is_some() } pub fn get_composer_information( @@ -258,7 +258,7 @@ impl SvnDriver { let identifier = format!("/{}/", trim(identifier, Some("/"))); let (path, rev) = if let Some(m) = - Preg::is_match3(php_regex!(r"{^(.+?)(@\d+)?/$}"), &identifier) + preg_match2(php_regex!(r"{^(.+?)(@\d+)?/$}"), &identifier, 0) && let Some(rev) = m.get(2) { (m.get(1).unwrap_or_default().to_string(), rev.to_string()) @@ -292,7 +292,7 @@ impl SvnDriver { let identifier = format!("/{}/", trim(identifier, Some("/"))); let (path, rev) = if let Some(m) = - Preg::is_match3(php_regex!(r"{^(.+?)(@\d+)?/$}"), &identifier) + preg_match2(php_regex!(r"{^(.+?)(@\d+)?/$}"), &identifier, 0) && let Some(rev) = m.get(2) { (m.get(1).unwrap_or_default().to_string(), rev.to_string()) @@ -306,8 +306,7 @@ impl SvnDriver { )?; for line in self.inner.process.borrow().split_lines(&output) { if !line.is_empty() - && let Some(m) = - Preg::is_match3(php_regex!(r"{^Last Changed Date: ([^(]+)}"), &line) + && let Some(m) = preg_match2(php_regex!(r"{^Last Changed Date: ([^(]+)}"), &line, 0) { let date_str = m.get(1).unwrap_or_default().to_string(); return Ok(shirabe_php_shim::date_create::(date_str.trim()) @@ -335,7 +334,7 @@ impl SvnDriver { let line = trim(&line, None); if !line.is_empty() && let Some(m) = - Preg::is_match3(php_regex!(r"{^\s*(\S+).*?(\S+)\s*$}"), &line) + preg_match2(php_regex!(r"{^\s*(\S+).*?(\S+)\s*$}"), &line, 0) { let rev: i64 = m.get(1).and_then(|s| s.parse().ok()).unwrap_or(0); let path = m.get(2).unwrap_or_default().to_string(); @@ -378,7 +377,7 @@ impl SvnDriver { let line = trim(&line, None); if !line.is_empty() && let Some(m) = - Preg::is_match3(php_regex!(r"{^\s*(\S+).*?(\S+)\s*$}"), &line) + preg_match2(php_regex!(r"{^\s*(\S+).*?(\S+)\s*$}"), &line, 0) { let rev: i64 = m.get(1).and_then(|s| s.parse().ok()).unwrap_or(0); let path = m.get(2).unwrap_or_default().to_string(); @@ -413,7 +412,7 @@ impl SvnDriver { let line = trim(&line, None); if !line.is_empty() && let Some(m) = - Preg::is_match3(php_regex!(r"{^\s*(\S+).*?(\S+)\s*$}"), &line) + preg_match2(php_regex!(r"{^\s*(\S+).*?(\S+)\s*$}"), &line, 0) { let rev: i64 = m.get(1).and_then(|s| s.parse().ok()).unwrap_or(0); let path = m.get(2).unwrap_or_default().to_string(); @@ -444,7 +443,7 @@ impl SvnDriver { deep: bool, ) -> anyhow::Result { let url = Self::normalize_url(url); - if Preg::is_match(php_regex!(r"#(^svn://|^svn\+ssh://|svn\.)#i"), &url) { + if preg_match2(php_regex!(r"#(^svn://|^svn\+ssh://|svn\.)#i"), &url, 0).is_some() { return Ok(true); } diff --git a/crates/shirabe/src/repository/vcs/vcs_driver.rs b/crates/shirabe/src/repository/vcs/vcs_driver.rs index a5192937..1a5ee72e 100644 --- a/crates/shirabe/src/repository/vcs/vcs_driver.rs +++ b/crates/shirabe/src/repository/vcs/vcs_driver.rs @@ -12,9 +12,8 @@ use crate::util::ProcessExecutor; use crate::util::http::Response; use chrono::{DateTime, FixedOffset}; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::Catch as _; -use shirabe_php_shim::{DATE_RFC3339, PhpMixed, extension_loaded, php_regex}; +use shirabe_php_shim::{DATE_RFC3339, PhpMixed, extension_loaded, php_regex, preg_match2}; #[derive(Debug)] pub struct VcsDriverBase { @@ -57,7 +56,8 @@ impl VcsDriverBase { } pub fn should_cache(&self, identifier: &str) -> bool { - self.cache.is_some() && Preg::is_match(php_regex!("{^[a-f0-9]{40}$}iD"), identifier) + self.cache.is_some() + && preg_match2(php_regex!("{^[a-f0-9]{40}$}iD"), identifier, 0).is_some() } pub fn get_scheme(&self) -> &str { @@ -202,7 +202,8 @@ 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(php_regex!("{^[a-f0-9]{40}$}iD"), identifier) + self.cache().is_some() + && preg_match2(php_regex!("{^[a-f0-9]{40}$}iD"), identifier, 0).is_some() } fn get_composer_information( diff --git a/crates/shirabe/src/repository/vcs_repository.rs b/crates/shirabe/src/repository/vcs_repository.rs index 4066ac44..33de3dfb 100644 --- a/crates/shirabe/src/repository/vcs_repository.rs +++ b/crates/shirabe/src/repository/vcs_repository.rs @@ -27,10 +27,10 @@ use crate::util::Platform; use crate::util::ProcessExecutor; use crate::util::Url; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ - InvalidArgumentException, PhpClass, PhpMixed, php_regex, str_replace, strpos, + InvalidArgumentException, PhpClass, PhpMixed, php_regex, preg_match2, preg_replace, + str_replace, strpos, }; use shirabe_semver::constraint::SimpleConstraint; @@ -479,7 +479,7 @@ impl VcsRepository { // make sure tag packages have no -dev flag data.insert( "version".to_string(), - PhpMixed::String(Preg::replace( + PhpMixed::String(preg_replace( php_regex!(r"{[.-]?dev$}i"), "", data.get("version") @@ -489,7 +489,7 @@ impl VcsRepository { ); data.insert( "version_normalized".to_string(), - PhpMixed::String(Preg::replace( + PhpMixed::String(preg_replace( php_regex!(r"{(^dev-|[.-]?dev$)}i"), "", data.get("version_normalized") @@ -510,7 +510,9 @@ impl VcsRepository { // broken package, version doesn't match tag if version_normalized != parsed_tag { if is_very_verbose { - if Preg::is_match(php_regex!(r"{(^dev-|[.-]?dev$)}i"), &parsed_tag) { + if preg_match2(php_regex!(r"{(^dev-|[.-]?dev$)}i"), &parsed_tag, 0) + .is_some() + { self.io.write_error(&format!( "Skipped tag {}, invalid tag name, tags can not use dev prefixes or suffixes", tag @@ -678,7 +680,7 @@ impl VcsRepository { version = format!( "{}{}", prefix, - Preg::replace(r"{(\.9{7})+}", ".x", &parsed_branch) + preg_replace(r"{(\.9{7})+}", ".x", &parsed_branch) ); } diff --git a/crates/shirabe/src/self_update/versions.rs b/crates/shirabe/src/self_update/versions.rs index 4276c646..89028dc5 100644 --- a/crates/shirabe/src/self_update/versions.rs +++ b/crates/shirabe/src/self_update/versions.rs @@ -5,9 +5,8 @@ use crate::io::IOInterface; use crate::io::IOInterfaceImmutable; use crate::util::HttpDownloader; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::{ - InvalidArgumentException, PHP_EOL, PhpMixed, UnexpectedValueException, php_regex, + InvalidArgumentException, PHP_EOL, PhpMixed, UnexpectedValueException, php_regex, preg_match2, }; pub struct Versions { @@ -90,7 +89,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(php_regex!(r"{^\d+$}D"), &channel) { + let stored_channel = if preg_match2(php_regex!(r"{^\d+$}D"), &channel, 0).is_some() { "stable".to_string() } else { channel diff --git a/crates/shirabe/src/util/auth_helper.rs b/crates/shirabe/src/util/auth_helper.rs index 7d47f088..8d35d817 100644 --- a/crates/shirabe/src/util/auth_helper.rs +++ b/crates/shirabe/src/util/auth_helper.rs @@ -9,11 +9,10 @@ use crate::util::Bitbucket; use crate::util::GitHub; use crate::util::GitLab; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::{ PhpMixed, RuntimeException, base64_encode, explode, in_array_loose, in_array_strict, is_array, - is_string, json_decode_assoc, parse_url, php_regex, str_replace, strpos, strtolower, substr, - trim, + is_string, json_decode_assoc, parse_url, php_regex, preg_match2, str_replace, strpos, + strtolower, substr, trim, }; #[derive(Debug)] @@ -537,7 +536,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(php_regex!(r"{^https?://api\.github\.com/}"), url) { + if preg_match2(php_regex!(r"{^https?://api\.github\.com/}"), url, 0).is_some() { 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 f7bc179f..78f38782 100644 --- a/crates/shirabe/src/util/composer_mirror.rs +++ b/crates/shirabe/src/util/composer_mirror.rs @@ -1,7 +1,6 @@ //! ref: composer/src/Composer/Util/ComposerMirror.php -use shirabe_pcre::Preg; -use shirabe_php_shim::{hash, php_regex}; +use shirabe_php_shim::{hash, php_regex, preg_match2, preg_replace}; pub struct ComposerMirror; @@ -15,7 +14,7 @@ impl ComposerMirror { pretty_version: Option<&str>, ) -> String { let reference = reference.map(|r| { - if Preg::is_match(php_regex!(r"{^([a-f0-9]*|%reference%)$}"), r) { + if preg_match2(php_regex!(r"{^([a-f0-9]*|%reference%)$}"), r, 0).is_some() { r.to_string() } else { hash("md5", r) @@ -53,20 +52,22 @@ impl ComposerMirror { url: &str, r#type: Option<&str>, ) -> String { - let normalized_url = if let Some(gh_matches) = Preg::match3( + let normalized_url = if let Some(gh_matches) = preg_match2( php_regex!( r"#^(?:(?:https?|git)://github\.com/|git@github\.com:)([^/]+)/(.+?)(?:\.git)?$#" ), url, + 0, ) { format!( "gh-{}/{}", gh_matches.get(1).unwrap_or_default(), gh_matches.get(2).unwrap_or_default(), ) - } else if let Some(bb_matches) = Preg::match3( + } else if let Some(bb_matches) = preg_match2( php_regex!(r"#^https://bitbucket\.org/([^/]+)/(.+?)(?:\.git)?/?$#"), url, + 0, ) { format!( "bb-{}/{}", @@ -74,7 +75,7 @@ impl ComposerMirror { bb_matches.get(2).unwrap_or_default(), ) } else { - Preg::replace(php_regex!(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 adf2aea2..52560caa 100644 --- a/crates/shirabe/src/util/config_validator.rs +++ b/crates/shirabe/src/util/config_validator.rs @@ -9,9 +9,8 @@ use crate::package::loader::LoaderInterface; use crate::package::loader::ValidatingArrayLoader; use indexmap::IndexMap; use serde::de::Error as _; -use shirabe_pcre::Preg; use shirabe_php_shim::Catch as _; -use shirabe_php_shim::{PhpMixed, php_regex}; +use shirabe_php_shim::{PhpMixed, php_regex, preg_match2, preg_replace}; use shirabe_spdx_licenses::SpdxLicenses; #[derive(Debug)] @@ -118,13 +117,17 @@ impl ConfigValidator { for license in &licenses { let spdx_license = license_validator.get_license_by_identifier(license); if spdx_license.is_some_and(|l| l.is_deprecated_license_id) { - if Preg::is_match(php_regex!(r"{^[AL]?GPL-[123](\.[01])?\+$}i"), license) { + if preg_match2(php_regex!(r"{^[AL]?GPL-[123](\.[01])?\+$}i"), license, 0) + .is_some() + { warnings.push(format!( "License \"{}\" is a deprecated SPDX license identifier, use \"{}-or-later\" instead", license, license.replace('+', "") )); - } else if Preg::is_match(php_regex!(r"{^[AL]?GPL-[123](\.[01])?$}i"), license) { + } else if preg_match2(php_regex!(r"{^[AL]?GPL-[123](\.[01])?$}i"), license, 0) + .is_some() + { warnings.push(format!( "License \"{}\" is a deprecated SPDX license identifier, use \"{}-only\" or \"{}-or-later\" instead", license, license, license @@ -145,9 +148,9 @@ impl ConfigValidator { if let Some(PhpMixed::String(name)) = manifest.get("name") && !name.is_empty() - && Preg::is_match(php_regex!(r"{[A-Z]}"), name) + && preg_match2(php_regex!(r"{[A-Z]}"), name, 0).is_some() { - let suggest_name = Preg::replace( + let suggest_name = preg_replace( php_regex!(r"{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}"), r"\1\3-\2\4", name, @@ -222,7 +225,7 @@ impl ConfigValidator { packages.extend(require_dev); for (package, version) in &packages { if let PhpMixed::String(version_str) = version - && Preg::is_match(php_regex!(r"{#}"), version_str) + && preg_match2(php_regex!(r"{#}"), version_str, 0).is_some() { 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 2ef51ba1..b79beeae 100644 --- a/crates/shirabe/src/util/filesystem.rs +++ b/crates/shirabe/src/util/filesystem.rs @@ -3,14 +3,14 @@ use crate::util::Platform; use crate::util::ProcessExecutor; use crate::util::Silencer; -use shirabe_pcre::Preg; use shirabe_php_shim::{ - ErrorException, LogicException, PhpMixed, RuntimeException, array_pop, basename, chdir, - clearstatcache, clearstatcache2, copy, dirname, explode, fclose, feof, file_exists, + ErrorException, LogicException, PhpMixed, PregMatches, RuntimeException, array_pop, basename, + chdir, clearstatcache, clearstatcache2, copy, dirname, 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, - php_regex, rename, rmdir, rtrim, str_repeat, str_replace, strlen, strpos, strtoupper, strtr, - substr, substr_count, symlink, touch, unlink, usleep, var_export, + php_regex, preg_match2, preg_replace, preg_replace_callback, rename, rmdir, rtrim, str_repeat, + str_replace, strlen, strpos, strtoupper, strtr, substr, substr_count, symlink, touch, unlink, + usleep, var_export, }; use shirabe_symfony_filesystem::exception::IOException; use shirabe_symfony_finder::Finder; @@ -246,7 +246,7 @@ impl Filesystem { return Ok(Some(true)); } - if Preg::is_match3(php_regex!("{^(?:[a-z]:)?[/\\\\]+$}i"), directory).is_some() { + if preg_match2(php_regex!("{^(?:[a-z]:)?[/\\\\]+$}i"), directory, 0).is_some() { return Err(RuntimeException::new(format!("Aborting an attempted deletion of {}, this was probably not intended, if it is a real use case please report it.", directory)) .into()); } @@ -578,7 +578,7 @@ impl Filesystem { let mut common_path = to.clone(); while strpos(&format!("{}/", from), &format!("{}/", common_path)) != Some(0) && "/" != common_path - && Preg::is_match3(php_regex!("{^[A-Z]:/?$}i"), &common_path).is_none() + && preg_match2(php_regex!("{^[A-Z]:/?$}i"), &common_path, 0).is_none() { common_path = strtr(&dirname(&common_path), "\\", "/"); } @@ -635,7 +635,7 @@ impl Filesystem { let mut common_path = to.clone(); while strpos(&format!("{}/", from), &format!("{}/", common_path)) != Some(0) && "/" != common_path - && Preg::is_match3(php_regex!("{^[A-Z]:/?$}i"), &common_path).is_none() + && preg_match2(php_regex!("{^[A-Z]:/?$}i"), &common_path, 0).is_none() && "." != common_path { common_path = strtr(&dirname(&common_path), "\\", "/"); @@ -735,9 +735,10 @@ impl Filesystem { } // extract a prefix being a protocol://, protocol:, protocol://drive: or simply drive: - if let Some(prefix_match) = Preg::is_match3( + if let Some(prefix_match) = preg_match2( php_regex!("{^( [0-9a-z]{2,}+: (?: // (?: [a-z]: )? )? | [a-z]: )}ix"), &path, + 0, ) { prefix = prefix_match.get(1).unwrap_or_default().to_string(); path = substr(&path, strlen(&prefix), None); @@ -760,14 +761,15 @@ impl Filesystem { } // ensure c: is normalized to C: - prefix = Preg::replace_callback( + prefix = preg_replace_callback( php_regex!("{(^|://)[a-z]:$}i"), - |m: &shirabe_pcre::PregMatches| -> String { + |m: &PregMatches| -> anyhow::Result { let s = m.get(0).unwrap_or_default().to_string(); - strtoupper(&s) + Ok(strtoupper(&s)) }, &prefix, - ); + ) + .expect("the replacement callback cannot fail"); format!("{}{}{}", prefix, absolute, implode("/", &parts)) } @@ -777,7 +779,7 @@ impl Filesystem { /// And other possible unforeseen disasters, see https://github.com/composer/composer/pull/9422 pub fn trim_trailing_slash(path: &str) -> String { let mut path = path.to_string(); - if Preg::is_match3(php_regex!("{^[/\\\\]+$}"), &path).is_none() { + if preg_match2(php_regex!("{^[/\\\\]+$}"), &path, 0).is_none() { path = rtrim(&path, Some("/\\")); } @@ -789,18 +791,20 @@ impl Filesystem { // on windows, \\foo indicates network paths so we exclude those from local paths, however it is unsafe // 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( + return preg_match2( php_regex!( "{^(file://(?!//)|/(?!/)|/?[a-z]:[\\\\/]|\\.\\.[\\\\/]|[a-z0-9_.-]+[\\\\/])}i" ), path, + 0, ) .is_some(); } - Preg::is_match3( + preg_match2( php_regex!("{^(file://|/|/?[a-z]:[\\\\/]|\\.\\.[\\\\/]|[a-z0-9_.-]+[\\\\/])}i"), path, + 0, ) .is_some() } @@ -808,14 +812,14 @@ impl Filesystem { pub fn get_platform_path(path: &str) -> String { let mut path = path.to_string(); if Platform::is_windows() { - path = Preg::replace( + path = preg_replace( php_regex!("{^(?:file:///([a-z]):?/)}i"), "file://$1:/", &path, ); } - Preg::replace(php_regex!("{^file://}i"), "", &path) + preg_replace(php_regex!("{^file://}i"), "", &path) } /// Cross-platform safe version of is_readable() diff --git a/crates/shirabe/src/util/forgejo_url.rs b/crates/shirabe/src/util/forgejo_url.rs index 9ae1cbee..abb39d88 100644 --- a/crates/shirabe/src/util/forgejo_url.rs +++ b/crates/shirabe/src/util/forgejo_url.rs @@ -1,7 +1,6 @@ //! ref: composer/src/Composer/Util/ForgejoUrl.php -use shirabe_pcre::Preg; -use shirabe_php_shim::InvalidArgumentException; +use shirabe_php_shim::{InvalidArgumentException, preg_match2}; #[derive(Debug)] pub struct ForgejoUrl { @@ -37,7 +36,7 @@ impl ForgejoUrl { pub fn try_from(repo_url: Option<&str>) -> Option { let repo_url = repo_url?; - let matches = Preg::match3(Self::URL_REGEX, repo_url)?; + let matches = preg_match2(Self::URL_REGEX, repo_url, 0)?; let m: Vec = (0..5) .map(|i| matches.get(i).unwrap_or_default().to_string()) diff --git a/crates/shirabe/src/util/git.rs b/crates/shirabe/src/util/git.rs index e14ff05f..31771e6c 100644 --- a/crates/shirabe/src/util/git.rs +++ b/crates/shirabe/src/util/git.rs @@ -14,12 +14,11 @@ use crate::util::ProcessExecutor; use crate::util::Url; use crate::util::{AuthHelper, StoreAuth}; use indexmap::IndexMap; -use shirabe_pcre::{Preg, PregMatches}; use shirabe_php_shim::{ - AnyThrowable, CmpOp, InvalidArgumentException, PHP_EOL, PhpMixed, RuntimeException, array_map, - clearstatcache, explode, implode, in_array_loose, in_array_strict, is_dir, php_regex, - preg_quote, rawurldecode, rawurlencode, str_replace_array, strlen, strpos, substr, trim, - version_compare, + AnyThrowable, CmpOp, InvalidArgumentException, PHP_EOL, PhpMixed, PregMatches, + RuntimeException, array_map, clearstatcache, explode, implode, in_array_loose, in_array_strict, + is_dir, php_regex, preg_match2, preg_quote, preg_replace, rawurldecode, rawurlencode, + str_replace_array, strlen, strpos, substr, trim, version_compare, }; use std::sync::Mutex; @@ -110,7 +109,7 @@ impl Git { map.insert("%url%".to_string(), url.to_string()); map.insert( "%sanitizedUrl%".to_string(), - Preg::replace(php_regex!(r"{://([^@]+?):(.+?)@}"), "://", url), + preg_replace(php_regex!(r"{://([^@]+?):(.+?)@}"), "://", url), ); array_map( @@ -210,7 +209,7 @@ impl Git { status }; - if Preg::is_match(php_regex!(r"{^ssh://[^@]+@[^:]+:[^0-9]+}"), url) { + if preg_match2(php_regex!(r"{^ssh://[^@]+@[^:]+:[^0-9]+}"), url, 0).is_some() { return Err(InvalidArgumentException::new(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.", url @@ -226,9 +225,10 @@ impl Git { &mut output, cwd, )?; - if let Some(m) = Preg::is_match3( + if let Some(m) = preg_match2( php_regex!(r"{^(?:composer|origin)\s+https?://(.+):(.+)@([^/]+)}im"), &output, + 0, ) { let m3 = m.get(3).unwrap_or_default().to_string(); if !self.io.has_authentication(&m3) { @@ -244,12 +244,13 @@ impl Git { let protocols = self.config.borrow_mut().get("github-protocols"); // public github, autoswitch protocols // @phpstan-ignore composerPcre.maybeUnsafeStrictGroups - if let Some(m) = Preg::is_match3( + if let Some(m) = preg_match2( format!( "{{^(?:https?|git)://{}/(.*)}}", Self::get_github_domains_regex(&self.config.borrow()) ), url, + 0, ) { let mut messages: Vec = vec![]; let protocols_list: Vec = match &protocols { @@ -280,7 +281,7 @@ impl Git { messages.push(format!( "- {}\n{}", proto_url, - Preg::replace(r"#^#m", " ", self.process.borrow().get_error_output()) + preg_replace(r"#^#m", " ", self.process.borrow().get_error_output()) )); if initial_clone && let Some(ref orig) = orig_cwd { @@ -311,19 +312,22 @@ impl Git { .collect(), _ => vec![], }; - let bypass_ssh_for_github = Preg::is_match( + let bypass_ssh_for_github = preg_match2( format!( "{{^git@{}:(.+?)\\.git$}}i", Self::get_github_domains_regex(&self.config.borrow()) ), url, - ) && !in_array_strict( - "ssh".to_string(), - &protocols_list - .iter() - .map(|s| PhpMixed::String(s.clone())) - .collect::>(), - ); + 0, + ) + .is_some() + && !in_array_strict( + "ssh".to_string(), + &protocols_list + .iter() + .map(|s| PhpMixed::String(s.clone())) + .collect::>(), + ); let mut auth: Option>> = None; let mut credentials: Vec = vec![]; @@ -338,20 +342,22 @@ impl Git { let mut error_msg = self.process.borrow().get_error_output().to_string(); // private github repository without ssh key access, try https with auth // @phpstan-ignore composerPcre.maybeUnsafeStrictGroups - let github_matched = Preg::is_match3( + let github_matched = preg_match2( format!( "{{^git@{}:(.+?)\\.git$}}i", Self::get_github_domains_regex(&self.config.borrow()) ), url, + 0, ) .or_else(|| { - Preg::is_match3( + preg_match2( format!( "{{^https?://{}/(.*?)(?:\\.git)?$}}i", Self::get_github_domains_regex(&self.config.borrow()) ), url, + 0, ) }); if let Some(m) = github_matched { @@ -404,12 +410,18 @@ impl Git { credentials = vec![rawurlencode(&username), rawurlencode(&password)]; error_msg = self.process.borrow().get_error_output().to_string(); } - } else if let Some(m) = Preg::is_match3( + } else if let Some(m) = preg_match2( php_regex!(r"{^(https?)://(bitbucket\.org)/(.*?)(?:\.git)?$}i"), url, + 0, ) - .or_else(|| Preg::is_match3(php_regex!(r"{^(git)@(bitbucket\.org):(.+?\.git)$}i"), url)) - { + .or_else(|| { + preg_match2( + php_regex!(r"{^(git)@(bitbucket\.org):(.+?\.git)$}i"), + url, + 0, + ) + }) { // bitbucket either through oauth or app password, with fallback to ssh. let mut bitbucket_util = Bitbucket::new( self.io.clone(), @@ -546,20 +558,22 @@ impl Git { } error_msg = self.process.borrow().get_error_output().to_string(); - } else if let Some(m) = Preg::is_match3( + } else if let Some(m) = preg_match2( format!( "{{^(git)@{}:(.+?\\.git)$}}i", Self::get_gitlab_domains_regex(&self.config.borrow()) ), url, + 0, ) .or_else(|| { - Preg::is_match3( + preg_match2( format!( "{{^(https?)://{}/(.*)}}i", Self::get_gitlab_domains_regex(&self.config.borrow()) ), url, + 0, ) }) { let mut m1 = m.get(1).unwrap_or_default().to_string(); @@ -914,10 +928,10 @@ impl Git { pretty_version: Option<&str>, ) -> anyhow::Result { if self.check_ref_is_in_mirror(dir, r#ref)? { - if Preg::is_match(php_regex!(r"{^[a-f0-9]{40}$}"), r#ref) + if preg_match2(php_regex!(r"{^[a-f0-9]{40}$}"), r#ref, 0).is_some() && let Some(pretty_version) = pretty_version { - let branch = Preg::replace( + let branch = preg_replace( php_regex!(r"{(?:^dev-|(?:\.x)?-dev$)}i"), "", pretty_version, @@ -948,15 +962,19 @@ impl Git { // this can occur if a git tag gets created *after* the reference is already put into the cache, as the ref check above will then not sync the new tags // see https://github.com/composer/composer/discussions/11002 if branches.is_some() - && !Preg::is_match( + && preg_match2( format!(r"{{^[\s*]*v?{}$}}m", preg_quote(&branch, None)), branches.as_deref().unwrap_or(""), + 0, ) + .is_none() && tags.is_some() - && !Preg::is_match( + && preg_match2( format!(r"{{^[\s*]*{}$}}m", preg_quote(&branch, None)), tags.as_deref().unwrap_or(""), + 0, ) + .is_none() { self.sync_mirror(url, dir)?; } @@ -1042,7 +1060,7 @@ impl Git { } // Filter out "commit " lines for older git versions - Preg::replace(php_regex!(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 { @@ -1081,7 +1099,7 @@ impl Git { } fn get_authentication_failure<'u>(&self, url: &'u str) -> Option> { - let m = Preg::is_match3(php_regex!(r"{^(https?://)([^/]+)(.*)$}i"), url)?; + let m = preg_match2(php_regex!(r"{^(https?://)([^/]+)(.*)$}i"), url, 0)?; let auth_failures = [ "fatal: Authentication failed", @@ -1164,7 +1182,7 @@ impl Git { .split_lines(output_mixed.as_string().unwrap_or("")); for line in lines { if let Some(matches) = - Preg::is_match3(php_regex!(r"{^\s*HEAD branch:\s(.+)\s*$}m"), &line) + preg_match2(php_regex!(r"{^\s*HEAD branch:\s(.+)\s*$}m"), &line, 0) { return Ok(Some(matches.get(1).unwrap_or_default().to_string())); } @@ -1285,7 +1303,7 @@ impl Git { ); if exit_code == 0 && let Some(matches) = - Preg::is_match3(php_regex!(r"/^git version (\d+(?:\.\d+)+)/m"), &output) + preg_match2(php_regex!(r"/^git version (\d+(?:\.\d+)+)/m"), &output, 0) { *version = Some(matches.get(1).map(str::to_string)); } diff --git a/crates/shirabe/src/util/github.rs b/crates/shirabe/src/util/github.rs index 570a33bb..9d73ae84 100644 --- a/crates/shirabe/src/util/github.rs +++ b/crates/shirabe/src/util/github.rs @@ -8,9 +8,10 @@ use crate::io::io_interface; use crate::util::HttpDownloader; use crate::util::ProcessExecutor; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::Catch as _; -use shirabe_php_shim::{PhpMixed, date_local, in_array_loose, php_regex, stripos, strtolower}; +use shirabe_php_shim::{ + PhpMixed, date_local, in_array_loose, php_regex, preg_match2, stripos, strtolower, +}; #[derive(Debug)] pub struct GitHub { @@ -325,7 +326,7 @@ impl GitHub { if stripos(header, "x-github-sso: required").is_none() { continue; } - if let Some(caps) = Preg::match3(php_regex!(r"{\burl=(?P[^\s;]+)}"), header) { + if let Some(caps) = preg_match2(php_regex!(r"{\burl=(?P[^\s;]+)}"), header, 0) { return caps.name("url").map(str::to_string); } } @@ -335,7 +336,13 @@ impl GitHub { pub fn is_rate_limited(&self, headers: &[String]) -> bool { for header in headers { - if Preg::is_match(php_regex!(r"{^x-ratelimit-remaining: *0$}i"), header.trim()) { + if preg_match2( + php_regex!(r"{^x-ratelimit-remaining: *0$}i"), + header.trim(), + 0, + ) + .is_some() + { return true; } } @@ -345,7 +352,7 @@ impl GitHub { pub fn requires_sso(&self, headers: &[String]) -> bool { for header in headers { - if Preg::is_match(php_regex!(r"{^x-github-sso: required}i"), header.trim()) { + if preg_match2(php_regex!(r"{^x-github-sso: required}i"), header.trim(), 0).is_some() { return true; } } diff --git a/crates/shirabe/src/util/gitlab.rs b/crates/shirabe/src/util/gitlab.rs index 52707b5b..c101b1f9 100644 --- a/crates/shirabe/src/util/gitlab.rs +++ b/crates/shirabe/src/util/gitlab.rs @@ -9,11 +9,10 @@ use crate::io::io_interface; use crate::util::HttpDownloader; use crate::util::ProcessExecutor; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ PhpMixed, RuntimeException, http_build_query, in_array_strict, json_decode_assoc, php_regex, - time, + preg_replace, time, }; #[derive(Debug)] @@ -54,7 +53,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(php_regex!("{:\\d+}"), "", origin_url); + let bc_origin_url = preg_replace(php_regex!("{:\\d+}"), "", origin_url); let gitlab_domains = self.config.borrow_mut().get("gitlab-domains"); if !in_array_strict(origin_url.to_string(), gitlab_domains.values()) diff --git a/crates/shirabe/src/util/hg.rs b/crates/shirabe/src/util/hg.rs index f95f15d5..00fee240 100644 --- a/crates/shirabe/src/util/hg.rs +++ b/crates/shirabe/src/util/hg.rs @@ -5,8 +5,7 @@ use crate::io::IOInterface; use crate::io::IOInterfaceImmutable; use crate::util::ProcessExecutor; use crate::util::Url; -use shirabe_pcre::Preg; -use shirabe_php_shim::{php_regex, rawurlencode}; +use shirabe_php_shim::{php_regex, preg_match2, rawurlencode}; use std::sync::OnceLock; static VERSION: OnceLock> = OnceLock::new(); @@ -56,11 +55,12 @@ impl Hg { } // Try with the authentication information available - let matched = Preg::is_match3( + let matched = preg_match2( php_regex!( r"{^(?Pssh|https?)://(?:(?P[^:@]+)(?::(?P[^:@]+))?@)?(?P[^/]+)(?P/.*)?}mi" ), &url, + 0, ); if let Some(matches) = matched @@ -151,9 +151,10 @@ impl Hg { &mut output, None, ) == 0 - && let Some(matches) = Preg::is_match3( + && let Some(matches) = preg_match2( php_regex!(r"/^.+? (\d+(?:\.\d+)+)(?:\+.*?)?\)?\r?\n/"), &output, + 0, ) { return matches.get(1).map(str::to_string); diff --git a/crates/shirabe/src/util/http/curl_downloader.rs b/crates/shirabe/src/util/http/curl_downloader.rs index 6140bb08..91165015 100644 --- a/crates/shirabe/src/util/http/curl_downloader.rs +++ b/crates/shirabe/src/util/http/curl_downloader.rs @@ -31,10 +31,9 @@ use crate::util::http::ProxyManager; use crate::util::http::Response; use crate::util::{AuthHelper, PromptAuthResult, StoreAuth}; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::{ - PhpMixed, in_array_loose, in_array_strict, parse_url, php_regex, preg_quote, rename, strpos, - substr, unlink_silent, + PhpMixed, in_array_loose, in_array_strict, parse_url, php_regex, preg_match2, preg_quote, + preg_replace, rename, strpos, substr, unlink_silent, }; use std::sync::atomic::{AtomicBool, Ordering}; @@ -147,7 +146,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(php_regex!(r"{^http://(repo\.)?packagist\.org/p/}"), url) + if preg_match2(php_regex!(r"{^http://(repo\.)?packagist\.org/p/}"), url, 0).is_none() || (strpos(url, "$").is_none() && strpos(url, "%24").is_none()) { self.config.borrow_mut().prohibit_url_by_config( @@ -653,7 +652,7 @@ impl CurlDownloader { // Absolute path; e.g. /foo let url_host = parse_url(url).and_then(|parsed| parsed.host); let url_host_str = url_host.as_deref().unwrap_or(""); - target_url = Preg::replace( + target_url = preg_replace( format!( r"{{^(.+(?://|@){}(?::\d+)?)(?:[/\?].*)?$}}", preg_quote(url_host_str, None) @@ -663,7 +662,7 @@ impl CurlDownloader { ); } else { // Relative path; e.g. foo - target_url = Preg::replace( + target_url = preg_replace( php_regex!(r"{^(.+/)[^/?]*(?:\?.*)?$}"), &format!("\\1{}", location_header), url, @@ -747,13 +746,15 @@ impl CurlDownloader { && substr(url, -4, None) == ".zip" && (location_header.is_none() || substr(location_header.as_deref().unwrap_or(""), -4, None) != ".zip") - && Preg::is_match( + && preg_match2( php_regex!(r"{^text/html\b}i"), &response .inner .get_header("content-type") .unwrap_or_default(), + 0, ) + .is_some() { needs_auth_retry = Some("Bitbucket requires authentication and it was not provided"); } diff --git a/crates/shirabe/src/util/http/response.rs b/crates/shirabe/src/util/http/response.rs index bd117a24..ed5c5214 100644 --- a/crates/shirabe/src/util/http/response.rs +++ b/crates/shirabe/src/util/http/response.rs @@ -1,8 +1,7 @@ //! ref: composer/src/Composer/Util/Http/Response.php use crate::json::JsonFile; -use shirabe_pcre::Preg; -use shirabe_php_shim::{PhpMixed, php_regex, preg_quote}; +use shirabe_php_shim::{PhpMixed, php_regex, preg_match2, preg_quote}; #[derive(Debug)] pub struct Response { @@ -29,7 +28,7 @@ impl Response { pub fn get_status_message(&self) -> Option { let mut value = None; for header in &self.headers { - if Preg::is_match(php_regex!(r"{^HTTP/\S+ \d+}i"), header) { + if preg_match2(php_regex!(r"{^HTTP/\S+ \d+}i"), header, 0).is_some() { // 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()); @@ -65,7 +64,7 @@ impl Response { let mut value = None; let pattern = format!("{{^{}:\\s*(.+?)\\s*$}}i", preg_quote(name, None)); for header in headers { - if let Some(matches) = Preg::match3(&pattern, header) + if let Some(matches) = preg_match2(&pattern, header, 0) && let Some(s) = matches.get(1) { value = Some(s.to_string()); diff --git a/crates/shirabe/src/util/http_downloader.rs b/crates/shirabe/src/util/http_downloader.rs index 151b2646..8210a5c4 100644 --- a/crates/shirabe/src/util/http_downloader.rs +++ b/crates/shirabe/src/util/http_downloader.rs @@ -16,12 +16,11 @@ use crate::util::http::CurlDownloader; use crate::util::http::Response; use crate::util::sync_executor; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ InvalidArgumentException, LogicException, PhpMixed, array_replace_recursive, extension_loaded, - file_get_contents, function_exists, implode, is_numeric, php_regex, rawurldecode, - stream_context_create, stripos, strpos, substr, ucfirst, + file_get_contents, function_exists, implode, is_numeric, php_regex, preg_match2, preg_replace, + rawurldecode, stream_context_create, stripos, strpos, substr, ucfirst, }; use shirabe_semver::constraint::SimpleConstraint; @@ -240,8 +239,11 @@ impl HttpDownloader { let origin = Url::get_origin(&self.config.borrow(), url); // capture username/password from URL if there is one - if let Some(m) = Preg::is_match3(php_regex!(r"{^https?://([^:/]+):([^@/]+)@([^/]+)}i"), url) - { + if let Some(m) = preg_match2( + php_regex!(r"{^https?://([^:/]+):([^@/]+)@([^/]+)}i"), + url, + 0, + ) { self.io.borrow_mut().set_authentication( origin.clone(), rawurldecode(m.get(1).unwrap_or_default().to_string().as_str()), @@ -355,7 +357,7 @@ impl HttpDownloader { ) -> anyhow::Result<()> { let clean_message = |msg: &str| -> anyhow::Result { if !io.is_decorated() { - return Ok(Preg::replace("{\x1b\\[[;\\d]*m}u", "", msg)); + return Ok(preg_replace("{\x1b\\[[;\\d]*m}u", "", msg)); } Ok(msg.to_string()) @@ -487,7 +489,7 @@ impl HttpDownloader { return false; } - if !Preg::is_match(php_regex!(r"{^https?://}i"), url) { + if preg_match2(php_regex!(r"{^https?://}i"), url, 0).is_none() { return false; } diff --git a/crates/shirabe/src/util/perforce.rs b/crates/shirabe/src/util/perforce.rs index c0cd5a08..32e3e9cd 100644 --- a/crates/shirabe/src/util/perforce.rs +++ b/crates/shirabe/src/util/perforce.rs @@ -6,11 +6,10 @@ use crate::util::Filesystem; use crate::util::Platform; use crate::util::ProcessExecutor; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::{ Exception, PHP_EOL, PhpMixed, PhpResource, chdir, date_local, explode, fclose, feof, fgets, - file_get_contents, fopen, fwrite, gethostname, json_decode_assoc, php_regex, str_replace_array, - strcmp, strlen, strpos, strrpos, substr, time, trim, + file_get_contents, fopen, fwrite, gethostname, json_decode_assoc, php_regex, preg_replace, + str_replace_array, strcmp, strlen, strpos, strrpos, substr, time, trim, }; use shirabe_symfony_process::ExecutableFinder; use shirabe_symfony_process::Process; @@ -660,7 +659,7 @@ impl Perforce { for line in &res_array { let res_bits = explode(" ", line); if res_bits.len() > 4 { - let branch = Preg::replace( + let branch = preg_replace( 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 606ff43d..91039c17 100644 --- a/crates/shirabe/src/util/platform.rs +++ b/crates/shirabe/src/util/platform.rs @@ -2,12 +2,12 @@ use crate::util::ProcessExecutor; use crate::util::Silencer; -use shirabe_pcre::{Preg, PregMatches}; use shirabe_php_shim::{ - PHP_ENV, PHP_SERVER, PhpMixed, PhpResource, RuntimeException, defined, file_exists, - file_get_contents, fstat, function_exists, getcwd, getenv, ini_get, 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, + PHP_ENV, PHP_SERVER, PhpMixed, PhpResource, PregMatches, RuntimeException, defined, + file_exists, file_get_contents, fstat, function_exists, getcwd, getenv, ini_get, is_readable, + mb_strlen, php_os_family, php_regex, posix_geteuid, posix_getpwuid, posix_getuid, posix_isatty, + preg_match2, preg_replace_callback, putenv, putenv_clear, realpath, stream_isatty, stripos, + strlen, strtoupper, substr, usleep, }; use std::sync::Mutex; @@ -83,7 +83,7 @@ impl Platform { /// Parses tildes and environment variables in paths. pub fn expand_path(path: &str) -> String { - if Preg::is_match(php_regex!(r"#^~[\\/]#"), path) { + if preg_match2(php_regex!(r"#^~[\\/]#"), path, 0).is_some() { return format!( "{}{}", Self::get_user_directory().unwrap(), @@ -95,9 +95,9 @@ impl Platform { // The original pattern uses a conditional subpattern to make the trailing `%` required // 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( + preg_replace_callback( php_regex!(r"#^(?:\$(?P\w+)|%(?P\w+)%)(?P.*)#"), - |matches: &PregMatches| -> String { + |matches: &PregMatches| -> anyhow::Result { let var = matches .name("dvar") .or_else(|| matches.name("pvar")) @@ -108,24 +108,25 @@ impl Platform { let home = Platform::get_env("HOME").filter(|v| PhpMixed::String(v.clone()).to_bool()); if let Some(home) = home { - return format!("{}{}", home, path_part); + return Ok(format!("{}{}", home, path_part)); } - return format!( + return Ok(format!( "{}{}", Platform::get_env("USERPROFILE").unwrap_or_default(), path_part, - ); + )); } - format!( + Ok(format!( "{}{}", Platform::get_env(var).unwrap_or_default(), path_part, - ) + )) }, path, ) + .expect("the replacement callback cannot fail") } /// @throws \RuntimeException If the user home could not reliably be determined diff --git a/crates/shirabe/src/util/process_executor.rs b/crates/shirabe/src/util/process_executor.rs index 2bfaeb94..158729b4 100644 --- a/crates/shirabe/src/util/process_executor.rs +++ b/crates/shirabe/src/util/process_executor.rs @@ -7,13 +7,12 @@ use crate::signal::SignalSubscription; use crate::util::GitHub; use crate::util::Platform; use indexmap::IndexMap; -use shirabe_pcre::{Preg, PregMatches}; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ - LogicException, PHP_EOL, PhpMixed, RuntimeException, array_intersect, array_map, + LogicException, PHP_EOL, PhpMixed, PregMatches, RuntimeException, array_intersect, array_map, escapeshellarg, explode, implode, in_array_strict, is_array, is_dir, is_numeric, is_string, - php_regex, preg_split, rtrim, str_replace, strcspn, strlen, strpbrk, strtolower, strtr_array, - substr_replace, trim, + php_regex, preg_match2, preg_replace, preg_replace_callback, preg_replace2, preg_split, rtrim, + str_replace, strcspn, strlen, strpbrk, strtolower, strtr_array, substr_replace, trim, }; use shirabe_symfony_process::ExecutableFinder; use shirabe_symfony_process::Process; @@ -217,7 +216,7 @@ impl ProcessExecutor { if is_string(&command) { let mut command_str = command.as_string().unwrap_or("").to_string(); if Platform::is_windows() - && let Some(m) = Preg::is_match3(php_regex!(r"{^([^:/\\]++) }"), &command_str) + && let Some(m) = preg_match2(php_regex!(r"{^([^:/\\]++) }"), &command_str, 0) { let m1 = m.get(1).unwrap_or_default().to_string(); command_str = substr_replace( @@ -829,25 +828,31 @@ impl ProcessExecutor { } else { String::new() }; - let safe_command = Preg::replace_callback( + let safe_command = preg_replace_callback( php_regex!(r"{://(?P[^:/\s]+):(?P[^@\s/]+)@}i"), - |m: &PregMatches| -> String { + |m: &PregMatches| -> anyhow::Result { // 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 - if Preg::is_match( + if preg_match2( GitHub::GITHUB_TOKEN_REGEX, m.name("user").unwrap_or_default(), - ) { - return "://***:***@".to_string(); + 0, + ) + .is_some() + { + return Ok("://***:***@".to_string()); } - if Preg::is_match(r"{^[a-f0-9]{12,}$}", m.name("user").unwrap_or_default()) { - return "://***:***@".to_string(); + if preg_match2(r"{^[a-f0-9]{12,}$}", m.name("user").unwrap_or_default(), 0) + .is_some() + { + return Ok("://***:***@".to_string()); } - format!("://{}:***@", m.name("user").unwrap_or_default()) + Ok(format!("://{}:***@", m.name("user").unwrap_or_default())) }, &command_string, - ); - let safe_command = Preg::replace( + ) + .expect("the replacement callback cannot fail"); + let safe_command = preg_replace( php_regex!(r"{--password (.*[^\\]') }"), "--password '***' ", &safe_command, @@ -894,26 +899,27 @@ 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( + argument = preg_replace2( php_regex!(r#"/(\\*)"/"#), r#"$1$1\""#, &argument, -1, - &mut dquotes, + Some(&mut dquotes), ); - let meta = dquotes > 0 || Preg::is_match(php_regex!(r"/%[^%]+%|![^!]+!/"), &argument); + let meta = + dquotes > 0 || preg_match2(php_regex!(r"/%[^%]+%|![^!]+!/"), &argument, 0).is_some(); if !meta && !quote { quote = strpbrk(&argument, "^&|<>()").is_some(); } if quote { - argument = format!("\"{}\"", Preg::replace(r"/(\\*)$/", "$1$1", &argument)); + argument = format!("\"{}\"", preg_replace(r"/(\\*)$/", "$1$1", &argument)); } if meta { - argument = Preg::replace(php_regex!(r#"/(["^&|<>()%])/"#), "^$1", &argument); - argument = Preg::replace(php_regex!(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 e55e5200..7af5473a 100644 --- a/crates/shirabe/src/util/remote_filesystem.rs +++ b/crates/shirabe/src/util/remote_filesystem.rs @@ -13,14 +13,14 @@ use crate::util::Url; use crate::util::http::ProxyManager; use crate::util::http::Response; use indexmap::IndexMap; -use shirabe_pcre::Preg; use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ PhpMixed, RuntimeException, STREAM_NOTIFY_FAILURE, STREAM_NOTIFY_FILE_SIZE_IS, STREAM_NOTIFY_PROGRESS, 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_assoc, - parse_url, php_regex, preg_quote, strpos, strtolower, strtr, substr, trim, zlib_decode, + parse_url, php_regex, preg_match2, preg_quote, preg_replace, strpos, strtolower, strtr, substr, + trim, zlib_decode, }; /// Result of `RemoteFilesystem::get` — string content, `true` (for copy), or `false`. @@ -148,7 +148,7 @@ impl RemoteFilesystem { pub fn find_status_code(headers: &[String]) -> Option { let mut value: Option = None; for header in headers { - if let Some(m) = Preg::is_match3(php_regex!("{^HTTP/\\S+ (\\d+)}i"), header) { + if let Some(m) = preg_match2(php_regex!("{^HTTP/\\S+ (\\d+)}i"), header, 0) { value = m.get(1).and_then(|s| s.parse().ok()).or(Some(0)); } } @@ -159,7 +159,7 @@ impl RemoteFilesystem { pub fn find_status_message(&self, headers: &[String]) -> Option { let mut value: Option = None; for header in headers { - if Preg::is_match(php_regex!("{^HTTP/\\S+ \\d+}i"), header) { + if preg_match2(php_regex!("{^HTTP/\\S+ \\d+}i"), header, 0).is_some() { value = Some(header.clone()); } } @@ -285,10 +285,13 @@ impl RemoteFilesystem { crate::io::DEBUG, ); - if (!Preg::is_match( + if (preg_match2( php_regex!("{^http://(repo\\.)?packagist\\.org/p/}"), &file_url, - ) || (strpos(&file_url, "$").is_none() && strpos(&file_url, "%24").is_none())) + 0, + ) + .is_none() + || (strpos(&file_url, "$").is_none() && strpos(&file_url, "%24").is_none())) && !degraded_packagist { let _ = self.config.borrow_mut().prohibit_url_by_config( @@ -472,10 +475,12 @@ impl RemoteFilesystem { None, ) != ".zip") && content_type.is_some() - && Preg::is_match( + && preg_match2( php_regex!("{^text/html\\b}i"), content_type.as_deref().unwrap_or(""), - ); + 0, + ) + .is_some(); if bitbucket_login_match { result = None; if retry_auth_failure { @@ -941,7 +946,7 @@ impl RemoteFilesystem { .and_then(|parsed| parsed.host) .unwrap_or_default(); - target_url = Some(Preg::replace( + target_url = Some(preg_replace( format!( "{{^(.+(?://|@){}(?::\\d+)?)(?:[/\\?].*)?$}}", preg_quote(&url_host, None) @@ -950,7 +955,7 @@ impl RemoteFilesystem { &self.file_url, )); } else { - target_url = Some(Preg::replace( + 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 5ff6a025..38189d31 100644 --- a/crates/shirabe/src/util/svn.rs +++ b/crates/shirabe/src/util/svn.rs @@ -6,10 +6,9 @@ use crate::io::IOInterfaceImmutable; use crate::io::io_interface; use crate::util::Platform; use crate::util::ProcessExecutor; -use shirabe_pcre::Preg; use shirabe_php_shim::{ - LogicException, PhpMixed, RuntimeException, implode, parse_url, php_regex, stripos, strpos, - trim, + LogicException, PhpMixed, RuntimeException, implode, parse_url, php_regex, preg_match2, + stripos, strpos, trim, }; use std::sync::Mutex; @@ -405,7 +404,7 @@ impl Svn { &["svn".to_string(), "--version".to_string()], &mut output, None, - ) && let Some(matches) = Preg::is_match3(php_regex!(r"{(\d+(?:\.\d+)+)}"), &output) + ) && let Some(matches) = preg_match2(php_regex!(r"{(\d+(?:\.\d+)+)}"), &output, 0) { *cached = Some(matches.get(1).unwrap_or_default().to_string()); } diff --git a/crates/shirabe/src/util/url.rs b/crates/shirabe/src/util/url.rs index eb533a06..2754ef09 100644 --- a/crates/shirabe/src/util/url.rs +++ b/crates/shirabe/src/util/url.rs @@ -2,8 +2,10 @@ use crate::config::Config; use crate::util::GitHub; -use shirabe_pcre::Preg; -use shirabe_php_shim::{PhpMixed, in_array_strict, parse_url, php_regex}; +use shirabe_php_shim::{ + PhpMixed, in_array_strict, parse_url, php_regex, preg_match2, preg_replace, + preg_replace_callback, +}; pub struct Url; @@ -14,11 +16,12 @@ impl Url { .unwrap_or_default(); if host == "api.github.com" || host == "github.com" || host == "www.github.com" { - if let Some(m) = Preg::match3( + if let Some(m) = preg_match2( php_regex!( r"{^https?://(?:www\.)?github\.com/([^/]+)/([^/]+)/(zip|tar)ball/(.+)$}i" ), &url, + 0, ) { url = format!( "https://api.github.com/repos/{}/{}/{}ball/{}", @@ -27,11 +30,12 @@ impl Url { m.get(3).unwrap_or_default(), r#ref ); - } else if let Some(m) = Preg::match3( + } else if let Some(m) = preg_match2( php_regex!( r"{^https?://(?:www\.)?github\.com/([^/]+)/([^/]+)/archive/.+\.(zip|tar)(?:\.gz)?$}i" ), &url, + 0, ) { url = format!( "https://api.github.com/repos/{}/{}/{}ball/{}", @@ -40,11 +44,12 @@ impl Url { m.get(3).unwrap_or_default(), r#ref ); - } else if let Some(m) = Preg::match3( + } else if let Some(m) = preg_match2( php_regex!( r"{^https?://api\.github\.com/repos/([^/]+)/([^/]+)/(zip|tar)ball(?:/.+)?$}i" ), &url, + 0, ) { url = format!( "https://api.github.com/repos/{}/{}/{}ball/{}", @@ -55,11 +60,12 @@ impl Url { ); } } else if host == "bitbucket.org" || host == "www.bitbucket.org" { - if let Some(m) = Preg::match3( + if let Some(m) = preg_match2( php_regex!( r"{^https?://(?:www\.)?bitbucket\.org/([^/]+)/([^/]+)/get/(.+)\.(zip|tar\.gz|tar\.bz2)$}i" ), &url, + 0, ) { url = format!( "https://bitbucket.org/{}/{}/get/{}.{}", @@ -70,11 +76,12 @@ impl Url { ); } } else if host == "gitlab.com" || host == "www.gitlab.com" { - if let Some(m) = Preg::match3( + if let Some(m) = preg_match2( php_regex!( r"{^https?://(?:www\.)?gitlab\.com/api/v[34]/projects/([^/]+)/repository/archive\.(zip|tar\.gz|tar\.bz2|tar)\?sha=.+$}i" ), &url, + 0, ) { url = format!( "https://gitlab.com/api/v4/projects/{}/repository/archive.{}?sha={}", @@ -84,13 +91,13 @@ impl Url { ); } } else if in_array_strict(host.clone(), config.get("github-domains").values()) { - url = Preg::replace( + url = preg_replace( php_regex!(r"{(/repos/[^/]+/[^/]+/(zip|tar)ball)(?:/.+)?$}i"), &format!("$1/{}", r#ref), &url, ); } else if in_array_strict(host, config.get("gitlab-domains").values()) { - url = Preg::replace( + url = preg_replace( php_regex!( r"{(/api/v[34]/projects/[^/]+/repository/archive\.(?:zip|tar\.gz|tar\.bz2|tar)\?sha=).+$}i" ), @@ -158,21 +165,24 @@ 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(php_regex!(r"{([&?]access_token=)[^&]+}"), "$1***", &url); + let url = preg_replace(php_regex!(r"{([&?]access_token=)[^&]+}"), "$1***", &url); - Preg::replace_callback( + preg_replace_callback( php_regex!(r"{^(?P[a-z0-9]+://)?(?P[^:/\s@]+):(?P[^@\s/]+)@}i"), |m| { let user = m.name("user").unwrap_or_default().to_string(); let prefix = m.name("prefix").unwrap_or_default().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 - if Preg::is_match(GitHub::GITHUB_TOKEN_REGEX, &user) { - format!("{}***:***@", prefix) - } else { - format!("{}{}:***@", prefix, user) - } + Ok( + if preg_match2(GitHub::GITHUB_TOKEN_REGEX, &user, 0).is_some() { + format!("{}***:***@", prefix) + } else { + format!("{}{}:***@", prefix, user) + }, + ) }, &url, ) + .expect("the replacement callback cannot fail") } } diff --git a/crates/shirabe/tests/all_functional_test.rs b/crates/shirabe/tests/all_functional_test.rs index d947a054..36137955 100644 --- a/crates/shirabe/tests/all_functional_test.rs +++ b/crates/shirabe/tests/all_functional_test.rs @@ -8,8 +8,7 @@ use indexmap::IndexMap; use serial_test::serial; use shirabe::util::filesystem::Filesystem; -use shirabe_pcre::preg::Preg; -use shirabe_php_shim::{PhpMixed, intval, php_regex, preg_split_delim_capture}; +use shirabe_php_shim::{PhpMixed, intval, php_regex, preg_match2, preg_split_delim_capture}; use std::path::{Path, PathBuf}; /// ref: AllFunctionalTest's `$oldcwd` / `$testDir` instance state plus its `setUp`/`tearDown`. @@ -141,13 +140,13 @@ fn expect_matches(expected: &str, output: &str) { line += 1; } if eb[i] == b'%' { - let Some(m) = Preg::is_match3(php_regex!("{%(.+?)%}"), &expected[i..]) else { + let Some(m) = preg_match2(php_regex!("{%(.+?)%}"), &expected[i..], 0) else { panic!("Failed to match %...% in {}", &expected[i..]); }; let regex = m.get(1).map(str::to_string).unwrap(); let pattern = format!("{{{}}}", regex); - if let Some(m) = Preg::is_match3(&pattern, &output[j..]) { + if let Some(m) = preg_match2(&pattern, &output[j..], 0) { let full = m.get(0).map(str::to_string).unwrap(); i += regex.len() + 2; j += full.len(); @@ -222,12 +221,16 @@ fn run_integration(test_filename: &str) { expect_matches(expected, output); } if let Some(expect_regex) = test_data.get("EXPECT-REGEX") { - assert!(Preg::is_match(expect_regex, &clean_output(&raw_output))); + assert!(preg_match2(expect_regex, &clean_output(&raw_output), 0).is_some()); } if let Some(expect_regexes) = test_data.get("EXPECT-REGEXES") { let clean = clean_output(&raw_output); for regex in expect_regexes.split('\n') { - assert!(Preg::is_match(regex, &clean), "Output: {}", raw_output); + assert!( + preg_match2(regex, &clean, 0).is_some(), + "Output: {}", + raw_output + ); } } if let Some(expect_exit_code) = test_data.get("EXPECT-EXIT-CODE") { diff --git a/crates/shirabe/tests/common/io_mock.rs b/crates/shirabe/tests/common/io_mock.rs index c1bd5e00..7aaa231a 100644 --- a/crates/shirabe/tests/common/io_mock.rs +++ b/crates/shirabe/tests/common/io_mock.rs @@ -5,8 +5,7 @@ use shirabe::io::buffer_io::BufferIO; use shirabe::io::io_interface; use shirabe::io::{IOInterface, IOInterfaceImmutable, IOInterfaceMutable}; use shirabe::util::platform::Platform; -use shirabe_pcre::Preg; -use shirabe_php_shim::{PHP_EOL, PhpMixed, php_regex, preg_quote, preg_split}; +use shirabe_php_shim::{PHP_EOL, PhpMixed, php_regex, preg_match2, preg_quote, preg_split}; use shirabe_symfony_console::output::output_interface; use std::collections::VecDeque; @@ -167,7 +166,7 @@ impl IOMock { }; while let Some(line) = lines.pop_front() { - if Preg::is_match(&pattern, &line) { + if preg_match2(&pattern, &line, 0).is_some() { continue 'expects; } diff --git a/crates/shirabe/tests/dependency_resolver/pool_builder_test.rs b/crates/shirabe/tests/dependency_resolver/pool_builder_test.rs index a4d118ee..27359fa3 100644 --- a/crates/shirabe/tests/dependency_resolver/pool_builder_test.rs +++ b/crates/shirabe/tests/dependency_resolver/pool_builder_test.rs @@ -19,8 +19,7 @@ use shirabe::repository::handle::{LockArrayRepositoryHandle, RepositoryInterface use shirabe::repository::lock_array_repository::LockArrayRepository; use shirabe::repository::repository_factory::RepositoryFactory; use shirabe::repository::repository_set::{RepositorySet, RootAliasInput}; -use shirabe_pcre::preg::Preg; -use shirabe_php_shim::{PhpMixed, php_regex, preg_split_delim_capture}; +use shirabe_php_shim::{PhpMixed, php_regex, preg_match2, preg_split_delim_capture}; use std::path::PathBuf; /// Maps the PHP `$loadPackage` closure: pops the optional `id` from the data, loads the @@ -138,7 +137,7 @@ fn get_integration_tests(fixtures_dir: &std::path::Path) -> IndexMap BasePackageHandle { @@ -141,7 +140,7 @@ fn provide_integration_tests() -> IndexMap< for file in files { let file = file.to_str().unwrap().to_string(); - if !Preg::is_match(php_regex!(r"/\.test$/"), &file) { + if preg_match2(php_regex!(r"/\.test$/"), &file, 0).is_none() { continue; } diff --git a/crates/shirabe/tests/installer_test.rs b/crates/shirabe/tests/installer_test.rs index 7b86be89..5503824e 100644 --- a/crates/shirabe/tests/installer_test.rs +++ b/crates/shirabe/tests/installer_test.rs @@ -42,8 +42,7 @@ use shirabe::util::r#loop::Loop; use shirabe::util::platform::Platform; use shirabe::util::process_executor::ProcessExecutor; use shirabe_class_map_generator::class_map::ClassMap; -use shirabe_pcre::preg::Preg; -use shirabe_php_shim::{PhpMixed, php_regex, preg_split_delim_capture}; +use shirabe_php_shim::{PhpMixed, php_regex, preg_match2, preg_replace, preg_split_delim_capture}; use shirabe_semver::VersionParser; use shirabe_semver::constraint::AnyConstraint; use shirabe_symfony_console::command::Command as SymfonyCommand; @@ -692,7 +691,7 @@ fn load_integration_tests(path: &str) -> Vec { return; } if let Some(url) = repo.get("url").and_then(|u| u.as_str()) - && Preg::is_match(php_regex!(r"{^file://[^/]}"), url) + && preg_match2(php_regex!(r"{^file://[^/]}"), url, 0).is_some() { let new_url = format!("file://{}/{}", fixtures_str, &url[7..]); repo["url"] = serde_json::Value::String(new_url); @@ -1138,7 +1137,7 @@ fn do_test_integration(case: &IntegrationCase, expect_output: Option<&str>) { .unwrap(); assert!( - Preg::is_match(r"{^(install|update)\b}", &case.run), + preg_match2(r"{^(install|update)\b}", &case.run, 0).is_some(), "The run command only supports install and update" ); @@ -1276,12 +1275,12 @@ fn do_test_integration(case: &IntegrationCase, expect_output: Option<&str>) { if let Some(expect_output) = expect_output && !expect_output.is_empty() { - let output = Preg::replace( + let output = preg_replace( php_regex!(r"{^ - .*?\.ini$}m"), "__inilist__", &output_string, ); - let output = Preg::replace( + let output = preg_replace( php_regex!(r"{(__inilist__\r?\n)+}"), "__inilist__\n", &output, diff --git a/crates/shirabe/tests/package/archiver/archivable_files_finder_test.rs b/crates/shirabe/tests/package/archiver/archivable_files_finder_test.rs index 499e08dc..d932dd4e 100644 --- a/crates/shirabe/tests/package/archiver/archivable_files_finder_test.rs +++ b/crates/shirabe/tests/package/archiver/archivable_files_finder_test.rs @@ -3,8 +3,9 @@ use indexmap::IndexMap; use shirabe::package::archiver::ArchivableFilesFinder; use shirabe::util::Filesystem; -use shirabe_pcre::Preg; -use shirabe_php_shim::{PhpMixed, ZipArchive, dirname, file_put_contents, preg_quote}; +use shirabe_php_shim::{ + PhpMixed, ZipArchive, dirname, file_put_contents, preg_quote, preg_replace, +}; use shirabe_symfony_process::Process; use tempfile::TempDir; @@ -85,7 +86,7 @@ fn get_archivable_files(set_up: &SetUp, finder: ArchivableFilesFinder) -> Vec Vec { continue; } let virtual_path = format!("phar://{}/archive.zip/{}", set_up.sources, name); - files.push(Preg::replace( + files.push(preg_replace( &prefix, "", &set_up.fs.normalize_path(&virtual_path), -- cgit v1.3.1-4-g156e