Skip to main content

lockdocs_core/query/
workspace.rs

1//! Reuse engines by project root, lockfile state, and network policy.
2
3use super::{Engine, Options, Workspace};
4use std::path::Path;
5use std::sync::Arc;
6
7fn lock_stamp(root: &Path) -> u64 {
8    // Re-read the project when any lockfile in the root changes.
9    let mut h: u64 = 0;
10    if let Ok(rd) = std::fs::read_dir(root) {
11        for e in rd.flatten() {
12            let n = e.file_name().to_string_lossy().to_string();
13            if crate::lockfile::LOCKFILES.iter().any(|(f, _)| *f == n) || crate::lockfile::is_requirements(&n) || n == "package.json" || n == "pyproject.toml" {
14                if let Ok(m) = e.metadata() {
15                    let t = m
16                        .modified()
17                        .ok()
18                        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
19                        .map_or(0, |d| d.as_nanos() as u64);
20                    h = h.wrapping_mul(31).wrapping_add(t ^ m.len());
21                }
22            }
23        }
24    }
25    h
26}
27
28impl Workspace {
29    pub fn engine(&self, root: &Path, opts: &Options) -> Arc<Engine> {
30        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
31        let stamp = lock_stamp(&root);
32        let mut m = self.engines.lock().unwrap();
33        if let Some((s, e)) = m.get(&root) {
34            if *s == stamp && e.opts == *opts {
35                return e.clone();
36            }
37        }
38        let e = Arc::new(Engine::new(&root, opts.clone()));
39        m.insert(root, (stamp, e.clone()));
40        e
41    }
42}