testcontainers-build 0.1.0

Build Testcontainers images from folders, remote contexts, and pluggable Git providers
Documentation
use crate::{
    BuildContextProvider, BuildOptions, BuiltImage, ContextLocation, DockerCliBackend, Error,
    ImageBuildBackend, ImageBuildRequest, RemoteUriSource, Result, sources::resolve_inside,
};
use std::sync::Arc;

/// Resolve sources and build unique local images.
/// Keep each context until its image build completes.
#[derive(Clone)]
pub struct ImageBuilder {
    backend: Arc<dyn ImageBuildBackend>,
}

impl Default for ImageBuilder {
    fn default() -> Self {
        Self::new(DockerCliBackend::default())
    }
}

impl ImageBuilder {
    /// Start a fluent build request for this source.
    /// Resolve the source only when build is called.
    pub fn with_source<S: BuildContextProvider>(&self, source: S) -> ImageBuildRequest<S> {
        ImageBuildRequest::new(self.clone(), source)
    }

    /// Set the image build backend.
    /// Use this constructor to replace Docker CLI execution.
    pub fn new(backend: impl ImageBuildBackend + 'static) -> Self {
        Self {
            backend: Arc::new(backend),
        }
    }

    /// Resolve the source and build its image.
    /// Apply the timeout to both operations.
    pub async fn build(
        &self,
        source: &dyn BuildContextProvider,
        options: &BuildOptions,
    ) -> Result<BuiltImage> {
        options.validate()?;
        tokio::time::timeout(options.timeout, self.build_inner(source, options))
            .await
            .map_err(|_| Error::Timeout)?
    }

    async fn build_inner(
        &self,
        source: &dyn BuildContextProvider,
        options: &BuildOptions,
    ) -> Result<BuiltImage> {
        let context = source.resolve().await?;
        let location = match &context.location {
            ContextLocation::Directory(path) => {
                let path = dunce::canonicalize(path)?;
                let dockerfile = resolve_inside(&path, &options.dockerfile)?;
                if !dockerfile.is_file() {
                    return Err(Error::InvalidInput("Dockerfile is not a file".into()));
                }
                path.into_os_string()
            }
            ContextLocation::Remote(uri) => RemoteUriSource::new(uri)?.uri.into(),
        };
        let tag = uuid::Uuid::new_v4().simple().to_string();
        let reference = format!("testcontainers-build:{tag}");
        self.backend.build(&location, &reference, options).await?;
        Ok(BuiltImage::new(reference, tag, self.backend.clone()))
    }
}