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
//! The server's console: lines a tool runs on the server as an
//! administrator with no character, such as each line of a dedicated
//! server's command file.
//!
//! Unstable: needs the `unstable` feature and may change in any release.
//!
//! A line is `enshwick ...` for the loader's own tools (`enshwick help`
//! lists them), or a mod's id followed by the text form of one of its
//! [actions](crate::actions), such as `you.lockers access Ann on`. Players never
//! type these: they use the game's interface.
use crate::abi::{Status, Str};
/// Why [`run`] ran nothing.
///
/// # Examples
///
/// ```
/// use enshwick::console::{RunError, run};
///
/// assert_eq!(run(" "), Err(RunError::Empty));
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum RunError {
/// The line holds no word.
#[error("the line is empty")]
Empty,
/// Neither the loader nor a running mod with actions answers the line's
/// first word.
#[error("no mod with actions has that id")]
Unknown,
/// Not on the server's game thread, or no server runs.
#[error("console lines run on the server's game thread only")]
NotOnGameThread,
/// No loader runs, as in a unit test.
#[error("no loader runs console lines here")]
NoLoader,
/// The loader refused for another reason, with its status.
#[error("refused by the loader (status {0})")]
Refused(u32),
}
/// Runs the console line `line`, such as `enshwick status` or
/// `you.my-mod world`, as the server's console, and returns its answer.
///
/// Call it on the server's game thread, from a scheduled task or a game
/// event, where action handlers expect to run.
///
/// # Errors
///
/// [`RunError`] when the line is empty, nothing answers its first word, the
/// call is not on the game thread or no loader runs.
///
/// # Examples
///
/// ```
/// use enshwick::console::{RunError, run};
///
/// // Outside the game no loader answers.
/// assert_eq!(run("enshwick status"), Err(RunError::NoLoader));
/// ```
pub fn run(line: &str) -> Result<String, RunError> {
let line = line.trim();
if line.is_empty() {
return Err(RunError::Empty);
}
let host = crate::host().ok_or(RunError::NoLoader)?;
let mut out = Str::EMPTY;
let status = (host.api().run_console)(host.handle(), Str::new(line), &raw mut out);
match status {
// SAFETY: the reply stays valid until the next call on this thread.
Status::OK => Ok(unsafe { out.as_str() }.unwrap_or("").to_owned()),
Status::MISSING => Err(RunError::Unknown),
Status::WRONG_THREAD => Err(RunError::NotOnGameThread),
other => Err(RunError::Refused(other.0)),
}
}