1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
//! This library provides a convenient way to programmatically generate Dockerfiles using Rust.
//!
//! Dockerfiles instructions can be generated using structured and type-safe interfaces, or they can be added flexibly in raw form.
//!
//! # Usage
//!
//! ## Build Dockerfile
//!
//! [Dockerfile] contains a list of [`Instruction`](instruction::Instruction).
//!
//!```rust
//!use dockerfile_builder::Dockerfile;
//!use dockerfile_builder::instruction::{RUN, EXPOSE};
//!
//!let dockerfile = Dockerfile::default()
//!    .push(RUN::from("echo $HOME"))
//!    .push(EXPOSE::from("80/tcp"))
//!    .push_any("# Just adding a comment");
//!    
//!let expected = r#"RUN echo $HOME
//!EXPOSE 80/tcp
//!## Just adding a comment"#;
//!
//!assert_eq!(
//!    dockerfile.to_string(),
//!    expected
//!);
//!```
//!
//! ## Dockerfile Instructions
//!
//! [`Instruction`] can be created from String or from [Instruction Builder].
//! Instruction Builders provide structured and type-safe interfaces to build instructions.
//!
//! [Instruction]: instruction::Instruction
//! [Instruction Builder]: instruction_builder
//!
//! ```rust
//!use dockerfile_builder::Dockerfile;
//!use dockerfile_builder::instruction::EXPOSE;
//!use dockerfile_builder::instruction_builder::ExposeBuilder;
//!
//!let expose = EXPOSE::from("80/tcp");
//!
//!let expose_from_builder = ExposeBuilder::builder()
//!    .port(80)
//!    .protocol("tcp")
//!    .build()
//!    .unwrap();
//!
//!assert_eq!(expose, expose_from_builder);
//!
//!let dockerfile = Dockerfile::default()
//!    .push(expose_from_builder);
//!  
//!assert_eq!(
//!    dockerfile.to_string(),
//!    "EXPOSE 80/tcp"
//!);
//!
//! ```

use std::fmt::{self, Display};

use instruction::Instruction;

pub mod instruction;
pub mod instruction_builder;

/// Dockerfile builder
#[derive(Debug, Default)]
pub struct Dockerfile {
    instructions: Vec<Instruction>,
}

impl Dockerfile {
    /// Adds an [`Instruction`] to the end of the Dockerfile
    ///
    /// [Instruction]: instruction::Instruction
    pub fn push<T: Into<Instruction>>(mut self, instruction: T) -> Self {
        self.instructions.push(instruction.into());
        self
    }

    /// Adds any raw string to the end of the Dockerfile
    pub fn push_any<T: Into<String>>(mut self, instruction: T) -> Self {
        self.instructions.push(Instruction::ANY(instruction.into()));
        self
    }

    /// Appends multiple [`Instruction`]s to the end of the Dockerfile
    ///
    /// [Instruction]: instruction::Instruction
    pub fn append<T: Into<Instruction>>(mut self, instructions: Vec<T>) -> Self {
        for i in instructions {
            self.instructions.push(i.into());
        }
        self
    }

    /// Appends multiple strings to the end of the Dockerfile
    pub fn append_any<T: Into<String>>(mut self, instructions: Vec<T>) -> Self {
        for i in instructions {
            self.instructions.push(Instruction::ANY(i.into()));
        }
        self
    }

    /// Adds `syntax` data to the end of the Dockerfile
    pub fn syntax<T: Into<String>>(self, syntax: T) -> Self {
        self.push_any(format!("# syntax={}", syntax.into()))
    }

    /// Adds `escape` data to the end of the Dockerfile
    pub fn escape<T: Into<String>>(self, escape: T) -> Self {
        self.push_any(format!("# escape={}", escape.into()))
    }

    /// Adds a comment to the end of the Dockerfile
    pub fn comment<T: Into<String>>(self, comment: T) -> Self {
        self.push_any(format!("# {}", comment.into()))
    }

    /// Retrieves [`Instruction`] vec from Dockerfile
    ///
    /// [Instruction]: instruction::Instruction
    pub fn into_inner(self) -> Vec<Instruction> {
        self.instructions
    }
}

impl Display for Dockerfile {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let instructions = self
            .instructions
            .iter()
            .map(|i| i.to_string())
            .collect::<Vec<String>>();
        write!(f, "{}", instructions.join("\n"))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        instruction::{EXPOSE, FROM, RUN},
        instruction_builder::ExposeBuilder,
    };
    use expect_test::expect;

    #[test]
    fn quick_start() {
        let dockerfile = Dockerfile::default()
            .push(RUN::from("echo $HOME"))
            .push(EXPOSE::from("80/tcp"))
            .push_any("# Just adding a comment");

        let expected = expect![[r#"
            RUN echo $HOME
            EXPOSE 80/tcp
            # Just adding a comment"#]];
        expected.assert_eq(&dockerfile.to_string());
    }

    #[test]
    fn build_dockerfile() {
        // 2 ways of constructing Instruction.

        // Directly from String/&str
        let expose = EXPOSE::from("80/tcp");

        // Use a builder
        let expose_from_builder = ExposeBuilder::builder()
            .port(80)
            .protocol("tcp")
            .build()
            .unwrap();

        assert_eq!(expose, expose_from_builder);

        let dockerfile = Dockerfile::default().push(expose_from_builder);

        let expected = expect!["EXPOSE 80/tcp"];
        expected.assert_eq(&dockerfile.to_string());
    }

    #[test]
    fn append_instructions() {
        let comments = vec!["# syntax=docker/dockerfile:1", "# escape=`"];
        let instruction_vec = vec![
            Instruction::FROM(FROM::from("cargo-chef AS chef")),
            Instruction::RUN(RUN::from("cargo run")),
        ];

        let dockerfile = Dockerfile::default()
            .append_any(comments)
            .append(instruction_vec);

        let expected = expect![[r#"
            # syntax=docker/dockerfile:1
            # escape=`
            FROM cargo-chef AS chef
            RUN cargo run"#]];
        expected.assert_eq(&dockerfile.to_string());
    }
}