Skip to main content

zsh/extensions/
compinit_bg.rs

1//! Background compinit pre-warm — extension; no zsh C counterpart.
2use crate::compsys::cache::CompsysCache;
3use crate::compsys::CompInitResult;
4#[allow(unused_imports)]
5use crate::ported::vm_helper::ShellExecutor;
6#[allow(unused_imports)]
7use std::{collections::HashMap, env, path::PathBuf};
8
9/// Result from background compinit thread.
10/// Outcome of background `compinit` autoload.
11/// zshrs-original — Src/Modules/complete.c blocks on `compinit`
12/// inline. The Rust port runs it on the worker pool.
13pub struct CompInitBgResult {
14    /// `result` field.
15    pub result: CompInitResult,
16    /// `cache` field.
17    pub cache: CompsysCache,
18}
19
20// ===========================================================
21// Methods moved verbatim from src/ported/vm_helper because their
22// C counterpart's source file maps 1:1 to this Rust module.
23// Phase: drift
24// ===========================================================
25
26// BEGIN moved-from-exec-rs
27impl crate::ported::vm_helper::ShellExecutor {
28    /// Non-blocking drain of background compinit results.
29    /// Call this before any completion lookup (prompt, tab-complete, etc.).
30    /// If the background thread hasn't finished yet, this is a no-op.
31    pub fn drain_compinit_bg(&mut self) {
32        tracing::debug!(target: "compsys_args", pending = self.compinit_pending.is_some(), "drain_compinit_bg ENTER");
33        if let Some((rx, start)) = self.compinit_pending.take() {
34            match rx.try_recv() {
35                Ok(bg) => {
36                    let comps = bg.result.comps.len();
37                    // `#compdef -k`/`-K` header bindings — must run on the
38                    // shell thread (dispatches zle -C + bindkey).
39                    crate::compsys::ported::compinit::apply_keybindings(&bg.result);
40                    self.set_assoc("_comps".to_string(), bg.result.comps.into_iter().collect());
41                    self.set_assoc(
42                        "_services".to_string(),
43                        bg.result.services.into_iter().collect(),
44                    );
45                    self.set_assoc(
46                        "_patcomps".to_string(),
47                        bg.result.patcomps.into_iter().collect(),
48                    );
49                    self.compsys_cache = Some(bg.cache);
50                    tracing::info!(
51                        wall_ms = start.elapsed().as_millis() as u64,
52                        comps,
53                        "compinit: background results merged"
54                    );
55                }
56                Err(std::sync::mpsc::TryRecvError::Empty) => {
57                    // Not ready yet — put the receiver back for next poll
58                    self.compinit_pending = Some((rx, start));
59                }
60                Err(std::sync::mpsc::TryRecvError::Disconnected) => {
61                    tracing::warn!("compinit: background thread died without sending results");
62                }
63            }
64        }
65    }
66    /// Traditional zsh compinit (--zsh-compat mode)
67    /// Uses fpath scanning, .zcompdump files, no SQLite
68    pub(crate) fn compinit_compat(
69        &mut self,
70        quiet: bool,
71        no_dump: bool,
72        dump_file: Option<String>,
73        use_cache: bool,
74    ) -> i32 {
75        let zdotdir = self
76            .scalar("ZDOTDIR")
77            .or_else(|| std::env::var("ZDOTDIR").ok())
78            .unwrap_or_else(|| std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string()));
79
80        let dump_path = dump_file
81            .map(PathBuf::from)
82            .unwrap_or_else(|| PathBuf::from(&zdotdir).join(".zcompdump"));
83
84        // -C: Try to use existing .zcompdump if valid
85        if use_cache
86            && dump_path.exists()
87            && crate::compsys::check_dump(&dump_path, &self.fpath, "zshrs-0.1.0")
88        {
89            // Valid dump - source it to load _comps
90            // For now, just rescan (proper impl would source the dump file)
91            if !quiet {
92                tracing::info!("compinit: .zcompdump valid, rescanning for compat");
93            }
94        }
95
96        // Full fpath scan (traditional zsh algorithm)
97        let result = crate::compsys::compinit(&self.fpath);
98
99        if !quiet {
100            tracing::info!(
101                functions = result.files_scanned,
102                comps = result.comps.len(),
103                dirs = result.dirs_scanned,
104                ms = result.scan_time_ms,
105                "compinit: fpath scan complete"
106            );
107        }
108
109        // Write .zcompdump unless -D
110        if !no_dump {
111            let _ = crate::compsys::compdump(&result, &dump_path, "zshrs-0.1.0");
112        }
113
114        // Set up _comps associative array
115        self.set_assoc(
116            "_comps".to_string(),
117            result.comps.clone().into_iter().collect(),
118        );
119        self.set_assoc(
120            "_services".to_string(),
121            result.services.clone().into_iter().collect(),
122        );
123        self.set_assoc(
124            "_patcomps".to_string(),
125            result.patcomps.clone().into_iter().collect(),
126        );
127
128        // `#compdef -k`/`-K` header bindings (^X? _complete_debug,
129        // ^Xh _complete_help, …) — the in-shell half of the scan.
130        crate::compsys::ported::compinit::apply_keybindings(&result);
131
132        // No SQLite cache in compat mode
133        self.compsys_cache = None;
134
135        0
136    }
137}
138// END moved-from-exec-rs