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
219use crate::files::*;
use crate::gen::*;
use anyhow::Result;
use comfy_table::modifiers::UTF8_ROUND_CORNERS;
use comfy_table::presets::UTF8_BORDERS_ONLY;
use comfy_table::Table;
use crossbeam_queue::ArrayQueue;
use dashmap::DashMap;
use glob::glob;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};
use structopt::StructOpt;
#[macro_use]
extern crate anyhow;
#[macro_use]
extern crate lazy_static;
mod files;
mod gen;
mod util;
#[derive(StructOpt, Debug)]
#[structopt(name = "Dwarf Fortress Crash Miner")]
struct Opt {
/// Number of world gens to run simultaneously
#[structopt(short, long, default_value = "4")]
concurrency: usize,
#[structopt(subcommand)]
cmd: Command,
}
#[derive(StructOpt, Debug)]
enum Command {
/// Discover new crashes
Crash {
/// World gen params file
#[structopt(short, long, parse(from_os_str))]
params: PathBuf,
},
/// Reproduce crashes with param files from the crashes directory
Repro {
/// Number of times to re-run each world gen
#[structopt(short, long, default_value = "4")]
num: usize,
/// Reproduce only crashes with filenames that contain this text
#[structopt(short, long)]
filter: Option<String>,
},
/// Download the latest version of Dwarf Fortress
Update,
}
#[tokio::main]
async fn main() -> Result<()> {
let opt = Opt::from_args();
ensure_dirs()?;
match opt.cmd {
Command::Update => {
let _ = get_latest(false).await?;
ensure_worker_dirs(opt.concurrency, false)?;
}
Command::Crash { params } => {
ensure_worker_dirs(opt.concurrency, false)?;
if files::base_dir().map_or(false, |base| !base.join("params").join(¶ms).is_file())
{
println!("Invalid params file.");
return Ok(());
}
let mut handles = vec![];
for n in 0..opt.concurrency {
let params = PathBuf::from("params").join(¶ms);
handles.push(tokio::spawn(async move {
loop {
let f = gen_world(format!("{}", n), ¶ms, true);
tokio::select! {
res = f => {
match res {
Ok(r) => {
println!("{}", r);
},
Err(e) => {
println!("Error generating world.");
println!("{}", e);
}
}
}
_ = tokio::signal::ctrl_c() => { println!("Worker caught ctr-c. Quitting."); break }
}
}
}));
}
futures::future::join_all(handles).await;
}
Command::Repro { num, filter } => {
ensure_worker_dirs(opt.concurrency, false)?;
let paths: Vec<_> = glob(
files::base_dir()?
.join("crashes")
.join("*.txt")
.to_str()
.unwrap(),
)?
.filter_map(Result::ok)
.filter(|p| {
if let Some(f) = &filter {
p.to_string_lossy().contains(f)
} else {
true
}
})
.collect();
if paths.is_empty() {
bail!("No crashes in the crashes directory.")
}
let queue = ArrayQueue::new(paths.len() * num);
for path in paths {
for _ in 0..num {
let _ = queue.push(path.clone()).unwrap();
}
}
let queue_arc = Arc::new(queue);
let repro_stats = Arc::new(DashMap::<PathBuf, (u32, u32, Duration)>::new());
let mut handles = vec![];
for n in 0..opt.concurrency {
let queue_ours = queue_arc.clone();
let repro_stats_ours = repro_stats.clone();
handles.push(tokio::spawn(async move {
loop {
let params = queue_ours.pop();
let param = match params {
Some(p) => p,
None => break,
};
let started = Instant::now();
let f = gen_world(format!("{}", n), ¶m, false);
tokio::select! {
res = f => {
match res {
Ok(r) => {
let finished = Instant::now();
println!("{}", r);
match r.result {
WorldGenResult::Crash => {
let mut e = repro_stats_ours.entry(param).or_insert((0, 0, Duration::new(0, 0)));
(*e).0 += 1;
(*e).2 += finished - started;
},
WorldGenResult::Success => {
let mut e = repro_stats_ours.entry(param).or_insert((0, 0, Duration::new(0, 0)));
(*e).1 += 1;
},
_ => {}
}
},
Err(e) => {
println!("Error generating world.");
println!("{}", e);
}
}
}
_ = tokio::signal::ctrl_c() => { println!("Worker caught ctr-c. Quitting."); break }
}
}
}));
}
futures::future::join_all(handles).await;
let mut table = Table::new();
table.set_header(vec!["Params", "Crash", "Success", "Avg Time"]);
table.load_preset(UTF8_BORDERS_ONLY);
table.apply_modifier(UTF8_ROUND_CORNERS);
for k in repro_stats.iter() {
let (k, v) = k.pair();
table.add_row(vec![
format!("{}", k.file_name().unwrap().to_string_lossy()),
format!("{}", v.0),
format!("{}", v.1),
if v.0 > 0 {
format!(
"{}",
humantime::format_duration(Duration::new((v.2 / v.0).as_secs(), 0))
)
} else {
"?".to_string()
},
]);
}
println!("{}", table);
}
}
Ok(())
}