op_composer/
utils.rs

1use std::io::Write;
2
3use bollard::service::PortBinding;
4use eyre::Result;
5use flate2::{write::GzEncoder, Compression};
6
7/// Given a dockerfile string and any number of files as `(filename, file contents)`,
8/// create a tarball and gzip the tarball. Returns the compressed output bytes.
9pub(crate) fn create_dockerfile_build_context(
10    dockerfile: &str,
11    files: &[(&str, &[u8])],
12) -> Result<Vec<u8>> {
13    // First create a Dockerfile tarball
14    let mut header = tar::Header::new_gnu();
15    header.set_path("Dockerfile")?;
16    header.set_size(dockerfile.len() as u64);
17    header.set_mode(0o755);
18    header.set_cksum();
19    let mut tar = tar::Builder::new(Vec::new());
20    tar.append(&header, dockerfile.as_bytes())?;
21
22    // Then append any additional files
23    for (filename, contents) in files {
24        let mut header = tar::Header::new_gnu();
25        header.set_path(filename)?;
26        header.set_size(contents.len() as u64);
27        header.set_mode(0o755);
28        header.set_cksum();
29        tar.append(&header, *contents)?;
30    }
31
32    // Finally, gzip the tarball
33    let uncompressed = tar.into_inner()?;
34    let mut c = GzEncoder::new(Vec::new(), Compression::default());
35    c.write_all(&uncompressed)?;
36    c.finish().map_err(Into::into)
37}
38
39/// Given a host port, bind it to the container.
40pub fn bind_host_port(host_port: u16) -> Option<Vec<PortBinding>> {
41    Some(vec![PortBinding {
42        host_ip: Some("127.0.0.1".to_string()),
43        host_port: Some(host_port.to_string()),
44    }])
45}