Skip to main content

nanite_docker/instruction/
add.rs

1use alloc::format;
2use alloc::string::String;
3use alloc::vec::Vec;
4use core::fmt::{Display, Formatter, Write};
5
6/// Represents an `ADD` instruction.
7///
8/// ```rust
9/// use nanite_docker::{Add, AddOpt};
10///
11/// let add = Add {
12///     opts: vec![AddOpt::KeepGitDir],
13///     src: vec!["src".to_string()],
14///     dest: "dest".to_string(),
15/// };
16/// let add_built = format!("{add}");
17/// assert_eq!(add_built, r#"ADD --keep-git-dir=true "src" "dest""#);
18///
19/// ```
20#[derive(Clone, Debug)]
21pub struct Add {
22    pub opts: Vec<AddOpt>,
23    pub src: Vec<String>,
24    pub dest: String,
25}
26impl Display for Add {
27    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
28        let mut opt_string = String::new();
29
30        for opt in &self.opts {
31            // Add a space to the end (THIS IS NOT A BUG)
32            write!(opt_string, "{opt} ")?;
33        }
34
35        let src_string = self
36            .src
37            .iter()
38            .map(|i| format!(r#""{i}""#))
39            .collect::<Vec<String>>()
40            .join(" ");
41
42        write!(f, r#"ADD {opt_string}{src_string} "{}""#, self.dest)
43    }
44}
45
46#[derive(Clone, Debug)]
47pub enum AddOpt {
48    KeepGitDir,
49    Checksum { hash: String },
50    Chown { user: String, group: Option<String> },
51    Chmod { perms: String },
52    Link,
53    Exclude { path: String },
54}
55
56impl Display for AddOpt {
57    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
58        match self {
59            AddOpt::KeepGitDir => write!(f, "--keep-git-dir=true"),
60
61            AddOpt::Checksum { hash: e } => write!(f, "--checksum={e}"),
62
63            AddOpt::Chown { user: u, group: g } => match g {
64                Some(group) => write!(f, "--chown={u}:{group}"),
65                None => write!(f, "--chown={u}"),
66            },
67
68            AddOpt::Chmod { perms: p } => write!(f, "--chmod={p}"),
69
70            AddOpt::Link => write!(f, "--link"),
71
72            AddOpt::Exclude { path: p } => write!(f, r#"--exclude="{p}""#),
73        }
74    }
75}