aboutsummaryrefslogtreecommitdiff
path: root/azalea-brigadier/src/exceptions/command_syntax_exception.rs
diff options
context:
space:
mode:
authormat <27899617+mat-1@users.noreply.github.com>2022-04-20 01:34:12 +0000
committerGitHub <noreply@github.com>2022-04-20 01:34:12 +0000
commit5fd87615cf1514c7f9a0358988964768ded3f06e (patch)
tree001c3c760fdae8fe7b72cacb1f87d3703cc4e82c /azalea-brigadier/src/exceptions/command_syntax_exception.rs
parentd09762f5d38ab1200fb08ca3b1178813b4e47081 (diff)
parentbe194c1ca136100fd8f53ed068d82c9f7ae32870 (diff)
downloadazalea-drasl-5fd87615cf1514c7f9a0358988964768ded3f06e.tar.xz
Merge pull request #1 from mat-1/brigadier
azalea-brigadier
Diffstat (limited to 'azalea-brigadier/src/exceptions/command_syntax_exception.rs')
-rw-r--r--azalea-brigadier/src/exceptions/command_syntax_exception.rs91
1 files changed, 91 insertions, 0 deletions
diff --git a/azalea-brigadier/src/exceptions/command_syntax_exception.rs b/azalea-brigadier/src/exceptions/command_syntax_exception.rs
new file mode 100644
index 00000000..4bfe9cda
--- /dev/null
+++ b/azalea-brigadier/src/exceptions/command_syntax_exception.rs
@@ -0,0 +1,91 @@
+use std::{cmp, fmt};
+
+use super::builtin_exceptions::BuiltInExceptions;
+use crate::message::Message;
+
+#[derive(Clone, PartialEq)]
+pub struct CommandSyntaxException {
+ pub type_: BuiltInExceptions,
+ message: Message,
+ input: Option<String>,
+ cursor: Option<usize>,
+}
+
+const CONTEXT_AMOUNT: usize = 10;
+
+impl CommandSyntaxException {
+ pub fn new(type_: BuiltInExceptions, message: Message, input: &str, cursor: usize) -> Self {
+ Self {
+ type_,
+ message,
+ input: Some(input.to_string()),
+ cursor: Some(cursor),
+ }
+ }
+
+ pub fn create(type_: BuiltInExceptions, message: Message) -> Self {
+ Self {
+ type_,
+ message,
+ input: None,
+ cursor: None,
+ }
+ }
+
+ pub fn message(&self) -> String {
+ let mut message = self.message.string();
+ let context = self.context();
+ if let Some(context) = context {
+ message.push_str(&format!(
+ " at position {}: {}",
+ self.cursor.unwrap_or(usize::MAX),
+ context
+ ));
+ }
+ message
+ }
+
+ pub fn raw_message(&self) -> &Message {
+ &self.message
+ }
+
+ pub fn context(&self) -> Option<String> {
+ if let Some(input) = &self.input {
+ if 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 get_type(&self) -> &BuiltInExceptions {
+ &self.type_
+ }
+
+ pub fn input(&self) -> &Option<String> {
+ &self.input
+ }
+
+ pub fn cursor(&self) -> Option<usize> {
+ self.cursor
+ }
+}
+
+impl fmt::Debug for CommandSyntaxException {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}", self.message())
+ }
+}