diff options
| author | mat <git@matdoes.dev> | 2025-05-30 20:07:28 -0330 |
|---|---|---|
| committer | mat <git@matdoes.dev> | 2025-05-30 16:37:40 -0700 |
| commit | a5e7ff771d657258cedcc7a8b3ce265c655f0860 (patch) | |
| tree | ea5fdbbee32c1b9917a7ece03f6a1a70ee8e63fa /azalea-brigadier/src/errors/command_syntax_error.rs | |
| parent | da73b4316de4b26322c53f14222c7751a0be55a1 (diff) | |
| download | azalea-drasl-a5e7ff771d657258cedcc7a8b3ce265c655f0860.tar.xz | |
implement missing brigadier features and cleanup some more
Diffstat (limited to 'azalea-brigadier/src/errors/command_syntax_error.rs')
| -rw-r--r-- | azalea-brigadier/src/errors/command_syntax_error.rs | 93 |
1 files changed, 93 insertions, 0 deletions
diff --git a/azalea-brigadier/src/errors/command_syntax_error.rs b/azalea-brigadier/src/errors/command_syntax_error.rs new file mode 100644 index 00000000..a476fec4 --- /dev/null +++ b/azalea-brigadier/src/errors/command_syntax_error.rs @@ -0,0 +1,93 @@ +use std::{ + cmp, + fmt::{self, Debug, Write}, +}; + +use super::builtin_errors::BuiltInError; + +#[derive(Clone, PartialEq)] +pub struct CommandSyntaxError { + kind: BuiltInError, + message: String, + input: Option<String>, + cursor: Option<usize>, +} + +const CONTEXT_AMOUNT: usize = 10; + +impl CommandSyntaxError { + pub fn new(kind: BuiltInError, message: String, input: &str, cursor: usize) -> Self { + Self { + kind, + message, + input: Some(input.to_string()), + cursor: Some(cursor), + } + } + + pub fn create(kind: BuiltInError, message: String) -> Self { + Self { + kind, + message, + input: None, + cursor: None, + } + } + + pub fn message(&self) -> String { + let mut message = self.message.clone(); + let context = self.context(); + if let Some(context) = context { + write!( + message, + " at position {}: {context}", + self.cursor.unwrap_or(usize::MAX) + ) + .unwrap(); + } + message + } + + pub fn raw_message(&self) -> &String { + &self.message + } + + pub fn context(&self) -> Option<String> { + if let Some(input) = &self.input + && let Some(cursor) = self.cursor + { + let mut builder = String::new(); + let cursor = cmp::min(input.len(), cursor); + + if cursor > CONTEXT_AMOUNT { + builder.push_str("..."); + } + + builder.push_str( + &input[(cmp::max(0, cursor as isize - CONTEXT_AMOUNT as isize) as usize)..cursor], + ); + builder.push_str("<--[HERE]"); + + return Some(builder); + } + None + } + + pub fn kind(&self) -> &BuiltInError { + &self.kind + } + + pub fn input(&self) -> &Option<String> { + &self.input + } + + pub fn cursor(&self) -> Option<usize> { + self.cursor + } +} + +impl Debug for CommandSyntaxError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.message()) + } +} |
