sledoview 1.1.0

A CLI tool for viewing and managing SLED database files
Documentation
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
use crate::commands::Command;
use crate::db::SledViewer;
use anyhow::Result;
use colored::*;
use rustyline::error::ReadlineError;
use rustyline::history::MemHistory;
use rustyline::{Context, Editor};
use rustyline_derive::{Helper, Highlighter, Hinter, Validator};

#[derive(Helper, Highlighter, Hinter, Validator)]
struct SledCompleter {
    keys: Vec<String>,
    trees: Vec<String>,
}

impl SledCompleter {
    fn new() -> Self {
        Self {
            keys: Vec::new(),
            trees: Vec::new(),
        }
    }

    fn update_keys(&mut self, keys: Vec<String>) {
        self.keys = keys;
    }

    fn update_trees(&mut self, trees: Vec<String>) {
        self.trees = trees;
    }
}

impl rustyline::completion::Completer for SledCompleter {
    type Candidate = rustyline::completion::Pair;

    fn complete(
        &self,
        line: &str,
        pos: usize,
        _ctx: &Context<'_>,
    ) -> rustyline::Result<(usize, Vec<Self::Candidate>)> {
        let line_up_to_cursor = &line[..pos];

        // Parse the command to see if we can complete keys
        let parts: Vec<&str> = line_up_to_cursor.split_whitespace().collect();

        if parts.len() >= 2 {
            let command = parts[0].to_lowercase();
            if command == "get"
                || command == "delete"
                || command == "del"
                || (command == "set" && parts.len() == 2)
                || ((command == "list" || command == "ls")
                    && parts.len() >= 2
                    && parts[1] != "regex")
                || (command == "search" && parts.len() >= 2 && parts[1] != "regex")
            {
                // We're completing a key - find the current word being typed
                let current_word = if let Some(last_space) = line_up_to_cursor.rfind(' ') {
                    &line_up_to_cursor[last_space + 1..]
                } else {
                    ""
                };

                let mut candidates = Vec::new();
                for key in &self.keys {
                    if key.starts_with(current_word) {
                        candidates.push(rustyline::completion::Pair {
                            display: key.clone(),
                            replacement: key.clone(),
                        });
                    }
                }

                // Calculate the start position for replacement
                let start = if let Some(last_space) = line_up_to_cursor.rfind(' ') {
                    last_space + 1
                } else {
                    0
                };

                return Ok((start, candidates));
            } else if (command == "select"
                || (command == "trees" && parts.len() >= 2 && parts[1] != "regex"))
                && parts.len() >= 2
            {
                // We're completing a tree name
                let current_word = if let Some(last_space) = line_up_to_cursor.rfind(' ') {
                    &line_up_to_cursor[last_space + 1..]
                } else {
                    ""
                };

                let mut candidates = Vec::new();
                for tree in &self.trees {
                    if tree.starts_with(current_word) {
                        candidates.push(rustyline::completion::Pair {
                            display: tree.clone(),
                            replacement: tree.clone(),
                        });
                    }
                }

                // Calculate the start position for replacement
                let start = if let Some(last_space) = line_up_to_cursor.rfind(' ') {
                    last_space + 1
                } else {
                    0
                };

                return Ok((start, candidates));
            }
        }

        // Fallback to command completion
        let commands = vec![
            "count", "list", "ls", "get", "set", "delete", "del", "search", "trees", "select",
            "unselect", "help", "exit", "quit",
        ];
        let mut candidates = Vec::new();

        if let Some(word_start) = line_up_to_cursor.rfind(' ') {
            let word = &line_up_to_cursor[word_start + 1..];
            for cmd in commands {
                if cmd.starts_with(word) {
                    candidates.push(rustyline::completion::Pair {
                        display: cmd.to_string(),
                        replacement: cmd.to_string(),
                    });
                }
            }
            Ok((word_start + 1, candidates))
        } else {
            for cmd in commands {
                if cmd.starts_with(line_up_to_cursor) {
                    candidates.push(rustyline::completion::Pair {
                        display: cmd.to_string(),
                        replacement: cmd.to_string(),
                    });
                }
            }
            Ok((0, candidates))
        }
    }
}

pub struct Repl {
    editor: Editor<SledCompleter, MemHistory>,
    viewer: SledViewer,
    keys: Vec<String>,
    trees: Vec<String>,
}

impl Repl {
    #[must_use]
    pub fn new(viewer: SledViewer) -> Self {
        let mut editor = Editor::<SledCompleter, MemHistory>::with_history(
            rustyline::Config::default(),
            MemHistory::new(),
        )
        .expect("Failed to create readline editor");
        let completer = SledCompleter::new();
        editor.set_helper(Some(completer));

        Self {
            editor,
            viewer,
            keys: Vec::new(),
            trees: Vec::new(),
        }
    }

    fn load_keys(&mut self) {
        match self.viewer.list_keys("*", false) {
            Ok(keys) => {
                keys.clone_into(&mut self.keys);
                // Update the completer with new keys
                if let Some(helper) = self.editor.helper_mut() {
                    helper.update_keys(keys);
                }
            }
            Err(e) => {
                eprintln!("Warning: Failed to load keys for completion: {e}");
            }
        }
    }

    fn load_trees(&mut self) {
        match self.viewer.list_trees("*", false) {
            Ok(trees) => {
                trees.clone_into(&mut self.trees);
                // Update the completer with new trees
                if let Some(helper) = self.editor.helper_mut() {
                    helper.update_trees(trees);
                }
            }
            Err(e) => {
                eprintln!("Warning: Failed to load trees for completion: {e}");
            }
        }
    }

    fn find_completions(&self, line: &str) -> Vec<String> {
        let parts: Vec<&str> = line.split_whitespace().collect();

        if parts.len() >= 2 {
            let command = parts[0].to_lowercase();
            if command == "get"
                || command == "delete"
                || command == "del"
                || (command == "set" && parts.len() == 2)
                || ((command == "list" || command == "ls")
                    && parts.len() >= 2
                    && parts[1] != "regex")
                || (command == "search" && parts.len() >= 2 && parts[1] != "regex")
            {
                // Find the current word being typed
                let prefix = parts.last().copied().unwrap_or("");

                let mut candidates = Vec::new();
                for key in &self.keys {
                    if key.starts_with(prefix) {
                        candidates.push(key.clone());
                    }
                }

                return candidates;
            } else if (command == "select"
                || (command == "trees" && parts.len() >= 2 && parts[1] != "regex"))
                && parts.len() >= 2
            {
                // Find the current tree being typed
                let prefix = parts.last().copied().unwrap_or("");

                let mut candidates = Vec::new();
                for tree in &self.trees {
                    if tree.starts_with(prefix) {
                        candidates.push(tree.clone());
                    }
                }

                return candidates;
            }
        }

        Vec::new()
    }

    fn try_auto_complete(&self, line: &str) -> Option<String> {
        let completions = self.find_completions(line);

        // If there's exactly one completion, auto-complete it
        if completions.len() == 1 {
            let parts: Vec<&str> = line.split_whitespace().collect();
            if let Some(prefix) = parts.last() {
                if let Some(pos) = line.rfind(prefix) {
                    return Some(format!("{}{}", &line[..pos], &completions[0]));
                }
            }
        }

        None
    }

    fn should_show_completion_hint(&self, line: &str) -> bool {
        if line.trim().is_empty() {
            return false;
        }

        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() >= 2 {
            let command = parts[0].to_lowercase();
            if command == "get"
                || command == "delete"
                || command == "del"
                || command == "list"
                || command == "ls"
                || command == "search"
                || (command == "set" && parts.len() == 2)
            {
                let prefix = parts.last().copied().unwrap_or("");
                // Show hint if we have a partial key that could be completed
                return !prefix.is_empty()
                    && self
                        .keys
                        .iter()
                        .any(|k| k.starts_with(prefix) && k != prefix);
            }
        }

        false
    }

    #[allow(clippy::unnecessary_wraps)] // avoid breaking public API
    pub fn run(&mut self) -> Result<()> {
        println!();
        println!(
            "{}",
            "Interactive SLED Database Client".bright_cyan().bold()
        );
        println!(
            "{}",
            "Type 'help' for available commands or 'exit' to quit.".bright_black()
        );
        println!(
            "{}",
            "Use TAB for completion, type partial keys and TAB to auto-complete!".bright_black()
        );
        println!();

        // Load keys and trees for completion
        self.load_keys();
        self.load_trees();

        loop {
            // Create prompt that shows selected tree
            let prompt = match self.viewer.get_selected_tree() {
                Some(tree) => format!("[{tree}]> "),
                None => "> ".to_string(),
            };

            let readline = self.editor.readline(&prompt);

            match readline {
                Ok(line) => {
                    let line = line.trim();
                    if line.is_empty() {
                        continue;
                    }

                    // Check for tab completion command
                    if line == "tab" || line == "\\t" {
                        println!("{}", "Tab completion: Type your partial command (e.g., 'get user_') and I'll complete it.".bright_blue());
                        continue;
                    }

                    // Check for completion command (keep this for manual completion)
                    if let Some(completion_line) = line.strip_prefix("complete ") {
                        // Remove "complete "
                        self.show_completions(completion_line);
                        continue;
                    }

                    // Check for auto-completion opportunity
                    if self.should_show_completion_hint(line) {
                        if let Some(completed) = self.try_auto_complete(line) {
                            println!(
                                "{} {}",
                                "Auto-completed:".bright_green(),
                                completed.bright_white()
                            );
                            // Automatically execute the completed command
                            match Command::parse(&completed) {
                                Some(Command::Exit) => {
                                    println!("{}", "Goodbye!".bright_green());
                                    break;
                                }
                                Some(command) => {
                                    if let Err(e) = command.execute(&mut self.viewer) {
                                        println!(
                                            "{} {}",
                                            "Error:".bright_red().bold(),
                                            e.to_string().red()
                                        );
                                    } else if !command.is_usage_error() {
                                        let _ = self.editor.add_history_entry(&completed);
                                    }
                                    // Reload keys and trees after any command in case database changed
                                    self.load_keys();
                                    self.load_trees();
                                }
                                None => {
                                    println!(
                                        "{} Unknown command: '{}'. Type 'help' for available commands.",
                                        "Error:".bright_red().bold(),
                                        completed.bright_yellow()
                                    );
                                }
                            }
                            continue;
                        }

                        // Couldn't find *one single* completion to use
                        let completions = self.find_completions(line);
                        if !completions.is_empty() {
                            println!(
                                "{} {} {}. {}",
                                "Found".bright_blue(),
                                completions.len().to_string().bright_yellow().bold(),
                                "possible completions".bright_blue(),
                                format!("Type 'complete {line}' to see them.").yellow()
                            );
                            continue;
                        }
                    }

                    match Command::parse(line) {
                        Some(Command::Exit) => {
                            println!("{}", "Goodbye!".bright_green());
                            break;
                        }
                        Some(command) => {
                            if let Err(e) = command.execute(&mut self.viewer) {
                                println!(
                                    "{} {}",
                                    "Error:".bright_red().bold(),
                                    e.to_string().red()
                                );
                            } else if !command.is_usage_error() {
                                let _ = self.editor.add_history_entry(line);
                            }
                            // Reload keys and trees after any command in case database changed
                            self.load_keys();
                            self.load_trees();
                        }
                        None => {
                            println!(
                                "{} Unknown command: '{}'. Type 'help' for available commands.",
                                "Error:".bright_red().bold(),
                                line.bright_yellow()
                            );
                        }
                    }
                }
                Err(ReadlineError::Interrupted) => {
                    // Check if the line was empty (exit) or had content (cancel)
                    // For now, we'll just show a message and continue - rustyline
                    // doesn't give us access to the current line content on interrupt
                    println!("^C");
                    println!("{}", "Use 'exit' or Ctrl-D to quit.".bright_black());
                }
                Err(ReadlineError::Eof) => {
                    println!("{}", "Goodbye!".bright_green());
                    break;
                }
                Err(err) => {
                    println!("{} {}", "Error:".bright_red().bold(), err);
                    break;
                }
            }
        }
        Ok(())
    }

    fn show_completions(&self, line: &str) {
        let completions = self.find_completions(line);
        if completions.is_empty() {
            println!("{}", "No completions available for this context.".yellow());
            return;
        }

        println!(
            "{} {} {}:",
            "Found".bright_blue(),
            completions.len().to_string().bright_yellow().bold(),
            "possible completions".bright_blue()
        );

        for (i, completion) in completions.iter().enumerate() {
            println!(
                "  {}: {}",
                (i + 1).to_string().bright_black(),
                completion.bright_white()
            );
        }

        if completions.len() == 1 {
            // Auto-complete if there's only one match
            let parts: Vec<&str> = line.split_whitespace().collect();
            if let Some(prefix) = parts.last() {
                if let Some(pos) = line.rfind(prefix) {
                    let completed = format!("{}{}", &line[..pos], &completions[0]);
                    println!(
                        "{} {}",
                        "Auto-completed:".bright_green(),
                        completed.bright_white()
                    );
                }
            }
        }
    }
}