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
use std::{
process::{Child, Command},
time::Duration,
};
const SLEEP_TIME: Duration = Duration::from_secs(3);
pub struct GanacheInstance(Child);
impl Drop for GanacheInstance {
fn drop(&mut self) {
self.0.kill().expect("could not kill ganache");
}
}
#[derive(Clone, Default)]
pub struct Ganache {
port: Option<u64>,
block_time: Option<u64>,
mnemonic: Option<String>,
}
impl Ganache {
pub fn new() -> Self {
Self::default()
}
pub fn port<T: Into<u64>>(mut self, port: T) -> Self {
self.port = Some(port.into());
self
}
pub fn mnemonic<T: Into<String>>(mut self, mnemonic: T) -> Self {
self.mnemonic = Some(mnemonic.into());
self
}
pub fn block_time<T: Into<u64>>(mut self, block_time: T) -> Self {
self.block_time = Some(block_time.into());
self
}
pub fn spawn(self) -> GanacheInstance {
let mut cmd = Command::new("ganache-cli");
cmd.stdout(std::process::Stdio::null());
if let Some(port) = self.port {
cmd.arg("-p").arg(port.to_string());
}
if let Some(mnemonic) = self.mnemonic {
cmd.arg("-m").arg(mnemonic);
}
if let Some(block_time) = self.block_time {
cmd.arg("-b").arg(block_time.to_string());
}
let ganache_pid = cmd.spawn().expect("couldnt start ganache-cli");
std::thread::sleep(SLEEP_TIME);
GanacheInstance(ganache_pid)
}
}