sandbox: add the Sandbox trait and the host backend
Build code needs an interface it can receive explicitly instead of a global context. Add the 11-method Sandbox trait, the command description and builder, the transfer options, and the shared stage_tree helper that owns VCS pruning. Host implements the trait with std::process and std::fs. A conformance test runs against it and pins the command contract through an Arc<dyn Sandbox>.
This commit is contained in:
1 parent
48306f3719
commit
f1a21e0923
7 files changed
+648
-38
No files matched your search
+13
-3
@@ -142,15 +142,25 @@ pub struct BuildCommand<'a> {
|
||||
}
|
||||
|
||||
pub trait SandboxExt: Sandbox {
|
||||
fn command(&self, program: &str) -> BuildCommand<'_> { /* ... */ }
|
||||
fn command(&self, program: &str) -> BuildCommand<'_>;
|
||||
fn stage_tree(
|
||||
&self,
|
||||
host: &Path,
|
||||
dest: &Path,
|
||||
opts: &StageOptions,
|
||||
) -> io::Result<PutOutcome>;
|
||||
}
|
||||
|
||||
impl<T: Sandbox + ?Sized> SandboxExt for T {}
|
||||
impl<T: Sandbox> SandboxExt for T { /* forward to free functions */ }
|
||||
impl SandboxExt for dyn Sandbox + '_ { /* same */ }
|
||||
```
|
||||
|
||||
The extension trait keeps `sandbox.command("apt-get")` working on
|
||||
`Arc<dyn Sandbox>` without putting a generic or `Self: Sized` method on the
|
||||
trait. `status`, `output` and `capture` keep their current behavior.
|
||||
trait. Two impls are needed: a default method cannot coerce `&Self` to
|
||||
`&dyn Sandbox` when `Self` is unsized, so the blanket impl covers sized
|
||||
backends and a second impl covers `dyn Sandbox`. Both forward to the same
|
||||
free functions. `status`, `output` and `capture` keep their current behavior.
|
||||
|
||||
`src/exec.rs` holds the parts that are about processes, not environments:
|
||||
`Stream`, `LineSink`, `pump`, the `sanitize_fds` pre-exec hook, the
|
||||
|
||||
+1
-20
@@ -6,6 +6,7 @@ use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use crate::exec::LineSink;
|
||||
use crate::sandbox::contextualize_spawn_error;
|
||||
|
||||
use super::local::LocalDriver;
|
||||
use super::schroot::SchrootDriver;
|
||||
@@ -534,26 +535,6 @@ impl<'a> ContextCommand<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrap an I/O error from launching a command with a more helpful message.
|
||||
///
|
||||
/// In particular, a `NotFound` error (e.g. "No such file or directory") is almost always
|
||||
/// caused by the requested program not being installed or not on `PATH`; we make that
|
||||
/// explicit instead of leaking the raw OS error.
|
||||
fn contextualize_spawn_error(program: &str, e: io::Error) -> io::Error {
|
||||
if e.kind() == io::ErrorKind::NotFound {
|
||||
io::Error::new(
|
||||
e.kind(),
|
||||
format!(
|
||||
"Could not run '{program}': {e}. \
|
||||
The program does not seem to be installed or is not on PATH; \
|
||||
install the corresponding package and retry.",
|
||||
),
|
||||
)
|
||||
} else {
|
||||
io::Error::new(e.kind(), format!("Could not run '{program}': {e}"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod endpoint_tests {
|
||||
use super::*;
|
||||
|
||||
+1
-15
@@ -26,21 +26,7 @@ pub fn current() -> Arc<Context> {
|
||||
manager::MANAGER.current()
|
||||
}
|
||||
|
||||
/// Version-control metadata directories that must never leak into a
|
||||
/// prepared build tree.
|
||||
///
|
||||
/// Their presence flips autotools' "building from VCS" detection (e.g. GNU
|
||||
/// hello's `BUILD_FROM_GIT`, triggered by a `.git` directory next to
|
||||
/// `configure.ac`), which activates maintainer-only regeneration rules
|
||||
/// requiring tools that are deliberately not declared as build-dependencies
|
||||
/// (e.g. `help2man`). Source packages produced by dpkg-source never contain
|
||||
/// them, so package builds must not see them either.
|
||||
pub(crate) fn is_vcs_dir_name(name: &std::ffi::OsStr) -> bool {
|
||||
matches!(
|
||||
name.to_str(),
|
||||
Some(".git") | Some(".hg") | Some(".svn") | Some(".bzr") | Some("CVS")
|
||||
)
|
||||
}
|
||||
pub(crate) use crate::sandbox::staging::is_vcs_dir_name;
|
||||
|
||||
/// Recursively remove version-control metadata directories below `root`.
|
||||
///
|
||||
|
||||
@@ -47,6 +47,10 @@ pub mod quirks;
|
||||
/// Run a source package's DEP-8 as-installed tests (`pkh test`)
|
||||
pub mod test;
|
||||
|
||||
/// A place builds run: the command and filesystem interface, its host
|
||||
/// implementation and the source-tree staging helper
|
||||
pub mod sandbox;
|
||||
|
||||
/// Line classifiers rewriting raw subprocess output into display actions
|
||||
/// and countable progress (pure logic, shared by build views)
|
||||
pub mod logfmt;
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
//! The host machine as a sandbox.
|
||||
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::os::unix::fs::symlink;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::{BuildOutcome, Capture, CommandSpec, Execution, PutOptions, PutOutcome, Sandbox};
|
||||
|
||||
/// The host machine.
|
||||
///
|
||||
/// Commands run with [`std::process::Command`], files use [`std::fs`], and
|
||||
/// there is no teardown. This serves `pkh test --mode local` and the unit
|
||||
/// tests that build a local context.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Host;
|
||||
|
||||
impl Host {
|
||||
/// Create a host sandbox.
|
||||
pub fn new() -> Self {
|
||||
Host
|
||||
}
|
||||
}
|
||||
|
||||
impl Sandbox for Host {
|
||||
fn run(&self, cmd: &CommandSpec, capture: Capture) -> io::Result<Execution> {
|
||||
let args: Vec<String> = cmd
|
||||
.args
|
||||
.iter()
|
||||
.map(|arg| arg.to_string_lossy().into_owned())
|
||||
.collect();
|
||||
let env: Vec<(String, String)> = cmd
|
||||
.env
|
||||
.iter()
|
||||
.map(|(key, value)| {
|
||||
(
|
||||
key.to_string_lossy().into_owned(),
|
||||
value.to_string_lossy().into_owned(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let cwd = cmd.cwd.as_deref().map(|path| path.to_string_lossy());
|
||||
let program = cmd.program.to_string_lossy();
|
||||
|
||||
match capture {
|
||||
Capture::Inherit => {
|
||||
let status = crate::exec::run(&program, &args, &env, cwd.as_deref())?;
|
||||
Ok(Execution {
|
||||
status,
|
||||
stdout: Vec::new(),
|
||||
stderr: Vec::new(),
|
||||
})
|
||||
}
|
||||
Capture::Lines(sink) => {
|
||||
let status =
|
||||
crate::exec::run_captured(&program, &args, &env, cwd.as_deref(), sink)?;
|
||||
Ok(Execution {
|
||||
status,
|
||||
stdout: Vec::new(),
|
||||
stderr: Vec::new(),
|
||||
})
|
||||
}
|
||||
Capture::Output => {
|
||||
let output = crate::exec::run_output(&program, &args, &env, cwd.as_deref())?;
|
||||
Ok(Execution {
|
||||
status: output.status,
|
||||
stdout: output.stdout,
|
||||
stderr: output.stderr,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_file(&self, path: &Path) -> io::Result<String> {
|
||||
fs::read_to_string(path)
|
||||
}
|
||||
|
||||
fn write_file(&self, path: &Path, content: &str) -> io::Result<()> {
|
||||
fs::write(path, content)
|
||||
}
|
||||
|
||||
fn exists(&self, path: &Path) -> io::Result<bool> {
|
||||
Ok(path.exists())
|
||||
}
|
||||
|
||||
fn is_dir(&self, path: &Path) -> io::Result<bool> {
|
||||
Ok(path.is_dir())
|
||||
}
|
||||
|
||||
fn list_files(&self, path: &Path) -> io::Result<Vec<PathBuf>> {
|
||||
let mut entries = Vec::new();
|
||||
for entry in fs::read_dir(path)? {
|
||||
entries.push(entry?.path());
|
||||
}
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
fn put(&self, host: &Path, dest: &Path, opts: &PutOptions) -> io::Result<PutOutcome> {
|
||||
copy_tree(host, dest, &opts.skip_dirs)?;
|
||||
Ok(PutOutcome::Fresh)
|
||||
}
|
||||
|
||||
fn get(&self, src: &Path, dest: &Path) -> io::Result<()> {
|
||||
copy_tree(src, dest, &[])
|
||||
}
|
||||
|
||||
fn remove(&self, path: &Path) -> io::Result<()> {
|
||||
match fs::symlink_metadata(path) {
|
||||
Ok(meta) if meta.is_dir() => fs::remove_dir_all(path),
|
||||
Ok(_) => fs::remove_file(path),
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
fn create_temp_dir(&self) -> io::Result<String> {
|
||||
super::unique_dir(&std::env::temp_dir(), "pkh-")
|
||||
.map(|path| path.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
fn cleanup(&self, _outcome: Option<BuildOutcome>) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy `src` to `dest`, reproducing symlinks and skipping `skip_dirs` by
|
||||
/// name at any depth.
|
||||
fn copy_tree(src: &Path, dest: &Path, skip_dirs: &[std::ffi::OsString]) -> io::Result<()> {
|
||||
let meta = fs::symlink_metadata(src)?;
|
||||
if meta.file_type().is_symlink() {
|
||||
let target = fs::read_link(src)?;
|
||||
let _ = fs::remove_file(dest);
|
||||
return symlink(target, dest);
|
||||
}
|
||||
|
||||
if meta.is_dir() {
|
||||
fs::create_dir_all(dest)?;
|
||||
for entry in fs::read_dir(src)? {
|
||||
let entry = entry?;
|
||||
let name = entry.file_name();
|
||||
if entry.file_type()?.is_dir() && skip_dirs.iter().any(|skip| skip == &name) {
|
||||
continue;
|
||||
}
|
||||
copy_tree(&entry.path(), &dest.join(&name), skip_dirs)?;
|
||||
}
|
||||
} else {
|
||||
fs::copy(src, dest)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,397 @@
|
||||
//! A place builds run: a command runner and a filesystem.
|
||||
//!
|
||||
//! Build code receives a `Sandbox` explicitly. Paths passed to the trait are
|
||||
//! paths inside the sandbox; only [`Sandbox::put`] and [`Sandbox::get`] cross
|
||||
//! the host boundary.
|
||||
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{ExitStatus, Output};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::exec::LineSink;
|
||||
|
||||
mod host;
|
||||
pub(crate) mod staging;
|
||||
|
||||
pub use host::Host;
|
||||
pub use staging::{StageOptions, stage_tree};
|
||||
|
||||
/// A place a build runs: a command runner and a filesystem.
|
||||
pub trait Sandbox: Send + Sync {
|
||||
/// Run a command inside the environment.
|
||||
fn run(&self, cmd: &CommandSpec, capture: Capture) -> io::Result<Execution>;
|
||||
|
||||
/// Read a small text file from inside the environment.
|
||||
fn read_file(&self, path: &Path) -> io::Result<String>;
|
||||
|
||||
/// Write a small text file inside the environment.
|
||||
fn write_file(&self, path: &Path, content: &str) -> io::Result<()>;
|
||||
|
||||
/// Check whether a path exists inside the environment.
|
||||
fn exists(&self, path: &Path) -> io::Result<bool>;
|
||||
|
||||
/// Check whether a path is a directory inside the environment.
|
||||
fn is_dir(&self, path: &Path) -> io::Result<bool>;
|
||||
|
||||
/// List the entries of a directory inside the environment.
|
||||
fn list_files(&self, path: &Path) -> io::Result<Vec<PathBuf>>;
|
||||
|
||||
/// Copy a host file or tree to `dest` inside the environment.
|
||||
///
|
||||
/// `dest` is the copied entry's full path, not a parent directory.
|
||||
fn put(&self, host: &Path, dest: &Path, opts: &PutOptions) -> io::Result<PutOutcome>;
|
||||
|
||||
/// Copy a file or tree from the environment to `dest` on the host.
|
||||
///
|
||||
/// `dest` is the copied entry's full path, not a parent directory.
|
||||
fn get(&self, src: &Path, dest: &Path) -> io::Result<()>;
|
||||
|
||||
/// Remove a file or directory tree inside the environment.
|
||||
///
|
||||
/// Removing a path that does not exist succeeds.
|
||||
fn remove(&self, path: &Path) -> io::Result<()>;
|
||||
|
||||
/// Create a fresh temporary directory inside the environment.
|
||||
fn create_temp_dir(&self) -> io::Result<String>;
|
||||
|
||||
/// Release mounts, devices or guest state and apply the teardown policy.
|
||||
///
|
||||
/// Idempotent. `outcome` is `None` when the owner did not report one.
|
||||
fn cleanup(&self, outcome: Option<BuildOutcome>) -> io::Result<()> {
|
||||
let _ = outcome;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A command description, independent of the backend that runs it.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct CommandSpec {
|
||||
/// Program to run.
|
||||
pub program: OsString,
|
||||
/// Arguments passed to the program.
|
||||
pub args: Vec<OsString>,
|
||||
/// Environment variables set for the program.
|
||||
pub env: Vec<(OsString, OsString)>,
|
||||
/// Working directory inside the environment.
|
||||
pub cwd: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// How a command's output is handled.
|
||||
#[derive(Clone)]
|
||||
pub enum Capture {
|
||||
/// Let the child use the parent's standard streams.
|
||||
Inherit,
|
||||
/// Pipe the output and forward each decoded line to a sink.
|
||||
Lines(Arc<dyn LineSink>),
|
||||
/// Capture the complete output.
|
||||
Output,
|
||||
}
|
||||
|
||||
/// The result of running a command.
|
||||
#[derive(Debug)]
|
||||
pub struct Execution {
|
||||
/// Exit status of the command.
|
||||
pub status: ExitStatus,
|
||||
/// Standard output, filled only for [`Capture::Output`].
|
||||
pub stdout: Vec<u8>,
|
||||
/// Standard error, filled only for [`Capture::Output`].
|
||||
pub stderr: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Copy policies a backend applies when importing a host tree.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct PutOptions {
|
||||
/// Backend state to reuse for a resumable tree copy.
|
||||
pub reuse: Option<PathBuf>,
|
||||
/// Directory names to skip at any depth.
|
||||
pub skip_dirs: Vec<OsString>,
|
||||
}
|
||||
|
||||
/// Whether a `put` copied from scratch or reused earlier state.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PutOutcome {
|
||||
/// The destination was copied from the host.
|
||||
Fresh,
|
||||
/// A previous copy's state was reused.
|
||||
Resumed,
|
||||
}
|
||||
|
||||
/// Final outcome reported to [`Sandbox::cleanup`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum BuildOutcome {
|
||||
/// The build completed successfully.
|
||||
Success,
|
||||
/// The build failed.
|
||||
Failure,
|
||||
}
|
||||
|
||||
/// Builder for one command run through a [`Sandbox`].
|
||||
pub struct BuildCommand<'a> {
|
||||
sandbox: &'a dyn Sandbox,
|
||||
spec: CommandSpec,
|
||||
capture: Capture,
|
||||
}
|
||||
|
||||
impl<'a> BuildCommand<'a> {
|
||||
/// Add an argument to the command.
|
||||
pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Self {
|
||||
self.spec.args.push(arg.as_ref().to_os_string());
|
||||
self
|
||||
}
|
||||
|
||||
/// Add several arguments to the command.
|
||||
pub fn args<I, S>(&mut self, args: I) -> &mut Self
|
||||
where
|
||||
I: IntoIterator<Item = S>,
|
||||
S: AsRef<OsStr>,
|
||||
{
|
||||
for arg in args {
|
||||
self.arg(arg);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Set an environment variable for the command.
|
||||
pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Self
|
||||
where
|
||||
K: AsRef<OsStr>,
|
||||
V: AsRef<OsStr>,
|
||||
{
|
||||
self.spec
|
||||
.env
|
||||
.push((key.as_ref().to_os_string(), val.as_ref().to_os_string()));
|
||||
self
|
||||
}
|
||||
|
||||
/// Set several environment variables for the command.
|
||||
pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Self
|
||||
where
|
||||
I: IntoIterator<Item = (K, V)>,
|
||||
K: AsRef<OsStr>,
|
||||
V: AsRef<OsStr>,
|
||||
{
|
||||
for (key, val) in vars {
|
||||
self.env(key, val);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the command's working directory inside the environment.
|
||||
pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Self {
|
||||
self.spec.cwd = Some(dir.as_ref().to_path_buf());
|
||||
self
|
||||
}
|
||||
|
||||
/// Forward the command's output line by line to `sink`.
|
||||
pub fn capture(&mut self, sink: Arc<dyn LineSink>) -> &mut Self {
|
||||
self.capture = Capture::Lines(sink);
|
||||
self
|
||||
}
|
||||
|
||||
/// Run the command and return its exit status.
|
||||
pub fn status(&mut self) -> io::Result<ExitStatus> {
|
||||
let capture = self.capture.clone();
|
||||
self.sandbox
|
||||
.run(&self.spec, capture)
|
||||
.map(|execution| execution.status)
|
||||
.map_err(|e| contextualize_spawn_error(&self.spec.program.to_string_lossy(), e))
|
||||
}
|
||||
|
||||
/// Run the command and capture its complete output.
|
||||
pub fn output(&mut self) -> io::Result<Output> {
|
||||
self.sandbox
|
||||
.run(&self.spec, Capture::Output)
|
||||
.map(|execution| Output {
|
||||
status: execution.status,
|
||||
stdout: execution.stdout,
|
||||
stderr: execution.stderr,
|
||||
})
|
||||
.map_err(|e| contextualize_spawn_error(&self.spec.program.to_string_lossy(), e))
|
||||
}
|
||||
}
|
||||
|
||||
/// Convenience methods available on every [`Sandbox`].
|
||||
pub trait SandboxExt: Sandbox {
|
||||
/// Start building a command to run in this sandbox.
|
||||
fn command(&self, program: &str) -> BuildCommand<'_>;
|
||||
|
||||
/// Copy a host source tree into the sandbox, applying the build policy.
|
||||
fn stage_tree(&self, host: &Path, dest: &Path, opts: &StageOptions) -> io::Result<PutOutcome>;
|
||||
}
|
||||
|
||||
fn command_for<'a>(sandbox: &'a dyn Sandbox, program: &str) -> BuildCommand<'a> {
|
||||
BuildCommand {
|
||||
sandbox,
|
||||
spec: CommandSpec {
|
||||
program: OsString::from(program),
|
||||
..CommandSpec::default()
|
||||
},
|
||||
capture: Capture::Inherit,
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Sandbox> SandboxExt for T {
|
||||
fn command(&self, program: &str) -> BuildCommand<'_> {
|
||||
command_for(self, program)
|
||||
}
|
||||
|
||||
fn stage_tree(&self, host: &Path, dest: &Path, opts: &StageOptions) -> io::Result<PutOutcome> {
|
||||
staging::stage_tree(self, host, dest, opts)
|
||||
}
|
||||
}
|
||||
|
||||
impl SandboxExt for dyn Sandbox + '_ {
|
||||
fn command(&self, program: &str) -> BuildCommand<'_> {
|
||||
command_for(self, program)
|
||||
}
|
||||
|
||||
fn stage_tree(&self, host: &Path, dest: &Path, opts: &StageOptions) -> io::Result<PutOutcome> {
|
||||
staging::stage_tree(self, host, dest, opts)
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrap an I/O error from launching a command with a more helpful message.
|
||||
pub(crate) fn contextualize_spawn_error(program: &str, e: io::Error) -> io::Error {
|
||||
if e.kind() == io::ErrorKind::NotFound {
|
||||
io::Error::new(
|
||||
e.kind(),
|
||||
format!(
|
||||
"Could not run '{program}': {e}. \
|
||||
The program does not seem to be installed or is not on PATH; \
|
||||
install the corresponding package and retry.",
|
||||
),
|
||||
)
|
||||
} else {
|
||||
io::Error::new(e.kind(), format!("Could not run '{program}': {e}"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a uniquely named directory under `base`.
|
||||
pub(crate) fn unique_dir(base: &Path, prefix: &str) -> io::Result<PathBuf> {
|
||||
let base_timestamp = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_millis();
|
||||
|
||||
let mut attempt = 0;
|
||||
loop {
|
||||
let name = if attempt == 0 {
|
||||
format!("{prefix}{base_timestamp}")
|
||||
} else {
|
||||
format!("{prefix}{base_timestamp}-{attempt}")
|
||||
};
|
||||
let path = base.join(name);
|
||||
match std::fs::create_dir(&path) {
|
||||
Ok(()) => return Ok(path),
|
||||
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => attempt += 1,
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::exec::{LineSink, Stream};
|
||||
use std::sync::Mutex;
|
||||
|
||||
struct CollectingSink(Mutex<Vec<(Stream, String)>>);
|
||||
|
||||
impl CollectingSink {
|
||||
fn new() -> Self {
|
||||
CollectingSink(Mutex::new(Vec::new()))
|
||||
}
|
||||
}
|
||||
|
||||
impl LineSink for CollectingSink {
|
||||
fn line(&self, stream: Stream, line: &str) {
|
||||
self.0.lock().unwrap().push((stream, line.to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
fn conformance(sandbox: &dyn Sandbox) {
|
||||
let root = PathBuf::from(sandbox.create_temp_dir().unwrap());
|
||||
assert!(sandbox.is_dir(&root).unwrap());
|
||||
|
||||
let file = root.join("hello.txt");
|
||||
sandbox.write_file(&file, "hello").unwrap();
|
||||
assert!(sandbox.exists(&file).unwrap());
|
||||
assert_eq!(sandbox.read_file(&file).unwrap(), "hello");
|
||||
assert_eq!(sandbox.list_files(&root).unwrap().len(), 1);
|
||||
|
||||
let host = tempfile::tempdir().unwrap();
|
||||
let src = host.path().join("src.txt");
|
||||
std::fs::write(&src, "host").unwrap();
|
||||
let dest = root.join("imported.txt");
|
||||
let outcome = sandbox.put(&src, &dest, &PutOptions::default()).unwrap();
|
||||
assert_eq!(outcome, PutOutcome::Fresh);
|
||||
assert_eq!(sandbox.read_file(&dest).unwrap(), "host");
|
||||
|
||||
let out = host.path().join("out.txt");
|
||||
sandbox.get(&dest, &out).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&out).unwrap(), "host");
|
||||
|
||||
let tree = host.path().join("tree");
|
||||
std::fs::create_dir_all(tree.join(".git")).unwrap();
|
||||
std::fs::write(tree.join("keep.txt"), "keep").unwrap();
|
||||
std::fs::write(tree.join(".git/HEAD"), "ref").unwrap();
|
||||
let staged = root.join("tree");
|
||||
let opts = PutOptions {
|
||||
reuse: None,
|
||||
skip_dirs: vec![".git".into()],
|
||||
};
|
||||
sandbox.put(&tree, &staged, &opts).unwrap();
|
||||
assert!(sandbox.exists(&staged.join("keep.txt")).unwrap());
|
||||
assert!(!sandbox.exists(&staged.join(".git")).unwrap());
|
||||
|
||||
let staged_by_helper = root.join("tree-helper");
|
||||
let stage_opts = StageOptions {
|
||||
reuse: None,
|
||||
prune_vcs: true,
|
||||
};
|
||||
sandbox
|
||||
.stage_tree(&tree, &staged_by_helper, &stage_opts)
|
||||
.unwrap();
|
||||
assert!(sandbox.exists(&staged_by_helper.join("keep.txt")).unwrap());
|
||||
assert!(!sandbox.exists(&staged_by_helper.join(".git")).unwrap());
|
||||
|
||||
let output = sandbox
|
||||
.command("sh")
|
||||
.args(["-c", "echo out; echo err >&2"])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success());
|
||||
assert_eq!(output.stdout, b"out\n");
|
||||
assert_eq!(output.stderr, b"err\n");
|
||||
|
||||
let sink = Arc::new(CollectingSink::new());
|
||||
let status = sandbox
|
||||
.command("sh")
|
||||
.args(["-c", "echo line"])
|
||||
.capture(sink.clone())
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success());
|
||||
assert_eq!(
|
||||
sink.0.lock().unwrap().as_slice(),
|
||||
&[(Stream::Stdout, "line".to_string())]
|
||||
);
|
||||
|
||||
sandbox.remove(&root).unwrap();
|
||||
assert!(!sandbox.exists(&root).unwrap());
|
||||
sandbox.cleanup(None).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_conforms() {
|
||||
conformance(&Host::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_works_through_arc() {
|
||||
let sandbox: Arc<dyn Sandbox> = Arc::new(Host::new());
|
||||
assert!(sandbox.command("true").status().unwrap().success());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
//! Source-tree staging: VCS pruning and resumable copies.
|
||||
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::{PutOptions, PutOutcome, Sandbox};
|
||||
|
||||
/// Policy for [`stage_tree`].
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct StageOptions {
|
||||
/// Backend state to reuse for a resumable tree copy.
|
||||
pub reuse: Option<PathBuf>,
|
||||
/// Remove VCS metadata from the staged tree.
|
||||
pub prune_vcs: bool,
|
||||
}
|
||||
|
||||
/// Version-control metadata directories that must never leak into a build
|
||||
/// tree.
|
||||
///
|
||||
/// Their presence flips autotools' "building from VCS" detection (e.g. GNU
|
||||
/// hello's `BUILD_FROM_GIT`, triggered by a `.git` directory next to
|
||||
/// `configure.ac`), which activates maintainer-only regeneration rules
|
||||
/// requiring tools that are deliberately not declared as build-dependencies
|
||||
/// (e.g. `help2man`). Source packages produced by dpkg-source never contain
|
||||
/// them, so package builds must not see them either.
|
||||
pub(crate) const VCS_DIR_NAMES: &[&str] = &[".git", ".hg", ".svn", ".bzr", "CVS"];
|
||||
|
||||
/// Copy a host source tree into `sandbox`, applying the staging policy.
|
||||
pub fn stage_tree(
|
||||
sandbox: &dyn Sandbox,
|
||||
host: &Path,
|
||||
dest: &Path,
|
||||
opts: &StageOptions,
|
||||
) -> io::Result<PutOutcome> {
|
||||
let put = PutOptions {
|
||||
reuse: opts.reuse.clone(),
|
||||
skip_dirs: if opts.prune_vcs {
|
||||
vcs_dir_names()
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
};
|
||||
let outcome = sandbox.put(host, dest, &put)?;
|
||||
if opts.prune_vcs {
|
||||
// An overlay mount exposes the lower tree, so skipping during the
|
||||
// copy is not enough.
|
||||
prune_vcs_dirs(sandbox, dest)?;
|
||||
}
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
/// Check whether a directory name is version-control metadata.
|
||||
pub(crate) fn is_vcs_dir_name(name: &OsStr) -> bool {
|
||||
name.to_str()
|
||||
.is_some_and(|name| VCS_DIR_NAMES.contains(&name))
|
||||
}
|
||||
|
||||
fn vcs_dir_names() -> Vec<OsString> {
|
||||
VCS_DIR_NAMES.iter().map(OsString::from).collect()
|
||||
}
|
||||
|
||||
/// Recursively remove version-control metadata directories below `root`.
|
||||
pub(crate) fn prune_vcs_dirs(sandbox: &dyn Sandbox, root: &Path) -> io::Result<()> {
|
||||
let mut pending = vec![root.to_path_buf()];
|
||||
while let Some(dir) = pending.pop() {
|
||||
for entry in sandbox.list_files(&dir)? {
|
||||
let Some(name) = entry.file_name() else {
|
||||
continue;
|
||||
};
|
||||
if !sandbox.is_dir(&entry)? {
|
||||
continue;
|
||||
}
|
||||
if is_vcs_dir_name(name) {
|
||||
sandbox.remove(&entry)?;
|
||||
} else {
|
||||
pending.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Reference in new issue
Block a user