diff options
| author | nsfisis <nsfisis@gmail.com> | 2026-08-06 20:04:25 +0900 |
|---|---|---|
| committer | nsfisis <nsfisis@gmail.com> | 2026-08-06 20:04:25 +0900 |
| commit | 3f525f228052ad04e6f9da6ff160bef803d079bd (patch) | |
| tree | 3fe2d078e6a30b12ce041b1b3f1e589bc47cf8f3 /crates/shirabe | |
| parent | d9dca94603766712b5989ea8169c9e286d27a60c (diff) | |
| download | php-shirabe-3f525f228052ad04e6f9da6ff160bef803d079bd.tar.gz php-shirabe-3f525f228052ad04e6f9da6ff160bef803d079bd.tar.zst php-shirabe-3f525f228052ad04e6f9da6ff160bef803d079bd.zip | |
feat(plugin): let links and release dates cross the RPC boundary
The link getters and setters and the release date accessors were explicit
errors for every non-empty value, because an immutable value has no entity
to point a handle at. They now cross as materialized values: the descriptor
names the real class and the constructor arguments, and each side builds a
genuine instance of its own.
The semver constraint a link holds is encoded structurally rather than
re-parsed from its string form, so the pretty strings and the conjunctive
flag survive the crossing.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Diffstat (limited to 'crates/shirabe')
| -rw-r--r-- | crates/shirabe/src/plugin.rs | 1 | ||||
| -rw-r--r-- | crates/shirabe/src/plugin/php_plugin_proxy.rs | 127 | ||||
| -rw-r--r-- | crates/shirabe/src/plugin/php_plugin_value.rs | 289 | ||||
| -rw-r--r-- | crates/shirabe/tests/plugin/fixtures/values-v1/Values/Plugin.php | 85 | ||||
| -rw-r--r-- | crates/shirabe/tests/plugin/fixtures/values-v1/composer.json | 12 | ||||
| -rw-r--r-- | crates/shirabe/tests/plugin/main.rs | 1 | ||||
| -rw-r--r-- | crates/shirabe/tests/plugin/value_round_trip_test.rs | 168 |
7 files changed, 630 insertions, 53 deletions
diff --git a/crates/shirabe/src/plugin.rs b/crates/shirabe/src/plugin.rs index a629e4c0..5e6b804e 100644 --- a/crates/shirabe/src/plugin.rs +++ b/crates/shirabe/src/plugin.rs @@ -2,6 +2,7 @@ pub mod capability; pub mod capable; pub mod command_event; pub mod php_plugin_proxy; +pub mod php_plugin_value; pub mod plugin_blocked_exception; pub mod plugin_events; pub mod plugin_interface; diff --git a/crates/shirabe/src/plugin/php_plugin_proxy.rs b/crates/shirabe/src/plugin/php_plugin_proxy.rs index 2b3622f2..354b89aa 100644 --- a/crates/shirabe/src/plugin/php_plugin_proxy.rs +++ b/crates/shirabe/src/plugin/php_plugin_proxy.rs @@ -18,6 +18,9 @@ use crate::package::handle::AnyPackage; use crate::package::{DisplayMode, PackageInterfaceHandle}; use crate::plugin::capability::{Capability, CommandProvider}; use crate::plugin::capable::Capable; +use crate::plugin::php_plugin_value::{ + date_time_from_wire, date_time_to_wire, link_from_wire, link_to_wire, +}; use crate::plugin::plugin_interface::PluginInterface; use crate::repository::{ InstalledArrayRepository, InstalledFilesystemRepository, InstalledRepositoryInterfaceHandle, @@ -990,6 +993,38 @@ fn string_list_arg(method: &str, value: Option<&PluginValue>) -> Result<Vec<Stri .collect() } +/// An `array<string, Link>` argument, keyed by the target package name as PHP keys it. +fn link_map_arg( + method: &str, + value: Option<&PluginValue>, +) -> Result<IndexMap<String, crate::package::Link>, PhpThrow> { + let entries: Vec<(Vec<u8>, &PluginValue)> = match value { + Some(PluginValue::Array(map)) => { + map.iter().map(|(key, item)| (key.clone(), item)).collect() + } + Some(PluginValue::List(items)) => items + .iter() + .enumerate() + .map(|(index, item)| (index.to_string().into_bytes(), item)) + .collect(), + None | Some(PluginValue::Null) => Vec::new(), + other => { + return Err(runtime_throw(format!( + "{method} expects an array of Link values, got {other:?}" + ))); + } + }; + entries + .into_iter() + .map(|(key, item)| { + Ok(( + String::from_utf8_lossy(&key).into_owned(), + link_from_wire(item)?, + )) + }) + .collect() +} + /// A `list<array<string, string>>` argument (`authors`, `aliases`). fn string_map_list_arg( method: &str, @@ -1189,18 +1224,22 @@ fn dispatch_package_method( method_name: &str, args: &[PluginValue], ) -> Result<PluginValue, PhpThrow> { - // The link getters return `array<string, Link>`; only the empty case has a wire image so - // far (an empty PHP array crosses as a list). + // The link getters return `array<string, Link>`. Each link is rebuilt in the child as a + // real `Composer\Package\Link`, constraint included; an empty map crosses as a list, the + // wire image of an empty PHP array. // - // TODO(plugin): Link is a rust-snapshot value whose constraint field must materialize as a - // real composer/semver object in the child; the snapshot encoding does not exist yet. - let links = |links: IndexMap<String, crate::package::Link>| -> Result<PluginValue, PhpThrow> { + // TODO(plugin): links have no entity to intern against, so two calls of the same getter + // answer with distinct child-side objects where upstream returns the identical one. + let links = |links: IndexMap<String, crate::package::Link>| -> PluginValue { if links.is_empty() { - Ok(PluginValue::List(Vec::new())) + PluginValue::List(Vec::new()) } else { - Err(runtime_throw(format!( - "the package method `{method_name}` returns Link values, whose encoding over RPC is not implemented yet" - ))) + PluginValue::Array( + links + .iter() + .map(|(name, link)| (name.clone().into_bytes(), link_to_wire(link))) + .collect(), + ) } }; @@ -1359,16 +1398,8 @@ fn dispatch_package_method( } return Ok(PluginValue::Null); } - // TODO(plugin): the link setters take `array<string, Link>`, whose wire image is missing - // for the same reason the link getters below have none. "setRequires" | "setConflicts" | "setProvides" | "setReplaces" | "setDevRequires" => { - if !list_arg(method_name, args.first())?.is_empty() - || !map_arg(method_name, args.first())?.is_empty() - { - return Err(runtime_throw(format!( - "the package method `{method_name}` takes Link values, whose encoding over RPC is not implemented yet" - ))); - } + let links = link_map_arg(method_name, args.first())?; let mut borrowed = package.borrow_mut(); let package = borrowed.as_package_mut().ok_or_else(|| { runtime_throw(format!( @@ -1376,33 +1407,27 @@ fn dispatch_package_method( )) })?; match method_name { - "setRequires" => package.set_requires(IndexMap::new()), - "setConflicts" => package.set_conflicts(IndexMap::new()), - "setProvides" => package.set_provides(IndexMap::new()), - "setReplaces" => package.set_replaces(IndexMap::new()), - _ => package.set_dev_requires(IndexMap::new()), + "setRequires" => package.set_requires(links), + "setConflicts" => package.set_conflicts(links), + "setProvides" => package.set_provides(links), + "setReplaces" => package.set_replaces(links), + _ => package.set_dev_requires(links), } return Ok(PluginValue::Null); } - // TODO(plugin): a \DateTimeInterface argument has to be decoded from a real PHP object in - // the child, which needs the value-object encoding `getReleaseDate` is missing too. "setReleaseDate" => { - return match args.first() { - None | Some(PluginValue::Null) => { - let mut borrowed = package.borrow_mut(); - let package = borrowed.as_package_mut().ok_or_else(|| { - runtime_throw( - "`setReleaseDate` is not available on an alias package over RPC" - .to_string(), - ) - })?; - package.set_release_date(None); - Ok(PluginValue::Null) - } - _ => Err(runtime_throw( - "decoding a release date over RPC is not implemented yet".to_string(), - )), + let date = match args.first() { + None | Some(PluginValue::Null) => None, + Some(value) => Some(date_time_from_wire(value)?), }; + let mut borrowed = package.borrow_mut(); + let package = borrowed.as_package_mut().ok_or_else(|| { + runtime_throw( + "`setReleaseDate` is not available on an alias package over RPC".to_string(), + ) + })?; + package.set_release_date(date); + return Ok(PluginValue::Null); } "setScripts" | "setRepositories" | "setLicense" | "setKeywords" | "setDescription" | "setHomepage" | "setAuthors" | "setSupport" | "setFunding" | "setAbandoned" @@ -1572,11 +1597,11 @@ fn dispatch_package_method( )) } "getStability" => Ok(PluginValue::string(package.get_stability().to_string())), - "getRequires" => links(package.get_requires()), - "getConflicts" => links(package.get_conflicts()), - "getProvides" => links(package.get_provides()), - "getReplaces" => links(package.get_replaces()), - "getDevRequires" => links(package.get_dev_requires()), + "getRequires" => Ok(links(package.get_requires())), + "getConflicts" => Ok(links(package.get_conflicts())), + "getProvides" => Ok(links(package.get_provides())), + "getReplaces" => Ok(links(package.get_replaces())), + "getDevRequires" => Ok(links(package.get_dev_requires())), "getSuggests" => { let suggests = package.get_suggests(); if suggests.is_empty() { @@ -1620,14 +1645,10 @@ fn dispatch_package_method( .unwrap_or(&crate::package::base_package::STABILITY_STABLE), )), "getTransportOptions" => Ok(string_keyed_map(package.get_transport_options())), - "getReleaseDate" => match package.get_release_date() { - None => Ok(PluginValue::Null), - // TODO(plugin): a \DateTimeInterface has to materialize as a real PHP object in the - // child, which needs a snapshot encoding for value objects. - Some(_) => Err(runtime_throw( - "encoding the release date over RPC is not implemented yet".to_string(), - )), - }, + "getReleaseDate" => Ok(match package.get_release_date() { + None => PluginValue::Null, + Some(date) => date_time_to_wire(&date), + }), other => Err(runtime_throw(format!( "the package method `{other}` is not available over RPC yet" ))), diff --git a/crates/shirabe/src/plugin/php_plugin_value.rs b/crates/shirabe/src/plugin/php_plugin_value.rs new file mode 100644 index 00000000..bbb8fb94 --- /dev/null +++ b/crates/shirabe/src/plugin/php_plugin_value.rs @@ -0,0 +1,289 @@ +//! Codec for the immutable values that cross the plugin boundary as real PHP objects. +//! +//! This module has no Composer counterpart: it is part of the plugin runtime split (see +//! `docs/dev/php-rpc.md`). A proxied entity crosses as a handle, but a value object has no +//! entity to point at — the child has to hold a genuine instance of the real class. Each value +//! is therefore described structurally (class name, constructor arguments, post-construction +//! calls) and rebuilt on the other side; `Shirabe\MaterializedValue` in the worker is the PHP +//! half of the same protocol, and describes those instances back in the same shape. + +use crate::package::Link; +use chrono::{DateTime, TimeZone, Utc}; +use indexmap::IndexMap; +use shirabe_php_rpc::{PhpThrow, PluginValue}; +use shirabe_semver::constraint::{ + AnyConstraint, MatchAllConstraint, MatchNoneConstraint, MultiConstraint, SimpleConstraint, +}; + +const CLASS_KEY: &[u8] = b"__pnew"; +const ARGS_KEY: &[u8] = b"__args"; +const CALLS_KEY: &[u8] = b"__calls"; + +const LINK_CLASS: &str = "Composer\\Package\\Link"; +const CONSTRAINT_CLASS: &str = "Composer\\Semver\\Constraint\\Constraint"; +const MULTI_CONSTRAINT_CLASS: &str = "Composer\\Semver\\Constraint\\MultiConstraint"; +const MATCH_ALL_CLASS: &str = "Composer\\Semver\\Constraint\\MatchAllConstraint"; +const MATCH_NONE_CLASS: &str = "Composer\\Semver\\Constraint\\MatchNoneConstraint"; +const DATE_TIME_CLASS: &str = "DateTimeImmutable"; + +/// PHP's `DateTimeInterface::ATOM` widened by the microseconds PHP dates carry: the child +/// reconstructs the instant from this rendering, so it must keep both the offset and the full +/// precision the other side can represent. +const DATE_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%S%.6f%:z"; + +fn throw(message: String) -> PhpThrow { + PhpThrow { + exception_class: "RuntimeException".to_string(), + message, + code: 0, + } +} + +fn materialized( + class: &str, + args: Vec<PluginValue>, + calls: Vec<(&str, Vec<PluginValue>)>, +) -> PluginValue { + let mut map = IndexMap::new(); + map.insert(CLASS_KEY.to_vec(), PluginValue::string(class)); + map.insert(ARGS_KEY.to_vec(), PluginValue::List(args)); + if !calls.is_empty() { + map.insert( + CALLS_KEY.to_vec(), + PluginValue::List( + calls + .into_iter() + .map(|(method, args)| { + PluginValue::List(vec![ + PluginValue::string(method), + PluginValue::List(args), + ]) + }) + .collect(), + ), + ); + } + PluginValue::Array(map) +} + +/// The class name and constructor arguments of a materialized value, or `None` for any other +/// value shape. +fn as_materialized(value: &PluginValue) -> Option<(String, &[PluginValue])> { + let map = match value { + PluginValue::Array(map) => map, + _ => return None, + }; + let class = match map.get(CLASS_KEY) { + Some(PluginValue::String(bytes)) => String::from_utf8_lossy(bytes).into_owned(), + _ => return None, + }; + let args = match map.get(ARGS_KEY) { + Some(PluginValue::List(args)) => args.as_slice(), + None => &[], + _ => return None, + }; + Some((class, args)) +} + +fn optional_string(value: Option<&PluginValue>) -> Option<String> { + match value { + Some(PluginValue::String(bytes)) => Some(String::from_utf8_lossy(bytes).into_owned()), + _ => None, + } +} + +fn required_string(context: &str, value: Option<&PluginValue>) -> Result<String, PhpThrow> { + match value { + Some(PluginValue::String(bytes)) => Ok(String::from_utf8_lossy(bytes).into_owned()), + other => Err(throw(format!("{context} expects a string, got {other:?}"))), + } +} + +/// The `setPrettyString` call a constraint needs after construction. PHP stores the pretty +/// string in a protected field that no constructor takes, and leaving it unset is observable +/// (`getPrettyString()` falls back to the string form), so an unset one is sent as null. +fn pretty_string_call(constraint: &AnyConstraint) -> Vec<(&'static str, Vec<PluginValue>)> { + let value = match constraint.pretty_string() { + Some(pretty) => PluginValue::string(pretty), + None => PluginValue::Null, + }; + vec![("setPrettyString", vec![value])] +} + +fn constraint_to_wire(constraint: &AnyConstraint) -> PluginValue { + let calls = pretty_string_call(constraint); + match constraint { + AnyConstraint::Simple(c) => materialized( + CONSTRAINT_CLASS, + vec![ + PluginValue::string(c.get_operator()), + PluginValue::string(c.get_version()), + ], + calls, + ), + AnyConstraint::Multi(c) => materialized( + MULTI_CONSTRAINT_CLASS, + vec![ + PluginValue::List(c.get_constraints().iter().map(constraint_to_wire).collect()), + PluginValue::Bool(c.is_conjunctive()), + ], + calls, + ), + AnyConstraint::MatchAll(_) => materialized(MATCH_ALL_CLASS, Vec::new(), calls), + AnyConstraint::MatchNone(_) => materialized(MATCH_NONE_CLASS, Vec::new(), calls), + } +} + +/// The pretty string carried by a materialized constraint's `setPrettyString` call. +fn wire_pretty_string(value: &PluginValue) -> Option<String> { + let map = match value { + PluginValue::Array(map) => map, + _ => return None, + }; + let calls = match map.get(CALLS_KEY) { + Some(PluginValue::List(calls)) => calls, + _ => return None, + }; + calls.iter().find_map(|call| match call { + PluginValue::List(parts) => match (parts.first(), parts.get(1)) { + (Some(PluginValue::String(method)), Some(PluginValue::List(args))) + if method == b"setPrettyString" => + { + optional_string(args.first()) + } + _ => None, + }, + _ => None, + }) +} + +fn constraint_from_wire(value: &PluginValue) -> Result<AnyConstraint, PhpThrow> { + let (class, args) = as_materialized(value).ok_or_else(|| { + throw(format!( + "expected a semver constraint from the plugin, got {value:?}" + )) + })?; + let pretty_string = wire_pretty_string(value); + Ok(match class.as_str() { + CONSTRAINT_CLASS => AnyConstraint::Simple(SimpleConstraint::new( + required_string("a semver constraint operator", args.first())?, + required_string("a semver constraint version", args.get(1))?, + pretty_string, + )), + MULTI_CONSTRAINT_CLASS => { + let constraints = match args.first() { + Some(PluginValue::List(items)) => items + .iter() + .map(constraint_from_wire) + .collect::<Result<Vec<_>, _>>()?, + // A MultiConstraint built from a PHP associative array crosses as a map. + Some(PluginValue::Array(items)) => items + .values() + .map(constraint_from_wire) + .collect::<Result<Vec<_>, _>>()?, + other => { + return Err(throw(format!( + "a MultiConstraint expects a list of constraints, got {other:?}" + ))); + } + }; + if constraints.len() < 2 { + return Err(throw( + "a MultiConstraint needs at least two constraints".to_string(), + )); + } + let conjunctive = match args.get(1) { + Some(PluginValue::Bool(conjunctive)) => *conjunctive, + // PHP defaults the parameter to true. + None => true, + other => { + return Err(throw(format!( + "a MultiConstraint expects a bool conjunctive flag, got {other:?}" + ))); + } + }; + AnyConstraint::Multi(MultiConstraint::new( + constraints, + conjunctive, + pretty_string, + )) + } + MATCH_ALL_CLASS => AnyConstraint::MatchAll(MatchAllConstraint::new(pretty_string)), + MATCH_NONE_CLASS => AnyConstraint::MatchNone(MatchNoneConstraint::new(pretty_string)), + // TODO(plugin): a plugin-defined ConstraintInterface implementation has no Rust + // counterpart; the four composer/semver classes are the whole vocabulary here. + other => { + return Err(throw(format!( + "the semver constraint class `{other}` cannot cross the plugin boundary" + ))); + } + }) +} + +pub(crate) fn link_to_wire(link: &Link) -> PluginValue { + materialized( + LINK_CLASS, + vec![ + PluginValue::string(link.get_source()), + PluginValue::string(link.get_target()), + constraint_to_wire(link.get_constraint()), + PluginValue::string(link.get_description()), + PluginValue::string(link.get_pretty_constraint()), + ], + Vec::new(), + ) +} + +pub(crate) fn link_from_wire(value: &PluginValue) -> Result<Link, PhpThrow> { + let (class, args) = as_materialized(value) + .ok_or_else(|| throw(format!("expected a Link from the plugin, got {value:?}")))?; + if class != LINK_CLASS { + // TODO(plugin): Link subclasses have no Rust counterpart; the port models links as a + // single value type. + return Err(throw(format!( + "the class `{class}` cannot cross the plugin boundary as a Link" + ))); + } + let constraint = constraint_from_wire( + args.get(2) + .ok_or_else(|| throw("a Link expects a constraint argument".to_string()))?, + )?; + // TODO(plugin): PHP's Link leaves $prettyConstraint nullable and throws from + // getPrettyConstraint() when it was never given, but this port stores a string, so a link + // a plugin built without one comes back carrying the empty string instead. + let pretty_constraint = optional_string(args.get(4)).unwrap_or_default(); + Ok(Link::new( + required_string("a Link source", args.first())?, + required_string("a Link target", args.get(1))?, + constraint, + optional_string(args.get(3)), + pretty_constraint, + )) +} + +pub(crate) fn date_time_to_wire(date: &DateTime<Utc>) -> PluginValue { + materialized( + DATE_TIME_CLASS, + vec![PluginValue::string( + date.format(DATE_TIME_FORMAT).to_string(), + )], + Vec::new(), + ) +} + +pub(crate) fn date_time_from_wire(value: &PluginValue) -> Result<DateTime<Utc>, PhpThrow> { + let (class, args) = as_materialized(value) + .ok_or_else(|| throw(format!("expected a date from the plugin, got {value:?}")))?; + if class != DATE_TIME_CLASS { + return Err(throw(format!( + "the class `{class}` cannot cross the plugin boundary as a date" + ))); + } + let rendered = required_string("a date", args.first())?; + let parsed = DateTime::parse_from_str(&rendered, DATE_TIME_FORMAT).map_err(|e| { + throw(format!( + "the date `{rendered}` from the plugin is not in the expected format: {e}" + )) + })?; + Ok(Utc.from_utc_datetime(&parsed.naive_utc())) +} diff --git a/crates/shirabe/tests/plugin/fixtures/values-v1/Values/Plugin.php b/crates/shirabe/tests/plugin/fixtures/values-v1/Values/Plugin.php new file mode 100644 index 00000000..685aa903 --- /dev/null +++ b/crates/shirabe/tests/plugin/fixtures/values-v1/Values/Plugin.php @@ -0,0 +1,85 @@ +<?php + +namespace Values; + +use Composer\Composer; +use Composer\IO\IOInterface; +use Composer\Package\Link; +use Composer\Plugin\PluginInterface; +use Composer\Semver\Constraint\Constraint; +use Composer\Semver\Constraint\ConstraintInterface; +use Composer\Semver\Constraint\MatchAllConstraint; +use Composer\Semver\Constraint\MatchNoneConstraint; +use Composer\Semver\Constraint\MultiConstraint; + +class Plugin implements PluginInterface +{ + public function activate(Composer $composer, IOInterface $io) + { + $package = $composer->getPackage(); + + foreach ($package->getRequires() as $name => $link) { + if (!$link instanceof Link) { + throw new \RuntimeException('not a Link: ' . get_class($link)); + } + $io->write(sprintf( + '%s | %s | %s | %s | %s | %s', + $name, + $link->getSource(), + $link->getTarget(), + $link->getDescription(), + $link->getPrettyConstraint(), + self::render($link->getConstraint()) + )); + } + + $package->setRequires([ + 'bar/plain' => new Link('dummy/root', 'bar/plain', self::pretty(new Constraint('==', '2.0.0.0'), '2.0'), Link::TYPE_REQUIRE, '2.0'), + 'bar/multi' => new Link('dummy/root', 'bar/multi', new MultiConstraint([ + new Constraint('<', '1.0.0.0'), + new Constraint('>=', '3.0.0.0'), + ], false), Link::TYPE_DEV_REQUIRE, '<1.0 || >=3.0'), + 'bar/all' => new Link('dummy/root', 'bar/all', new MatchAllConstraint(), Link::TYPE_REQUIRE, '*'), + 'bar/none' => new Link('dummy/root', 'bar/none', self::pretty(new MatchNoneConstraint(), 'nothing'), Link::TYPE_REQUIRE, ''), + ]); + + $package->setReleaseDate(new \DateTimeImmutable('2024-03-04 05:06:07.123456', new \DateTimeZone('Asia/Tokyo'))); + $io->write('release date: ' . $package->getReleaseDate()->format('Y-m-d\TH:i:s.uP')); + } + + public function deactivate(Composer $composer, IOInterface $io) + { + } + + public function uninstall(Composer $composer, IOInterface $io) + { + } + + private static function pretty(ConstraintInterface $constraint, string $prettyString): ConstraintInterface + { + $constraint->setPrettyString($prettyString); + + return $constraint; + } + + private static function render(ConstraintInterface $constraint): string + { + if ($constraint instanceof Constraint) { + $shape = sprintf('Constraint(%s %s)', $constraint->getOperator(), $constraint->getVersion()); + } elseif ($constraint instanceof MultiConstraint) { + $shape = sprintf( + 'MultiConstraint(%s: %s)', + $constraint->isConjunctive() ? 'and' : 'or', + implode(', ', array_map([self::class, 'render'], $constraint->getConstraints())) + ); + } elseif ($constraint instanceof MatchAllConstraint) { + $shape = 'MatchAllConstraint()'; + } elseif ($constraint instanceof MatchNoneConstraint) { + $shape = 'MatchNoneConstraint()'; + } else { + throw new \RuntimeException('unexpected constraint: ' . get_class($constraint)); + } + + return $shape . ' pretty=' . $constraint->getPrettyString(); + } +} diff --git a/crates/shirabe/tests/plugin/fixtures/values-v1/composer.json b/crates/shirabe/tests/plugin/fixtures/values-v1/composer.json new file mode 100644 index 00000000..d4e5861e --- /dev/null +++ b/crates/shirabe/tests/plugin/fixtures/values-v1/composer.json @@ -0,0 +1,12 @@ +{ + "name": "values-v1", + "version": "1.0.0", + "type": "composer-plugin", + "autoload": { "psr-0": { "Values": "" } }, + "extra": { + "class": "Values\\Plugin" + }, + "require": { + "composer-plugin-api": "^2.0" + } +} diff --git a/crates/shirabe/tests/plugin/main.rs b/crates/shirabe/tests/plugin/main.rs index 0b404ee9..f5a29ba6 100644 --- a/crates/shirabe/tests/plugin/main.rs +++ b/crates/shirabe/tests/plugin/main.rs @@ -10,3 +10,4 @@ mod e2e_installers_test; mod e2e_normalize_test; mod plugin_installer_test; mod subscriber_test; +mod value_round_trip_test; diff --git a/crates/shirabe/tests/plugin/value_round_trip_test.rs b/crates/shirabe/tests/plugin/value_round_trip_test.rs new file mode 100644 index 00000000..3e01422a --- /dev/null +++ b/crates/shirabe/tests/plugin/value_round_trip_test.rs @@ -0,0 +1,168 @@ +//! Shirabe-specific integration tests for the immutable values that cross the plugin boundary +//! as real PHP objects: `Composer\Package\Link` with its `composer/semver` constraint, and the +//! `\DateTimeInterface` release date. Upstream Composer has no test for this (its plugins run +//! in-process), so the fixture `fixtures/values-v1` is Shirabe-owned. + +use crate::async_runtime::run; +use crate::plugin_installer_test::{lock_php_worker, new_installer, php_runtime_available, set_up}; +use indexmap::IndexMap; +use shirabe::installer::InstallerInterface; +use shirabe::package::Link; +use shirabe::package::PackageInterfaceHandle; +use shirabe::package::loader::{ArrayLoader, JsonLoader, JsonLoaderInput}; +use shirabe_semver::constraint::{ + AnyConstraint, MatchAllConstraint, MatchNoneConstraint, MultiConstraint, SimpleConstraint, +}; + +fn values_fixture_package() -> PackageInterfaceHandle { + let loader = JsonLoader::new(Box::new(ArrayLoader::new(None, false))); + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/plugin/fixtures/values-v1/composer.json"); + loader + .load(JsonLoaderInput::String( + path.canonicalize().unwrap().to_str().unwrap().to_string(), + )) + .unwrap() +} + +fn simple(operator: &str, version: &str, pretty_string: Option<&str>) -> AnyConstraint { + AnyConstraint::Simple(SimpleConstraint::new( + operator.to_string(), + version.to_string(), + pretty_string.map(str::to_string), + )) +} + +fn link(target: &str, constraint: AnyConstraint, pretty_constraint: &str) -> Link { + Link::new( + "dummy/root".to_string(), + target.to_string(), + constraint, + Some(Link::TYPE_REQUIRE.to_string()), + pretty_constraint.to_string(), + ) +} + +/// Every constraint shape the codec knows, so the rendering the plugin writes covers all four +/// classes and both the set and the unset pretty string. +fn seeded_requires() -> IndexMap<String, Link> { + let mut requires = IndexMap::new(); + requires.insert( + "foo/simple".to_string(), + link("foo/simple", simple(">=", "1.0.0.0", None), ">=1.0"), + ); + requires.insert( + "foo/multi".to_string(), + link( + "foo/multi", + AnyConstraint::Multi(MultiConstraint::new( + vec![ + simple(">=", "1.0.0.0", None), + simple("<", "2.0.0.0", Some("<2.0")), + ], + true, + Some("^1.0".to_string()), + )), + "^1.0", + ), + ); + requires.insert( + "foo/all".to_string(), + link( + "foo/all", + AnyConstraint::MatchAll(MatchAllConstraint::new(None)), + "*", + ), + ); + requires.insert( + "foo/none".to_string(), + link( + "foo/none", + AnyConstraint::MatchNone(MatchNoneConstraint::new(Some("nothing".to_string()))), + "", + ), + ); + requires +} + +fn describe(constraint: &AnyConstraint) -> String { + let shape = match constraint { + AnyConstraint::Simple(c) => { + format!("Constraint({} {})", c.get_operator(), c.get_version()) + } + AnyConstraint::Multi(c) => format!( + "MultiConstraint({}: {})", + if c.is_conjunctive() { "and" } else { "or" }, + c.get_constraints() + .iter() + .map(describe) + .collect::<Vec<_>>() + .join(", ") + ), + AnyConstraint::MatchAll(_) => "MatchAllConstraint()".to_string(), + AnyConstraint::MatchNone(_) => "MatchNoneConstraint()".to_string(), + }; + format!("{shape} pretty={}", constraint.get_pretty_string()) +} + +fn describe_links(links: &IndexMap<String, Link>) -> Vec<String> { + links + .iter() + .map(|(name, link)| { + format!( + "{name} | {} | {} | {} | {} | {}", + link.get_source(), + link.get_target(), + link.get_description(), + link.get_pretty_constraint(), + describe(link.get_constraint()) + ) + }) + .collect() +} + +#[test] +fn test_links_and_release_date_round_trip_through_the_plugin() { + if !php_runtime_available() { + return; + } + let _worker = lock_php_worker(); + let set_up = set_up(); + let package = set_up.composer.borrow().get_package().clone(); + package.set_requires(seeded_requires()); + + let installer = new_installer(&set_up); + set_up.pm.borrow_mut().load_installed_plugins().unwrap(); + run(installer.install(&set_up.repository, values_fixture_package())).unwrap(); + + // What the plugin saw: each seeded link rebuilt in the child as a real Link over a real + // composer/semver constraint. + assert_eq!( + "foo/simple | dummy/root | foo/simple | requires | >=1.0 | Constraint(>= 1.0.0.0) pretty=>= 1.0.0.0\n\ + foo/multi | dummy/root | foo/multi | requires | ^1.0 | MultiConstraint(and: Constraint(>= 1.0.0.0) pretty=>= 1.0.0.0, Constraint(< 2.0.0.0) pretty=<2.0) pretty=^1.0\n\ + foo/all | dummy/root | foo/all | requires | * | MatchAllConstraint() pretty=*\n\ + foo/none | dummy/root | foo/none | requires | | MatchNoneConstraint() pretty=nothing\n\ + release date: 2024-03-03T20:06:07.123456+00:00\n", + set_up.io.borrow().get_output() + ); + + // What the plugin wrote back: links it built PHP-side, decoded into Rust values. + assert_eq!( + vec![ + "bar/plain | dummy/root | bar/plain | requires | 2.0 | Constraint(== 2.0.0.0) pretty=2.0", + "bar/multi | dummy/root | bar/multi | requires (for development) | <1.0 || >=3.0 | MultiConstraint(or: Constraint(< 1.0.0.0) pretty=< 1.0.0.0, Constraint(>= 3.0.0.0) pretty=>= 3.0.0.0) pretty=[< 1.0.0.0 || >= 3.0.0.0]", + "bar/all | dummy/root | bar/all | requires | * | MatchAllConstraint() pretty=*", + "bar/none | dummy/root | bar/none | requires | | MatchNoneConstraint() pretty=nothing", + ], + describe_links(&package.get_requires()) + ); + // The plugin wrote an Asia/Tokyo instant with microseconds; both survive the crossing, + // and the child sees the same instant back in UTC. + assert_eq!( + "2024-03-03T20:06:07.123456Z", + package + .get_release_date() + .unwrap() + .to_rfc3339_opts(chrono::SecondsFormat::Micros, true) + ); +} |
