vx_rez_adapter/lib.rs
1//! `vx-rez-adapter` bridges [vx](https://github.com/vx-org) and
2//! [rez-next](https://github.com/vx-org/rez-next) package environments.
3//!
4//! The crate is intended to expose two capabilities:
5//!
6//! 1. Resolving the environment of one or more rez packages.
7//! 2. Launching a tool as a child process with that environment applied.
8//!
9//! Both capabilities are implemented on top of the `rez-next` SDK:
10//!
11//! - [`RezAdapter::resolve_env`] delegates repository discovery, dependency
12//! resolution, variant selection, and Rex activation to `rez-next-runtime`.
13//! - [`RezAdapter::launch`] spawns the program with that environment applied
14//! and reports its exit status.
15
16#![deny(missing_docs)]
17
18use std::collections::BTreeMap;
19use std::path::PathBuf;
20
21pub mod env;
22pub mod error;
23pub mod launch;
24pub mod process;
25pub mod resolve;
26
27pub use env::{EnvAction, EnvDelta, ResolvedEnv, env_key, path_separator};
28pub use error::{Error, Result};
29pub use launch::{LaunchOutcome, LaunchRequest};
30pub use process::which;
31pub use resolve::{resolve_env, resolve_env_async};
32
33/// The platform and architecture used to select package variants.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct ResolveTarget {
36 /// Rez platform name, such as `windows`, `linux`, or `osx`.
37 pub platform: String,
38 /// Rez architecture name, such as `AMD64`, `x86_64`, or `arm64`.
39 pub architecture: String,
40}
41
42/// A request to resolve the environment of a set of rez packages.
43///
44/// Package selectors use rez syntax, e.g. `"python-3.11"` or `"maya-2024"`.
45#[derive(Debug, Clone, Default, PartialEq, Eq)]
46pub struct ResolveRequest {
47 /// Package requests to resolve, in rez request syntax.
48 pub requests: Vec<String>,
49 /// Additional package requests included in the same dependency solve.
50 pub implicit_requests: Vec<String>,
51 /// Paths searched for packages, overriding the ambient configuration.
52 pub package_paths: Option<Vec<PathBuf>>,
53 /// Explicit target for variant selection; `None` adds no target constraints.
54 pub target: Option<ResolveTarget>,
55 /// Base environment for activation; `None` inherits the current process.
56 /// An explicit empty map starts activation without parent variables.
57 pub parent_environment: Option<Environment>,
58}
59
60impl ResolveRequest {
61 /// Creates a request for the given package selectors.
62 #[must_use]
63 pub fn new<I, S>(requests: I) -> Self
64 where
65 I: IntoIterator<Item = S>,
66 S: Into<String>,
67 {
68 Self {
69 requests: requests.into_iter().map(Into::into).collect(),
70 implicit_requests: Vec::new(),
71 package_paths: None,
72 target: None,
73 parent_environment: None,
74 }
75 }
76
77 /// Overrides the package search paths.
78 ///
79 /// Without this the resolve falls back to the `REZ_PACKAGES_PATH`
80 /// environment variable.
81 #[must_use]
82 pub fn package_paths<I, P>(mut self, paths: I) -> Self
83 where
84 I: IntoIterator<Item = P>,
85 P: Into<PathBuf>,
86 {
87 self.package_paths = Some(paths.into_iter().map(Into::into).collect());
88 self
89 }
90
91 /// Adds package requests to the same dependency solve.
92 #[must_use]
93 pub fn implicit_requests<I, S>(mut self, requests: I) -> Self
94 where
95 I: IntoIterator<Item = S>,
96 S: Into<String>,
97 {
98 self.implicit_requests = requests.into_iter().map(Into::into).collect();
99 self
100 }
101
102 /// Selects package variants for an explicit platform and architecture.
103 #[must_use]
104 pub fn target(mut self, platform: impl Into<String>, architecture: impl Into<String>) -> Self {
105 self.target = Some(ResolveTarget {
106 platform: platform.into(),
107 architecture: architecture.into(),
108 });
109 self
110 }
111
112 /// Supplies the exact base environment used by package activation.
113 ///
114 /// Pass an empty map to prevent ambient variables from entering the
115 /// resolved environment. Windows variable names are normalized to uppercase.
116 #[must_use]
117 pub fn parent_environment<I, K, V>(mut self, environment: I) -> Self
118 where
119 I: IntoIterator<Item = (K, V)>,
120 K: Into<String>,
121 V: Into<String>,
122 {
123 self.parent_environment = Some(
124 environment
125 .into_iter()
126 .map(|(key, value)| (env_key(&key.into()), value.into()))
127 .collect(),
128 );
129 self
130 }
131}
132
133/// Resolves rez package environments and launches tools inside them.
134///
135/// This is the top-level entry point of the crate.
136#[derive(Debug, Clone, Default)]
137pub struct RezAdapter;
138
139impl RezAdapter {
140 /// Creates an adapter with default settings.
141 #[must_use]
142 pub fn new() -> Self {
143 Self
144 }
145
146 /// Resolves the environment described by `request`.
147 ///
148 /// Packages are looked up under [`ResolveRequest::package_paths`], or under
149 /// `REZ_PACKAGES_PATH` when the request does not override them. Their Rex
150 /// commands are then applied to the requested parent environment.
151 /// In an existing Tokio runtime, use [`Self::resolve_env_async`] instead.
152 ///
153 /// # Errors
154 ///
155 /// Returns [`Error::Resolve`] when a request cannot be parsed or no package
156 /// satisfies it, and [`Error::PackagePath`] when a configured package path
157 /// cannot be read.
158 ///
159 /// # Examples
160 ///
161 /// ```no_run
162 /// use vx_rez_adapter::{RezAdapter, ResolveRequest};
163 ///
164 /// let request = ResolveRequest::new(["python-3.11"])
165 /// .package_paths(["/packages"]);
166 /// let resolved = RezAdapter::new().resolve_env(&request)?;
167 /// println!("{}", resolved.environment["PATH"]);
168 /// # Ok::<(), vx_rez_adapter::Error>(())
169 /// ```
170 pub fn resolve_env(&self, request: &ResolveRequest) -> Result<ResolvedEnv> {
171 resolve::resolve_env(request)
172 }
173
174 /// Resolves packages and their environment inside an existing async runtime.
175 ///
176 /// # Errors
177 ///
178 /// Returns the same repository, dependency, and activation diagnostics as
179 /// [`Self::resolve_env`]. This method never creates a nested Tokio runtime.
180 pub async fn resolve_env_async(&self, request: &ResolveRequest) -> Result<ResolvedEnv> {
181 resolve::resolve_env_async(request).await
182 }
183
184 /// Launches `request.program` with the resolved environment applied.
185 ///
186 /// The child inherits this process's stdin, stdout, and stderr, and its
187 /// exit code and terminating signal are returned in a [`LaunchOutcome`].
188 ///
189 /// A program that runs and exits non-zero is a **successful launch**: this
190 /// returns `Ok(outcome)` with [`LaunchOutcome::success`] reporting `false`.
191 /// Only a failure to *start* the program is an `Err`. Callers must check
192 /// `success()` — inspecting only the `Result` cannot distinguish a tool
193 /// that ran and failed from one that ran and succeeded.
194 ///
195 /// # Errors
196 ///
197 /// Returns [`Error::Spawn`] when the program cannot be started.
198 ///
199 /// # Examples
200 ///
201 /// ```no_run
202 /// use vx_rez_adapter::{LaunchRequest, RezAdapter, ResolveRequest};
203 ///
204 /// let adapter = RezAdapter::new();
205 /// let resolved = adapter.resolve_env(&ResolveRequest::new(["python-3.11"]))?;
206 ///
207 /// let outcome = adapter.launch(
208 /// &LaunchRequest::new("python")
209 /// .arg("--version")
210 /// .environment(resolved.environment),
211 /// )?;
212 /// assert!(outcome.success());
213 /// # Ok::<(), vx_rez_adapter::Error>(())
214 /// ```
215 pub fn launch(&self, request: &LaunchRequest) -> Result<LaunchOutcome> {
216 process::launch(request)
217 }
218}
219
220/// An ordered map of environment variable name to value.
221///
222/// `BTreeMap` keeps the rendering of an environment deterministic, which
223/// matters for diffing and for reproducible launches.
224///
225/// Keys should be built with [`env_key`] so that the case-insensitive
226/// environment of Windows collapses `Path` and `PATH` into one entry instead of
227/// handing a child process two competing definitions.
228pub type Environment = BTreeMap<String, String>;