testcontainers-build 0.1.0

Build Testcontainers images from folders, remote contexts, and pluggable Git providers
Documentation
use crate::{BuildOptions, ImageBuildBackend, Result, process::run};
use async_trait::async_trait;

/// Run image operations with the Docker CLI.
/// Use the active Docker context and environment.
pub struct DockerCliBackend {
    /// Set the Docker executable.
    /// The default is docker.
    pub executable: String,
}

impl Default for DockerCliBackend {
    fn default() -> Self {
        Self {
            executable: "docker".into(),
        }
    }
}

#[async_trait]
impl ImageBuildBackend for DockerCliBackend {
    /// Build and load an image with the supplied reference.
    /// Keep the context available until this operation completes.
    async fn build(
        &self,
        context: &std::ffi::OsStr,
        reference: &str,
        options: &BuildOptions,
    ) -> Result<()> {
        options.validate()?;
        let path = std::path::Path::new(context);
        let dockerfile = if path.is_dir() {
            path.join(&options.dockerfile).into_os_string()
        } else {
            options.dockerfile.clone().into()
        };
        let mut args = vec![
            "build".into(),
            "--load".into(),
            "--tag".into(),
            reference.into(),
            "--file".into(),
            dockerfile,
        ];
        for (key, value) in &options.build_arguments {
            args.extend(["--build-arg".into(), format!("{key}={value}").into()]);
        }
        if let Some(target) = &options.target {
            args.extend(["--target".into(), target.into()]);
        }
        if let Some(platform) = &options.platform {
            args.extend(["--platform".into(), platform.into()]);
        }
        if options.no_cache {
            args.push("--no-cache".into());
        }
        args.extend(["--".into(), context.into()]);
        run(&self.executable, &args, None).await?;
        Ok(())
    }

    /// Remove the supplied image reference.
    /// Do not remove containers that use the image.
    async fn remove(&self, reference: &str) -> Result<()> {
        run(
            &self.executable,
            &["image".into(), "rm".into(), reference.into()],
            None,
        )
        .await?;
        Ok(())
    }
}