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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
use crate::bom;
use crate::newtypes::libcnb_newtype;
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize, Debug, Default)]
#[serde(deny_unknown_fields)]
pub struct Launch {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub bom: bom::Bom,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub labels: Vec<Label>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub processes: Vec<Process>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub slices: Vec<Slice>,
}

/// Data Structure for the launch.toml file.
///
/// # Examples
/// ```
/// use libcnb_data::launch;
/// use libcnb_data::process_type;
///
/// let mut launch_toml = launch::Launch::new();
/// let web = launch::ProcessBuilder::new(process_type!("web"), "bundle")
///     .args(vec!["exec", "ruby", "app.rb"])
///     .build();
///
/// launch_toml.processes.push(web);
/// assert!(toml::to_string(&launch_toml).is_ok());
/// ```
impl Launch {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a process to the launch configuration.
    #[must_use]
    pub fn process<P: Into<Process>>(mut self, process: P) -> Self {
        self.processes.push(process.into());
        self
    }

    /// Adds multiple processes to the launch configuration.
    #[must_use]
    pub fn processes<I: IntoIterator<Item = P>, P: Into<Process>>(mut self, processes: I) -> Self {
        for process in processes {
            self.processes.push(process.into());
        }

        self
    }
}

#[derive(Deserialize, Serialize, Debug)]
#[serde(deny_unknown_fields)]
pub struct Label {
    pub key: String,
    pub value: String,
}

#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct Process {
    pub r#type: ProcessType,
    pub command: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub args: Vec<String>,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub direct: bool,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub default: bool,
}

pub struct ProcessBuilder {
    process: Process,
}

/// A non-consuming builder for [`Process`] values.
///
/// # Examples
/// ```
/// # use libcnb_data::process_type;
/// # use libcnb_data::launch::ProcessBuilder;
/// ProcessBuilder::new(process_type!("web"), "java")
///     .arg("-jar")
///     .arg("target/application-1.0.0.jar")
///     .default(true)
///     .build();
/// ```
impl ProcessBuilder {
    /// Constructs a new `ProcessBuilder` with the following defaults:
    ///
    /// * No arguments to the process
    /// * `direct` is `false`
    /// * `default` is `false`
    pub fn new(r#type: ProcessType, command: impl Into<String>) -> Self {
        Self {
            process: Process {
                r#type,
                command: command.into(),
                args: Vec::new(),
                direct: false,
                default: false,
            },
        }
    }

    /// Adds an argument to the process.
    ///
    /// Only one argument can be passed per use. So instead of:
    /// ```no_run
    /// # use libcnb_data::process_type;
    /// # libcnb_data::launch::ProcessBuilder::new(process_type!("web"), "command")
    /// .arg("-C /path/to/repo")
    /// # ;
    /// ```
    ///
    /// usage would be:
    ///
    /// ```no_run
    /// # use libcnb_data::process_type;
    /// # libcnb_data::launch::ProcessBuilder::new(process_type!("web"), "command")
    /// .arg("-C")
    /// .arg("/path/to/repo")
    /// # ;
    /// ```
    ///
    /// To pass multiple arguments see [`args`](Self::args).
    pub fn arg(&mut self, arg: impl Into<String>) -> &mut Self {
        self.process.args.push(arg.into());
        self
    }

    /// Adds multiple arguments to pass to the process.
    ///
    /// To pass a single argument see [`arg`](Self::arg).
    pub fn args(&mut self, args: impl IntoIterator<Item = impl Into<String>>) -> &mut Self {
        for arg in args {
            self.arg(arg);
        }

        self
    }

    /// Sets the `direct` flag on the process.
    ///
    /// If this is true, the lifecycle will launch the command directly, rather than via a shell.
    pub fn direct(&mut self, value: bool) -> &mut Self {
        self.process.direct = value;
        self
    }

    /// Sets the `default` flag on the process.
    ///
    /// Indicates that the process type should be selected as the buildpack-provided
    /// default during the export phase.
    pub fn default(&mut self, value: bool) -> &mut Self {
        self.process.default = value;
        self
    }

    /// Builds the `Process` based on the configuration of this builder.
    #[must_use]
    pub fn build(&self) -> Process {
        self.process.clone()
    }
}

#[derive(Deserialize, Serialize, Debug)]
#[serde(deny_unknown_fields)]
pub struct Slice {
    pub paths: Vec<String>,
}

libcnb_newtype!(
    launch,
    /// Construct a [`ProcessType`] value at compile time.
    ///
    /// Passing a string that is not a valid `ProcessType` value will yield a compilation error.
    ///
    /// # Examples:
    /// ```
    /// use libcnb_data::launch::ProcessType;
    /// use libcnb_data::process_type;
    ///
    /// let process_type: ProcessType = process_type!("web");
    /// ```
    process_type,
    /// The type of a process.
    ///
    /// It MUST only contain numbers, letters, and the characters `.`, `_`, and `-`.
    ///
    /// Use the [`process_type`](crate::process_type) macro to construct a `ProcessType` from a
    /// literal string. To parse a dynamic string into a `ProcessType`, use
    /// [`str::parse`](str::parse).
    ///
    /// # Examples
    /// ```
    /// use libcnb_data::launch::ProcessType;
    /// use libcnb_data::process_type;
    ///
    /// let from_literal = process_type!("web");
    ///
    /// let input = "web";
    /// let from_dynamic: ProcessType = input.parse().unwrap();
    /// assert_eq!(from_dynamic, from_literal);
    ///
    /// let input = "!nv4lid";
    /// let invalid: Result<ProcessType, _> = input.parse();
    /// assert!(invalid.is_err());
    /// ```
    ProcessType,
    ProcessTypeError,
    r"^[[:alnum:]._-]+$"
);

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn launch_add_processes() {
        let mut launch = Launch::new();

        assert_eq!(launch.processes, vec![]);

        launch = launch.process(ProcessBuilder::new(process_type!("web"), "web_command").build());

        assert_eq!(
            launch.processes,
            vec![ProcessBuilder::new(process_type!("web"), "web_command").build()]
        );

        launch = launch.processes(vec![
            ProcessBuilder::new(process_type!("another"), "another_command").build(),
            ProcessBuilder::new(process_type!("worker"), "worker_command").build(),
        ]);

        assert_eq!(
            launch.processes,
            vec![
                ProcessBuilder::new(process_type!("web"), "web_command").build(),
                ProcessBuilder::new(process_type!("another"), "another_command").build(),
                ProcessBuilder::new(process_type!("worker"), "worker_command").build(),
            ]
        );
    }

    #[test]
    fn process_type_validation_valid() {
        assert!("web".parse::<ProcessType>().is_ok());
        assert!("Abc123._-".parse::<ProcessType>().is_ok());
    }

    #[test]
    fn process_type_validation_invalid() {
        assert_eq!(
            "worker/foo".parse::<ProcessType>(),
            Err(ProcessTypeError::InvalidValue(String::from("worker/foo")))
        );
        assert_eq!(
            "worker:foo".parse::<ProcessType>(),
            Err(ProcessTypeError::InvalidValue(String::from("worker:foo")))
        );
        assert_eq!(
            "worker foo".parse::<ProcessType>(),
            Err(ProcessTypeError::InvalidValue(String::from("worker foo")))
        );
        assert_eq!(
            "".parse::<ProcessType>(),
            Err(ProcessTypeError::InvalidValue(String::new()))
        );
    }

    #[test]
    fn process_with_default_values_deserialization() {
        let toml_str = r#"
type = "web"
command = "foo"
"#;

        assert_eq!(
            toml::from_str::<Process>(toml_str),
            Ok(Process {
                r#type: process_type!("web"),
                command: String::from("foo"),
                args: vec![],
                direct: false,
                default: false
            })
        );
    }

    #[test]
    fn process_with_default_values_serialization() {
        let process = ProcessBuilder::new(process_type!("web"), "foo").build();

        let string = toml::to_string(&process).unwrap();
        assert_eq!(
            string,
            r#"type = "web"
command = "foo"
"#
        );
    }

    #[test]
    fn process_with_some_default_values_serialization() {
        let process = ProcessBuilder::new(process_type!("web"), "foo")
            .default(true)
            .build();

        let string = toml::to_string(&process).unwrap();
        assert_eq!(
            string,
            r#"type = "web"
command = "foo"
default = true
"#
        );
    }

    #[test]
    fn process_builder() {
        let mut process_builder = ProcessBuilder::new(process_type!("web"), "java");

        assert_eq!(
            process_builder.build(),
            Process {
                r#type: process_type!("web"),
                command: String::from("java"),
                args: vec![],
                direct: false,
                default: false
            }
        );

        process_builder.default(true);

        assert_eq!(
            process_builder.build(),
            Process {
                r#type: process_type!("web"),
                command: String::from("java"),
                args: vec![],
                direct: false,
                default: true
            }
        );

        process_builder.direct(true);

        assert_eq!(
            process_builder.build(),
            Process {
                r#type: process_type!("web"),
                command: String::from("java"),
                args: vec![],
                direct: true,
                default: true
            }
        );
    }

    #[test]
    fn process_builder_args() {
        assert_eq!(
            ProcessBuilder::new(process_type!("web"), "java")
                .arg("foo")
                .args(vec!["baz", "eggs"])
                .arg("bar")
                .build(),
            Process {
                r#type: process_type!("web"),
                command: String::from("java"),
                args: vec![
                    String::from("foo"),
                    String::from("baz"),
                    String::from("eggs"),
                    String::from("bar"),
                ],
                direct: false,
                default: false
            }
        );
    }
}