diff options
| author | nsfisis <nsfisis@gmail.com> | 2026-05-17 02:53:53 +0900 |
|---|---|---|
| committer | nsfisis <nsfisis@gmail.com> | 2026-05-17 02:53:53 +0900 |
| commit | a1c7e6908a26e10f6e1f23a51721664b5e2d838d (patch) | |
| tree | c575c76f1b43359ed74913da4c6a2636643f1ba0 /crates/shirabe/src/package | |
| parent | 7f606f36fef0c0467c3c0db3d0da33af486dae8a (diff) | |
| download | php-shirabe-a1c7e6908a26e10f6e1f23a51721664b5e2d838d.tar.gz php-shirabe-a1c7e6908a26e10f6e1f23a51721664b5e2d838d.tar.zst php-shirabe-a1c7e6908a26e10f6e1f23a51721664b5e2d838d.zip | |
chore(style): cargo fmt
Diffstat (limited to 'crates/shirabe/src/package')
34 files changed, 700 insertions, 400 deletions
diff --git a/crates/shirabe/src/package/alias_package.rs b/crates/shirabe/src/package/alias_package.rs index 0c8158f..a101a1f 100644 --- a/crates/shirabe/src/package/alias_package.rs +++ b/crates/shirabe/src/package/alias_package.rs @@ -2,7 +2,7 @@ use chrono::{DateTime, Utc}; use indexmap::IndexMap; -use shirabe_php_shim::{in_array, PhpMixed}; +use shirabe_php_shim::{PhpMixed, in_array}; use shirabe_semver::constraint::constraint::Constraint; use crate::package::base_package::BasePackage; diff --git a/crates/shirabe/src/package/archiver/archivable_files_filter.rs b/crates/shirabe/src/package/archiver/archivable_files_filter.rs index a267cf1..f820e08 100644 --- a/crates/shirabe/src/package/archiver/archivable_files_filter.rs +++ b/crates/shirabe/src/package/archiver/archivable_files_filter.rs @@ -1,7 +1,7 @@ //! ref: composer/src/Composer/Package/Archiver/ArchivableFilesFilter.php -use std::path::PathBuf; use shirabe_php_shim::PharData; +use std::path::PathBuf; pub struct ArchivableFilesFilter { inner: Box<dyn Iterator<Item = PathBuf>>, diff --git a/crates/shirabe/src/package/archiver/archivable_files_finder.rs b/crates/shirabe/src/package/archiver/archivable_files_finder.rs index 7d1b94e..35ec36f 100644 --- a/crates/shirabe/src/package/archiver/archivable_files_finder.rs +++ b/crates/shirabe/src/package/archiver/archivable_files_finder.rs @@ -1,12 +1,12 @@ //! ref: composer/src/Composer/Package/Archiver/ArchivableFilesFinder.php -use shirabe_external_packages::composer::pcre::preg::Preg; -use shirabe_external_packages::symfony::component::finder::finder::Finder; -use shirabe_external_packages::symfony::component::finder::spl_file_info::SplFileInfo; -use shirabe_php_shim::{preg_quote, realpath, RuntimeException}; use crate::package::archiver::composer_exclude_filter::ComposerExcludeFilter; use crate::package::archiver::git_exclude_filter::GitExcludeFilter; use crate::util::filesystem::Filesystem; +use shirabe_external_packages::composer::pcre::preg::Preg; +use shirabe_external_packages::symfony::component::finder::finder::Finder; +use shirabe_external_packages::symfony::component::finder::spl_file_info::SplFileInfo; +use shirabe_php_shim::{RuntimeException, preg_quote, realpath}; pub struct ArchivableFilesFinder { pub(crate) finder: Finder, @@ -30,7 +30,8 @@ impl ArchivableFilesFinder { return Err(RuntimeException { message: format!("Could not realpath() the source directory \"{}\"", sources), code: 0, - }.into()); + } + .into()); } let sources = fs.normalize_path(&sources_real_path.unwrap()); diff --git a/crates/shirabe/src/package/archiver/archive_manager.rs b/crates/shirabe/src/package/archiver/archive_manager.rs index ed7c6f7..3f7bfe0 100644 --- a/crates/shirabe/src/package/archiver/archive_manager.rs +++ b/crates/shirabe/src/package/archiver/archive_manager.rs @@ -1,11 +1,11 @@ //! ref: composer/src/Composer/Package/Archiver/ArchiveManager.php use indexmap::IndexMap; +use shirabe_external_packages::composer::pcre::preg::Preg; use shirabe_php_shim::{ - bin2hex, file_exists, random_bytes, realpath, sys_get_temp_dir, InvalidArgumentException, - RuntimeException, + InvalidArgumentException, RuntimeException, bin2hex, file_exists, random_bytes, realpath, + sys_get_temp_dir, }; -use shirabe_external_packages::composer::pcre::preg::Preg; use crate::downloader::download_manager::DownloadManager; use crate::json::json_file::JsonFile; @@ -58,11 +58,7 @@ impl ArchiveManager { ) -> IndexMap<String, String> { let base_name = match package.get_archive_name() { Some(name) => name.to_string(), - None => Preg::replace( - "#[^a-z0-9-_]#i", - "-", - package.get_name(), - ), + None => Preg::replace("#[^a-z0-9-_]#i", "-", package.get_name()), }; let mut parts: IndexMap<String, String> = IndexMap::new(); @@ -129,7 +125,10 @@ impl ArchiveManager { let mut usable_archiver_idx: Option<usize> = None; for (i, archiver) in self.archivers.iter().enumerate() { - if archiver.supports(format.clone(), package.get_source_type().map(|s| s.to_string())) { + if archiver.supports( + format.clone(), + package.get_source_type().map(|s| s.to_string()), + ) { usable_archiver_idx = Some(i); break; } diff --git a/crates/shirabe/src/package/archiver/base_exclude_filter.rs b/crates/shirabe/src/package/archiver/base_exclude_filter.rs index 7f737fe..f20af20 100644 --- a/crates/shirabe/src/package/archiver/base_exclude_filter.rs +++ b/crates/shirabe/src/package/archiver/base_exclude_filter.rs @@ -53,7 +53,10 @@ impl BaseExcludeFilter { } pub fn generate_patterns(&self, rules: Vec<String>) -> Vec<(String, bool, bool)> { - rules.into_iter().map(|rule| self.generate_pattern(&rule)).collect() + rules + .into_iter() + .map(|rule| self.generate_pattern(&rule)) + .collect() } pub fn generate_pattern(&self, rule: &str) -> (String, bool, bool) { diff --git a/crates/shirabe/src/package/archiver/git_exclude_filter.rs b/crates/shirabe/src/package/archiver/git_exclude_filter.rs index b3e43dc..8028c15 100644 --- a/crates/shirabe/src/package/archiver/git_exclude_filter.rs +++ b/crates/shirabe/src/package/archiver/git_exclude_filter.rs @@ -1,8 +1,8 @@ //! ref: composer/src/Composer/Package/Archiver/GitExcludeFilter.php -use std::path::Path; -use shirabe_external_packages::composer::pcre::preg::Preg; use crate::package::archiver::base_exclude_filter::BaseExcludeFilter; +use shirabe_external_packages::composer::pcre::preg::Preg; +use std::path::Path; pub struct GitExcludeFilter { inner: BaseExcludeFilter, @@ -20,10 +20,9 @@ impl GitExcludeFilter { .lines() .map(|l| l.to_string()) .collect(); - let patterns = filter.inner.parse_lines( - lines, - |line| GitExcludeFilter::parse_git_attributes_line_static(line), - ); + let patterns = filter.inner.parse_lines(lines, |line| { + GitExcludeFilter::parse_git_attributes_line_static(line) + }); filter.inner.exclude_patterns.extend(patterns); } diff --git a/crates/shirabe/src/package/archiver/mod.rs b/crates/shirabe/src/package/archiver/mod.rs new file mode 100644 index 0000000..ecf86c8 --- /dev/null +++ b/crates/shirabe/src/package/archiver/mod.rs @@ -0,0 +1,9 @@ +pub mod archivable_files_filter; +pub mod archivable_files_finder; +pub mod archive_manager; +pub mod archiver_interface; +pub mod base_exclude_filter; +pub mod composer_exclude_filter; +pub mod git_exclude_filter; +pub mod phar_archiver; +pub mod zip_archiver; diff --git a/crates/shirabe/src/package/archiver/phar_archiver.rs b/crates/shirabe/src/package/archiver/phar_archiver.rs index 24cd738..2e9d96e 100644 --- a/crates/shirabe/src/package/archiver/phar_archiver.rs +++ b/crates/shirabe/src/package/archiver/phar_archiver.rs @@ -2,8 +2,8 @@ use indexmap::IndexMap; use shirabe_php_shim::{ - bzcompress, file_exists, file_put_contents, function_exists, gzcompress, pack, str_repeat, - strrpos, unlink, FilesystemIterator, Phar, PharData, PhpMixed, RuntimeException, + FilesystemIterator, Phar, PharData, PhpMixed, RuntimeException, bzcompress, file_exists, + file_put_contents, function_exists, gzcompress, pack, str_repeat, strrpos, unlink, }; use crate::package::archiver::archivable_files_filter::ArchivableFilesFilter; @@ -79,14 +79,14 @@ impl ArchiverInterface for PharArchiver { let eocd = pack( "VvvvvVVv", &[ - PhpMixed::Int(0x06054b50), // End of central directory signature - PhpMixed::Int(0), // Number of this disk - PhpMixed::Int(0), // Disk where central directory starts - PhpMixed::Int(0), // Number of central directory records on this disk - PhpMixed::Int(0), // Total number of central directory records - PhpMixed::Int(0), // Size of central directory (bytes) - PhpMixed::Int(0), // Offset of start of central directory - PhpMixed::Int(0), // Comment length + PhpMixed::Int(0x06054b50), // End of central directory signature + PhpMixed::Int(0), // Number of this disk + PhpMixed::Int(0), // Disk where central directory starts + PhpMixed::Int(0), // Number of central directory records on this disk + PhpMixed::Int(0), // Total number of central directory records + PhpMixed::Int(0), // Size of central directory (bytes) + PhpMixed::Int(0), // Offset of start of central directory + PhpMixed::Int(0), // Comment length ], ); file_put_contents(&target, &eocd); @@ -100,10 +100,12 @@ impl ArchiverInterface for PharArchiver { .into()); } if format == "tar.gz" && function_exists("gzcompress") { - let data = gzcompress(&str_repeat("\0", 10240).into_bytes()).unwrap_or_default(); + let data = + gzcompress(&str_repeat("\0", 10240).into_bytes()).unwrap_or_default(); file_put_contents(&target, &data); } else if format == "tar.bz2" && function_exists("bzcompress") { - let data = bzcompress(&str_repeat("\0", 10240).into_bytes()).unwrap_or_default(); + let data = + bzcompress(&str_repeat("\0", 10240).into_bytes()).unwrap_or_default(); file_put_contents(&target, &data); } } diff --git a/crates/shirabe/src/package/archiver/zip_archiver.rs b/crates/shirabe/src/package/archiver/zip_archiver.rs index 104c544..ef5b40a 100644 --- a/crates/shirabe/src/package/archiver/zip_archiver.rs +++ b/crates/shirabe/src/package/archiver/zip_archiver.rs @@ -1,11 +1,13 @@ //! ref: composer/src/Composer/Package/Archiver/ZipArchiver.php -use indexmap::IndexMap; -use shirabe_php_shim::{class_exists, fileperms, method_exists, pack, realpath, PhpMixed, RuntimeException, ZipArchive}; use crate::package::archiver::archivable_files_finder::ArchivableFilesFinder; use crate::package::archiver::archiver_interface::ArchiverInterface; use crate::util::filesystem::Filesystem; use crate::util::platform::Platform; +use indexmap::IndexMap; +use shirabe_php_shim::{ + PhpMixed, RuntimeException, ZipArchive, class_exists, fileperms, method_exists, pack, realpath, +}; #[derive(Debug)] pub struct ZipArchiver; @@ -60,22 +62,29 @@ impl ArchiverInterface for ZipArchiver { // setExternalAttributesName() is only available with libzip 0.11.2 or above if method_exists(&PhpMixed::Null, "setExternalAttributesName") { let perms = fileperms(&filepath); - zip.set_external_attributes_name(&relative_path, ZipArchive::OPSYS_UNIX, perms << 16); + zip.set_external_attributes_name( + &relative_path, + ZipArchive::OPSYS_UNIX, + perms << 16, + ); } } if zip.close() { if !std::path::Path::new(&target).exists() { // create minimal valid ZIP file (Empty Central Directory + End of Central Directory record) - let eocd = pack("VvvvvVVv", &[ - PhpMixed::Int(0x06054b50), // End of central directory signature - PhpMixed::Int(0), // Number of this disk - PhpMixed::Int(0), // Disk where central directory starts - PhpMixed::Int(0), // Number of central directory records on this disk - PhpMixed::Int(0), // Total number of central directory records - PhpMixed::Int(0), // Size of central directory (bytes) - PhpMixed::Int(0), // Offset of start of central directory - PhpMixed::Int(0), // Comment length - ]); + let eocd = pack( + "VvvvvVVv", + &[ + PhpMixed::Int(0x06054b50), // End of central directory signature + PhpMixed::Int(0), // Number of this disk + PhpMixed::Int(0), // Disk where central directory starts + PhpMixed::Int(0), // Number of central directory records on this disk + PhpMixed::Int(0), // Total number of central directory records + PhpMixed::Int(0), // Size of central directory (bytes) + PhpMixed::Int(0), // Offset of start of central directory + PhpMixed::Int(0), // Comment length + ], + ); std::fs::write(&target, &eocd)?; } diff --git a/crates/shirabe/src/package/base_package.rs b/crates/shirabe/src/package/base_package.rs index 820e51b..4cbd11c 100644 --- a/crates/shirabe/src/package/base_package.rs +++ b/crates/shirabe/src/package/base_package.rs @@ -3,7 +3,7 @@ use std::sync::LazyLock; use indexmap::IndexMap; -use shirabe_php_shim::{preg_quote, LogicException, UnexpectedValueException}; +use shirabe_php_shim::{LogicException, UnexpectedValueException, preg_quote}; use crate::package::link::Link; use crate::package::package_interface::PackageInterface; diff --git a/crates/shirabe/src/package/comparer/comparer.rs b/crates/shirabe/src/package/comparer/comparer.rs index 8f7f312..0e0d295 100644 --- a/crates/shirabe/src/package/comparer/comparer.rs +++ b/crates/shirabe/src/package/comparer/comparer.rs @@ -81,17 +81,26 @@ impl Comparer { let dest_file_hash = destination.get(dir).and_then(|d| d.get(file)); if let Some(dest_hash) = dest_file_hash { if hash != dest_hash { - self.changed.entry("changed".to_string()).or_default().push(format!("{}/{}", dir, file)); + self.changed + .entry("changed".to_string()) + .or_default() + .push(format!("{}/{}", dir, file)); } } else { - self.changed.entry("removed".to_string()).or_default().push(format!("{}/{}", dir, file)); + self.changed + .entry("removed".to_string()) + .or_default() + .push(format!("{}/{}", dir, file)); } } } for (dir, value) in &destination { for (file, _hash) in value { if !source.get(dir).map_or(false, |d| d.contains_key(file)) { - self.changed.entry("added".to_string()).or_default().push(format!("{}/{}", dir, file)); + self.changed + .entry("added".to_string()) + .or_default() + .push(format!("{}/{}", dir, file)); } } } @@ -106,8 +115,13 @@ impl Comparer { } let path = format!("{}/{}", dir, file); if Path::new(&path).is_symlink() { - let link_target = std::fs::read_link(&path).ok().and_then(|p| p.to_str().map(|s| s.to_string())); - array.entry(dir.to_string()).or_default().insert(file, link_target); + let link_target = std::fs::read_link(&path) + .ok() + .and_then(|p| p.to_str().map(|s| s.to_string())); + array + .entry(dir.to_string()) + .or_default() + .insert(file, link_target); } else if Path::new(&path).is_dir() { if array.is_empty() { array.insert("0".to_string(), IndexMap::new()); @@ -118,7 +132,11 @@ impl Comparer { } else if Path::new(&path).is_file() { let size = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0); if size > 0 { - let algo = if shirabe_php_shim::PHP_VERSION_ID > 80100 { "xxh3" } else { "sha1" }; + let algo = if shirabe_php_shim::PHP_VERSION_ID > 80100 { + "xxh3" + } else { + "sha1" + }; let hash = shirabe_php_shim::hash_file(algo, &path); array.entry(dir.to_string()).or_default().insert(file, hash); } diff --git a/crates/shirabe/src/package/comparer/mod.rs b/crates/shirabe/src/package/comparer/mod.rs new file mode 100644 index 0000000..4c5c6d2 --- /dev/null +++ b/crates/shirabe/src/package/comparer/mod.rs @@ -0,0 +1 @@ +pub mod comparer; diff --git a/crates/shirabe/src/package/complete_alias_package.rs b/crates/shirabe/src/package/complete_alias_package.rs index 9da998a..134ed3a 100644 --- a/crates/shirabe/src/package/complete_alias_package.rs +++ b/crates/shirabe/src/package/complete_alias_package.rs @@ -33,7 +33,10 @@ impl CompleteAliasPackage { self.alias_of.get_repositories() } - pub fn set_repositories(&mut self, repositories: Vec<indexmap::IndexMap<String, shirabe_php_shim::PhpMixed>>) { + pub fn set_repositories( + &mut self, + repositories: Vec<indexmap::IndexMap<String, shirabe_php_shim::PhpMixed>>, + ) { self.alias_of.set_repositories(repositories); } @@ -89,7 +92,10 @@ impl CompleteAliasPackage { self.alias_of.get_funding() } - pub fn set_funding(&mut self, funding: Vec<indexmap::IndexMap<String, shirabe_php_shim::PhpMixed>>) { + pub fn set_funding( + &mut self, + funding: Vec<indexmap::IndexMap<String, shirabe_php_shim::PhpMixed>>, + ) { self.alias_of.set_funding(funding); } diff --git a/crates/shirabe/src/package/complete_package.rs b/crates/shirabe/src/package/complete_package.rs index 2120eec..ec2a42a 100644 --- a/crates/shirabe/src/package/complete_package.rs +++ b/crates/shirabe/src/package/complete_package.rs @@ -1,9 +1,9 @@ //! ref: composer/src/Composer/Package/CompletePackage.php -use indexmap::IndexMap; -use shirabe_php_shim::PhpMixed; use crate::package::complete_package_interface::CompletePackageInterface; use crate::package::package::Package; +use indexmap::IndexMap; +use shirabe_php_shim::PhpMixed; #[derive(Debug)] pub struct CompletePackage { diff --git a/crates/shirabe/src/package/dumper/array_dumper.rs b/crates/shirabe/src/package/dumper/array_dumper.rs index bee9aa7..02f1092 100644 --- a/crates/shirabe/src/package/dumper/array_dumper.rs +++ b/crates/shirabe/src/package/dumper/array_dumper.rs @@ -20,28 +20,63 @@ impl ArrayDumper { pub fn dump(&self, package: &dyn PackageInterface) -> IndexMap<String, PhpMixed> { let mut data: IndexMap<String, PhpMixed> = IndexMap::new(); - data.insert("name".to_string(), PhpMixed::String(package.get_pretty_name().to_string())); - data.insert("version".to_string(), PhpMixed::String(package.get_pretty_version().to_string())); - data.insert("version_normalized".to_string(), PhpMixed::String(package.get_version().to_string())); + data.insert( + "name".to_string(), + PhpMixed::String(package.get_pretty_name().to_string()), + ); + data.insert( + "version".to_string(), + PhpMixed::String(package.get_pretty_version().to_string()), + ); + data.insert( + "version_normalized".to_string(), + PhpMixed::String(package.get_version().to_string()), + ); if let Some(target_dir) = package.get_target_dir() { - data.insert("target-dir".to_string(), PhpMixed::String(target_dir.to_string())); + data.insert( + "target-dir".to_string(), + PhpMixed::String(target_dir.to_string()), + ); } if let Some(source_type) = package.get_source_type() { let mut source: IndexMap<String, Box<PhpMixed>> = IndexMap::new(); - source.insert("type".to_string(), Box::new(PhpMixed::String(source_type.to_string()))); - source.insert("url".to_string(), Box::new(PhpMixed::String(package.get_source_url().unwrap_or("").to_string()))); + source.insert( + "type".to_string(), + Box::new(PhpMixed::String(source_type.to_string())), + ); + source.insert( + "url".to_string(), + Box::new(PhpMixed::String( + package.get_source_url().unwrap_or("").to_string(), + )), + ); if let Some(reference) = package.get_source_reference() { - source.insert("reference".to_string(), Box::new(PhpMixed::String(reference.to_string()))); + source.insert( + "reference".to_string(), + Box::new(PhpMixed::String(reference.to_string())), + ); } if let Some(mirrors) = package.get_source_mirrors() { if !mirrors.is_empty() { - source.insert("mirrors".to_string(), Box::new(PhpMixed::Array( - mirrors.into_iter().enumerate().map(|(i, m)| (i.to_string(), Box::new(PhpMixed::Array( - m.into_iter().map(|(k, v)| (k, Box::new(v))).collect() - )))).collect() - ))); + source.insert( + "mirrors".to_string(), + Box::new(PhpMixed::Array( + mirrors + .into_iter() + .enumerate() + .map(|(i, m)| { + ( + i.to_string(), + Box::new(PhpMixed::Array( + m.into_iter().map(|(k, v)| (k, Box::new(v))).collect(), + )), + ) + }) + .collect(), + )), + ); } } data.insert("source".to_string(), PhpMixed::Array(source)); @@ -49,21 +84,47 @@ impl ArrayDumper { if let Some(dist_type) = package.get_dist_type() { let mut dist: IndexMap<String, Box<PhpMixed>> = IndexMap::new(); - dist.insert("type".to_string(), Box::new(PhpMixed::String(dist_type.to_string()))); - dist.insert("url".to_string(), Box::new(PhpMixed::String(package.get_dist_url().unwrap_or("").to_string()))); + dist.insert( + "type".to_string(), + Box::new(PhpMixed::String(dist_type.to_string())), + ); + dist.insert( + "url".to_string(), + Box::new(PhpMixed::String( + package.get_dist_url().unwrap_or("").to_string(), + )), + ); if let Some(reference) = package.get_dist_reference() { - dist.insert("reference".to_string(), Box::new(PhpMixed::String(reference.to_string()))); + dist.insert( + "reference".to_string(), + Box::new(PhpMixed::String(reference.to_string())), + ); } if let Some(shasum) = package.get_dist_sha1_checksum() { - dist.insert("shasum".to_string(), Box::new(PhpMixed::String(shasum.to_string()))); + dist.insert( + "shasum".to_string(), + Box::new(PhpMixed::String(shasum.to_string())), + ); } if let Some(mirrors) = package.get_dist_mirrors() { if !mirrors.is_empty() { - dist.insert("mirrors".to_string(), Box::new(PhpMixed::Array( - mirrors.into_iter().enumerate().map(|(i, m)| (i.to_string(), Box::new(PhpMixed::Array( - m.into_iter().map(|(k, v)| (k, Box::new(v))).collect() - )))).collect() - ))); + dist.insert( + "mirrors".to_string(), + Box::new(PhpMixed::Array( + mirrors + .into_iter() + .enumerate() + .map(|(i, m)| { + ( + i.to_string(), + Box::new(PhpMixed::Array( + m.into_iter().map(|(k, v)| (k, Box::new(v))).collect(), + )), + ) + }) + .collect(), + )), + ); } } data.insert("dist".to_string(), PhpMixed::Array(dist)); @@ -77,7 +138,10 @@ impl ArrayDumper { } let mut link_map: IndexMap<String, Box<PhpMixed>> = IndexMap::new(); for link in &links { - link_map.insert(link.get_target().to_string(), Box::new(PhpMixed::String(link.get_pretty_constraint().to_string()))); + link_map.insert( + link.get_target().to_string(), + Box::new(PhpMixed::String(link.get_pretty_constraint().to_string())), + ); } link_map.sort_keys(); data.insert(type_name, PhpMixed::Array(link_map)); @@ -87,13 +151,22 @@ impl ArrayDumper { if !suggests.is_empty() { let mut sorted_suggests = suggests.clone(); sorted_suggests.sort_keys(); - data.insert("suggest".to_string(), PhpMixed::Array( - sorted_suggests.into_iter().map(|(k, v)| (k, Box::new(PhpMixed::String(v)))).collect() - )); + data.insert( + "suggest".to_string(), + PhpMixed::Array( + sorted_suggests + .into_iter() + .map(|(k, v)| (k, Box::new(PhpMixed::String(v)))) + .collect(), + ), + ); } if let Some(release_date) = package.get_release_date() { - data.insert("time".to_string(), PhpMixed::String(release_date.to_rfc3339())); + data.insert( + "time".to_string(), + PhpMixed::String(release_date.to_rfc3339()), + ); } if package.is_default_branch() { @@ -103,7 +176,15 @@ impl ArrayDumper { // dumpValues for base package keys (corresponds to dynamic PHP dispatch) let binaries = package.get_binaries(); if !binaries.is_empty() { - data.insert("bin".to_string(), PhpMixed::List(binaries.into_iter().map(|b| Box::new(PhpMixed::String(b))).collect())); + data.insert( + "bin".to_string(), + PhpMixed::List( + binaries + .into_iter() + .map(|b| Box::new(PhpMixed::String(b))) + .collect(), + ), + ); } if let Some(pkg_type) = package.get_type() { if !pkg_type.is_empty() { @@ -112,103 +193,223 @@ impl ArrayDumper { } let extra = package.get_extra(); if !extra.is_empty() { - data.insert("extra".to_string(), PhpMixed::Array(extra.into_iter().map(|(k, v)| (k, Box::new(v))).collect())); + data.insert( + "extra".to_string(), + PhpMixed::Array(extra.into_iter().map(|(k, v)| (k, Box::new(v))).collect()), + ); } if let Some(installation_source) = package.get_installation_source() { - data.insert("installation-source".to_string(), PhpMixed::String(installation_source.to_string())); + data.insert( + "installation-source".to_string(), + PhpMixed::String(installation_source.to_string()), + ); } let autoload = package.get_autoload(); if !autoload.is_empty() { - data.insert("autoload".to_string(), PhpMixed::Array(autoload.into_iter().map(|(k, v)| (k, Box::new(v))).collect())); + data.insert( + "autoload".to_string(), + PhpMixed::Array( + autoload + .into_iter() + .map(|(k, v)| (k, Box::new(v))) + .collect(), + ), + ); } let dev_autoload = package.get_dev_autoload(); if !dev_autoload.is_empty() { - data.insert("autoload-dev".to_string(), PhpMixed::Array(dev_autoload.into_iter().map(|(k, v)| (k, Box::new(v))).collect())); + data.insert( + "autoload-dev".to_string(), + PhpMixed::Array( + dev_autoload + .into_iter() + .map(|(k, v)| (k, Box::new(v))) + .collect(), + ), + ); } if let Some(notification_url) = package.get_notification_url() { - data.insert("notification-url".to_string(), PhpMixed::String(notification_url.to_string())); + data.insert( + "notification-url".to_string(), + PhpMixed::String(notification_url.to_string()), + ); } let include_paths = package.get_include_paths(); if !include_paths.is_empty() { - data.insert("include-path".to_string(), PhpMixed::List(include_paths.into_iter().map(|p| Box::new(PhpMixed::String(p))).collect())); + data.insert( + "include-path".to_string(), + PhpMixed::List( + include_paths + .into_iter() + .map(|p| Box::new(PhpMixed::String(p))) + .collect(), + ), + ); } let php_ext = package.get_php_ext(); if !php_ext.is_empty() { - data.insert("php-ext".to_string(), PhpMixed::Array(php_ext.into_iter().map(|(k, v)| (k, Box::new(v))).collect())); + data.insert( + "php-ext".to_string(), + PhpMixed::Array(php_ext.into_iter().map(|(k, v)| (k, Box::new(v))).collect()), + ); } - if let Some(complete_pkg) = (package.as_any() as &dyn Any).downcast_ref::<CompletePackage>() { + if let Some(complete_pkg) = (package.as_any() as &dyn Any).downcast_ref::<CompletePackage>() + { if let Some(archive_name) = complete_pkg.get_archive_name() { - let entry = data.entry("archive".to_string()).or_insert_with(|| PhpMixed::Array(IndexMap::new())); + let entry = data + .entry("archive".to_string()) + .or_insert_with(|| PhpMixed::Array(IndexMap::new())); if let PhpMixed::Array(ref mut archive) = entry { - archive.insert("name".to_string(), Box::new(PhpMixed::String(archive_name.to_string()))); + archive.insert( + "name".to_string(), + Box::new(PhpMixed::String(archive_name.to_string())), + ); } } let archive_excludes = complete_pkg.get_archive_excludes(); if !archive_excludes.is_empty() { - let entry = data.entry("archive".to_string()).or_insert_with(|| PhpMixed::Array(IndexMap::new())); + let entry = data + .entry("archive".to_string()) + .or_insert_with(|| PhpMixed::Array(IndexMap::new())); if let PhpMixed::Array(ref mut archive) = entry { - archive.insert("exclude".to_string(), Box::new(PhpMixed::List( - archive_excludes.into_iter().map(|e| Box::new(PhpMixed::String(e))).collect() - ))); + archive.insert( + "exclude".to_string(), + Box::new(PhpMixed::List( + archive_excludes + .into_iter() + .map(|e| Box::new(PhpMixed::String(e))) + .collect(), + )), + ); } } // dumpValues for complete package keys let scripts = complete_pkg.get_scripts(); if !scripts.is_empty() { - data.insert("scripts".to_string(), PhpMixed::Array( - scripts.into_iter().map(|(k, v)| (k, Box::new(PhpMixed::List(v.into_iter().map(|s| Box::new(PhpMixed::String(s))).collect())))).collect() - )); + data.insert( + "scripts".to_string(), + PhpMixed::Array( + scripts + .into_iter() + .map(|(k, v)| { + ( + k, + Box::new(PhpMixed::List( + v.into_iter() + .map(|s| Box::new(PhpMixed::String(s))) + .collect(), + )), + ) + }) + .collect(), + ), + ); } let license = complete_pkg.get_license(); if !license.is_empty() { - data.insert("license".to_string(), PhpMixed::List(license.into_iter().map(|l| Box::new(PhpMixed::String(l))).collect())); + data.insert( + "license".to_string(), + PhpMixed::List( + license + .into_iter() + .map(|l| Box::new(PhpMixed::String(l))) + .collect(), + ), + ); } let authors = complete_pkg.get_authors(); if !authors.is_empty() { - data.insert("authors".to_string(), PhpMixed::List( - authors.into_iter().map(|a| Box::new(PhpMixed::Array( - a.into_iter().map(|(k, v)| (k, Box::new(PhpMixed::String(v)))).collect() - ))).collect() - )); + data.insert( + "authors".to_string(), + PhpMixed::List( + authors + .into_iter() + .map(|a| { + Box::new(PhpMixed::Array( + a.into_iter() + .map(|(k, v)| (k, Box::new(PhpMixed::String(v)))) + .collect(), + )) + }) + .collect(), + ), + ); } if let Some(description) = complete_pkg.get_description() { - data.insert("description".to_string(), PhpMixed::String(description.to_string())); + data.insert( + "description".to_string(), + PhpMixed::String(description.to_string()), + ); } if let Some(homepage) = complete_pkg.get_homepage() { - data.insert("homepage".to_string(), PhpMixed::String(homepage.to_string())); + data.insert( + "homepage".to_string(), + PhpMixed::String(homepage.to_string()), + ); } let mut keywords = complete_pkg.get_keywords(); if !keywords.is_empty() { keywords.sort(); - data.insert("keywords".to_string(), PhpMixed::List(keywords.into_iter().map(|k| Box::new(PhpMixed::String(k))).collect())); + data.insert( + "keywords".to_string(), + PhpMixed::List( + keywords + .into_iter() + .map(|k| Box::new(PhpMixed::String(k))) + .collect(), + ), + ); } let repositories = complete_pkg.get_repositories(); if !repositories.is_empty() { - data.insert("repositories".to_string(), PhpMixed::List( - repositories.into_iter().map(|r| Box::new(PhpMixed::Array( - r.into_iter().map(|(k, v)| (k, Box::new(v))).collect() - ))).collect() - )); + data.insert( + "repositories".to_string(), + PhpMixed::List( + repositories + .into_iter() + .map(|r| { + Box::new(PhpMixed::Array( + r.into_iter().map(|(k, v)| (k, Box::new(v))).collect(), + )) + }) + .collect(), + ), + ); } let support = complete_pkg.get_support(); if !support.is_empty() { - data.insert("support".to_string(), PhpMixed::Array( - support.into_iter().map(|(k, v)| (k, Box::new(PhpMixed::String(v)))).collect() - )); + data.insert( + "support".to_string(), + PhpMixed::Array( + support + .into_iter() + .map(|(k, v)| (k, Box::new(PhpMixed::String(v)))) + .collect(), + ), + ); } let funding = complete_pkg.get_funding(); if !funding.is_empty() { - data.insert("funding".to_string(), PhpMixed::List( - funding.into_iter().map(|f| Box::new(PhpMixed::Array( - f.into_iter().map(|(k, v)| (k, Box::new(v))).collect() - ))).collect() - )); + data.insert( + "funding".to_string(), + PhpMixed::List( + funding + .into_iter() + .map(|f| { + Box::new(PhpMixed::Array( + f.into_iter().map(|(k, v)| (k, Box::new(v))).collect(), + )) + }) + .collect(), + ), + ); } if complete_pkg.is_abandoned() { - let abandoned_value = complete_pkg.get_replacement_package() + let abandoned_value = complete_pkg + .get_replacement_package() .map(|r| PhpMixed::String(r.to_string())) .unwrap_or(PhpMixed::Bool(true)); data.insert("abandoned".to_string(), abandoned_value); @@ -218,15 +419,24 @@ impl ArrayDumper { if let Some(root_pkg) = (package.as_any() as &dyn Any).downcast_ref::<RootPackage>() { let minimum_stability = root_pkg.get_minimum_stability(); if !minimum_stability.is_empty() { - data.insert("minimum-stability".to_string(), PhpMixed::String(minimum_stability.to_string())); + data.insert( + "minimum-stability".to_string(), + PhpMixed::String(minimum_stability.to_string()), + ); } } let transport_options = package.get_transport_options(); if !transport_options.is_empty() { - data.insert("transport-options".to_string(), PhpMixed::Array( - transport_options.into_iter().map(|(k, v)| (k, Box::new(v))).collect() - )); + data.insert( + "transport-options".to_string(), + PhpMixed::Array( + transport_options + .into_iter() + .map(|(k, v)| (k, Box::new(v))) + .collect(), + ), + ); } data diff --git a/crates/shirabe/src/package/dumper/mod.rs b/crates/shirabe/src/package/dumper/mod.rs new file mode 100644 index 0000000..b50c878 --- /dev/null +++ b/crates/shirabe/src/package/dumper/mod.rs @@ -0,0 +1 @@ +pub mod array_dumper; diff --git a/crates/shirabe/src/package/link.rs b/crates/shirabe/src/package/link.rs index 37f8124..2233eb1 100644 --- a/crates/shirabe/src/package/link.rs +++ b/crates/shirabe/src/package/link.rs @@ -87,7 +87,10 @@ impl Link { pub fn get_pretty_constraint(&self) -> anyhow::Result<&str> { match &self.pretty_constraint { None => Err(anyhow::anyhow!(UnexpectedValueException { - message: format!("Link {} has been misconfigured and had no prettyConstraint given.", self.to_string()), + message: format!( + "Link {} has been misconfigured and had no prettyConstraint given.", + self.to_string() + ), code: 0, })), Some(s) => Ok(s.as_str()), @@ -95,7 +98,10 @@ impl Link { } pub fn to_string(&self) -> String { - format!("{} {} {} ({})", self.source, self.description, self.target, self.constraint) + format!( + "{} {} {} ({})", + self.source, self.description, self.target, self.constraint + ) } pub fn get_pretty_string(&self, source_package: &dyn PackageInterface) -> String { diff --git a/crates/shirabe/src/package/loader/array_loader.rs b/crates/shirabe/src/package/loader/array_loader.rs index c0dc2a2..72d9754 100644 --- a/crates/shirabe/src/package/loader/array_loader.rs +++ b/crates/shirabe/src/package/loader/array_loader.rs @@ -5,9 +5,9 @@ use chrono::{DateTime, TimeZone, Utc}; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::preg::Preg; use shirabe_php_shim::{ - is_scalar, is_string, json_encode, ltrim, sprintf, stripos, strpos, strtolower, strval, substr, - trigger_error, trim, ucfirst, Exception, LogicException, PhpMixed, UnexpectedValueException, - E_USER_DEPRECATED, + E_USER_DEPRECATED, Exception, LogicException, PhpMixed, UnexpectedValueException, is_scalar, + is_string, json_encode, ltrim, sprintf, stripos, strpos, strtolower, strval, substr, + trigger_error, trim, ucfirst, }; use crate::package::base_package::{BasePackage, SUPPORTED_LINK_TYPES}; @@ -213,7 +213,9 @@ impl ArrayLoader { let _name = config.get("name").and_then(|v| v.as_string()).unwrap_or(""); let _pretty_version = config_version.as_string().unwrap_or("").to_string(); let _ = version; - todo!("phase-b: dynamic class-string instantiation new $class($name, $version, $prettyVersion)") + todo!( + "phase-b: dynamic class-string instantiation new $class($name, $version, $prettyVersion)" + ) } /// @param CompletePackage $package @@ -482,9 +484,7 @@ impl ArrayLoader { if let Some(description) = config.get("description") { if !shirabe_php_shim::empty(description) && is_string(description) { - package.set_description( - description.as_string().unwrap_or("").to_string(), - ); + package.set_description(description.as_string().unwrap_or("").to_string()); } } @@ -629,10 +629,9 @@ impl ArrayLoader { let mut links: IndexMap<String, Link> = IndexMap::new(); let entries: IndexMap<String, PhpMixed> = match entry { - PhpMixed::Array(m) => m - .iter() - .map(|(k, v)| (k.clone(), (**v).clone())) - .collect(), + PhpMixed::Array(m) => { + m.iter().map(|(k, v)| (k.clone(), (**v).clone())).collect() + } _ => continue, }; for (pretty_target, constraint) in entries { @@ -781,10 +780,7 @@ impl ArrayLoader { /// @param mixed[] $config the entire package config /// /// @return string|null normalized version of the branch alias or null if there is none - pub fn get_branch_alias( - &self, - config: &IndexMap<String, PhpMixed>, - ) -> Result<Option<String>> { + pub fn get_branch_alias(&self, config: &IndexMap<String, PhpMixed>) -> Result<Option<String>> { if !config.contains_key("version") || !is_scalar(config.get("version").unwrap()) { return Err(UnexpectedValueException { message: "no/invalid version defined".to_string(), @@ -824,7 +820,8 @@ impl ArrayLoader { } // normalize without -dev and ensure it's a numeric branch that is parseable - let validated_target_branch = if target_branch == VersionParser::DEFAULT_BRANCH_ALIAS + let validated_target_branch = if target_branch + == VersionParser::DEFAULT_BRANCH_ALIAS { VersionParser::DEFAULT_BRANCH_ALIAS.to_string() } else { @@ -841,9 +838,12 @@ impl ArrayLoader { } // If using numeric aliases ensure the alias is a valid subversion - let source_prefix = - self.version_parser.parse_numeric_alias_prefix(&source_branch); - let target_prefix = self.version_parser.parse_numeric_alias_prefix(&target_branch); + let source_prefix = self + .version_parser + .parse_numeric_alias_prefix(&source_branch); + let target_prefix = self + .version_parser + .parse_numeric_alias_prefix(&target_branch); if let (Some(sp), Some(tp)) = (source_prefix.as_ref(), target_prefix.as_ref()) { if stripos(tp, sp) != Some(0) { continue; diff --git a/crates/shirabe/src/package/loader/invalid_package_exception.rs b/crates/shirabe/src/package/loader/invalid_package_exception.rs index 88a7f5f..b0eeb23 100644 --- a/crates/shirabe/src/package/loader/invalid_package_exception.rs +++ b/crates/shirabe/src/package/loader/invalid_package_exception.rs @@ -14,7 +14,12 @@ impl InvalidPackageException { pub fn new(errors: Vec<String>, warnings: Vec<String>, data: Vec<PhpMixed>) -> Self { let message = format!( "Invalid package information: \n{}", - errors.iter().chain(warnings.iter()).cloned().collect::<Vec<_>>().join("\n") + errors + .iter() + .chain(warnings.iter()) + .cloned() + .collect::<Vec<_>>() + .join("\n") ); Self { inner: Exception { message, code: 0 }, diff --git a/crates/shirabe/src/package/loader/json_loader.rs b/crates/shirabe/src/package/loader/json_loader.rs index 5e5829a..8f10995 100644 --- a/crates/shirabe/src/package/loader/json_loader.rs +++ b/crates/shirabe/src/package/loader/json_loader.rs @@ -1,10 +1,10 @@ //! ref: composer/src/Composer/Package/Loader/JsonLoader.php -use std::path::Path; -use anyhow::Result; use crate::json::json_file::JsonFile; use crate::package::base_package::BasePackage; use crate::package::loader::loader_interface::LoaderInterface; +use anyhow::Result; +use std::path::Path; pub enum JsonLoaderInput { File(JsonFile), @@ -26,9 +26,7 @@ impl JsonLoader { JsonLoaderInput::String(ref s) if Path::new(s).exists() => { JsonFile::parse_json(&std::fs::read_to_string(s)?, Some(s))? } - JsonLoaderInput::String(ref s) => { - JsonFile::parse_json(s, None)? - } + JsonLoaderInput::String(ref s) => JsonFile::parse_json(s, None)?, }; self.loader.load(config, None) diff --git a/crates/shirabe/src/package/loader/loader_interface.rs b/crates/shirabe/src/package/loader/loader_interface.rs index 9f1e6da..530f1eb 100644 --- a/crates/shirabe/src/package/loader/loader_interface.rs +++ b/crates/shirabe/src/package/loader/loader_interface.rs @@ -1,9 +1,13 @@ //! ref: composer/src/Composer/Package/Loader/LoaderInterface.php +use crate::package::base_package::BasePackage; use indexmap::IndexMap; use shirabe_php_shim::PhpMixed; -use crate::package::base_package::BasePackage; pub trait LoaderInterface { - fn load(&self, config: IndexMap<String, PhpMixed>, class: Option<String>) -> anyhow::Result<Box<BasePackage>>; + fn load( + &self, + config: IndexMap<String, PhpMixed>, + class: Option<String>, + ) -> anyhow::Result<Box<BasePackage>>; } diff --git a/crates/shirabe/src/package/loader/mod.rs b/crates/shirabe/src/package/loader/mod.rs new file mode 100644 index 0000000..402b59c --- /dev/null +++ b/crates/shirabe/src/package/loader/mod.rs @@ -0,0 +1,6 @@ +pub mod array_loader; +pub mod invalid_package_exception; +pub mod json_loader; +pub mod loader_interface; +pub mod root_package_loader; +pub mod validating_array_loader; diff --git a/crates/shirabe/src/package/loader/root_package_loader.rs b/crates/shirabe/src/package/loader/root_package_loader.rs index eef7d70..59c9cf5 100644 --- a/crates/shirabe/src/package/loader/root_package_loader.rs +++ b/crates/shirabe/src/package/loader/root_package_loader.rs @@ -2,7 +2,9 @@ use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::preg::Preg; -use shirabe_php_shim::{strtolower, ucfirst, LogicException, RuntimeException, UnexpectedValueException}; +use shirabe_php_shim::{ + LogicException, RuntimeException, UnexpectedValueException, strtolower, ucfirst, +}; use crate::config::Config; use crate::io::io_interface::IOInterface; @@ -92,12 +94,16 @@ impl RootPackageLoader { Box::new(shirabe_php_shim::PhpMixed::String(version)), ); } else { - let cwd_str = cwd.map(|s| s.to_string()).unwrap_or_else(|| Platform::get_cwd(true)); + let cwd_str = cwd + .map(|s| s.to_string()) + .unwrap_or_else(|| Platform::get_cwd(true)); let version_data = self.version_guesser.guess_version(&config, &cwd_str); if let Some(data) = version_data { config.insert( "version".to_string(), - Box::new(shirabe_php_shim::PhpMixed::String(data.pretty_version.clone())), + Box::new(shirabe_php_shim::PhpMixed::String( + data.pretty_version.clone(), + )), ); config.insert( "version_normalized".to_string(), @@ -110,10 +116,7 @@ impl RootPackageLoader { if !config.contains_key("version") { if let Some(ref io) = self.io { let name = config["name"].as_string().unwrap_or(""); - let package_type = config - .get("type") - .and_then(|v| v.as_string()) - .unwrap_or(""); + let package_type = config.get("type").and_then(|v| v.as_string()).unwrap_or(""); if name != "__root__" && package_type != "project" { io.warning(&format!( "Composer could not detect the root package ({}) version, defaulting to '1.0.0'. See https://getcomposer.org/root-version", @@ -167,42 +170,43 @@ impl RootPackageLoader { } } - let package = self.inner.load(config.clone(), "Composer\\Package\\RootPackage")?; + let package = self + .inner + .load(config.clone(), "Composer\\Package\\RootPackage")?; - let real_package: &mut RootPackage = if let Some(alias_pkg) = - package.as_any_mut().downcast_mut::<RootAliasPackage>() - { - alias_pkg - .get_alias_of_mut() - .as_any_mut() - .downcast_mut::<RootPackage>() - .ok_or_else(|| { - anyhow::anyhow!(LogicException { - message: "Expecting a Composer\\Package\\RootPackage at this point" - .to_string(), - code: 0, - }) - })? - } else if let Some(root_pkg) = package.as_any_mut().downcast_mut::<RootPackage>() { - root_pkg - } else { - return Err(anyhow::anyhow!(LogicException { - message: "Expecting a Composer\\Package\\RootPackage at this point".to_string(), - code: 0, - })); - }; + let real_package: &mut RootPackage = + if let Some(alias_pkg) = package.as_any_mut().downcast_mut::<RootAliasPackage>() { + alias_pkg + .get_alias_of_mut() + .as_any_mut() + .downcast_mut::<RootPackage>() + .ok_or_else(|| { + anyhow::anyhow!(LogicException { + message: "Expecting a Composer\\Package\\RootPackage at this point" + .to_string(), + code: 0, + }) + })? + } else if let Some(root_pkg) = package.as_any_mut().downcast_mut::<RootPackage>() { + root_pkg + } else { + return Err(anyhow::anyhow!(LogicException { + message: "Expecting a Composer\\Package\\RootPackage at this point".to_string(), + code: 0, + })); + }; if auto_versioned { - real_package - .replace_version(real_package.get_version().to_string(), RootPackage::DEFAULT_PRETTY_VERSION.to_string()); + real_package.replace_version( + real_package.get_version().to_string(), + RootPackage::DEFAULT_PRETTY_VERSION.to_string(), + ); } - if let Some(min_stability) = config - .get("minimum-stability") - .and_then(|v| v.as_string()) - { - real_package - .set_minimum_stability(VersionParser::normalize_stability(min_stability).to_string()); + if let Some(min_stability) = config.get("minimum-stability").and_then(|v| v.as_string()) { + real_package.set_minimum_stability( + VersionParser::normalize_stability(min_stability).to_string(), + ); } let mut aliases: Vec<IndexMap<String, String>> = vec![]; @@ -362,16 +366,11 @@ impl RootPackageLoader { } let stability_names: Vec<&str> = stabilities.keys().copied().collect(); - let pattern = format!( - "^[^@]*?@({})$", - stability_names.join("|") - ); + let pattern = format!("^[^@]*?@({})$", stability_names.join("|")); let mut matched = false; for constraint in &constraints { - if let Some(Some(m)) = - Preg::is_match_strict_groups(&pattern, constraint).ok() - { + if let Some(Some(m)) = Preg::is_match_strict_groups(&pattern, constraint).ok() { let name = strtolower(req_name); let stability = stabilities[VersionParser::normalize_stability(&m[1])]; diff --git a/crates/shirabe/src/package/loader/validating_array_loader.rs b/crates/shirabe/src/package/loader/validating_array_loader.rs index 16806d7..c1be9f2 100644 --- a/crates/shirabe/src/package/loader/validating_array_loader.rs +++ b/crates/shirabe/src/package/loader/validating_array_loader.rs @@ -6,10 +6,10 @@ use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::preg::Preg; use shirabe_external_packages::composer::spdx_licenses::spdx_licenses::SpdxLicenses; use shirabe_php_shim::{ - array_intersect_key, array_values, filter_var, get_debug_type, is_array, is_bool, is_int, - is_numeric, is_scalar, is_string, json_encode, parse_url_all, php_to_string, sprintf, - str_replace, strcasecmp, strtolower, strtotime, substr, trigger_error, trim, var_export, - Exception, PhpMixed, E_USER_DEPRECATED, FILTER_VALIDATE_EMAIL, PHP_EOL, + E_USER_DEPRECATED, Exception, FILTER_VALIDATE_EMAIL, PHP_EOL, PhpMixed, array_intersect_key, + array_values, filter_var, get_debug_type, is_array, is_bool, is_int, is_numeric, is_scalar, + is_string, json_encode, parse_url_all, php_to_string, sprintf, str_replace, strcasecmp, + strtolower, strtotime, substr, trigger_error, trim, var_export, }; use shirabe_semver::constraint::constraint::Constraint; use shirabe_semver::constraint::match_none_constraint::MatchNoneConstraint; @@ -97,11 +97,8 @@ impl ValidatingArrayLoader { match self.version_parser.normalize(&version_str, None) { Ok(_) => {} Err(e) => { - self.errors.push(format!( - "version : invalid value ({}): {}", - version_str, - e - )); + self.errors + .push(format!("version : invalid value ({}): {}", version_str, e)); self.config.shift_remove("version"); } } @@ -173,10 +170,8 @@ impl ValidatingArrayLoader { release_date = Some(dt); } Err(e) => { - self.errors.push(format!( - "time : invalid value ({}): {}", - time_str, e - )); + self.errors + .push(format!("time : invalid value ({}): {}", time_str, e)); self.config.shift_remove("time"); } } @@ -209,9 +204,7 @@ impl ValidatingArrayLoader { // check for license validity on newly updated branches/tags let cutoff = strtotime("-8days").unwrap_or(0); - if release_date.is_none() - || release_date.unwrap().timestamp() >= cutoff - { + if release_date.is_none() || release_date.unwrap().timestamp() >= cutoff { let license_validator = SpdxLicenses::new(); for license in licenses.values() { let license_str = license.as_string().unwrap_or("").to_string(); @@ -219,10 +212,11 @@ impl ValidatingArrayLoader { if license_str == "proprietary" { continue; } - let license_to_validate = - str_replace("proprietary", "MIT", &license_str); + let license_to_validate = str_replace("proprietary", "MIT", &license_str); if !license_validator.validate(&license_to_validate) { - if license_validator.validate(&trim(&license_to_validate, " \t\n\r\0\u{0B}")) { + if license_validator + .validate(&trim(&license_to_validate, " \t\n\r\0\u{0B}")) + { self.warnings.push(sprintf( "License %s must not contain extra spaces, make sure to trim it.", &[PhpMixed::String( @@ -258,7 +252,9 @@ impl ValidatingArrayLoader { } else { self.warnings.push(sprintf( "License must be a string or array of strings, got %s.", - &[PhpMixed::String(json_encode(&*license_val).unwrap_or_default())], + &[PhpMixed::String( + json_encode(&*license_val).unwrap_or_default(), + )], )); self.config.shift_remove("license"); } @@ -277,20 +273,15 @@ impl ValidatingArrayLoader { key, get_debug_type(&*author) )); - if let Some(PhpMixed::Array(m)) = self - .config - .get_mut("authors") - .map(|v| v.as_mut()) + if let Some(PhpMixed::Array(m)) = + self.config.get_mut("authors").map(|v| v.as_mut()) { m.shift_remove(key); } continue; } for author_data in ["homepage", "email", "name", "role"] { - let val_opt = author - .as_array() - .and_then(|m| m.get(author_data)) - .cloned(); + let val_opt = author.as_array().and_then(|m| m.get(author_data)).cloned(); if let Some(val) = val_opt { if !is_string(&*val) { self.errors.push(format!( @@ -395,10 +386,8 @@ impl ValidatingArrayLoader { .cloned(); if let Some(val) = val_opt { if !is_string(&*val) { - self.errors.push(format!( - "support.{} : invalid value, must be a string", - key - )); + self.errors + .push(format!("support.{} : invalid value, must be a string", key)); if let Some(PhpMixed::Array(support)) = self.config.get_mut("support").map(|v| v.as_mut()) { @@ -450,7 +439,9 @@ impl ValidatingArrayLoader { } } - for key in ["issues", "forum", "wiki", "source", "docs", "chat", "security"] { + for key in [ + "issues", "forum", "wiki", "source", "docs", "chat", "security", + ] { let url_opt = self .config .get("support") @@ -647,8 +638,11 @@ impl ValidatingArrayLoader { )); php_ext.shift_remove("download-url-method"); } else { - let valid_download_url_methods = - ["composer-default", "pre-packaged-source", "pre-packaged-binary"]; + let valid_download_url_methods = [ + "composer-default", + "pre-packaged-source", + "pre-packaged-binary", + ]; let defined_download_url_methods: IndexMap<String, Box<PhpMixed>> = if is_array(&*v) { v.as_array().unwrap().clone() @@ -673,9 +667,9 @@ impl ValidatingArrayLoader { get_debug_type(&**download_url_method) )); php_ext.shift_remove("download-url-method"); - } else if !valid_download_url_methods.contains( - &download_url_method.as_string().unwrap_or(""), - ) { + } else if !valid_download_url_methods + .contains(&download_url_method.as_string().unwrap_or("")) + { self.errors.push(format!( "php-ext.download-url-method.{} : invalid value ({}), must be one of {}", key, @@ -718,15 +712,10 @@ impl ValidatingArrayLoader { )); php_ext.shift_remove(field_name); } else { - let field_keys: Vec<String> = field_val - .as_array() - .unwrap() - .keys() - .cloned() - .collect(); + let field_keys: Vec<String> = + field_val.as_array().unwrap().keys().cloned().collect(); for key in &field_keys { - let os_family = - field_val.as_array().unwrap()[key].clone(); + let os_family = field_val.as_array().unwrap()[key].clone(); if !is_string(&*os_family) { self.errors.push(format!( "php-ext.{}.{} : should be a string, {} given", @@ -785,8 +774,7 @@ impl ValidatingArrayLoader { .cloned() .collect(); for key in &configure_keys { - let option = - configure_options.as_array().unwrap()[key].clone(); + let option = configure_options.as_array().unwrap()[key].clone(); if !is_array(&*option) { self.errors.push(format!( "php-ext.configure-options.{} : should be an array, {} given", @@ -837,9 +825,8 @@ impl ValidatingArrayLoader { key, get_debug_type(&*needs_value) )); - if let Some(PhpMixed::Array(co)) = php_ext - .get_mut("configure-options") - .map(|v| v.as_mut()) + if let Some(PhpMixed::Array(co)) = + php_ext.get_mut("configure-options").map(|v| v.as_mut()) { if let Some(entry) = co.get_mut(key) { if let PhpMixed::Array(em) = entry.as_mut() { @@ -850,18 +837,15 @@ impl ValidatingArrayLoader { } } - if let Some(description) = - option_map.get("description").cloned() - { + if let Some(description) = option_map.get("description").cloned() { if !is_string(&*description) { self.errors.push(format!( "php-ext.configure-options.{}.description : should be a string, {} given", key, get_debug_type(&*description) )); - if let Some(PhpMixed::Array(co)) = php_ext - .get_mut("configure-options") - .map(|v| v.as_mut()) + if let Some(PhpMixed::Array(co)) = + php_ext.get_mut("configure-options").map(|v| v.as_mut()) { if let Some(entry) = co.get_mut(key) { if let PhpMixed::Array(em) = entry.as_mut() { @@ -886,10 +870,8 @@ impl ValidatingArrayLoader { // If php-ext is now empty, unset it if !php_ext.is_empty() { - self.config.insert( - "php-ext".to_string(), - Box::new(PhpMixed::Array(php_ext)), - ); + self.config + .insert("php-ext".to_string(), Box::new(PhpMixed::Array(php_ext))); } } } @@ -938,8 +920,7 @@ impl ValidatingArrayLoader { arr.shift_remove(&package); } } else if constraint.as_string().unwrap_or("") != "self.version" { - let constraint_str = - constraint.as_string().unwrap_or("").to_string(); + let constraint_str = constraint.as_string().unwrap_or("").to_string(); let link_constraint = match self.version_parser.parse_constraints(&constraint_str) { Ok(c) => c, @@ -972,9 +953,7 @@ impl ValidatingArrayLoader { && link_constraint .as_any() .downcast_ref::<Constraint>() - .map_or(false, |c| { - ["==", "="].contains(&c.get_operator()) - }) + .map_or(false, |c| ["==", "="].contains(&c.get_operator())) && Constraint::new(">=", "1.0.0.0-dev") .matches(link_constraint.as_ref()) { @@ -1063,7 +1042,13 @@ impl ValidatingArrayLoader { } if self.validate_array("autoload", false) && self.config.contains_key("autoload") { - let types = ["psr-0", "psr-4", "classmap", "files", "exclude-from-classmap"]; + let types = [ + "psr-0", + "psr-4", + "classmap", + "files", + "exclude-from-classmap", + ]; let autoload_keys: Vec<String> = self.config["autoload"] .as_array() .map(|m| m.keys().cloned().collect()) @@ -1086,9 +1071,7 @@ impl ValidatingArrayLoader { if let Some(type_map) = type_config.as_array() { for (namespace, _dirs) in type_map { let ns_str = namespace.as_str(); - if ns_str != "" - && substr(ns_str, -1, None) != "\\" - { + if ns_str != "" && substr(ns_str, -1, None) != "\\" { self.errors.push(format!( "autoload.psr-4 : invalid value ({}), namespaces must end with a namespace separator, should be {}\\\\", ns_str, ns_str @@ -1112,8 +1095,7 @@ impl ValidatingArrayLoader { ); // Unset the psr-4 setting, since unsetting target-dir might // interfere with other settings. - if let Some(PhpMixed::Array(arr)) = - self.config.get_mut("autoload").map(|v| v.as_mut()) + if let Some(PhpMixed::Array(arr)) = self.config.get_mut("autoload").map(|v| v.as_mut()) { arr.shift_remove("psr-4"); } @@ -1205,8 +1187,9 @@ impl ValidatingArrayLoader { if has_branch_alias { let branch_alias_val = self.config["extra"].as_array().unwrap()["branch-alias"].clone(); if !is_array(&*branch_alias_val) { - self.errors - .push("extra.branch-alias : must be an array of versions => aliases".to_string()); + self.errors.push( + "extra.branch-alias : must be an array of versions => aliases".to_string(), + ); } else { let branch_alias_map = branch_alias_val.as_array().cloned().unwrap_or_default(); for (source_branch, target_branch) in &branch_alias_map { @@ -1255,9 +1238,7 @@ impl ValidatingArrayLoader { 0, Some((target_branch_str.len() as i64) - 4), ); - let validated_target_branch = self - .version_parser - .normalize_branch(&trimmed); + let validated_target_branch = self.version_parser.normalize_branch(&trimmed); if substr(&validated_target_branch, -4, None) != "-dev" { self.warnings.push(format!( "extra.branch-alias.{} : the target branch ({}) must be a parseable number like 2.0-dev", @@ -1311,15 +1292,13 @@ impl ValidatingArrayLoader { ))); } - let package = self - .loader - .load( - self.config - .iter() - .map(|(k, v)| (k.clone(), (**v).clone())) - .collect(), - Some(class.to_string()), - )?; + let package = self.loader.load( + self.config + .iter() + .map(|(k, v)| (k.clone(), (**v).clone())) + .collect(), + Some(class.to_string()), + )?; self.config = IndexMap::new(); Ok(package) @@ -1344,7 +1323,10 @@ impl ValidatingArrayLoader { ) .unwrap_or(false) { - 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)); + 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 + )); } let reserved_names = [ @@ -1401,7 +1383,10 @@ impl ValidatingArrayLoader { let value = self.config[property].as_string().unwrap_or("").to_string(); if !Preg::is_match(&format!("{{^{}$}}u", regex), &value).unwrap_or(false) { - let message = format!("{} : invalid value ({}), must match {}", property, value, regex); + let message = format!( + "{} : invalid value ({}), must match {}", + property, value, regex + ); if mandatory { self.errors.push(message); } else { @@ -1428,11 +1413,13 @@ impl ValidatingArrayLoader { } let is_empty = !self.config.contains_key(property) - || trim(self.config[property].as_string().unwrap_or(""), " \t\n\r\0\u{0B}") == ""; + || trim( + self.config[property].as_string().unwrap_or(""), + " \t\n\r\0\u{0B}", + ) == ""; if is_empty { if mandatory { - self.errors - .push(format!("{} : must be present", property)); + self.errors.push(format!("{} : must be present", property)); } self.config.shift_remove(property); diff --git a/crates/shirabe/src/package/locker.rs b/crates/shirabe/src/package/locker.rs index a0401ba..b813bbb 100644 --- a/crates/shirabe/src/package/locker.rs +++ b/crates/shirabe/src/package/locker.rs @@ -6,10 +6,10 @@ use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::preg::Preg; use shirabe_external_packages::seld::json_lint::parsing_exception::ParsingException; use shirabe_php_shim::{ - array_intersect, array_keys, array_map, array_merge, call_user_func, file_get_contents, - filemtime, function_exists, hash, in_array, is_array, is_int, ksort, realpath, reset_first, - sprintf, strcmp, strtolower, touch, trim, usort, LogicException, PhpMixed, RuntimeException, - DATE_RFC3339, + DATE_RFC3339, LogicException, PhpMixed, RuntimeException, array_intersect, array_keys, + array_map, array_merge, call_user_func, file_get_contents, filemtime, function_exists, hash, + in_array, is_array, is_int, ksort, realpath, reset_first, sprintf, strcmp, strtolower, touch, + trim, usort, }; use crate::installer::installation_manager::InstallationManager; @@ -104,19 +104,18 @@ impl Locker { let mut relevant_content: IndexMap<String, PhpMixed> = IndexMap::new(); let content_keys: Vec<String> = array_keys(&content); - let relevant_keys_strings: Vec<String> = relevant_keys.iter().map(|s| s.to_string()).collect(); + let relevant_keys_strings: Vec<String> = + relevant_keys.iter().map(|s| s.to_string()).collect(); let intersected = array_intersect(&relevant_keys_strings, &content_keys); for key in intersected { if let Some(value) = content.get(&key) { relevant_content.insert(key, value.clone()); } } - let platform_value = content - .get("config") - .and_then(|v| match v { - PhpMixed::Array(m) => m.get("platform").cloned(), - _ => None, - }); + let platform_value = content.get("config").and_then(|v| match v { + PhpMixed::Array(m) => m.get("platform").cloned(), + _ => None, + }); if let Some(platform) = platform_value { let mut config_map: IndexMap<String, Box<PhpMixed>> = IndexMap::new(); config_map.insert("platform".to_string(), platform); @@ -174,10 +173,7 @@ impl Locker { } /// Searches and returns an array of locked packages, retrieved from registered repositories. - pub fn get_locked_repository( - &mut self, - with_dev_reqs: bool, - ) -> Result<LockArrayRepository> { + pub fn get_locked_repository(&mut self, with_dev_reqs: bool) -> Result<LockArrayRepository> { let lock_data = self.get_lock_data()?; let mut packages = LockArrayRepository::new(vec![])?; @@ -221,8 +217,7 @@ impl Locker { m.iter().map(|(k, v)| (k.clone(), (**v).clone())).collect(); let package = self.loader.load(info_map, None)?; packages.add_package(package.clone())?; - package_by_name - .insert(package.get_name().to_string(), package.clone()); + package_by_name.insert(package.get_name().to_string(), package.clone()); // TODO(phase-b): `$package instanceof AliasPackage` downcast let package_as_alias: Option<&AliasPackage> = None; @@ -245,8 +240,7 @@ impl Locker { .and_then(|v| v.as_string()) .unwrap_or("") .to_string(); - if let Some(base_pkg) = package_by_name.get(&alias_pkg_name).cloned() - { + if let Some(base_pkg) = package_by_name.get(&alias_pkg_name).cloned() { let mut alias_pkg = CompleteAliasPackage::new( todo!("phase-b: downcast Box<BasePackage> to CompletePackage"), m.get("alias_normalized") @@ -272,8 +266,9 @@ impl Locker { } Err(RuntimeException { - message: "Your composer.lock is invalid. Run \"composer update\" to generate a new one." - .to_string(), + message: + "Your composer.lock is invalid. Run \"composer update\" to generate a new one." + .to_string(), code: 0, } .into()) @@ -308,7 +303,9 @@ impl Locker { "1.0.0", Link::TYPE_REQUIRE, match platform_value.unwrap() { - PhpMixed::Array(m) => m.iter().map(|(k, v)| (k.clone(), (**v).clone())).collect(), + PhpMixed::Array(m) => { + m.iter().map(|(k, v)| (k.clone(), (**v).clone())).collect() + } _ => IndexMap::new(), }, )?; @@ -324,7 +321,9 @@ impl Locker { "1.0.0", Link::TYPE_REQUIRE, match platform_dev_value.unwrap() { - PhpMixed::Array(m) => m.iter().map(|(k, v)| (k.clone(), (**v).clone())).collect(), + PhpMixed::Array(m) => { + m.iter().map(|(k, v)| (k.clone(), (**v).clone())).collect() + } _ => IndexMap::new(), }, )?; @@ -514,10 +513,7 @@ impl Locker { "content-hash".to_string(), PhpMixed::String(self.content_hash.clone()), ); - lock.insert( - "packages".to_string(), - self.lock_packages(&packages)?, - ); + lock.insert("packages".to_string(), self.lock_packages(&packages)?); lock.insert("packages-dev".to_string(), PhpMixed::Null); lock.insert( "aliases".to_string(), @@ -526,7 +522,9 @@ impl Locker { .iter() .map(|m| { Box::new(PhpMixed::Array( - m.iter().map(|(k, v)| (k.clone(), Box::new(v.clone()))).collect(), + m.iter() + .map(|(k, v)| (k.clone(), Box::new(v.clone()))) + .collect(), )) }) .collect(), @@ -610,11 +608,7 @@ impl Locker { if !is_locked || Some(&lock) != current_data.as_ref() { if write { self.lock_file.write( - PhpMixed::Array( - lock.into_iter() - .map(|(k, v)| (k, Box::new(v))) - .collect(), - ), + PhpMixed::Array(lock.into_iter().map(|(k, v)| (k, Box::new(v))).collect()), None, )?; self.lock_data_cache = None; @@ -623,11 +617,7 @@ impl Locker { self.virtual_file_written = true; self.lock_data_cache = Some(JsonFile::parse_json( &JsonFile::encode( - &PhpMixed::Array( - lock.into_iter() - .map(|(k, v)| (k, Box::new(v))) - .collect(), - ), + &PhpMixed::Array(lock.into_iter().map(|(k, v)| (k, Box::new(v))).collect()), shirabe_php_shim::JSON_UNESCAPED_SLASHES | shirabe_php_shim::JSON_PRETTY_PRINT | shirabe_php_shim::JSON_UNESCAPED_UNICODE, @@ -886,7 +876,12 @@ impl Locker { r"{^\s*(\d+)\s*}", output.as_string().unwrap_or(""), ) { - let ts = m.get(1).cloned().unwrap_or_default().parse::<i64>().unwrap_or(0); + let ts = m + .get(1) + .cloned() + .unwrap_or_default() + .parse::<i64>() + .unwrap_or(0); datetime = chrono::DateTime::from_timestamp(ts, 0); } } @@ -941,10 +936,8 @@ impl Locker { ) .is_empty() { - let results = installed_repo.find_packages_with_replacers_and_providers( - &link.get_target(), - None, - ); + let results = installed_repo + .find_packages_with_replacers_and_providers(&link.get_target(), None); if !results.is_empty() { let provider = reset_first(&results).unwrap(); diff --git a/crates/shirabe/src/package/mod.rs b/crates/shirabe/src/package/mod.rs new file mode 100644 index 0000000..77a01a2 --- /dev/null +++ b/crates/shirabe/src/package/mod.rs @@ -0,0 +1,17 @@ +pub mod alias_package; +pub mod archiver; +pub mod base_package; +pub mod comparer; +pub mod complete_alias_package; +pub mod complete_package; +pub mod complete_package_interface; +pub mod dumper; +pub mod link; +pub mod loader; +pub mod locker; +pub mod package; +pub mod package_interface; +pub mod root_alias_package; +pub mod root_package; +pub mod root_package_interface; +pub mod version; diff --git a/crates/shirabe/src/package/package.rs b/crates/shirabe/src/package/package.rs index fac6d46..81d6131 100644 --- a/crates/shirabe/src/package/package.rs +++ b/crates/shirabe/src/package/package.rs @@ -4,7 +4,7 @@ use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::preg::Preg; use shirabe_external_packages::composer::util::composer_mirror::ComposerMirror; -use shirabe_php_shim::{strpos, trigger_error, PhpMixed, E_USER_DEPRECATED}; +use shirabe_php_shim::{E_USER_DEPRECATED, PhpMixed, strpos, trigger_error}; use crate::package::base_package::BasePackage; use crate::package::link::Link; @@ -109,7 +109,10 @@ impl Package { } pub fn get_type(&self) -> String { - self.r#type.clone().filter(|s| !s.is_empty()).unwrap_or_else(|| "library".to_string()) + self.r#type + .clone() + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| "library".to_string()) } pub fn get_stability(&self) -> &str { diff --git a/crates/shirabe/src/package/root_package.rs b/crates/shirabe/src/package/root_package.rs index f1c3ba8..55a6805 100644 --- a/crates/shirabe/src/package/root_package.rs +++ b/crates/shirabe/src/package/root_package.rs @@ -1,9 +1,9 @@ //! ref: composer/src/Composer/Package/RootPackage.php -use indexmap::IndexMap; -use shirabe_php_shim::PhpMixed; use crate::package::complete_package::CompletePackage; use crate::package::root_package_interface::RootPackageInterface; +use indexmap::IndexMap; +use shirabe_php_shim::PhpMixed; #[derive(Debug)] pub struct RootPackage { diff --git a/crates/shirabe/src/package/version/mod.rs b/crates/shirabe/src/package/version/mod.rs new file mode 100644 index 0000000..a734e23 --- /dev/null +++ b/crates/shirabe/src/package/version/mod.rs @@ -0,0 +1,5 @@ +pub mod stability_filter; +pub mod version_bumper; +pub mod version_guesser; +pub mod version_parser; +pub mod version_selector; diff --git a/crates/shirabe/src/package/version/stability_filter.rs b/crates/shirabe/src/package/version/stability_filter.rs index 65f024f..d08492c 100644 --- a/crates/shirabe/src/package/version/stability_filter.rs +++ b/crates/shirabe/src/package/version/stability_filter.rs @@ -1,7 +1,7 @@ //! ref: composer/src/Composer/Package/Version/StabilityFilter.php -use indexmap::IndexMap; use crate::package::base_package::BasePackage; +use indexmap::IndexMap; pub struct StabilityFilter; diff --git a/crates/shirabe/src/package/version/version_bumper.rs b/crates/shirabe/src/package/version/version_bumper.rs index 8717d19..5911458 100644 --- a/crates/shirabe/src/package/version/version_bumper.rs +++ b/crates/shirabe/src/package/version/version_bumper.rs @@ -1,15 +1,15 @@ //! ref: composer/src/Composer/Package/Version/VersionBumper.php -use anyhow::Result; -use indexmap::IndexMap; -use shirabe_external_packages::composer::pcre::preg::Preg; -use shirabe_semver::constraint::constraint_interface::ConstraintInterface; -use shirabe_semver::intervals::Intervals; use crate::package::dumper::array_dumper::ArrayDumper; use crate::package::loader::array_loader::ArrayLoader; use crate::package::package_interface::PackageInterface; use crate::package::version::version_parser::VersionParser; use crate::util::platform::Platform; +use anyhow::Result; +use indexmap::IndexMap; +use shirabe_external_packages::composer::pcre::preg::Preg; +use shirabe_semver::constraint::constraint_interface::ConstraintInterface; +use shirabe_semver::intervals::Intervals; #[derive(Debug)] pub struct VersionBumper; @@ -46,7 +46,8 @@ impl VersionBumper { } let major = Preg::replace(r"{^([1-9][0-9]*|0\.\d+).*}", "$1", version.clone())?; - let version_without_suffix = Preg::replace(r"{(?:\.(?:0|9999999))+(-dev)?$}", "", version.clone())?; + let version_without_suffix = + Preg::replace(r"{(?:\.(?:0|9999999))+(-dev)?$}", "", version.clone())?; let new_pretty_constraint = format!("^{}", version_without_suffix); if !Preg::is_match(r"{^\^\d+(\.\d+)*$}", &new_pretty_constraint)? { @@ -82,23 +83,27 @@ impl VersionBumper { } else { "" }; - let replacement = if match_str.starts_with('~') && match_str.matches('.').count() != 1 { - let mut version_bits: Vec<String> = - version_without_suffix.split('.').map(String::from).collect(); - let needed_len = match_str.matches('.').count() + 1; - while version_bits.len() < needed_len { - version_bits.push("0".to_string()); - } - let dots_in_match = match_str.matches('.').count(); - format!("~{}", version_bits[..dots_in_match + 1].join(".")) - } else if match_str == "*" || match_str.starts_with(">=") { - format!(">={}{}", version_without_suffix, suffix) - } else { - format!("{}{}", new_pretty_constraint, suffix) - }; + let replacement = + if match_str.starts_with('~') && match_str.matches('.').count() != 1 { + let mut version_bits: Vec<String> = version_without_suffix + .split('.') + .map(String::from) + .collect(); + let needed_len = match_str.matches('.').count() + 1; + while version_bits.len() < needed_len { + version_bits.push("0".to_string()); + } + let dots_in_match = match_str.matches('.').count(); + format!("~{}", version_bits[..dots_in_match + 1].join(".")) + } else if match_str == "*" || match_str.starts_with(">=") { + format!(">={}{}", version_without_suffix, suffix) + } else { + format!("{}{}", new_pretty_constraint, suffix) + }; let offset = match_offset as usize; let length = Platform::strlen(match_str) as usize; - modified = shirabe_php_shim::substr_replace(&modified, &replacement, offset, length); + modified = + shirabe_php_shim::substr_replace(&modified, &replacement, offset, length); } let new_constraint = parser.parse_constraints(&modified)?; diff --git a/crates/shirabe/src/package/version/version_guesser.rs b/crates/shirabe/src/package/version/version_guesser.rs index a97095d..c4e25e0 100644 --- a/crates/shirabe/src/package/version/version_guesser.rs +++ b/crates/shirabe/src/package/version/version_guesser.rs @@ -5,9 +5,9 @@ use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::preg::Preg; use shirabe_external_packages::symfony::component::process::process::Process; use shirabe_php_shim::{ - array_keys, array_map, array_merge, empty, function_exists, implode, is_string, json_encode, - preg_quote, str_replace, strlen, strnatcasecmp, strpos, substr, trim, usort, PhpMixed, - RuntimeException, PHP_INT_MAX, + PHP_INT_MAX, PhpMixed, RuntimeException, array_keys, array_map, array_merge, empty, + function_exists, implode, is_string, json_encode, preg_quote, str_replace, strlen, + strnatcasecmp, strpos, substr, trim, usort, }; use shirabe_semver::version_parser::VersionParser as SemverVersionParser; @@ -144,7 +144,12 @@ impl VersionGuesser { .map(|fv| !fv.is_empty()) .unwrap_or(false); if feature_non_empty - && "-dev" == substr(version_data.feature_version.as_deref().unwrap_or(""), -4, None) + && "-dev" + == substr( + version_data.feature_version.as_deref().unwrap_or(""), + -4, + None, + ) && Preg::is_match( r"{\.9{7}}", version_data.feature_version.as_deref().unwrap_or(""), @@ -296,7 +301,11 @@ impl VersionGuesser { &GitUtil::parse_rev_list_output(&command_output, &self.process), None, ); - commit = if parsed.is_empty() { None } else { Some(parsed) }; + commit = if parsed.is_empty() { + None + } else { + Some(parsed) + }; } } @@ -386,10 +395,8 @@ impl VersionGuesser { // TODO(phase-b): clone ProcessExecutor todo!("self.process.clone()"), ); - let branches: Vec<String> = array_map( - |k: &String| k.clone(), - &array_keys(driver.get_branches()), - ); + let branches: Vec<String> = + array_map(|k: &String| k.clone(), &array_keys(driver.get_branches())); // try to find the best (nearest) version branch to assume this feature's version let mut result = self.guess_feature_version( @@ -597,11 +604,7 @@ impl VersionGuesser { // try to fetch current version from fossil tags let mut output = String::new(); if 0 == self.process.execute( - &[ - "fossil".to_string(), - "tag".to_string(), - "list".to_string(), - ], + &["fossil".to_string(), "tag".to_string(), "list".to_string()], &mut output, Some(path.to_string()), ) { @@ -637,11 +640,7 @@ impl VersionGuesser { // try to fetch current version from svn let mut output = String::new(); if 0 == self.process.execute( - &[ - "svn".to_string(), - "info".to_string(), - "--xml".to_string(), - ], + &["svn".to_string(), "info".to_string(), "--xml".to_string()], &mut output, Some(path.to_string()), ) { @@ -670,7 +669,8 @@ impl VersionGuesser { let m1 = matches.get(1).cloned().unwrap_or_default(); let m2 = matches.get(2).cloned(); let m3 = matches.get(3).cloned(); - if m2.is_some() && m3.is_some() + if m2.is_some() + && m3.is_some() && (branches_path == *m2.as_ref().unwrap() || tags_path == *m2.as_ref().unwrap()) { diff --git a/crates/shirabe/src/package/version/version_parser.rs b/crates/shirabe/src/package/version/version_parser.rs index dbaa1c9..6bb1004 100644 --- a/crates/shirabe/src/package/version/version_parser.rs +++ b/crates/shirabe/src/package/version/version_parser.rs @@ -21,7 +21,10 @@ pub struct VersionParser { impl VersionParser { pub const DEFAULT_BRANCH_ALIAS: &'static str = "9999999-dev"; - pub fn parse_constraints(&self, constraints: &str) -> anyhow::Result<Arc<dyn ConstraintInterface + Send + Sync>> { + pub fn parse_constraints( + &self, + constraints: &str, + ) -> anyhow::Result<Arc<dyn ConstraintInterface + Send + Sync>> { let mut cache = CONSTRAINTS.lock().unwrap(); if !cache.contains_key(constraints) { let parsed = self.inner.parse_constraints(constraints)?; @@ -30,13 +33,20 @@ impl VersionParser { Ok(Arc::clone(cache.get(constraints).unwrap())) } - pub fn parse_name_version_pairs(&self, pairs: Vec<String>) -> anyhow::Result<Vec<IndexMap<String, String>>> { + pub fn parse_name_version_pairs( + &self, + pairs: Vec<String>, + ) -> anyhow::Result<Vec<IndexMap<String, String>>> { let pairs: Vec<String> = pairs; let mut result: Vec<IndexMap<String, String>> = Vec::new(); let count = pairs.len(); let mut i = 0_usize; while i < count { - let mut pair = Preg::replace(r"{^([^=: ]+)[=: ](.*)$}", "$1 $2", pairs[i].trim().to_string())?; + let mut pair = Preg::replace( + r"{^([^=: ]+)[=: ](.*)$}", + "$1 $2", + pairs[i].trim().to_string(), + )?; if !pair.contains(' ') && i + 1 < count && !pairs[i + 1].contains('/') diff --git a/crates/shirabe/src/package/version/version_selector.rs b/crates/shirabe/src/package/version/version_selector.rs index 85ce71d..f665320 100644 --- a/crates/shirabe/src/package/version/version_selector.rs +++ b/crates/shirabe/src/package/version/version_selector.rs @@ -5,7 +5,7 @@ use std::any::Any; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::preg::Preg; use shirabe_php_shim::{ - strtolower, version_compare, PHP_MAJOR_VERSION, PHP_MINOR_VERSION, PHP_RELEASE_VERSION, + PHP_MAJOR_VERSION, PHP_MINOR_VERSION, PHP_RELEASE_VERSION, strtolower, version_compare, }; use shirabe_semver::constraint::constraint::Constraint; use shirabe_semver::constraint::constraint_interface::ConstraintInterface; @@ -20,9 +20,9 @@ use crate::package::base_package::BasePackage; use crate::package::dumper::array_dumper::ArrayDumper; use crate::package::loader::array_loader::ArrayLoader; use crate::package::package_interface::PackageInterface; +use crate::package::version::version_parser::VersionParser; use crate::repository::platform_repository::PlatformRepository; use crate::repository::repository_set::RepositorySet; -use crate::package::version::version_parser::VersionParser; #[derive(Debug)] pub struct VersionSelector { @@ -140,7 +140,8 @@ impl VersionSelector { if link.get_constraint().matches(provided_constraint.as_ref()) { continue 'reqs; } - let list_filter_opt = (platform_requirement_filter.as_ref() as &dyn Any) + let list_filter_opt = (platform_requirement_filter.as_ref() + as &dyn Any) .downcast_ref::<IgnoreListPlatformRequirementFilter>(); if let Some(list_filter) = list_filter_opt { if list_filter.is_upper_bound_ignored(name) { @@ -168,8 +169,7 @@ impl VersionSelector { _ => true, }; if should_warn { - let warn_key = - format!("{}/{}", pkg.get_name(), link.get_target()); + let warn_key = format!("{}/{}", pkg.get_name(), link.get_target()); let is_first_warning = !already_warned_names.contains_key(&warn_key); already_warned_names.insert(warn_key, true); let latest = if is_latest_version { @@ -222,15 +222,16 @@ impl VersionSelector { Some(p) => p, }; - let package = if let Some(alias) = (package.as_ref() as &dyn Any).downcast_ref::<AliasPackage>() { - if alias.get_version() == VersionParser::DEFAULT_BRANCH_ALIAS { - alias.get_alias_of() + let package = + if let Some(alias) = (package.as_ref() as &dyn Any).downcast_ref::<AliasPackage>() { + if alias.get_version() == VersionParser::DEFAULT_BRANCH_ALIAS { + alias.get_alias_of() + } else { + package + } } else { package - } - } else { - package - }; + }; Ok(Some(package)) } @@ -288,7 +289,10 @@ impl VersionSelector { if semantic_version_parts.len() == 4 && Preg::is_match(r"{^\d+\D?}", semantic_version_parts[3]).unwrap_or(false) { - let mut parts: Vec<String> = semantic_version_parts.iter().map(|s| s.to_string()).collect(); + let mut parts: Vec<String> = semantic_version_parts + .iter() + .map(|s| s.to_string()) + .collect(); let version = if parts[0] == "0" { parts.truncate(3); parts.join(".") |
