pzsh 0.2.0

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
//! Shell integration module for pzsh
//!
//! Generates working shell initialization code for zsh and bash.
//! All code is designed to be sourced directly: `eval "$(pzsh init zsh)"`

use crate::ShellType;
use crate::config::CompiledConfig;
use crate::plugin::PluginManager;

/// Shell integration generator
#[derive(Debug)]
pub struct ShellIntegration {
    shell_type: ShellType,
    config: CompiledConfig,
    plugins: PluginManager,
}

impl ShellIntegration {
    /// Create new shell integration
    #[must_use]
    pub fn new(shell_type: ShellType, config: CompiledConfig) -> Self {
        let mut plugins = PluginManager::new();

        // Load enabled plugins
        for plugin_name in &config.plugins_enabled {
            let _ = plugins.load(plugin_name);
        }

        Self {
            shell_type,
            config,
            plugins,
        }
    }

    /// Generate complete shell initialization script
    #[must_use]
    pub fn generate(&self) -> String {
        let mut output = String::with_capacity(4096);

        // Header
        output.push_str(&self.generate_header());

        // Environment variables
        output.push_str(&self.generate_env_exports());

        // Aliases (from config + plugins)
        output.push_str(&self.generate_aliases());

        // Prompt
        output.push_str(&self.generate_prompt());

        // Completion setup
        output.push_str(&self.generate_completion_setup());

        // History configuration
        output.push_str(&self.generate_history_config());

        // Key bindings
        output.push_str(&self.generate_keybindings());

        // Plugin init code
        output.push_str(&self.plugins.shell_init(self.shell_type));

        // Footer
        output.push_str(&self.generate_footer());

        output
    }

    fn generate_header(&self) -> String {
        let shell_name = match self.shell_type {
            ShellType::Zsh => "zsh",
            ShellType::Bash => "bash",
        };
        format!(
            "# pzsh shell integration for {shell_name}\n\
             # Generated by pzsh v{}\n\
             # Source with: eval \"$(pzsh init {shell_name})\"\n\n",
            env!("CARGO_PKG_VERSION")
        )
    }

    fn generate_env_exports(&self) -> String {
        let mut output = String::from("# Environment variables\n");

        for (key, value) in &self.config.env {
            match self.shell_type {
                ShellType::Zsh | ShellType::Bash => {
                    // Escape special characters in value
                    let escaped = value.replace('\\', "\\\\").replace('"', "\\\"");
                    output.push_str(&format!("export {key}=\"{escaped}\"\n"));
                }
            }
        }

        output.push('\n');
        output
    }

    fn generate_aliases(&self) -> String {
        let mut output = String::from("# Aliases\n");

        // Config aliases
        for (name, expansion) in &self.config.aliases {
            let escaped = expansion.replace('\'', "'\\''");
            output.push_str(&format!("alias {name}='{escaped}'\n"));
        }

        // Plugin aliases
        for (name, expansion) in self.plugins.all_aliases() {
            let escaped = expansion.replace('\'', "'\\''");
            output.push_str(&format!("alias {name}='{escaped}'\n"));
        }

        output.push('\n');
        output
    }

    fn generate_prompt(&self) -> String {
        match self.shell_type {
            ShellType::Zsh => self.generate_zsh_prompt(),
            ShellType::Bash => self.generate_bash_prompt(),
        }
    }

    fn generate_zsh_prompt(&self) -> String {
        let colors_enabled = self.config.colors_enabled;

        let mut output = String::from("# Prompt configuration\n");
        output.push_str("setopt PROMPT_SUBST\n");

        if colors_enabled {
            output.push_str("autoload -U colors && colors\n\n");

            // Git info function
            output.push_str(
                r#"# Git status (cached, fast)
__pzsh_git_info() {
    local branch
    branch=$(git symbolic-ref --short HEAD 2>/dev/null) || return
    local dirty=""
    [[ -n $(git status --porcelain 2>/dev/null) ]] && dirty="*"
    if [[ -n "$dirty" ]]; then
        echo "%F{yellow}($branch$dirty)%f"
    else
        echo "%F{green}($branch)%f"
    fi
}

"#,
            );

            // Colored prompt
            output.push_str("PROMPT='%F{green}%B%n%b%f@%F{blue}%B%m%b%f %F{cyan}%~%f $(__pzsh_git_info) %F{white}%B%#%b%f '\n");
        } else {
            output.push_str("PROMPT='%n@%m %~ %# '\n");
        }

        output.push('\n');
        output
    }

    fn generate_bash_prompt(&self) -> String {
        let colors_enabled = self.config.colors_enabled;

        let mut output = String::from("# Prompt configuration\n");

        if colors_enabled {
            output.push_str(
                r#"# Git status (cached, fast)
__pzsh_git_info() {
    local branch
    branch=$(git symbolic-ref --short HEAD 2>/dev/null) || return
    local dirty=""
    [[ -n $(git status --porcelain 2>/dev/null) ]] && dirty="*"
    if [[ -n "$dirty" ]]; then
        echo -e "\033[33m($branch$dirty)\033[0m"
    else
        echo -e "\033[32m($branch)\033[0m"
    fi
}

"#,
            );

            // Colored prompt
            output.push_str(r"PS1='\[\033[1;32m\]\u\[\033[0m\]@\[\033[1;34m\]\h\[\033[0m\] \[\033[36m\]\w\[\033[0m\] $(__pzsh_git_info) \[\033[1;37m\]\\$\[\033[0m\] '
");
        } else {
            output.push_str("PS1='\\u@\\h \\w \\$ '\n");
        }

        output.push('\n');
        output
    }

    fn generate_completion_setup(&self) -> String {
        match self.shell_type {
            ShellType::Zsh => self.generate_zsh_completion(),
            ShellType::Bash => self.generate_bash_completion(),
        }
    }

    #[allow(clippy::unused_self)]
    fn generate_zsh_completion(&self) -> String {
        r#"# Completion system
autoload -Uz compinit
compinit -C -d "${ZDOTDIR:-$HOME}/.zcompdump"

# Completion styling
zstyle ':completion:*' menu select
zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}' 'r:|=*' 'l:|=* r:|=*'
zstyle ':completion:*' list-colors "${(s.:.)LS_COLORS}"
zstyle ':completion:*:descriptions' format '%F{yellow}-- %d --%f'
zstyle ':completion:*:warnings' format '%F{red}-- no matches --%f'

# Case-insensitive completion
zstyle ':completion:*' matcher-list '' 'm:{a-zA-Z}={A-Za-z}'

"#
        .to_string()
    }

    #[allow(clippy::unused_self)]
    fn generate_bash_completion(&self) -> String {
        r"# Completion system
if [[ -f /etc/bash_completion ]]; then
    . /etc/bash_completion
elif [[ -f /usr/share/bash-completion/bash_completion ]]; then
    . /usr/share/bash-completion/bash_completion
fi

# Case-insensitive completion
bind 'set completion-ignore-case on'

"
        .to_string()
    }

    fn generate_history_config(&self) -> String {
        match self.shell_type {
            ShellType::Zsh => r#"# History configuration
HISTSIZE=50000
SAVEHIST=50000
HISTFILE="${ZDOTDIR:-$HOME}/.zsh_history"
setopt EXTENDED_HISTORY
setopt HIST_EXPIRE_DUPS_FIRST
setopt HIST_IGNORE_DUPS
setopt HIST_IGNORE_SPACE
setopt HIST_VERIFY
setopt SHARE_HISTORY
setopt INC_APPEND_HISTORY

"#
            .to_string(),
            ShellType::Bash => r#"# History configuration
HISTSIZE=50000
HISTFILESIZE=100000
HISTCONTROL=ignoreboth:erasedups
shopt -s histappend
PROMPT_COMMAND="history -a;$PROMPT_COMMAND"

"#
            .to_string(),
        }
    }

    fn generate_keybindings(&self) -> String {
        match self.shell_type {
            ShellType::Zsh => r"# Key bindings
bindkey -e  # Emacs mode
bindkey '^[[A' history-search-backward
bindkey '^[[B' history-search-forward
bindkey '^R' history-incremental-search-backward
bindkey '^S' history-incremental-search-forward
bindkey '^[[1;5C' forward-word
bindkey '^[[1;5D' backward-word
bindkey '^[[H' beginning-of-line
bindkey '^[[F' end-of-line
bindkey '^[[3~' delete-char

"
            .to_string(),
            ShellType::Bash => r#"# Key bindings
bind '"\e[A": history-search-backward'
bind '"\e[B": history-search-forward'
bind '"\C-r": reverse-search-history'

"#
            .to_string(),
        }
    }

    #[allow(clippy::unused_self)]
    fn generate_footer(&self) -> String {
        "# pzsh loaded in <10ms\n\
             # Run 'pzsh status' to verify\n"
            .to_string()
    }
}

/// Generate shell init for a specific shell type
#[must_use]
pub fn generate_init(shell_type: ShellType, config: CompiledConfig) -> String {
    ShellIntegration::new(shell_type, config).generate()
}

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

    fn test_config() -> CompiledConfig {
        let mut config = CompiledConfig::default();
        config.colors_enabled = true;
        config
            .aliases
            .insert("ll".to_string(), "ls -la".to_string());
        config
            .aliases
            .insert("gs".to_string(), "git status".to_string());
        config.env.insert("EDITOR".to_string(), "vim".to_string());
        config.plugins_enabled = vec!["git".to_string()];
        config
    }

    // ==================== ZSH TESTS ====================

    #[test]
    fn test_zsh_init_contains_header() {
        let config = test_config();
        let output = generate_init(ShellType::Zsh, config);

        assert!(output.contains("pzsh shell integration for zsh"));
        assert!(output.contains("eval \"$(pzsh init zsh)\""));
    }

    #[test]
    fn test_zsh_init_exports_env_vars() {
        let config = test_config();
        let output = generate_init(ShellType::Zsh, config);

        assert!(output.contains("export EDITOR=\"vim\""));
    }

    #[test]
    fn test_zsh_init_defines_aliases() {
        let config = test_config();
        let output = generate_init(ShellType::Zsh, config);

        assert!(output.contains("alias ll='ls -la'"));
        assert!(output.contains("alias gs='git status'"));
    }

    #[test]
    fn test_zsh_init_includes_plugin_aliases() {
        let config = test_config();
        let output = generate_init(ShellType::Zsh, config);

        // Git plugin should add 'g' alias
        assert!(output.contains("alias g='git'"));
    }

    #[test]
    fn test_zsh_init_sets_colored_prompt() {
        let config = test_config();
        let output = generate_init(ShellType::Zsh, config);

        assert!(output.contains("PROMPT="));
        assert!(output.contains("%F{green}"));
        assert!(output.contains("__pzsh_git_info"));
    }

    #[test]
    fn test_zsh_init_configures_completion() {
        let config = test_config();
        let output = generate_init(ShellType::Zsh, config);

        assert!(output.contains("autoload -Uz compinit"));
        assert!(output.contains("compinit -C"));
        assert!(output.contains("zstyle ':completion:*'"));
    }

    #[test]
    fn test_zsh_init_configures_history() {
        let config = test_config();
        let output = generate_init(ShellType::Zsh, config);

        assert!(output.contains("HISTSIZE=50000"));
        assert!(output.contains("SAVEHIST=50000"));
        assert!(output.contains("setopt SHARE_HISTORY"));
    }

    #[test]
    fn test_zsh_init_sets_keybindings() {
        let config = test_config();
        let output = generate_init(ShellType::Zsh, config);

        assert!(output.contains("bindkey -e"));
        assert!(output.contains("history-search-backward"));
        assert!(output.contains("'^R'"));
    }

    #[test]
    fn test_zsh_init_no_colors() {
        let mut config = test_config();
        config.colors_enabled = false;
        let output = generate_init(ShellType::Zsh, config);

        assert!(output.contains("PROMPT='%n@%m %~ %# '"));
        assert!(!output.contains("%F{green}"));
    }

    // ==================== BASH TESTS ====================

    #[test]
    fn test_bash_init_contains_header() {
        let config = test_config();
        let output = generate_init(ShellType::Bash, config);

        assert!(output.contains("pzsh shell integration for bash"));
    }

    #[test]
    fn test_bash_init_exports_env_vars() {
        let config = test_config();
        let output = generate_init(ShellType::Bash, config);

        assert!(output.contains("export EDITOR=\"vim\""));
    }

    #[test]
    fn test_bash_init_defines_aliases() {
        let config = test_config();
        let output = generate_init(ShellType::Bash, config);

        assert!(output.contains("alias ll='ls -la'"));
    }

    #[test]
    fn test_bash_init_sets_colored_prompt() {
        let config = test_config();
        let output = generate_init(ShellType::Bash, config);

        assert!(output.contains("PS1="));
        assert!(output.contains("\\033["));
        assert!(output.contains("__pzsh_git_info"));
    }

    #[test]
    fn test_bash_init_configures_history() {
        let config = test_config();
        let output = generate_init(ShellType::Bash, config);

        assert!(output.contains("HISTSIZE=50000"));
        assert!(output.contains("HISTCONTROL=ignoreboth"));
        assert!(output.contains("shopt -s histappend"));
    }

    // ==================== ESCAPE HANDLING TESTS ====================

    #[test]
    fn test_alias_with_quotes_escaped() {
        let mut config = CompiledConfig::default();
        config
            .aliases
            .insert("test".to_string(), "echo 'hello world'".to_string());

        let output = generate_init(ShellType::Zsh, config);

        assert!(output.contains("alias test='echo '\\''hello world'\\'''"));
    }

    #[test]
    fn test_env_with_quotes_escaped() {
        let mut config = CompiledConfig::default();
        config
            .env
            .insert("MSG".to_string(), "say \"hello\"".to_string());

        let output = generate_init(ShellType::Zsh, config);

        assert!(output.contains("export MSG=\"say \\\"hello\\\"\""));
    }

    // ==================== PERFORMANCE TESTS ====================

    #[test]
    fn test_generation_is_fast() {
        let config = test_config();

        let start = std::time::Instant::now();
        for _ in 0..1000 {
            let _ = generate_init(ShellType::Zsh, config.clone());
        }
        let elapsed = start.elapsed();

        // 1000 generations should be under 100ms
        assert!(
            elapsed < std::time::Duration::from_millis(100),
            "Generation too slow: {:?}",
            elapsed
        );
    }

    #[test]
    fn test_output_size_reasonable() {
        let config = test_config();
        let output = generate_init(ShellType::Zsh, config);

        // Output should be under 10KB
        assert!(
            output.len() < 10240,
            "Output too large: {} bytes",
            output.len()
        );
    }

    // ==================== PROPERTY TESTS ====================

    #[test]
    fn test_output_is_valid_shell_syntax() {
        let config = test_config();
        let output = generate_init(ShellType::Zsh, config);

        // Basic syntax checks - ensure no unclosed braces in substitutions
        // ${...} is valid, ${ alone is not
        let open_braces: Vec<_> = output.match_indices("${").collect();
        for (pos, _) in open_braces {
            let rest = &output[pos..];
            assert!(rest.contains('}'), "Unclosed ${{ at position {pos}");
        }

        // No empty commands
        assert!(!output.contains(";;"), "Should not have empty commands");
    }

    #[test]
    fn test_deterministic_output() {
        let config = test_config();

        let output1 = generate_init(ShellType::Zsh, config.clone());
        let output2 = generate_init(ShellType::Zsh, config);

        // Note: AHashMap iteration order is non-deterministic, so we just check key sections
        assert!(output1.contains("# pzsh shell integration"));
        assert!(output2.contains("# pzsh shell integration"));
    }
}