pzsh 0.3.2

Performance-first shell framework with sub-10ms startup
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
//! Prompt module for pzsh
//!
//! O(1) prompt rendering with 2ms budget constraint.
//! Git status is async-updated, never blocks.

use crate::color::{Styled, themes::DefaultTheme};
use crate::config::CompiledConfig;
use crate::{MAX_PROMPT_MS, PzshError, Result};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};

/// Compiled prompt segment (pre-rendered where possible)
#[derive(Debug, Clone)]
pub enum PromptSegment {
    /// Literal text (pre-computed)
    Literal(String),
    /// User name
    User,
    /// Hostname
    Host,
    /// Current working directory
    Cwd,
    /// Git branch (cached, async-updated)
    Git,
    /// Prompt character ($ or #)
    Char,
    /// Custom segment
    Custom(String),
}

/// Cached git status (updated asynchronously)
#[derive(Debug, Clone, Default)]
pub struct GitCache {
    /// Current branch name
    pub branch: Option<String>,
    /// Is dirty
    pub dirty: bool,
    /// Cache valid flag
    valid: Arc<AtomicBool>,
}

impl GitCache {
    /// Create empty cache
    #[must_use]
    pub fn new() -> Self {
        Self {
            branch: None,
            dirty: false,
            valid: Arc::new(AtomicBool::new(false)),
        }
    }

    /// Check if cache is valid
    #[must_use]
    pub fn is_valid(&self) -> bool {
        self.valid.load(Ordering::Relaxed)
    }

    /// Invalidate cache
    pub fn invalidate(&self) {
        self.valid.store(false, Ordering::Relaxed);
    }

    /// Render git status string
    #[must_use]
    pub fn render(&self) -> String {
        self.render_colored(false)
    }

    /// Render git status with optional colors
    #[must_use]
    pub fn render_colored(&self, colors: bool) -> String {
        match &self.branch {
            Some(branch) => {
                let dirty_marker = if self.dirty { "*" } else { "" };
                let text = format!("({branch}{dirty_marker})");
                if colors {
                    let style = if self.dirty {
                        DefaultTheme::git_dirty()
                    } else {
                        DefaultTheme::git_clean()
                    };
                    Styled::new(text, style).render()
                } else {
                    text
                }
            }
            None => String::new(),
        }
    }
}

/// Prompt renderer with O(1) segment rendering
#[derive(Debug)]
pub struct Prompt {
    /// Pre-compiled segments
    segments: Vec<PromptSegment>,
    /// Git cache (async-updated)
    git_cache: GitCache,
    /// Cached values
    user: String,
    host: String,
    /// Color support enabled
    colors_enabled: bool,
}

impl Prompt {
    /// Create a new prompt from compiled config
    #[must_use]
    pub fn new(config: &CompiledConfig) -> Self {
        let segments = Self::parse_format(&config.prompt_format);

        // Pre-compute static values
        let user = std::env::var("USER").unwrap_or_else(|_| "user".to_string());
        let host = hostname::get()
            .ok()
            .and_then(|h| h.into_string().ok())
            .unwrap_or_else(|| "localhost".to_string());

        // Check color support
        let colors_enabled = config.colors_enabled && crate::color::supports_color();

        Self {
            segments,
            git_cache: GitCache::new(),
            user,
            host,
            colors_enabled,
        }
    }

    /// Enable or disable colors
    pub fn set_colors_enabled(&mut self, enabled: bool) {
        self.colors_enabled = enabled && crate::color::supports_color();
    }

    /// Check if colors are enabled
    #[must_use]
    pub const fn colors_enabled(&self) -> bool {
        self.colors_enabled
    }

    /// Parse format string into segments
    fn parse_format(format: &str) -> Vec<PromptSegment> {
        let mut segments = Vec::new();
        let mut current_literal = String::new();
        let mut in_brace = false;
        let mut brace_content = String::new();

        for ch in format.chars() {
            match ch {
                '{' if !in_brace => {
                    if !current_literal.is_empty() {
                        segments.push(PromptSegment::Literal(std::mem::take(&mut current_literal)));
                    }
                    in_brace = true;
                }
                '}' if in_brace => {
                    let segment = match brace_content.as_str() {
                        "user" => PromptSegment::User,
                        "host" => PromptSegment::Host,
                        "cwd" => PromptSegment::Cwd,
                        "git" => PromptSegment::Git,
                        "char" => PromptSegment::Char,
                        other => PromptSegment::Custom(other.to_string()),
                    };
                    segments.push(segment);
                    brace_content.clear();
                    in_brace = false;
                }
                _ if in_brace => {
                    brace_content.push(ch);
                }
                _ => {
                    current_literal.push(ch);
                }
            }
        }

        if !current_literal.is_empty() {
            segments.push(PromptSegment::Literal(current_literal));
        }

        segments
    }

    /// Render prompt in O(1) time
    ///
    /// # Errors
    /// Returns error if rendering exceeds 2ms budget
    pub fn render(&self) -> Result<String> {
        let start = Instant::now();

        let mut output = String::with_capacity(256);

        for segment in &self.segments {
            match segment {
                PromptSegment::Literal(s) => output.push_str(s),
                PromptSegment::User => {
                    if self.colors_enabled {
                        output.push_str(&Styled::new(&self.user, DefaultTheme::user()).render());
                    } else {
                        output.push_str(&self.user);
                    }
                }
                PromptSegment::Host => {
                    if self.colors_enabled {
                        output.push_str(&Styled::new(&self.host, DefaultTheme::host()).render());
                    } else {
                        output.push_str(&self.host);
                    }
                }
                PromptSegment::Cwd => {
                    // Use PWD or current_dir (no subprocess!)
                    let cwd = std::env::var("PWD")
                        .or_else(|_| std::env::current_dir().map(|p| p.display().to_string()))
                        .unwrap_or_else(|_| "~".to_string());
                    if self.colors_enabled {
                        output.push_str(&Styled::new(&cwd, DefaultTheme::cwd()).render());
                    } else {
                        output.push_str(&cwd);
                    }
                }
                PromptSegment::Git => {
                    // Use cached git status (never blocks)
                    output.push_str(&self.git_cache.render_colored(self.colors_enabled));
                }
                PromptSegment::Char => {
                    let is_root = self.user == "root";
                    let ch = if is_root { '#' } else { '$' };
                    if self.colors_enabled {
                        let style = if is_root {
                            DefaultTheme::prompt_root()
                        } else {
                            DefaultTheme::prompt_char()
                        };
                        output.push_str(&Styled::new(ch.to_string(), style).render());
                    } else {
                        output.push(ch);
                    }
                }
                PromptSegment::Custom(name) => {
                    output.push_str(&format!("{{{name}}}"));
                }
            }
        }

        let elapsed = start.elapsed();
        if elapsed > Duration::from_millis(MAX_PROMPT_MS) {
            return Err(PzshError::PromptBudgetExceeded(
                MAX_PROMPT_MS,
                elapsed.as_millis() as u64,
            ));
        }

        Ok(output)
    }

    /// Update git cache (called asynchronously)
    pub fn update_git_cache(&mut self, branch: Option<String>, dirty: bool) {
        self.git_cache.branch = branch;
        self.git_cache.dirty = dirty;
        self.git_cache.valid.store(true, Ordering::Relaxed);
    }

    /// Invalidate git cache
    pub fn invalidate_git_cache(&self) {
        self.git_cache.invalidate();
    }

    /// Get number of segments
    #[must_use]
    pub fn segment_count(&self) -> usize {
        self.segments.len()
    }
}

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

    fn test_config() -> CompiledConfig {
        let mut config = CompiledConfig::default();
        config.prompt_format = "{user}@{host} {cwd} {git} {char} ".to_string();
        config
    }

    #[test]
    fn test_prompt_render_under_2ms() {
        let config = test_config();
        let prompt = Prompt::new(&config);

        let start = Instant::now();
        let result = prompt.render();
        let elapsed = start.elapsed();

        assert!(result.is_ok());
        assert!(
            elapsed < Duration::from_millis(MAX_PROMPT_MS),
            "ANDON: Prompt exceeded 2ms budget: {:?}",
            elapsed
        );
    }

    #[test]
    fn test_parse_format() {
        let segments = Prompt::parse_format("{user}@{host} {cwd} {char}");

        assert_eq!(segments.len(), 7);
        assert!(matches!(segments[0], PromptSegment::User));
        assert!(matches!(segments[1], PromptSegment::Literal(ref s) if s == "@"));
        assert!(matches!(segments[2], PromptSegment::Host));
        assert!(matches!(segments[3], PromptSegment::Literal(ref s) if s == " "));
        assert!(matches!(segments[4], PromptSegment::Cwd));
        assert!(matches!(segments[5], PromptSegment::Literal(ref s) if s == " "));
        assert!(matches!(segments[6], PromptSegment::Char));
    }

    #[test]
    fn test_git_cache_render() {
        let mut cache = GitCache::new();

        // Empty cache
        assert_eq!(cache.render(), "");

        // With branch
        cache.branch = Some("main".to_string());
        assert_eq!(cache.render(), "(main)");

        // With dirty flag
        cache.dirty = true;
        assert_eq!(cache.render(), "(main*)");
    }

    #[test]
    fn test_git_cache_invalidation() {
        let cache = GitCache::new();

        assert!(!cache.is_valid());

        cache.valid.store(true, Ordering::Relaxed);
        assert!(cache.is_valid());

        cache.invalidate();
        assert!(!cache.is_valid());
    }

    #[test]
    fn test_prompt_contains_expected_parts() {
        let config = test_config();
        let prompt = Prompt::new(&config);

        let rendered = prompt.render().unwrap();

        // Should contain user
        assert!(
            rendered.contains(&prompt.user),
            "Prompt should contain user"
        );

        // Should contain host
        assert!(
            rendered.contains(&prompt.host),
            "Prompt should contain host"
        );

        // Should contain $ or #
        assert!(
            rendered.contains('$') || rendered.contains('#'),
            "Prompt should contain char"
        );
    }

    #[test]
    fn test_prompt_with_git_cache() {
        let config = test_config();
        let mut prompt = Prompt::new(&config);

        // Update git cache
        prompt.update_git_cache(Some("feature-branch".to_string()), true);

        let rendered = prompt.render().unwrap();

        assert!(
            rendered.contains("(feature-branch*)"),
            "Prompt should show git status: {}",
            rendered
        );
    }

    #[test]
    fn test_prompt_render_is_o1() {
        // Create prompts with different segment counts
        let config1 = CompiledConfig {
            prompt_format: "{user}".to_string(),
            ..Default::default()
        };
        let config2 = CompiledConfig {
            prompt_format: "{user}@{host} {cwd} {git} {char}".to_string(),
            ..Default::default()
        };

        let prompt1 = Prompt::new(&config1);
        let prompt2 = Prompt::new(&config2);

        // Measure render time for simple prompt
        let start = Instant::now();
        for _ in 0..1000 {
            let _ = prompt1.render();
        }
        let time1 = start.elapsed();

        // Measure render time for complex prompt
        let start = Instant::now();
        for _ in 0..1000 {
            let _ = prompt2.render();
        }
        let time2 = start.elapsed();

        // Complex should be at most 20x slower under coverage (O(k) where k is small constant)
        // Note: variance is expected in micro-benchmarks, especially under coverage
        assert!(
            time2 < time1 * 20,
            "Complex prompt too slow: {:?} vs {:?}",
            time2,
            time1
        );
    }

    #[test]
    fn test_prompt_deterministic() {
        let config = test_config();
        let prompt = Prompt::new(&config);

        let render1 = prompt.render().unwrap();
        let render2 = prompt.render().unwrap();

        assert_eq!(render1, render2, "Prompt must be deterministic");
    }

    #[test]
    fn test_prompt_segment_count() {
        let config = test_config();
        let prompt = Prompt::new(&config);
        assert!(prompt.segment_count() > 0);
    }

    #[test]
    fn test_prompt_colors_enabled() {
        let config = test_config();
        let prompt = Prompt::new(&config);
        // colors_enabled depends on terminal support
        let _ = prompt.colors_enabled();
    }

    #[test]
    fn test_prompt_set_colors_enabled() {
        let config = test_config();
        let mut prompt = Prompt::new(&config);
        prompt.set_colors_enabled(false);
        assert!(!prompt.colors_enabled());
    }

    #[test]
    fn test_git_cache_new() {
        let cache = GitCache::new();
        assert!(cache.branch.is_none());
        assert!(!cache.dirty);
        assert!(!cache.is_valid());
    }

    #[test]
    fn test_git_cache_valid_flag() {
        let cache = GitCache::new();
        cache.valid.store(true, Ordering::Relaxed);
        assert!(cache.is_valid());
        cache.invalidate();
        assert!(!cache.is_valid());
    }

    #[test]
    fn test_git_cache_render_colored() {
        let mut cache = GitCache::new();

        // Empty renders empty
        assert_eq!(cache.render_colored(true), "");
        assert_eq!(cache.render_colored(false), "");

        // With branch - clean
        cache.branch = Some("main".to_string());
        let colored = cache.render_colored(true);
        let plain = cache.render_colored(false);
        assert!(colored.contains("main") || plain.contains("main"));
        assert_eq!(plain, "(main)");

        // With branch - dirty
        cache.dirty = true;
        let colored = cache.render_colored(true);
        let plain = cache.render_colored(false);
        assert!(colored.contains("main") || plain.contains("main"));
        assert_eq!(plain, "(main*)");
    }

    #[test]
    fn test_prompt_update_git_cache() {
        let config = test_config();
        let mut prompt = Prompt::new(&config);

        prompt.update_git_cache(Some("develop".to_string()), false);
        let rendered = prompt.render().unwrap();
        assert!(rendered.contains("(develop)"), "Should show clean branch");

        prompt.update_git_cache(Some("develop".to_string()), true);
        let rendered = prompt.render().unwrap();
        assert!(rendered.contains("(develop*)"), "Should show dirty branch");
    }

    #[test]
    fn test_prompt_invalidate_git_cache() {
        let config = test_config();
        let mut prompt = Prompt::new(&config);

        prompt.update_git_cache(Some("main".to_string()), false);
        assert!(prompt.git_cache.is_valid());

        prompt.invalidate_git_cache();
        assert!(!prompt.git_cache.is_valid());
    }

    #[test]
    fn test_parse_format_empty() {
        let segments = Prompt::parse_format("");
        assert!(segments.is_empty());
    }

    #[test]
    fn test_parse_format_literal_only() {
        let segments = Prompt::parse_format("hello world");
        assert_eq!(segments.len(), 1);
        assert!(matches!(segments[0], PromptSegment::Literal(ref s) if s == "hello world"));
    }

    #[test]
    fn test_parse_format_custom_segment() {
        let segments = Prompt::parse_format("{custom_thing}");
        assert_eq!(segments.len(), 1);
        assert!(matches!(segments[0], PromptSegment::Custom(ref s) if s == "custom_thing"));
    }

    #[test]
    fn test_prompt_custom_segment_render() {
        let mut config = CompiledConfig::default();
        config.prompt_format = "{custom} $ ".to_string();
        let prompt = Prompt::new(&config);
        let rendered = prompt.render().unwrap();
        assert!(rendered.contains("{custom}"));
    }

    #[test]
    fn test_prompt_segment_debug() {
        let segments = vec![
            PromptSegment::Literal("test".to_string()),
            PromptSegment::User,
            PromptSegment::Host,
            PromptSegment::Cwd,
            PromptSegment::Git,
            PromptSegment::Char,
            PromptSegment::Custom("x".to_string()),
        ];
        for seg in segments {
            let debug = format!("{:?}", seg);
            assert!(!debug.is_empty());
        }
    }

    #[test]
    fn test_prompt_segment_clone() {
        let seg = PromptSegment::Literal("test".to_string());
        let cloned = seg.clone();
        assert!(matches!(cloned, PromptSegment::Literal(ref s) if s == "test"));
    }

    #[test]
    fn test_git_cache_debug() {
        let cache = GitCache::new();
        let debug = format!("{:?}", cache);
        assert!(debug.contains("GitCache"));
    }

    #[test]
    fn test_git_cache_clone() {
        let mut cache = GitCache::new();
        cache.branch = Some("main".to_string());
        cache.dirty = true;
        let cloned = cache.clone();
        assert_eq!(cloned.branch, Some("main".to_string()));
        assert!(cloned.dirty);
    }

    #[test]
    fn test_git_cache_default() {
        let cache = GitCache::default();
        assert!(cache.branch.is_none());
        assert!(!cache.dirty);
    }

    #[test]
    fn test_prompt_debug() {
        let config = test_config();
        let prompt = Prompt::new(&config);
        let debug = format!("{:?}", prompt);
        assert!(debug.contains("Prompt"));
    }

    #[test]
    fn test_prompt_root_char() {
        let mut config = CompiledConfig::default();
        config.prompt_format = "{char}".to_string();
        config.colors_enabled = false;
        let prompt = Prompt::new(&config);

        let rendered = prompt.render().unwrap();
        // Non-root user should see $
        assert!(rendered.contains('$') || rendered.contains('#'));
    }

    #[test]
    fn test_prompt_all_segments() {
        let mut config = CompiledConfig::default();
        config.prompt_format = "{user}@{host}:{cwd} {git} {char} ".to_string();
        config.colors_enabled = false;
        let mut prompt = Prompt::new(&config);
        prompt.update_git_cache(Some("feature".to_string()), false);

        let rendered = prompt.render().unwrap();
        assert!(rendered.contains('@'));
        assert!(rendered.contains(':'));
        assert!(rendered.contains("(feature)"));
    }
}