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