oxirs 0.3.1

Command-line interface for OxiRS - import, export, migration, and benchmarking tools
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
//! Advanced auto-completion support for CLI
//!
//! Provides context-aware completion for commands, arguments, and file paths.

use clap::Command;
use clap_complete::{generate, Generator, Shell};
use std::collections::HashMap;
use std::io;
use std::path::Path;

/// Generate shell completion scripts
pub fn generate_completion<G: Generator>(
    r#gen: G,
    app: &mut Command,
    name: &str,
    out: &mut dyn io::Write,
) {
    generate(r#gen, app, name, out);
}

/// Print completions for specified shell
pub fn print_completions(shell: Shell, app: &mut Command) {
    generate_completion(shell, app, "oxirs", &mut io::stdout());
}

/// Completion context for tracking state
pub struct CompletionContext {
    /// Current command being typed
    pub command: Option<String>,
    /// Current subcommand
    pub subcommand: Option<String>,
    /// Arguments provided so far
    pub args: Vec<String>,
    /// Current word being completed
    pub current_word: String,
    /// Position in the command line
    pub position: usize,
}

impl CompletionContext {
    /// Parse a command line into completion context
    pub fn from_line(line: &str, position: usize) -> Self {
        let prefix = &line[..position];
        let words: Vec<String> = shlex::split(prefix).unwrap_or_default();

        let (command, subcommand, args) = if words.len() > 1 {
            let cmd = words[0].clone();
            if words.len() > 2 {
                (Some(cmd), Some(words[1].clone()), words[2..].to_vec())
            } else {
                (Some(cmd), None, words[1..].to_vec())
            }
        } else {
            (words.first().cloned(), None, vec![])
        };

        let current_word = if line[..position].ends_with(' ') {
            String::new()
        } else {
            words.last().cloned().unwrap_or_default()
        };

        Self {
            command,
            subcommand,
            args,
            current_word,
            position,
        }
    }
}

/// Completion provider trait
pub trait CompletionProvider {
    /// Get completions for the current context
    fn get_completions(&self, context: &CompletionContext) -> Vec<CompletionItem>;
}

/// A single completion item
#[derive(Debug, Clone)]
pub struct CompletionItem {
    /// The text to insert
    pub replacement: String,
    /// Display text (may include description)
    pub display: String,
    /// Optional description
    pub description: Option<String>,
    /// Completion type (for styling)
    pub completion_type: CompletionType,
}

/// Type of completion for styling
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CompletionType {
    Command,
    Subcommand,
    Argument,
    Option,
    File,
    Directory,
    Value,
    Variable,
}

/// Command completion provider
pub struct CommandCompletionProvider {
    commands: HashMap<String, CommandInfo>,
}

/// Information about a command for completion
#[allow(dead_code)]
struct CommandInfo {
    description: String,
    subcommands: Vec<String>,
    options: Vec<OptionInfo>,
    positional_args: Vec<ArgInfo>,
}

/// Information about an option
#[allow(dead_code)]
struct OptionInfo {
    short: Option<char>,
    long: String,
    description: String,
    takes_value: bool,
    possible_values: Vec<String>,
}

/// Information about a positional argument
#[allow(dead_code)]
struct ArgInfo {
    name: String,
    description: String,
    completion_hint: CompletionHint,
}

/// Hints for argument completion
#[derive(Clone)]
#[allow(dead_code)]
enum CompletionHint {
    File { extensions: Vec<String> },
    Directory,
    Dataset,
    Format { values: Vec<String> },
    Url,
    Custom { values: Vec<String> },
}

impl CommandCompletionProvider {
    /// Create a new command completion provider
    pub fn new() -> Self {
        let mut provider = Self {
            commands: HashMap::new(),
        };
        provider.initialize_commands();
        provider
    }

    /// Initialize command information
    fn initialize_commands(&mut self) {
        // Query command
        self.commands.insert(
            "query".to_string(),
            CommandInfo {
                description: "Execute SPARQL query".to_string(),
                subcommands: vec![],
                options: vec![
                    OptionInfo {
                        short: Some('f'),
                        long: "file".to_string(),
                        description: "Read query from file".to_string(),
                        takes_value: false,
                        possible_values: vec![],
                    },
                    OptionInfo {
                        short: Some('o'),
                        long: "output".to_string(),
                        description: "Output format".to_string(),
                        takes_value: true,
                        possible_values: vec![
                            "json".to_string(),
                            "csv".to_string(),
                            "tsv".to_string(),
                            "table".to_string(),
                        ],
                    },
                ],
                positional_args: vec![
                    ArgInfo {
                        name: "dataset".to_string(),
                        description: "Target dataset".to_string(),
                        completion_hint: CompletionHint::Dataset,
                    },
                    ArgInfo {
                        name: "query".to_string(),
                        description: "SPARQL query".to_string(),
                        completion_hint: CompletionHint::Custom {
                            values: vec!["SELECT * WHERE { ?s ?p ?o } LIMIT 10".to_string()],
                        },
                    },
                ],
            },
        );

        // Import command
        self.commands.insert(
            "import".to_string(),
            CommandInfo {
                description: "Import RDF data".to_string(),
                subcommands: vec![],
                options: vec![
                    OptionInfo {
                        short: Some('f'),
                        long: "format".to_string(),
                        description: "Input format".to_string(),
                        takes_value: true,
                        possible_values: vec![
                            "turtle".to_string(),
                            "ntriples".to_string(),
                            "rdfxml".to_string(),
                            "jsonld".to_string(),
                        ],
                    },
                    OptionInfo {
                        short: Some('g'),
                        long: "graph".to_string(),
                        description: "Named graph URI".to_string(),
                        takes_value: true,
                        possible_values: vec![],
                    },
                ],
                positional_args: vec![
                    ArgInfo {
                        name: "dataset".to_string(),
                        description: "Target dataset".to_string(),
                        completion_hint: CompletionHint::Dataset,
                    },
                    ArgInfo {
                        name: "file".to_string(),
                        description: "Input file".to_string(),
                        completion_hint: CompletionHint::File {
                            extensions: vec![
                                "ttl".to_string(),
                                "nt".to_string(),
                                "rdf".to_string(),
                                "xml".to_string(),
                                "jsonld".to_string(),
                            ],
                        },
                    },
                ],
            },
        );

        // Riot command
        self.commands.insert(
            "riot".to_string(),
            CommandInfo {
                description: "RDF I/O tool".to_string(),
                subcommands: vec![],
                options: vec![
                    OptionInfo {
                        short: None,
                        long: "output".to_string(),
                        description: "Output format".to_string(),
                        takes_value: true,
                        possible_values: vec![
                            "turtle".to_string(),
                            "ntriples".to_string(),
                            "rdfxml".to_string(),
                            "jsonld".to_string(),
                            "trig".to_string(),
                            "nquads".to_string(),
                        ],
                    },
                    OptionInfo {
                        short: None,
                        long: "out".to_string(),
                        description: "Output file".to_string(),
                        takes_value: true,
                        possible_values: vec![],
                    },
                    OptionInfo {
                        short: None,
                        long: "validate".to_string(),
                        description: "Validate only".to_string(),
                        takes_value: false,
                        possible_values: vec![],
                    },
                ],
                positional_args: vec![ArgInfo {
                    name: "files".to_string(),
                    description: "Input files".to_string(),
                    completion_hint: CompletionHint::File {
                        extensions: vec![
                            "ttl".to_string(),
                            "nt".to_string(),
                            "rdf".to_string(),
                            "xml".to_string(),
                            "jsonld".to_string(),
                        ],
                    },
                }],
            },
        );
    }
}

impl CompletionProvider for CommandCompletionProvider {
    fn get_completions(&self, context: &CompletionContext) -> Vec<CompletionItem> {
        let mut completions = Vec::new();

        // If no command yet, complete commands
        if context.command.is_none()
            || (context.args.is_empty() && !context.current_word.is_empty())
        {
            for (cmd, info) in &self.commands {
                if cmd.starts_with(&context.current_word) {
                    completions.push(CompletionItem {
                        replacement: cmd.clone(),
                        display: format!("{:<20} {}", cmd, info.description),
                        description: Some(info.description.clone()),
                        completion_type: CompletionType::Command,
                    });
                }
            }
            return completions;
        }

        // Complete based on command context
        if let Some(ref cmd) = context.command {
            if let Some(cmd_info) = self.commands.get(cmd) {
                // Complete options
                if context.current_word.starts_with('-') {
                    for opt in &cmd_info.options {
                        if let Some(short) = opt.short {
                            let short_opt = format!("-{short}");
                            if short_opt.starts_with(&context.current_word) {
                                completions.push(CompletionItem {
                                    replacement: short_opt.clone(),
                                    display: format!("{:<20} {}", short_opt, opt.description),
                                    description: Some(opt.description.clone()),
                                    completion_type: CompletionType::Option,
                                });
                            }
                        }

                        let long_opt = format!("--{}", opt.long);
                        if long_opt.starts_with(&context.current_word) {
                            completions.push(CompletionItem {
                                replacement: long_opt.clone(),
                                display: format!("{:<20} {}", long_opt, opt.description),
                                description: Some(opt.description.clone()),
                                completion_type: CompletionType::Option,
                            });
                        }
                    }
                } else {
                    // Complete positional arguments
                    let arg_index = context
                        .args
                        .iter()
                        .filter(|arg| !arg.starts_with('-'))
                        .count();

                    if let Some(arg_info) = cmd_info.positional_args.get(arg_index) {
                        completions.extend(self.complete_argument(arg_info, &context.current_word));
                    }
                }
            }
        }

        completions
    }
}

impl CommandCompletionProvider {
    /// Complete a specific argument
    fn complete_argument(&self, arg_info: &ArgInfo, current: &str) -> Vec<CompletionItem> {
        match &arg_info.completion_hint {
            CompletionHint::File { extensions } => complete_files(current, Some(extensions)),
            CompletionHint::Directory => complete_directories(current),
            CompletionHint::Dataset => complete_datasets(current),
            CompletionHint::Format { values } => values
                .iter()
                .filter(|v| v.starts_with(current))
                .map(|v| CompletionItem {
                    replacement: v.clone(),
                    display: v.clone(),
                    description: None,
                    completion_type: CompletionType::Value,
                })
                .collect(),
            CompletionHint::Url => {
                if current.is_empty() {
                    vec![CompletionItem {
                        replacement: "http://".to_string(),
                        display: "http://".to_string(),
                        description: Some("HTTP URL".to_string()),
                        completion_type: CompletionType::Value,
                    }]
                } else {
                    vec![]
                }
            }
            CompletionHint::Custom { values } => values
                .iter()
                .filter(|v| current.is_empty() || v.contains(current))
                .map(|v| CompletionItem {
                    replacement: v.clone(),
                    display: v.clone(),
                    description: None,
                    completion_type: CompletionType::Value,
                })
                .collect(),
        }
    }
}

/// Complete file paths
fn complete_files(prefix: &str, extensions: Option<&Vec<String>>) -> Vec<CompletionItem> {
    let (dir, file_prefix) = if prefix.contains('/') {
        let path = Path::new(prefix);
        let parent = path.parent().unwrap_or(Path::new("."));
        let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
        (parent, file_name)
    } else {
        (Path::new("."), prefix)
    };

    let mut completions = Vec::new();

    if let Ok(entries) = std::fs::read_dir(dir) {
        for entry in entries.filter_map(Result::ok) {
            let path = entry.path();
            let name = entry.file_name();
            let name_str = name.to_string_lossy();

            if !name_str.starts_with(file_prefix) {
                continue;
            }

            if path.is_dir() {
                let display = format!("{name_str}/");
                completions.push(CompletionItem {
                    replacement: display.clone(),
                    display,
                    description: Some("Directory".to_string()),
                    completion_type: CompletionType::Directory,
                });
            } else if let Some(exts) = extensions {
                if let Some(ext) = path.extension() {
                    if exts.iter().any(|e| e == &ext.to_string_lossy().to_string()) {
                        completions.push(CompletionItem {
                            replacement: name_str.to_string(),
                            display: name_str.to_string(),
                            description: Some(format!("{} file", ext.to_string_lossy())),
                            completion_type: CompletionType::File,
                        });
                    }
                }
            } else {
                completions.push(CompletionItem {
                    replacement: name_str.to_string(),
                    display: name_str.to_string(),
                    description: Some("File".to_string()),
                    completion_type: CompletionType::File,
                });
            }
        }
    }

    completions
}

/// Complete directory paths
fn complete_directories(prefix: &str) -> Vec<CompletionItem> {
    let (dir, dir_prefix) = if prefix.contains('/') {
        let path = Path::new(prefix);
        let parent = path.parent().unwrap_or(Path::new("."));
        let dir_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
        (parent, dir_name)
    } else {
        (Path::new("."), prefix)
    };

    let mut completions = Vec::new();

    if let Ok(entries) = std::fs::read_dir(dir) {
        for entry in entries.filter_map(Result::ok) {
            if entry.path().is_dir() {
                let name = entry.file_name();
                let name_str = name.to_string_lossy();

                if name_str.starts_with(dir_prefix) {
                    let display = format!("{name_str}/");
                    completions.push(CompletionItem {
                        replacement: display.clone(),
                        display,
                        description: Some("Directory".to_string()),
                        completion_type: CompletionType::Directory,
                    });
                }
            }
        }
    }

    completions
}

/// Complete dataset names
fn complete_datasets(prefix: &str) -> Vec<CompletionItem> {
    // Try to load configuration and get actual dataset names
    let datasets = if let Ok(mut config_manager) = crate::config::ConfigManager::new() {
        if config_manager.load_profile("default").is_ok() {
            if let Ok(config) = config_manager.get_config() {
                // Get dataset names from configuration
                config.datasets.keys().cloned().collect::<Vec<_>>()
            } else {
                // Fallback to default examples if config fails to load
                vec![
                    "mykg".to_string(),
                    "test-db".to_string(),
                    "production".to_string(),
                ]
            }
        } else {
            // Fallback to default examples if config fails to load
            vec![
                "mykg".to_string(),
                "test-db".to_string(),
                "production".to_string(),
            ]
        }
    } else {
        // Fallback to default examples if config manager fails to create
        vec![
            "mykg".to_string(),
            "test-db".to_string(),
            "production".to_string(),
        ]
    };

    datasets
        .into_iter()
        .filter(|d| d.starts_with(prefix))
        .map(|d| CompletionItem {
            replacement: d.clone(),
            display: d.clone(),
            description: Some("Dataset".to_string()),
            completion_type: CompletionType::Value,
        })
        .collect()
}

/// Shell-specific completion generator
pub mod shell {
    use super::*;
    use clap::CommandFactory;
    use clap_complete::{generate, Shell};
    use std::io;

    /// Generate completion script for a specific shell
    pub fn generate_completion_script(shell: Shell, app: &mut Command) {
        generate(shell, app, "oxirs", &mut io::stdout());
    }

    /// Install completion for the current shell
    pub fn install_completion(shell: Shell) -> Result<(), Box<dyn std::error::Error>> {
        match shell {
            Shell::Bash => install_bash_completion(),
            Shell::Zsh => install_zsh_completion(),
            Shell::Fish => install_fish_completion(),
            _ => Err("Unsupported shell".into()),
        }
    }

    fn install_bash_completion() -> Result<(), Box<dyn std::error::Error>> {
        let completion_dir = dirs::home_dir()
            .ok_or("Could not find home directory")?
            .join(".local/share/bash-completion/completions");

        std::fs::create_dir_all(&completion_dir)?;

        let completion_file = completion_dir.join("oxirs");
        let mut app = crate::Cli::command();
        let mut file = std::fs::File::create(completion_file)?;
        generate(Shell::Bash, &mut app, "oxirs", &mut file);

        println!("Bash completion installed. Restart your shell or run:");
        println!("  source ~/.local/share/bash-completion/completions/oxirs");

        Ok(())
    }

    fn install_zsh_completion() -> Result<(), Box<dyn std::error::Error>> {
        let completion_dir = dirs::home_dir()
            .ok_or("Could not find home directory")?
            .join(".zsh/completions");

        std::fs::create_dir_all(&completion_dir)?;

        let completion_file = completion_dir.join("_oxirs");
        let mut app = crate::Cli::command();
        let mut file = std::fs::File::create(completion_file)?;
        generate(Shell::Zsh, &mut app, "oxirs", &mut file);

        println!("Zsh completion installed. Add this to your ~/.zshrc:");
        println!("  fpath=(~/.zsh/completions $fpath)");
        println!("  autoload -U compinit && compinit");

        Ok(())
    }

    fn install_fish_completion() -> Result<(), Box<dyn std::error::Error>> {
        let completion_dir = dirs::config_dir()
            .ok_or("Could not find config directory")?
            .join("fish/completions");

        std::fs::create_dir_all(&completion_dir)?;

        let completion_file = completion_dir.join("oxirs.fish");
        let mut app = crate::Cli::command();
        let mut file = std::fs::File::create(completion_file)?;
        generate(Shell::Fish, &mut app, "oxirs", &mut file);

        println!("Fish completion installed. It should work immediately.");

        Ok(())
    }
}

impl Default for CommandCompletionProvider {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_completion_context_parsing() {
        let ctx = CompletionContext::from_line("oxirs query mydb SEL", 20);
        assert_eq!(ctx.command, Some("oxirs".to_string()));
        assert_eq!(ctx.subcommand, Some("query".to_string()));
        assert_eq!(ctx.current_word, "SEL");
    }

    #[test]
    fn test_command_completion() {
        let provider = CommandCompletionProvider::new();
        let ctx = CompletionContext {
            command: None,
            subcommand: None,
            args: vec![],
            current_word: "que".to_string(),
            position: 3,
        };

        let completions = provider.get_completions(&ctx);
        assert!(completions.iter().any(|c| c.replacement == "query"));
    }
}