rush_sync_server/commands/
handler.rs1use super::registry::CommandRegistry;
6use crate::i18n;
7
8#[derive(Debug)]
9pub struct CommandResult {
10 pub message: String,
11 pub success: bool,
12 pub should_exit: bool,
13}
14
15pub struct CommandHandler {
17 registry: CommandRegistry,
18}
19
20impl CommandHandler {
21 pub fn new() -> Self {
23 Self {
24 registry: crate::create_default_registry(),
25 }
26 }
27
28 pub fn with_registry(registry: CommandRegistry) -> Self {
30 Self { registry }
31 }
32
33 pub fn handle_input(&self, input: &str) -> CommandResult {
35 let input = input.trim();
36 let parts: Vec<&str> = input.split_whitespace().collect();
37
38 if input.is_empty() {
39 return CommandResult {
40 message: String::new(),
41 success: false,
42 should_exit: false,
43 };
44 }
45
46 match self.registry.execute_sync(parts[0], &parts[1..]) {
48 Some(Ok(msg)) => {
49 let should_exit = self.should_exit_on_message(&msg);
50 CommandResult {
51 message: msg,
52 success: true,
53 should_exit,
54 }
55 }
56 Some(Err(e)) => CommandResult {
57 message: e.to_string(),
58 success: false,
59 should_exit: false,
60 },
61 None => CommandResult {
62 message: i18n::get_command_translation("system.commands.unknown", &[input]),
63 success: false,
64 should_exit: false,
65 },
66 }
67 }
68
69 pub async fn handle_input_async(&self, input: &str) -> CommandResult {
71 let input = input.trim();
72 let parts: Vec<&str> = input.split_whitespace().collect();
73
74 if input.is_empty() {
75 return CommandResult {
76 message: String::new(),
77 success: false,
78 should_exit: false,
79 };
80 }
81
82 match self.registry.execute_async(parts[0], &parts[1..]).await {
84 Some(Ok(msg)) => {
85 let should_exit = self.should_exit_on_message(&msg);
86 CommandResult {
87 message: msg,
88 success: true,
89 should_exit,
90 }
91 }
92 Some(Err(e)) => CommandResult {
93 message: e.to_string(),
94 success: false,
95 should_exit: false,
96 },
97 None => CommandResult {
98 message: i18n::get_command_translation("system.commands.unknown", &[input]),
99 success: false,
100 should_exit: false,
101 },
102 }
103 }
104
105 pub fn add_command<T: crate::commands::command::Command>(&mut self, command: T) {
107 self.registry.register(command);
108 }
109
110 pub fn list_commands(&self) -> Vec<(&str, &str)> {
112 self.registry.list_commands()
113 }
114
115 pub fn debug_info(&self) -> String {
117 self.registry.debug_info()
118 }
119
120 fn should_exit_on_message(&self, message: &str) -> bool {
122 message.starts_with("__EXIT__")
123 || message.starts_with("__CONFIRM_EXIT__")
124 || message.starts_with("__RESTART__")
125 || message.starts_with("__CONFIRM_RESTART__")
126 }
127}
128
129impl Default for CommandHandler {
130 fn default() -> Self {
131 Self::new()
132 }
133}