Skip to main content

testcontainers_build/
options.rs

1use crate::{Error, Result, validate_relative};
2use std::{collections::BTreeMap, time::Duration};
3
4/// Set the image build options.
5/// Use Default to set a ten-minute timeout.
6#[derive(Debug, Clone)]
7pub struct BuildOptions {
8    /// Set the Dockerfile path.
9    /// Use a path relative to the build context.
10    pub dockerfile: String,
11    /// Set Docker build arguments.
12    /// Do not use these values for secrets.
13    pub build_arguments: BTreeMap<String, String>,
14    /// Set the build stage.
15    /// Use None for the last stage.
16    pub target: Option<String>,
17    /// Set the target platform.
18    /// Use None for the Docker default.
19    pub platform: Option<String>,
20    /// Disable the Docker layer cache.
21    /// The default is false.
22    pub no_cache: bool,
23    /// Set the maximum operation time.
24    /// Include source resolution and the image build.
25    pub timeout: Duration,
26}
27
28impl BuildOptions {
29    pub(crate) fn validate(&self) -> Result<()> {
30        validate_relative(&self.dockerfile)?;
31        if self.timeout.is_zero() || self.timeout > Duration::from_millis(u32::MAX as u64 - 1) {
32            return Err(Error::InvalidInput(
33                "use a positive timeout of at most 4294967294 milliseconds".into(),
34            ));
35        }
36        for (key, value) in &self.build_arguments {
37            if key.trim().is_empty() || key.contains(['=', '\0']) || value.contains('\0') {
38                return Err(Error::InvalidInput("invalid build argument".into()));
39            }
40        }
41        for value in [&self.target, &self.platform].into_iter().flatten() {
42            if value.trim().is_empty() || value.contains('\0') {
43                return Err(Error::InvalidInput(
44                    "invalid target stage or platform".into(),
45                ));
46            }
47        }
48        Ok(())
49    }
50}
51
52impl Default for BuildOptions {
53    fn default() -> Self {
54        Self {
55            dockerfile: "Dockerfile".into(),
56            build_arguments: BTreeMap::new(),
57            target: None,
58            platform: None,
59            no_cache: false,
60            timeout: Duration::from_secs(600),
61        }
62    }
63}