paneship 1.1.4

A blazingly fast, high-performance shell prompt optimized for tmux and large Git repositories
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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
#[cfg(not(target_env = "msvc"))]
#[global_allocator]
static GLOBAL: std::alloc::System = std::alloc::System;

mod benchmark;
mod cache;
mod core;
#[cfg(unix)]
mod daemon;
mod modules;
#[cfg(unix)]
mod tmux;

use std::path::PathBuf;

#[cfg(unix)]
use benchmark::BenchmarkOptions;
use core::prompt::PromptContext;

#[derive(Debug, Clone)]
struct RenderOptions {
    exit_code: i32,
    width: Option<usize>,
    cwd: Option<PathBuf>,
    duration_ms: Option<u64>,
    shell: RenderShell,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RenderShell {
    Plain,
    Bash,
    Zsh,
    Fish,
    PowerShell,
    Nushell,
    Elvish,
    Xonsh,
    Tcsh,
    Ion,
    Cmd,
}

#[cfg(unix)]
#[derive(Debug, Clone)]
enum CliCommand {
    Init(InitOptions),
    Render(RenderOptions),
    Benchmark(BenchmarkOptions),
    Top,
    Daemon,
    DaemonPing,
    Help,
}

#[cfg(not(unix))]
#[derive(Debug, Clone)]
enum CliCommand {
    Render(RenderOptions),
    Top,
    Help,
}

#[cfg(unix)]
#[derive(Debug, Clone)]
struct InitOptions {
    shell: RenderShell,
    onboarding: bool,
}

fn main() {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let command = match parse_cli(args) {
        Ok(command) => command,
        Err(err) => {
            eprintln!("{err}\n\n{}", usage());
            std::process::exit(2);
        }
    };

    match command {
        CliCommand::Render(options) => {
            #[cfg(unix)]
            {
                let cwd = options
                    .cwd
                    .clone()
                    .unwrap_or_else(|| std::env::current_dir().unwrap_or_default());
                let width = options.width.unwrap_or(80);
                if let Some(mut prompt) =
                    daemon::render(cwd, options.exit_code, width, options.duration_ms)
                {
                    match options.shell {
                        RenderShell::Zsh => {
                            prompt = core::layout::wrap_ansi_for_zsh(prompt.as_str())
                        }
                        RenderShell::Bash => {
                            prompt = core::layout::wrap_ansi_for_bash(prompt.as_str())
                        }
                        _ => {}
                    }
                    print!("{prompt}");
                    return;
                }
            }

            let context = PromptContext::from_inputs(
                options.cwd,
                options.width,
                options.exit_code,
                options.duration_ms,
            );
            let mut prompt = core::renderer::render(&context);
            match options.shell {
                RenderShell::Zsh => prompt = core::layout::wrap_ansi_for_zsh(prompt.as_str()),
                RenderShell::Bash => prompt = core::layout::wrap_ansi_for_bash(prompt.as_str()),
                _ => {}
            }
            print!("{prompt}");
        }
        #[cfg(unix)]
        CliCommand::Benchmark(options) => match benchmark::run(options) {
            Ok(report) => {
                println!("{report}");
            }
            Err(err) => {
                eprintln!("benchmark failed: {err}");
                std::process::exit(1);
            }
        },
        CliCommand::Top => {
            if let Err(err) = benchmark::run_top() {
                eprintln!("top benchmark failed: {err}");
                std::process::exit(1);
            }
        }
        #[cfg(unix)]
        CliCommand::Daemon => {
            if let Err(err) = daemon::run() {
                eprintln!("daemon error: {err}");
                std::process::exit(1);
            }
        }
        #[cfg(unix)]
        CliCommand::DaemonPing => {
            if daemon::ping() {
                println!("ok");
            } else {
                std::process::exit(1);
            }
        }
        #[cfg(unix)]
        CliCommand::Init(options) => {
            handle_init(options);
        }
        CliCommand::Help => {
            println!("{}", usage());
        }
    }
}

fn parse_cli(args: Vec<String>) -> Result<CliCommand, String> {
    if args.is_empty() {
        return Ok(CliCommand::Render(RenderOptions {
            exit_code: 0,
            width: None,
            cwd: None,
            duration_ms: None,
            shell: RenderShell::Plain,
        }));
    }

    if matches!(args[0].as_str(), "help" | "--help" | "-h") {
        return Ok(CliCommand::Help);
    }

    if args[0] == "benchmark" {
        #[cfg(unix)]
        {
            return parse_benchmark_args(&args[1..]);
        }
        #[cfg(not(unix))]
        {
            return Err("benchmark command is only available on Unix".to_string());
        }
    }

    if matches!(args[0].as_str(), "top" | "-top") {
        return Ok(CliCommand::Top);
    }

    #[cfg(unix)]
    if args[0] == "daemon" {
        return parse_daemon_args(&args[1..]);
    }

    #[cfg(unix)]
    if args[0] == "init" {
        return parse_init_args(&args[1..]);
    }

    if args[0] == "render" {
        return parse_render_args(&args[1..]);
    }

    parse_render_args(&args)
}

#[cfg(unix)]
fn handle_init(options: InitOptions) {
    let script = match options.shell {
        RenderShell::Bash => bash_init_script(),
        RenderShell::Zsh => zsh_init_script(),
        RenderShell::Fish => fish_init_script(),
        RenderShell::PowerShell => powershell_init_script(),
        RenderShell::Nushell => nushell_init_script(),
        RenderShell::Elvish => elvish_init_script(),
        RenderShell::Xonsh => xonsh_init_script(),
        RenderShell::Tcsh => tcsh_init_script(),
        RenderShell::Ion => ion_init_script(),
        RenderShell::Cmd => cmd_init_script(),
        RenderShell::Plain => "".to_string(),
    };

    if options.onboarding {
        if let Err(err) = append_onboarding(options.shell, &script) {
            eprintln!("{err}");
            std::process::exit(1);
        }
        return;
    }

    print!("{script}");
}

#[cfg(unix)]
fn bash_init_script() -> String {
    [
        "if ! command -v paneship >/dev/null 2>&1; then",
        "    return 0",
        "fi",
        "PANESHIP_BIN=$(command -v paneship)",
        "",
        "if ! \"$PANESHIP_BIN\" daemon ping > /dev/null 2>&1; then",
        "    \"$PANESHIP_BIN\" daemon > /dev/null 2>&1 &",
        "fi",
        "",
        "paneship_precmd() {",
        "    local exit_code=$?",
        "    local duration_arg=()",
        "    if [[ -n \"$PANESHIP_START_TIME\" ]]; then",
        "        local end_time=$(date +%s%3N)",
        "        local elapsed=$((end_time - PANESHIP_START_TIME))",
        "        duration_arg=(--duration-ms \"$elapsed\")",
        "    fi",
        "    PS1=\"$(\"$PANESHIP_BIN\" render --shell bash --exit-code \"$exit_code\" --width \"${COLUMNS:-80}\" --cwd \"$PWD\" \"${duration_arg[@]}\" 2>/dev/null)\"",
        "    unset PANESHIP_START_TIME",
        "}",
        "",
        "paneship_preexec() {",
        "    PANESHIP_START_TIME=$(date +%s%3N)",
        "}",
        "",
        "if [[ \";$PROMPT_COMMAND;\" != *\";paneship_precmd;\"* ]]; then",
        "    PROMPT_COMMAND=\"paneship_precmd; $PROMPT_COMMAND\"",
        "fi",
        "",
        "trap 'paneship_preexec' DEBUG",
    ]
    .join("\n")
}

#[cfg(unix)]
fn zsh_init_script() -> String {
    [
        "if (( ! $+commands[paneship] )); then",
        "    return 0 2>/dev/null || true",
        "fi",
        "typeset -g PANESHIP_BIN=\"${commands[paneship]}\"",
        "",
        "if ! \"$PANESHIP_BIN\" daemon ping > /dev/null 2>&1; then",
        "    \"$PANESHIP_BIN\" daemon > /dev/null 2>&1 &!",
        "fi",
        "",
        "zmodload zsh/datetime",
        "autoload -Uz add-zsh-hook",
        "typeset -gF PANESHIP_CMD_START=0",
        "",
        "paneship_preexec() {",
        "    PANESHIP_CMD_START=$EPOCHREALTIME",
        "}",
        "",
        "paneship_precmd() {",
        "    local exit_code=$?",
        "    local -a duration_arg",
        "    if (( PANESHIP_CMD_START > 0 )); then",
        "        local -F now=$EPOCHREALTIME",
        "        local -F elapsed=$(( now - PANESHIP_CMD_START ))",
        "        local -i elapsed_ms=$(( elapsed * 1000 ))",
        "        if (( elapsed_ms < 0 )); then",
        "            elapsed_ms=0",
        "        fi",
        "        duration_arg=(--duration-ms \"$elapsed_ms\")",
        "    fi",
        "    local rendered",
        "    rendered=\"$(\"$PANESHIP_BIN\" render --shell zsh --exit-code \"$exit_code\" --width \"${COLUMNS:-80}\" --cwd \"$PWD\" \"${duration_arg[@]}\" 2>/dev/null)\" || rendered=\"\"",
        "    if [[ -z \"$rendered\" || \"$rendered\" != *$'\\n'* || \"$rendered\" == *$'\\n'*$'\\n'* ]]; then",
        "        PROMPT='%n@%m:%~ %# '",
        "    else",
        "        PROMPT=\"$rendered\"",
        "    fi",
        "    PANESHIP_CMD_START=0",
        "}",
        "",
        "add-zsh-hook -D preexec paneship_preexec 2>/dev/null",
        "add-zsh-hook -D precmd paneship_precmd 2>/dev/null",
        "add-zsh-hook preexec paneship_preexec",
        "add-zsh-hook precmd paneship_precmd",
    ]
    .join("\n")
}

#[cfg(unix)]
fn fish_init_script() -> String {
    [
        "if not command -v paneship >/dev/null 2>&1",
        "    exit",
        "end",
        "",
        "if not paneship daemon ping >/dev/null 2>&1",
        "    paneship daemon >/dev/null 2>&1 &",
        "    disown",
        "end",
        "",
        "function fish_prompt",
        "    set -l exit_code $status",
        "    set -l duration_arg",
        "    if test -n \"$CMD_DURATION\"",
        "        set duration_arg --duration-ms \"$CMD_DURATION\"",
        "    end",
        "    paneship render --shell fish --exit-code $exit_code --width $COLUMNS --cwd $PWD $duration_arg",
        "end",
    ]
    .join("\n")
}

#[cfg(unix)]
fn powershell_init_script() -> String {
    [
        "function prompt {",
        "    $lastExitCode = if ($null -eq $?) { 0 } else { [int](-not $?) }",
        "    & paneship render --shell powershell --exit-code $lastExitCode --width $Host.UI.RawUI.WindowSize.Width --cwd $PWD",
        "}",
        "if (!(Get-Command paneship -ErrorAction SilentlyContinue)) { return }",
        "if (!(paneship daemon ping)) { Start-Process paneship -ArgumentList \"daemon\" -NoNewWindow }",
    ]
    .join("\n")
}

#[cfg(unix)]
fn nushell_init_script() -> String {
    [
        "$env.PROMPT_COMMAND = { ||",
        "    paneship render --shell nushell --exit-code $env.LAST_EXIT_CODE --width (term size).columns --cwd $env.PWD",
        "}",
        "$env.PROMPT_COMMAND_RIGHT = \"\"",
    ]
    .join("\n")
}

#[cfg(unix)]
fn elvish_init_script() -> String {
    [
        "set edit:prompt = {",
        "    paneship render --shell elvish --exit-code (if $edit:exceptions-visible { put 1 } else { put 0 }) --width (take 1 (stty size | from-spaced)) --cwd $pwd",
        "}",
    ]
    .join("\n")
}

#[cfg(unix)]
fn xonsh_init_script() -> String {
    [
        "$PROMPT = lambda: $(paneship render --shell xonsh --exit-code __xonsh__.history[-1].rtn if len(__xonsh__.history) > 0 else 0 --width $COLUMNS --cwd $PWD)",
    ]
    .join("\n")
}

#[cfg(unix)]
fn tcsh_init_script() -> String {
    [
        "alias precmd 'set prompt=\"`paneship render --shell tcsh --exit-code $status --width $COLUMNS --cwd $cwd`\"'",
    ]
    .join("\n")
}

#[cfg(unix)]
fn ion_init_script() -> String {
    [
        "fn PROMPT",
        "    paneship render --shell ion --exit-code $? --width $COLUMNS --cwd $PWD",
        "end",
    ]
    .join("\n")
}

#[cfg(unix)]
fn cmd_init_script() -> String {
    "rem paneship init for cmd.exe usually requires clink or similar enhancements.\nset PROMPT=$E[32mpaneship$E[0m $P$G ".to_string()
}

#[cfg(unix)]
fn append_onboarding(shell: RenderShell, script: &str) -> Result<(), String> {
    use std::fs::OpenOptions;
    use std::io::Write;

    let home = std::env::var("HOME").map_err(|_| "Unable to find $HOME".to_string())?;

    let config_path = match shell {
        RenderShell::Bash => format!("{home}/.bashrc"),
        RenderShell::Zsh => format!("{home}/.zshrc"),
        RenderShell::Fish => format!("{home}/.config/fish/config.fish"),
        RenderShell::PowerShell => {
            format!("{home}/.config/powershell/Microsoft.PowerShell_profile.ps1")
        }
        RenderShell::Nushell => format!("{home}/.config/nushell/config.nu"),
        RenderShell::Elvish => format!("{home}/.elvish/rc.elv"),
        RenderShell::Xonsh => format!("{home}/.xonshrc"),
        RenderShell::Tcsh => format!("{home}/.tcshrc"),
        RenderShell::Ion => format!("{home}/.config/ion/initrc"),
        _ => {
            return Err(format!(
                "Onboarding is not supported for shell: {:?}",
                shell
            ))
        }
    };

    let start_marker = "# >>> paneship initialize >>>";
    let end_marker = "# <<< paneship initialize <<<";
    let block = format!("{start_marker}\n{script}\n{end_marker}\n");

    let existing = std::fs::read_to_string(&config_path).unwrap_or_default();
    if let Some(start_idx) = existing.find(start_marker) {
        let Some(rel_end_idx) = existing[start_idx..].find(end_marker) else {
            return Err(format!(
                "Found '{start_marker}' without matching '{end_marker}' in {config_path}. Please fix this block manually."
            ));
        };

        let end_marker_idx = start_idx + rel_end_idx;
        let mut replace_end = end_marker_idx + end_marker.len();
        if existing[replace_end..].starts_with('\n') {
            replace_end += 1;
        }

        let mut updated = existing.clone();
        updated.replace_range(start_idx..replace_end, block.as_str());

        if updated == existing {
            println!("Paneship onboarding is already up to date in {config_path}");
            return Ok(());
        }

        std::fs::write(&config_path, updated)
            .map_err(|err| format!("Failed to write to {config_path}: {err}"))?;

        println!("Paneship onboarding config updated in {config_path}");
        return Ok(());
    }

    if existing.contains(block.trim_end()) {
        println!("Paneship onboarding is already configured in {config_path}");
        return Ok(());
    }

    if let Some(parent) = std::path::Path::new(&config_path).parent() {
        if !parent.exists() {
            std::fs::create_dir_all(parent).map_err(|err| {
                format!("Failed to create directory {}: {}", parent.display(), err)
            })?;
        }
    }

    let mut file = OpenOptions::new()
        .append(true)
        .create(true)
        .open(&config_path)
        .map_err(|err| format!("Failed to open {config_path}: {err}"))?;

    if !existing.is_empty() && !existing.ends_with('\n') {
        writeln!(file).map_err(|err| format!("Failed to write to {config_path}: {err}"))?;
    }

    write!(file, "{block}").map_err(|err| format!("Failed to write to {config_path}: {err}"))?;

    println!("Paneship onboarding config appended to {config_path}");
    Ok(())
}

fn parse_render_args(args: &[String]) -> Result<CliCommand, String> {
    let mut options = RenderOptions {
        exit_code: 0,
        width: None,
        cwd: None,
        duration_ms: None,
        shell: RenderShell::Plain,
    };

    let mut idx = 0;
    while idx < args.len() {
        match args[idx].as_str() {
            "--exit-code" | "-s" => {
                idx += 1;
                let value = args
                    .get(idx)
                    .ok_or_else(|| "missing value for --exit-code".to_string())?;
                options.exit_code = value
                    .parse::<i32>()
                    .map_err(|_| format!("invalid exit code: {value}"))?;
            }
            "--width" | "-w" => {
                idx += 1;
                let value = args
                    .get(idx)
                    .ok_or_else(|| "missing value for --width".to_string())?;
                options.width = Some(
                    value
                        .parse::<usize>()
                        .map_err(|_| format!("invalid width: {value}"))?,
                );
            }
            "--cwd" => {
                idx += 1;
                let value = args
                    .get(idx)
                    .ok_or_else(|| "missing value for --cwd".to_string())?;
                options.cwd = Some(PathBuf::from(value));
            }
            "--duration-ms" => {
                idx += 1;
                let value = args
                    .get(idx)
                    .ok_or_else(|| "missing value for --duration-ms".to_string())?;
                options.duration_ms = Some(
                    value
                        .parse::<u64>()
                        .map_err(|_| format!("invalid duration ms: {value}"))?,
                );
            }
            "-h" | "--help" => {}
            "--shell" => {
                idx += 1;
                let value = args
                    .get(idx)
                    .ok_or_else(|| "missing value for --shell".to_string())?;
                options.shell = match value.as_str() {
                    "plain" => RenderShell::Plain,
                    "bash" => RenderShell::Bash,
                    "zsh" => RenderShell::Zsh,
                    "fish" => RenderShell::Fish,
                    "powershell" | "pwsh" => RenderShell::PowerShell,
                    "nushell" | "nu" => RenderShell::Nushell,
                    "elvish" => RenderShell::Elvish,
                    "xonsh" => RenderShell::Xonsh,
                    "tcsh" => RenderShell::Tcsh,
                    "ion" => RenderShell::Ion,
                    "cmd" => RenderShell::Cmd,
                    _ => {
                        return Err(format!(
                            "invalid shell value: {value}. Supported values: plain, bash, zsh, fish, powershell, nushell, elvish, xonsh, tcsh, ion, cmd"
                        ))
                    }
                };
            }
            unknown => {
                return Err(format!("unknown render argument: {unknown}"));
            }
        }
        idx += 1;
    }

    Ok(CliCommand::Render(options))
}

#[cfg(unix)]
fn parse_benchmark_args(args: &[String]) -> Result<CliCommand, String> {
    let mut options = crate::benchmark::BenchmarkOptions::default();
    let mut idx = 0;

    while idx < args.len() {
        match args[idx].as_str() {
            "--iterations" | "-n" => {
                idx += 1;
                let value = args
                    .get(idx)
                    .ok_or_else(|| "missing value for --iterations".to_string())?;
                options.iterations = value
                    .parse::<usize>()
                    .map_err(|_| format!("invalid iterations value: {value}"))?;
            }
            "--panes" | "-p" => {
                idx += 1;
                let value = args
                    .get(idx)
                    .ok_or_else(|| "missing value for --panes".to_string())?;
                options.panes = value
                    .parse::<usize>()
                    .map_err(|_| format!("invalid panes value: {value}"))?;
            }
            "--compare-starship" => {
                options.compare_starship = true;
            }
            "--width" | "-w" => {
                idx += 1;
                let value = args
                    .get(idx)
                    .ok_or_else(|| "missing value for --width".to_string())?;
                options.width = Some(
                    value
                        .parse::<usize>()
                        .map_err(|_| format!("invalid width: {value}"))?,
                );
            }
            "--cwd" => {
                idx += 1;
                let value = args
                    .get(idx)
                    .ok_or_else(|| "missing value for --cwd".to_string())?;
                options.cwd = Some(PathBuf::from(value));
            }
            "--exit-code" | "-s" => {
                idx += 1;
                let value = args
                    .get(idx)
                    .ok_or_else(|| "missing value for --exit-code".to_string())?;
                options.exit_code = value
                    .parse::<i32>()
                    .map_err(|_| format!("invalid exit code: {value}"))?;
            }
            unknown => {
                return Err(format!("unknown benchmark argument: {unknown}"));
            }
        }
        idx += 1;
    }

    if options.iterations == 0 {
        return Err("iterations must be greater than 0".to_string());
    }
    if options.panes == 0 {
        return Err("panes must be greater than 0".to_string());
    }

    Ok(CliCommand::Benchmark(options))
}

#[cfg(unix)]
fn parse_daemon_args(args: &[String]) -> Result<CliCommand, String> {
    match args {
        [] => Ok(CliCommand::Daemon),
        [subcommand] if subcommand == "ping" => Ok(CliCommand::DaemonPing),
        [unknown, ..] => Err(format!("unknown daemon argument: {unknown}")),
    }
}

#[cfg(unix)]
fn parse_init_args(args: &[String]) -> Result<CliCommand, String> {
    if args.is_empty() {
        return Err("missing init target. Try: paneship init zsh".to_string());
    }

    let shell = match args[0].as_str() {
        "bash" => RenderShell::Bash,
        "zsh" => RenderShell::Zsh,
        "fish" => RenderShell::Fish,
        "powershell" | "pwsh" => RenderShell::PowerShell,
        "nushell" | "nu" => RenderShell::Nushell,
        "elvish" => RenderShell::Elvish,
        "xonsh" => RenderShell::Xonsh,
        "tcsh" => RenderShell::Tcsh,
        "ion" => RenderShell::Ion,
        "cmd" => RenderShell::Cmd,
        _ => {
            return Err(format!(
                "unsupported init target '{}'. Supported: bash, zsh, fish, powershell, nushell, elvish, xonsh, tcsh, ion, cmd",
                args[0]
            ));
        }
    };

    let onboarding = match args.get(1).map(|v| v.as_str()) {
        None => false,
        Some("--onboarding") => true,
        Some("to") if args.get(2).map(|v| v.as_str()) == Some("onboarding") && args.len() == 3 => {
            true
        }
        Some("onboarding") if args.len() == 2 => true,
        Some(_) => {
            return Err(format!(
                "unsupported init syntax. Use: paneship init {} [--onboarding|to onboarding]",
                args[0]
            ))
        }
    };

    Ok(CliCommand::Init(InitOptions { shell, onboarding }))
}

fn usage() -> &'static str {
    "Paneship - high-performance shell prompt\n\nUSAGE:\n  paneship [render] [--exit-code <code>] [--width <cols>] [--cwd <path>] [--duration-ms <ms>] [--shell <name>]\n  paneship init <shell> [--onboarding|to onboarding]\n  paneship benchmark [--iterations <n>] [--panes <n>] [--compare-starship] [--width <cols>] [--cwd <path>] [--exit-code <code>]\n  paneship top\n  paneship daemon [ping]\n  paneship help\n\nSHELLS:\n  bash, zsh, fish, powershell, nushell, elvish, xonsh, tcsh, ion, cmd\n\nOPTIONS:\n  -s, --exit-code <code>    Last command exit code\n  -w, --width <cols>        Prompt width budget\n      --cwd <path>          Directory to render the prompt for\n      --duration-ms <ms>    Last command duration in milliseconds\n      --shell <name>        Prompt output mode (default: plain)\n\nINIT OPTIONS:\n  paneship init <shell>     Print shell init script (for eval)\n  paneship init <shell> to onboarding\n                            Append paneship block to shell config file\n  paneship init <shell> --onboarding\n                            Same as 'to onboarding'\n\nBENCHMARK OPTIONS:\n  -n, --iterations <n>      Renders per pane (default: 200)\n  -p, --panes <n>           Number of concurrent panes (default: 4)\n      --compare-starship    Include direct Starship comparison"
}