Skip to main content

testcontainers_build/
image.rs

1use crate::{ImageBuildBackend, Result};
2use std::sync::Arc;
3use testcontainers::{ContainerRequest, GenericImage};
4
5/// Hold the unique local image reference.
6/// Remove all containers before you call remove.
7#[must_use = "call remove().await after disposing containers to clean up the built image"]
8pub struct BuiltImage {
9    reference: String,
10    tag: String,
11    backend: Arc<dyn ImageBuildBackend>,
12    removed: bool,
13}
14
15impl BuiltImage {
16    pub(crate) fn new(reference: String, tag: String, backend: Arc<dyn ImageBuildBackend>) -> Self {
17        Self {
18            reference,
19            tag,
20            backend,
21            removed: false,
22        }
23    }
24
25    /// Get the unique local image reference.
26    /// Keep the image until all containers are removed.
27    pub fn reference(&self) -> &str {
28        &self.reference
29    }
30
31    /// Create a native Testcontainers image.
32    /// Use it to add wait conditions and container settings.
33    pub fn image(&self) -> GenericImage {
34        GenericImage::new("testcontainers-build", &self.tag)
35    }
36
37    /// Create a request for the local image.
38    /// Testcontainers can attempt a pull if the image is missing.
39    pub fn container_request(&self) -> ContainerRequest<GenericImage> {
40        self.image().into()
41    }
42
43    /// Remove the owned image reference.
44    /// Retry this operation if removal fails.
45    pub async fn remove(&mut self) -> Result<()> {
46        if !self.removed {
47            self.backend.remove(&self.reference).await?;
48            self.removed = true;
49        }
50        Ok(())
51    }
52}