kelora 1.5.0

A command-line log analysis tool with embedded Rhai scripting
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
//! CLI argument processing module
//!
//! This module handles parsing, validating, and processing command-line arguments,
//! including config file handling, aliases, and help text display.

use anyhow::Result;
use clap::{ArgMatches, CommandFactory, FromArgMatches};

use crate::cli::{Cli, OutputFormat, ShellCompletion};
use crate::config::MultilineJoin;
use crate::config_file::{ConfigExpansionInfo, ConfigFile};
use crate::help;
use crate::platform::{ExitCode, SafeStderr};
use crate::tty;

/// Validate CLI arguments for early error detection
pub fn validate_cli_args(cli: &Cli) -> Result<()> {
    // Validate --no-input conflicts
    if cli.no_input && !cli.files.is_empty() {
        return Err(anyhow::anyhow!(
            "--no-input cannot be used with input files. Remove --no-input to read files, or remove file arguments to run script-only stages."
        ));
    }

    // Check stdin usage
    let mut stdin_count = 0;
    for file_path in &cli.files {
        if file_path == "-" {
            stdin_count += 1;
            if stdin_count > 1 {
                return Err(anyhow::anyhow!("stdin (\"-\") can only be specified once"));
            }
        }
        // Note: File existence is checked at runtime during processing (exit 1),
        // not during CLI validation (exit 2)
    }

    // Check if exec files exist (if specified)
    for exec_file in &cli.exec_files {
        if !std::path::Path::new(exec_file).exists() {
            return Err(anyhow::anyhow!("Exec file not found: {}", exec_file));
        }
    }

    // Validate batch size
    if let Some(batch_size) = cli.batch_size {
        if batch_size == 0 {
            return Err(anyhow::anyhow!("Batch size must be greater than 0"));
        }
    }

    // Validate thread count
    if cli.threads > 1000 {
        return Err(anyhow::anyhow!("Thread count too high (max 1000)"));
    }

    if cli.span_close.is_some() && cli.span.is_none() && cli.span_idle.is_none() {
        return Err(anyhow::anyhow!(
            "--span-close requires --span or --span-idle. Use --span N for fixed-size spans or --span-idle 30s for inactivity-based spans."
        ));
    }

    if cli.multiline.is_none() && cli.multiline_join != MultilineJoin::Space {
        return Err(anyhow::anyhow!(
            "--multiline-join requires --multiline. Start with --multiline indent, --multiline blank, or see --help-multiline for regex/timestamp strategies."
        ));
    }

    // Check for --core with CSV/TSV formats (not allowed with these formats)
    if cli.core {
        match cli.output_format {
            OutputFormat::Csv => {
                return Err(anyhow::anyhow!(
                    "csv output format does not support --core. Use --keys to define column order, e.g. --keys ts,level,msg."
                ));
            }
            OutputFormat::Tsv => {
                return Err(anyhow::anyhow!(
                    "tsv output format does not support --core. Use --keys to define column order, e.g. --keys ts,level,msg."
                ));
            }
            OutputFormat::Csvnh => {
                return Err(anyhow::anyhow!(
                    "csvnh output format does not support --core. Use --keys to define column order, e.g. --keys ts,level,msg."
                ));
            }
            OutputFormat::Tsvnh => {
                return Err(anyhow::anyhow!(
                    "tsvnh output format does not support --core. Use --keys to define column order, e.g. --keys ts,level,msg."
                ));
            }
            _ => {
                // Other formats are fine with --core
            }
        }
    }

    // Check --discover and --drain conflicts with parallel mode
    let implies_parallel = cli.parallel || cli.threads > 0 || cli.batch_size.is_some();

    if (cli.discover_fields.is_some() || cli.discover_final_fields.is_some()) && implies_parallel {
        return Err(anyhow::anyhow!(
            "--discover and --discover-final are not supported with --parallel or thread overrides. Rerun without --parallel to use field discovery."
        ));
    }

    if cli.drain.is_some() && implies_parallel {
        return Err(anyhow::anyhow!(
            "--drain summary is not supported with --parallel or thread overrides. Rerun without --parallel to use Drain template mining."
        ));
    }

    if cli.drain.is_some() {
        // Calculate effective keys after applying exclusions
        let effective_keys: Vec<String> = cli
            .keys
            .iter()
            .filter(|key| !cli.exclude_keys.contains(key))
            .cloned()
            .collect();

        if effective_keys.len() != 1 {
            return Err(anyhow::anyhow!(
                "--drain requires exactly one effective field in --keys after exclusions, e.g. --keys msg. Use -s to inspect available fields."
            ));
        }
    }

    Ok(())
}

/// Extract --config-file argument from raw args
pub fn extract_config_file_arg(args: &[String]) -> Option<String> {
    for i in 0..args.len() {
        if args[i] == "--config-file" && i + 1 < args.len() {
            return Some(args[i + 1].clone());
        }
    }
    None
}

/// Extract --save-alias argument from raw args
pub fn extract_save_alias_arg(args: &[String]) -> Option<String> {
    for i in 0..args.len() {
        if args[i] == "--save-alias" && i + 1 < args.len() {
            return Some(args[i + 1].clone());
        }
    }
    None
}

/// Extract --completions argument from raw args
fn extract_completions_arg(args: &[String]) -> Option<ShellCompletion> {
    for i in 0..args.len() {
        if args[i] == "--completions" && i + 1 < args.len() {
            return match args[i + 1].to_lowercase().as_str() {
                "bash" => Some(ShellCompletion::Bash),
                "zsh" => Some(ShellCompletion::Zsh),
                "fish" => Some(ShellCompletion::Fish),
                "powershell" => Some(ShellCompletion::PowerShell),
                "elvish" => Some(ShellCompletion::Elvish),
                _ => None,
            };
        }
        // Also handle --completions=shell format
        if let Some(shell) = args[i].strip_prefix("--completions=") {
            return match shell.to_lowercase().as_str() {
                "bash" => Some(ShellCompletion::Bash),
                "zsh" => Some(ShellCompletion::Zsh),
                "fish" => Some(ShellCompletion::Fish),
                "powershell" => Some(ShellCompletion::PowerShell),
                "elvish" => Some(ShellCompletion::Elvish),
                _ => None,
            };
        }
    }
    None
}

/// Generate shell completion script and print to stdout
fn generate_completions(shell: ShellCompletion) {
    use clap_complete::{generate, Shell};

    let mut cmd = Cli::command();
    let name = cmd.get_name().to_string();

    let shell = match shell {
        ShellCompletion::Bash => Shell::Bash,
        ShellCompletion::Zsh => Shell::Zsh,
        ShellCompletion::Fish => Shell::Fish,
        ShellCompletion::PowerShell => Shell::PowerShell,
        ShellCompletion::Elvish => Shell::Elvish,
    };

    generate(shell, &mut cmd, name, &mut std::io::stdout());
}

/// Check if the given alias_name appears in any `-a` or `--alias` reference in the args
pub fn should_resolve_alias_references(args: &[String], alias_name: &str) -> bool {
    let mut i = 0;
    while i < args.len() {
        if (args[i] == "-a" || args[i] == "--alias") && i + 1 < args.len() {
            if args[i + 1] == alias_name {
                return true;
            }
            i += 2;
        } else {
            i += 1;
        }
    }
    false
}

/// Handle --save-alias command
pub fn handle_save_alias(raw_args: &[String], alias_name: &str, use_emoji: bool) {
    // Extract --config-file if specified
    let mut config_file_path: Option<String> = None;
    let mut command_args = Vec::new();
    let mut i = 0;
    while i < raw_args.len() {
        if raw_args[i] == "--save-alias" {
            // Skip --save-alias and its argument
            i += 2;
        } else if raw_args[i] == "--config-file" && i + 1 < raw_args.len() {
            // Extract --config-file for saving
            config_file_path = Some(raw_args[i + 1].clone());
            i += 2;
        } else {
            command_args.push(raw_args[i].clone());
            i += 1;
        }
    }

    // Skip the program name (first argument)
    if !command_args.is_empty() {
        command_args.remove(0);
    }

    // Check if we have any command left to save
    if command_args.is_empty() {
        let prefix = if use_emoji { "⚠️" } else { "kelora:" };
        eprintln!("{} No command to save as alias '{}'", prefix, alias_name);
        std::process::exit(2);
    }

    // Check if we should resolve alias references (when updating self-referencing alias)
    let should_resolve = should_resolve_alias_references(&command_args, alias_name);

    // If we need to resolve OR validate, load the config file
    let alias_value = if command_args
        .iter()
        .any(|arg| arg == "-a" || arg == "--alias")
    {
        // Command contains alias references - need to load config
        let config_result = match config_file_path.as_ref() {
            Some(path) => ConfigFile::load_with_custom_path(Some(path)),
            None => ConfigFile::load_with_custom_path(None),
        };

        match config_result {
            Ok((config, _path)) => {
                if should_resolve {
                    // Resolution mode: flatten all aliases
                    match config.resolve_args_only(&command_args) {
                        Ok(resolved_args) => {
                            if resolved_args.is_empty() {
                                let prefix = if use_emoji { "⚠️" } else { "kelora:" };
                                eprintln!(
                                    "{} Resolved command is empty for alias '{}'",
                                    prefix, alias_name
                                );
                                std::process::exit(2);
                            }
                            shell_words::join(resolved_args)
                        }
                        Err(e) => {
                            let prefix = if use_emoji { "⚠️" } else { "kelora:" };
                            eprintln!("{} Failed to resolve aliases in command: {}", prefix, e);
                            std::process::exit(1);
                        }
                    }
                } else {
                    // Preservation mode: validate references exist but keep them
                    if let Err(e) = config.validate_alias_references(&command_args) {
                        let prefix = if use_emoji { "⚠️" } else { "kelora:" };
                        eprintln!("{} {}", prefix, e);
                        eprintln!(
                            "{} Cannot save alias '{}' with reference to non-existent alias",
                            prefix, alias_name
                        );
                        std::process::exit(1);
                    }
                    shell_words::join(command_args)
                }
            }
            Err(_) if should_resolve => {
                // Trying to update non-existent alias
                let prefix = if use_emoji { "⚠️" } else { "kelora:" };
                eprintln!(
                    "{} Cannot update alias '{}' - no config file found",
                    prefix, alias_name
                );
                eprintln!(
                    "{} To create a new alias, use a command without referencing itself",
                    prefix
                );
                std::process::exit(1);
            }
            Err(_) => {
                // Preservation mode but config doesn't exist - that's an error
                // because we're referencing other aliases that don't exist
                let prefix = if use_emoji { "⚠️" } else { "kelora:" };
                eprintln!(
                    "{} Cannot save alias '{}' with alias references - no config file found",
                    prefix, alias_name
                );
                eprintln!(
                    "{} Create the referenced aliases first, or use a command without alias references",
                    prefix
                );
                std::process::exit(1);
            }
        }
    } else {
        // No alias references - just join and save
        shell_words::join(command_args)
    };

    // Save the alias to the specified config file or auto-detect
    let target_path = config_file_path.as_ref().map(std::path::Path::new);
    match ConfigFile::save_alias(alias_name, &alias_value, target_path) {
        Ok((config_path, previous_value)) => {
            let success_prefix = if use_emoji { "🔹" } else { "kelora:" };
            println!(
                "{} Alias '{}' saved to {}",
                success_prefix,
                alias_name,
                config_path.display()
            );

            if let Some(prev) = previous_value {
                let info_prefix = if use_emoji { "🔹" } else { "kelora:" };
                println!("{} Replaced previous alias:", info_prefix);
                println!("    {} = {}", alias_name, prev);
            }
        }
        Err(e) => {
            let error_prefix = if use_emoji { "⚠️" } else { "kelora:" };
            eprintln!(
                "{} Failed to save alias '{}': {}",
                error_prefix, alias_name, e
            );
            std::process::exit(1);
        }
    }
}

/// Process command line arguments with config file support
pub fn process_args_with_config(stderr: &mut SafeStderr) -> (ArgMatches, Cli, ConfigExpansionInfo) {
    // Get raw command line arguments
    let raw_args: Vec<String> = std::env::args().collect();

    // Extract --config-file argument early for use by config commands
    let config_file_path = extract_config_file_arg(&raw_args);

    // Check for config-related option conflicts
    let has_show_config = raw_args.iter().any(|arg| arg == "--show-config");
    let has_edit_config = raw_args.iter().any(|arg| arg == "--edit-config");
    let has_ignore_config = raw_args.iter().any(|arg| arg == "--ignore-config");

    if has_show_config && has_edit_config {
        stderr
            .writeln("kelora: Error: --show-config and --edit-config are mutually exclusive")
            .unwrap_or(());
        ExitCode::InvalidUsage.exit();
    }

    if has_ignore_config && has_edit_config {
        stderr
            .writeln("kelora: Error: --ignore-config and --edit-config are mutually exclusive")
            .unwrap_or(());
        ExitCode::InvalidUsage.exit();
    }

    // Check for --show-config first, before any other processing
    if has_show_config {
        ConfigFile::show_config();
        std::process::exit(0);
    }

    // Check for --edit-config
    if has_edit_config {
        ConfigFile::edit_config(config_file_path.as_deref());
        std::process::exit(0);
    }

    // Check for --help-time
    if raw_args.iter().any(|arg| arg == "--help-time") {
        help::print_time_format_help();
        std::process::exit(0);
    }

    // Check for --help-functions
    if raw_args.iter().any(|arg| arg == "--help-functions") {
        help::print_functions_help();
        std::process::exit(0);
    }

    // Check for -h (brief help)
    if raw_args.iter().any(|arg| arg == "-h") {
        help::print_quick_help();
        std::process::exit(0);
    }

    // Check for --help-examples
    if raw_args.iter().any(|arg| arg == "--help-examples") {
        help::print_examples_help();
        std::process::exit(0);
    }

    // Check for --help-rhai
    if raw_args.iter().any(|arg| arg == "--help-rhai") {
        help::print_rhai_help();
        std::process::exit(0);
    }

    // Check for --help-multiline
    if raw_args.iter().any(|arg| arg == "--help-multiline") {
        help::print_multiline_help();
        std::process::exit(0);
    }

    // Check for --help-regex
    if raw_args.iter().any(|arg| arg == "--help-regex") {
        help::print_regex_help();
        std::process::exit(0);
    }

    // Check for --help-formats
    if raw_args.iter().any(|arg| arg == "--help-formats") {
        help::print_formats_help();
        std::process::exit(0);
    }

    // Check for --completions
    if let Some(shell) = extract_completions_arg(&raw_args) {
        generate_completions(shell);
        std::process::exit(0);
    }

    // Check for --save-alias before other processing
    if let Some(alias_name) = extract_save_alias_arg(&raw_args) {
        let use_emoji = tty::should_use_emoji_for_stderr();
        handle_save_alias(&raw_args, &alias_name, use_emoji);
        std::process::exit(0);
    }

    // Check for --ignore-config
    let ignore_config = has_ignore_config;
    let disable_auto_config = std::env::var_os("KELORA_IGNORE_CONFIG").is_some();

    let (processed_args, expansion_info) = if ignore_config {
        // Skip all config file processing
        (raw_args, ConfigExpansionInfo::default())
    } else if let Some(path) = config_file_path.as_deref() {
        // Explicit config files still load even when automatic config discovery is disabled.
        match ConfigFile::load_with_custom_path(Some(path)) {
            Ok((config_file, loaded_path)) => match config_file.process_args(raw_args) {
                Ok((processed, mut info)) => {
                    info.loaded_config_path = loaded_path;
                    info.explicit_config_path = true;
                    (processed, info)
                }
                Err(e) => {
                    stderr
                        .writeln(&format!("kelora: Config error: {}", e))
                        .unwrap_or(());
                    std::process::exit(1);
                }
            },
            Err(e) => {
                stderr
                    .writeln(&format!("kelora: Config file error: {}", e))
                    .unwrap_or(());
                std::process::exit(1);
            }
        }
    } else if disable_auto_config {
        // Skip automatic project/user config discovery.
        (raw_args, ConfigExpansionInfo::default())
    } else {
        // Load config file and process aliases
        match ConfigFile::load_with_custom_path(config_file_path.as_deref()) {
            Ok((config_file, loaded_path)) => match config_file.process_args(raw_args) {
                Ok((processed, mut info)) => {
                    info.loaded_config_path = loaded_path;
                    info.explicit_config_path = config_file_path.is_some();
                    (processed, info)
                }
                Err(e) => {
                    stderr
                        .writeln(&format!("kelora: Config error: {}", e))
                        .unwrap_or(());
                    std::process::exit(1);
                }
            },
            Err(e) => {
                stderr
                    .writeln(&format!("kelora: Config file error: {}", e))
                    .unwrap_or(());
                std::process::exit(1);
            }
        }
    };

    // Parse with potentially modified arguments
    let matches = Cli::command().get_matches_from(processed_args);
    let mut cli = Cli::from_arg_matches(&matches).unwrap_or_else(|e| {
        stderr
            .writeln(&format!("kelora: Error: {}", e))
            .unwrap_or(());
        std::process::exit(1);
    });

    // Resolve inverted boolean flags
    cli.resolve_boolean_flags();

    // Config file defaults and aliases are already applied in process_args above

    // Check if we should enter interactive mode
    // Interactive mode is activated when:
    // - stdin is a TTY (not piped input)
    // - no input files are provided
    // - --no-input is not specified
    // - no other arguments are provided (just the program name)
    if crate::tty::is_stdin_tty() && cli.files.is_empty() && !cli.no_input {
        // Check if this is truly no arguments (interactive mode) or just missing input files
        let raw_args: Vec<String> = std::env::args().collect();

        // If only program name, enter interactive mode
        if raw_args.len() == 1 {
            // Enter interactive mode
            if let Err(e) = crate::interactive::run_interactive_mode() {
                eprintln!("Interactive mode error: {}", e);
                std::process::exit(1);
            }
            std::process::exit(0);
        }

        // Otherwise, show error (user provided flags but no input files)
        eprintln!("error: no input files or stdin provided");
        eprintln!();
        eprintln!("{}", Cli::command().render_usage());
        eprintln!();
        eprintln!(
            "Pass one or more files, pipe input on stdin, or run plain 'kelora' to enter interactive mode."
        );
        eprintln!("For a quick reference, try '-h'.");
        std::process::exit(2);
    }

    (matches, cli, expansion_info)
}