-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmod.rs
90 lines (78 loc) · 1.99 KB
/
mod.rs
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
use std::process::{Command, Stdio};
pub mod images {
pub const UBUNTU: &str = "dra-ubuntu";
}
pub mod users {
pub const TESTER: &str = "tester";
}
#[derive(Debug)]
pub struct Docker {
id: String,
}
impl Docker {
pub fn run(image: &str) -> Self {
let result = Command::new("docker")
.arg("run")
.arg("-d")
.arg("-i")
.arg("--rm")
.arg(image)
.arg("bash")
.output()
.expect("'docker run' failed to start");
let id = String::from_utf8(result.stdout)
.expect("cannot read 'docker run' output")
.replace('\n', "");
Self { id }
}
pub fn stop(&self) {
Command::new("docker")
.arg("stop")
.arg(&self.id)
.stdout(Stdio::piped())
.spawn()
.expect("'docker stop' failed to start");
}
pub fn exec(&self, command: &str, args: ExecArgs) -> ExecResult {
let result = Command::new("docker")
.arg("exec")
.args(&args.to_args())
.arg(&self.id)
.arg("sh")
.arg("-c")
.arg(command)
.output()
.expect("'docker exec' failed to start");
if result.status.success() {
ExecResult::Success(
String::from_utf8(result.stdout).unwrap_or_else(|_| String::from("NO_STDOUT")),
)
} else {
ExecResult::Error(
String::from_utf8(result.stderr).unwrap_or_else(|_| String::from("NO_STDERR")),
)
}
}
}
impl Drop for Docker {
fn drop(&mut self) {
self.stop()
}
}
#[derive(Debug)]
pub enum ExecResult {
Success(String),
Error(String),
}
pub enum ExecArgs {
Default,
User(String),
}
impl ExecArgs {
pub fn to_args(&self) -> Vec<&str> {
match self {
ExecArgs::Default => Vec::new(),
ExecArgs::User(user) => vec!["--user", user],
}
}
}