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
use crate::context::Context;
use crate::repl::{Error, Subcommand};
use factorio_bot_core::miette::{IntoDiagnostic, Result};
use factorio_bot_core::paris::{error, info};
use factorio_bot_core::process::process_control::{
FactorioInstance, FactorioParams, FactorioStartCondition,
};
use reedline_repl_rs::clap::{
builder::PossibleValuesParser, Arg, ArgMatches, Command, PossibleValue,
};
use reedline_repl_rs::crossterm::event::{KeyCode, KeyModifiers};
use reedline_repl_rs::reedline::ReedlineEvent;
use reedline_repl_rs::Repl;
use std::str::FromStr;
use strum::{EnumIter, EnumMessage, EnumString, IntoEnumIterator, IntoStaticStr};
async fn run(matches: ArgMatches, context: &mut Context) -> Result<Option<String>, Error> {
let action =
Action::from_str(matches.value_of("action").expect("Has default value")).into_diagnostic()?;
match action {
Action::Start => {
let app_settings = context.app_settings.read().await;
let client_count: u8 = match matches.value_of("clients").expect("Has default value") {
"" => app_settings.factorio.client_count,
clients => clients.parse().into_diagnostic()?,
};
let write_logs: bool = matches.is_present("logs");
let verbose: bool = matches.is_present("verbose");
let seed = config_fallback(matches.value_of("seed"), &app_settings.factorio.seed);
let map_exchange_string = config_fallback(
matches.value_of("map"),
&app_settings.factorio.map_exchange_string,
);
let wait_until_finished = matches.is_present("wait_until_finished");
let recreate = matches.is_present("new");
drop(app_settings);
subcommand_start(
context,
client_count,
write_logs,
verbose,
seed,
map_exchange_string,
wait_until_finished,
recreate,
)
.await?
}
Action::Status => subcommand_status(context).await?,
Action::ToggleVerbose => subcommand_toggle_verbose(context).await?,
Action::Add => subcommand_add(context).await?,
Action::Stop => subcommand_stop(context).await?,
};
Ok(None)
}
#[allow(clippy::fn_params_excessive_bools, clippy::too_many_arguments)]
async fn subcommand_start(
context: &mut Context,
client_count: u8,
write_logs: bool,
verbose: bool,
seed: Option<String>,
map_exchange_string: Option<String>,
wait_until_finished: bool,
recreate: bool,
) -> Result<Option<String>, Error> {
{
let instance_state = context.instance_state.read().await;
if instance_state.is_some() {
error!("failed: already started");
return Ok(None);
}
}
print_hint();
let app_settings = context.app_settings.read().await;
let params = FactorioParams {
client_count,
recreate,
write_logs,
seed,
map_exchange_string,
silent: !verbose,
wait_until: if wait_until_finished {
FactorioStartCondition::DiscoveryComplete
} else {
FactorioStartCondition::Initialized
},
..FactorioParams::default()
};
match FactorioInstance::start(&app_settings.factorio, params).await {
Ok(new_instance_state) => {
let mut instance_state = context.instance_state.write().await;
*instance_state = Some(new_instance_state);
drop(instance_state);
}
Err(err) => {
error!("failed to start factorio: {:?}", err);
}
}
if verbose {
print_hint();
}
Ok(None)
}
async fn subcommand_stop(context: &mut Context) -> Result<Option<String>, Error> {
let mut instance_state = context.instance_state.write().await;
if instance_state.is_none() {
error!("failed: not started");
return Ok(None);
}
instance_state.take().expect("Already checked").stop()?;
info!("successfully stopped");
Ok(None)
}
async fn subcommand_status(context: &mut Context) -> Result<Option<String>, Error> {
let instance_state = context.instance_state.read().await;
if let Some(instance_state) = instance_state.as_ref() {
info!(
"started {} with {} clients @ Port {} with RCON {}",
if *instance_state.silent.read() {
"silently"
} else {
"verbosely"
},
instance_state.client_count,
instance_state.server_port.unwrap_or(0),
instance_state.rcon_port
);
} else {
info!("factorio not started");
return Ok(None);
}
Ok(None)
}
async fn subcommand_add(context: &mut Context) -> Result<Option<String>, Error> {
let instance_state = context.instance_state.write().await;
if instance_state.is_none() {
error!("failed: not started");
return Ok(None);
}
error!("not implemented");
Ok(None)
}
async fn subcommand_toggle_verbose(context: &mut Context) -> Result<Option<String>, Error> {
let instance_state = context.instance_state.read().await;
if let Some(instance_state) = instance_state.as_ref() {
let mut silent = instance_state.silent.write();
*silent = !*silent;
if *silent {
info!("verbose mode enabled");
} else {
info!("silent mode enabled");
}
} else {
error!("failed: not started");
return Ok(None);
}
Ok(None)
}
fn config_fallback(value: Option<&str>, config: &str) -> Option<String> {
if let Some(str) = value {
Some(str.to_owned())
} else if config.is_empty() {
None
} else {
Some(config.to_owned())
}
}
fn print_hint() {
#[cfg(windows)]
{
info!("Hint: press CTRL+Z if you loose the ability to type");
}
}
#[derive(EnumString, EnumMessage, EnumIter, IntoStaticStr)]
#[strum(serialize_all = "kebab-case")]
enum Action {
#[strum(message = "starts factorio")]
Start,
#[strum(message = "stops factorio")]
Stop,
#[strum(message = "show status of factorio processes")]
Status,
#[strum(message = "toggle verbosity of factorio process")]
ToggleVerbose,
#[strum(message = "start additional clients")]
Add,
}
impl Subcommand for ThisCommand {
fn name(&self) -> &str {
"factorio"
}
fn build_command(&self, repl: Repl<Context, Error>) -> Repl<Context, Error> {
repl
.with_keybinding(
KeyModifiers::CONTROL,
KeyCode::Char('s'),
ReedlineEvent::ExecuteHostCommand("factorio status".to_owned()),
)
.with_keybinding(
KeyModifiers::CONTROL,
KeyCode::Char('k'),
ReedlineEvent::ExecuteHostCommand("factorio toggle-verbose".to_owned()),
)
.with_command_async(
Command::new(self.name())
.about("control factorio instances")
.arg(
Arg::new("action")
.default_value(Action::Start.into())
.value_parser(PossibleValuesParser::new(Action::iter().map(|action| {
let message = action.get_message().unwrap();
PossibleValue::new(action.into()).help(message)
})))
.help("what action to take"),
)
.arg(
Arg::new("clients")
.short('c')
.default_value("")
.long("clients")
.help("number of clients to start in addition to the server"),
)
.arg(
Arg::new("seed")
.long("seed")
.value_name("seed")
.required(false)
.help("use given seed to recreate level"),
)
.arg(
Arg::new("map")
.long("map")
.value_name("map")
.required(false)
.help("use given map exchange string"),
)
.arg(
Arg::new("new")
.long("new")
.short('n')
.help("recreate level by deleting server map if exists"),
)
.arg(
Arg::new("logs")
.short('l')
.long("logs")
.help("enabled writing server & client logs to workspace"),
)
.arg(
Arg::new("verbose")
.short('v')
.long("verbose")
.help("log server output to console"),
)
.arg(
Arg::new("wait_until_finished")
.short('w')
.long("wait")
.help("wait until world discovery is done"),
),
|args, context| Box::pin(run(args, context)),
)
}
}
struct ThisCommand {}
pub fn build() -> Box<dyn Subcommand> {
Box::new(ThisCommand {})
}