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
///
/// # Represent a test environment
///
pub mod continuous {
    use std::fs;
    use std::fs::File;
    use std::io::Write;
    use std::ops::Add;
    use std::path::Path;
    use std::process::Command;
    use std::thread::sleep;
    use std::time::{Duration, Instant};

    ///
    ///
    /// # Run command in a virtual machine
    ///
    /// - `directory`   The path to store the configuration
    /// - [**os**](https://app.vagrantup.com/boxes/search)          The box os
    /// - `memory`      The memory for the virtual machine
    /// - `cpus`        The cpus for the virtual machine
    /// - `command`     The test commands
    ///
    #[macro_export]
    macro_rules! install {
        ($directory:expr,$os:expr,$memory:expr,$cpus:expr,$command:expr) => {
            continuous::testing::Again::on($directory, $os, $memory, $cpus, $command)
        };
    }

    ///
    ///
    /// # Generate and run the configuration
    ///
    pub struct Again {}

    impl Again {
        ///
        ///
        /// - `directory`   The path to store the configuration
        /// - [**os**](https://app.vagrantup.com/boxes/search)          The box os
        /// - `memory`      The memory for the virtual machine
        /// - `cpus`        The cpus for the virtual machine
        /// - `command`     The test commands
        ///
        ///
        pub fn on(
            directory: &String,
            os: &String,
            memory: &String,
            cpus: &String,
            command: &String,
        ) -> Result<String, String> {
            if String::from(directory).is_empty() {
                return Err(String::from("Missing directory name"));
            }

            if String::from(os).is_empty() {
                return Err(String::from("Missing os url"));
            }

            if String::from(memory).is_empty() {
                return Err(String::from("Missing memory size"));
            }

            if String::from(cpus).is_empty() {
                return Err(String::from("Missing cpus size"));
            }

            if String::from(command).is_empty() {
                return Err(String::from("Missing commands"));
            }

            println!("\nDirectory : {}\nOperating system : {}\nMemory used : {}\nCpus used : {}\nCommand to run : {}\n", directory, os, memory, cpus, command);

            println!("Waiting...Press CTRL-C to cancel");

            sleep(Duration::from_secs(5));

            Command::new("clear").spawn().expect("linux");

            println!("[  OK  ] Starting configuration creation");

            if Path::new(directory.as_str()).is_dir() {
                fs::remove_dir_all(directory.as_str()).expect("failed to remove the directory");
                fs::create_dir(directory.as_str()).expect("Failed to create the directory");
            } else {
                fs::create_dir(directory.as_str()).expect("Failed to create the directory");
            }

            println!("[  OK  ] Directory has been created successfully");

            let binding = String::from(directory.as_str()).add("/").add("Vagrantfile");

            let mut f = File::create(binding.as_str()).expect("");

            f.write_all(format!("Vagrant.configure(\"2\") do |config|\n\tconfig.vm.box = \"{}\"\n\tconfig.vm.disk :disk, size: \"100GB\", primary: true\n\n\tconfig.vm.provider \"virtualbox\" do |vb|\n\t\tvb.gui = false\n\t\tvb.memory = \"{}\"\n\t\tvb.cpus =  {}\n\tend\n\n\tconfig.vm.provision \"shell\", path: \"bootstrap.sh\"\nend", os, memory, cpus).as_bytes()).expect("failed to create vagrant fie content");

            println!("[  OK  ] Vagrantfile has been created successfully");

            let bootstrap = String::from(directory.as_str())
                .add("/")
                .add("bootstrap.sh");

            let boot = bootstrap.as_str();

            File::create(boot).expect("");

            let mut b = File::options().append(true).open(boot).expect("");

            writeln!(&mut b, "#!/bin/bash").expect("");

            writeln!(&mut b, "{}", command).expect("");

            println!("[  OK  ] bootstrap.sh has been created successfully");

            Command::new("chmod")
                .arg("+x")
                .arg(boot)
                .spawn()
                .expect("")
                .wait()
                .expect("");

            println!("[  OK  ] bootstrap.sh is now executable");

            println!("[  OK  ] Configuration ready to use");

            println!("[  OK  ] Running the virtual machine");

            Command::new("vagrant")
                .arg("up")
                .arg("--no-color")
                .current_dir(directory.as_str())
                .spawn()
                .expect("")
                .wait()
                .expect("");

            println!("[  OK  ] Removing temporary files");

            Command::new("vagrant")
                .arg("destroy")
                .arg("-f")
                .current_dir(directory.as_str())
                .spawn()
                .expect("")
                .wait()
                .expect("");

            fs::remove_dir_all(directory.as_str()).expect("a");

            println!("[  OK  ] Temporary files removed successfully");

            Ok(String::from("success"))
        }
    }

    ///
    /// # A Vm builder
    ///
    pub struct Encore {
        started: Instant,
        directory: String,
        os: String,
        memory: String,
        cpus: String,
        command: String,
    }

    impl Default for Encore {
        fn default() -> Self {
            Self::new()
        }
    }

    impl Encore {
        ///
        /// # Constructor
        ///
        pub fn new() -> Encore {
            Self {
                started: Instant::now(),
                directory: "".to_string(),
                os: "".to_string(),
                memory: "".to_string(),
                cpus: "".to_string(),
                command: "".to_string(),
            }
        }

        ///
        /// # Set the dirname to store Vagrantfile and bootstrap.sh files
        ///
        /// - `dir` The dirname
        ///
        ///
        pub fn set_directory(&mut self, dir: &str) -> &mut Encore {
            self.directory = dir.to_string();
            self
        }

        ///
        /// # Get the defined user's directory
        ///
        pub fn get_directory(self) -> String {
            self.directory
        }

        ///
        /// # Set the os to install inside the vm
        ///
        /// - `os` The os box to use
        ///
        ///
        pub fn set_os(&mut self, os: &str) -> &mut Encore {
            self.os = os.to_string();
            self
        }

        ///
        /// # Get the defined user's os
        ///
        pub fn get_os(self) -> String {
            self.os
        }

        ///
        /// # Set the memory to use from the host
        ///
        /// - `memory` The host memory to use
        ///
        ///
        pub fn set_memory(&mut self, memory: &str) -> &mut Encore {
            self.memory = memory.to_string();
            self
        }

        ///
        /// # Get the defined user's memory size
        ///
        pub fn get_memory(self) -> String {
            self.memory
        }

        ///
        /// # Set the all cpus used by the host to run the test
        ///
        /// - `cpus` The host cpus to use
        ///
        ///
        pub fn set_cpus(&mut self, cpus: &str) -> &mut Encore {
            self.cpus = cpus.to_string();
            self
        }

        ///
        /// # Get the defined user's cpus usage
        ///
        pub fn get_cpus(self) -> String {
            self.cpus
        }

        ///
        /// # Set the command to run inside the vm
        ///
        /// - `command` The command to install and test the project
        ///
        pub fn set_command(&mut self, command: &str) -> &mut Encore {
            self.command = command.to_string();
            self
        }

        ///
        /// # Get the defined user's install command
        ///
        pub fn get_commands(self) -> String {
            self.command
        }

        ///
        /// # Build and run the configuration os
        ///
        pub fn run(self) -> Result<String, String> {
            let r = Again::on(
                &self.directory,
                &self.os,
                &self.memory,
                &self.cpus,
                &self.command,
            );

            println!(
                "Execution time : {} min",
                self.started.elapsed().as_secs() / 60
            );
            r
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::continuous::Encore;

    #[test]
    pub fn ok() -> Result<(), String> {
        let mut encore = Encore::new();

        encore.set_cpus("1");
        encore.set_directory("Encore");
        encore.set_os("generic/arch");
        encore.set_memory("1024");
        encore.set_command("pacman -Syyu git base base-devel virtualbox xterm vagrant libvirt --noconfirm && git clone https://github.com/taishingi/zuu && cd zuu && cargo build");
        encore.run().expect("failed");

        Ok(())
    }
}