pub struct Environment { /* private fields */ }Expand description
A sandboxed temporary environment. Build one with Environment::temporary and enter it with
Environment::run, or use the free run function to do both at once.
Implementations§
Source§impl Environment
impl Environment
Sourcepub fn temporary() -> Self
pub fn temporary() -> Self
Create a fresh, not-yet-entered environment. The temporary directory is created later, inside
run, while the global lock is held.
Sourcepub fn directory(&self) -> Option<&Path>
pub fn directory(&self) -> Option<&Path>
The active sandbox directory (the canonicalized temporary directory), or None before
run has entered.
Sourcepub fn run<T>(
self,
f: impl FnOnce(&mut Environment) -> Result<T, Error>,
) -> Result<T, Error>
pub fn run<T>( self, f: impl FnOnce(&mut Environment) -> Result<T, Error>, ) -> Result<T, Error>
Enter the sandbox and run f inside it.
Acquires the global lock, creates a temporary directory (falling back to the current directory
if the system temporary directory is not writable), snapshots the environment and working
directory, and chdirs into the sandbox. When f returns — or panics — the environment and
working directory are restored and the sandbox is deleted before the lock is released.
User errors convert into Error::Other, so ? works inside the closure for any
Box<dyn Error + Send + Sync> or std::io::Error.
Sourcepub fn clear_env(&mut self)
pub fn clear_env(&mut self)
Remove every environment variable from the process. The full environment was snapshotted on
entry, so it is restored when the sandbox is dropped. A no-op if called outside of
run.
Sourcepub fn set_env(
&mut self,
key: impl AsRef<OsStr>,
value: impl AsRef<OsStr>,
) -> Result<(), Error>
pub fn set_env( &mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>, ) -> Result<(), Error>
Set the environment variable key to value for the duration of the sandbox. The full
environment was snapshotted on entry, so this is undone when the sandbox is dropped — use it
instead of a hand-rolled unsafe { std::env::set_var(..) } so tests stay self-contained.
Returns Error::Inactive when called outside of run.
Sourcepub fn create_file(&mut self, path: impl AsRef<Path>) -> Result<(), Error>
pub fn create_file(&mut self, path: impl AsRef<Path>) -> Result<(), Error>
Create an empty file at path (relative to the sandbox), truncating any existing file. The
sandbox is the current directory during run, so read it back with the
same relative path.