Skip to main content

ridx_format/workspace/
discover.rs

1/*
2 * rust-intelligence — Ultra-fast, zero-memory code intelligence for Rust
3 * Copyright (c) 2026 Alexander Panasenko
4 *
5 * Contact: alex@prod.codes
6 * Author: https://prod.codes/about/
7 * Project: https://github.com/alex09x/rust-intelligence
8 * SPDX-License-Identifier: MIT OR Apache-2.0
9 */
10
11//! Manifest resolution, workspace auto-discovery, and bounded `.ridx` file collection.
12
13use super::{DependencyShardInfo, VariantManifest, WorkspaceIndex};
14use std::fs;
15use std::io;
16use std::path::{Path, PathBuf};
17
18pub(super) struct OpenManifestInfo {
19    pub path: PathBuf,
20    pub mtime: Option<std::time::SystemTime>,
21    pub len: Option<u64>,
22    pub ino: Option<u64>,
23    pub hash: Option<u64>,
24    pub generation: Option<u64>,
25    pub active_variant_id: String,
26    pub dependency_shards: Vec<DependencyShardInfo>,
27    pub workspace_root: Option<PathBuf>,
28    pub sysroot_cas_key: Option<String>,
29}
30
31fn manifest_file_meta(path: &Path, content: &[u8]) -> (Option<std::time::SystemTime>, Option<u64>, Option<u64>, Option<u64>) {
32    let meta = fs::metadata(path).ok();
33    let mtime = meta.as_ref().and_then(|m| m.modified().ok());
34    let len = meta.as_ref().map(|m| m.len());
35    #[cfg(unix)]
36    let ino = meta.as_ref().map(|m| {
37        use std::os::unix::fs::MetadataExt;
38        m.ino()
39    });
40    #[cfg(not(unix))]
41    let ino: Option<u64> = None;
42    let hash = Some(crate::format::normalized_source_hash(content));
43    (mtime, len, ino, hash)
44}
45
46impl WorkspaceIndex {
47    pub(super) fn resolve_open_manifest(search_dir: &Path) -> io::Result<(PathBuf, Option<OpenManifestInfo>)> {
48        let manifest_file = search_dir.join("ridx_manifest.json");
49        let res = if manifest_file.is_file() {
50            let content = fs::read(&manifest_file)?;
51            let manifest = serde_json::from_slice::<VariantManifest>(&content)
52                .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("Failed to parse variant manifest {:?}: {e}", manifest_file)))?;
53
54            let (mtime, len, ino, hash) = manifest_file_meta(&manifest_file, &content);
55            if !manifest.active_variant_id.is_empty() {
56                let expected_variant_dir = format!("variants/{}", manifest.active_variant_id);
57                let vdir_str = manifest.variant_dir.trim();
58                let vpath = Path::new(vdir_str);
59                if vdir_str.is_empty()
60                    || vpath.is_absolute()
61                    || vpath.components().any(|c| c == std::path::Component::ParentDir)
62                    || vpath == Path::new(".")
63                    || vdir_str != expected_variant_dir
64                {
65                    return Err(io::Error::new(
66                        io::ErrorKind::InvalidData,
67                        format!(
68                            "Active variant manifest {:?} specifies variant_dir {:?} which does not match active_variant_id {:?} (expected {:?})",
69                            manifest_file, manifest.variant_dir, manifest.active_variant_id, expected_variant_dir
70                        ),
71                    ));
72                }
73
74                let vdir = search_dir.join(&expected_variant_dir);
75                if vdir == search_dir || !vdir.is_dir() {
76                    return Err(io::Error::new(
77                        io::ErrorKind::NotFound,
78                        format!("Active variant directory {:?} specified in {:?} does not exist. Run 'ridx index' to build this variant.", vdir, manifest_file),
79                    ));
80                }
81
82                if !crate::format::is_readable_format_version(manifest.format_version) {
83                    return Err(io::Error::new(
84                        io::ErrorKind::InvalidData,
85                        format!(
86                            "Format version mismatch in manifest {:?}: format_version {} != current {}",
87                            manifest_file,
88                            manifest.format_version,
89                            crate::format::CURRENT_FORMAT_VERSION
90                        ),
91                    ));
92                }
93
94                match manifest.extractor_version.as_deref() {
95                    Some(ver) if ver == crate::format::EXTRACTOR_VERSION => {}
96                    Some(ver) => {
97                        return Err(io::Error::new(
98                            io::ErrorKind::InvalidData,
99                            format!("Extractor version mismatch in manifest {:?}: extractor_version {} != current {}", manifest_file, ver, crate::format::EXTRACTOR_VERSION),
100                        ));
101                    }
102                    None => {
103                        return Err(io::Error::new(io::ErrorKind::InvalidData, format!("Extractor version missing in manifest {:?}", manifest_file)));
104                    }
105                }
106
107                (
108                    vdir,
109                    Some(OpenManifestInfo {
110                        path: manifest_file,
111                        mtime,
112                        len,
113                        ino,
114                        hash,
115                        generation: Some(manifest.generation),
116                        active_variant_id: manifest.active_variant_id,
117                        dependency_shards: manifest.dependency_shards,
118                        workspace_root: if !manifest.workspace_root.is_empty() { Some(PathBuf::from(manifest.workspace_root)) } else { None },
119                        sysroot_cas_key: manifest.sysroot_cas_key,
120                    }),
121                )
122            } else {
123                // Legacy manifest without active_variant_id: scan search_dir directly
124                (search_dir.to_path_buf(), None)
125            }
126        } else if search_dir.join("variant_manifest.json").is_file() {
127            let v_manifest_file = search_dir.join("variant_manifest.json");
128            let content = fs::read(&v_manifest_file)?;
129            let manifest = serde_json::from_slice::<VariantManifest>(&content)
130                .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("Failed to parse variant manifest {:?}: {e}", v_manifest_file)))?;
131            let (mtime, len, ino, hash) = manifest_file_meta(&v_manifest_file, &content);
132            if !crate::format::is_readable_format_version(manifest.format_version) {
133                return Err(io::Error::new(
134                    io::ErrorKind::InvalidData,
135                    format!(
136                        "Format version mismatch in manifest {:?}: format_version {} != current {}",
137                        v_manifest_file,
138                        manifest.format_version,
139                        crate::format::CURRENT_FORMAT_VERSION
140                    ),
141                ));
142            }
143            match manifest.extractor_version.as_deref() {
144                Some(ver) if ver == crate::format::EXTRACTOR_VERSION => {}
145                Some(ver) => {
146                    return Err(io::Error::new(
147                        io::ErrorKind::InvalidData,
148                        format!("Extractor version mismatch in manifest {:?}: extractor_version {} != current {}", v_manifest_file, ver, crate::format::EXTRACTOR_VERSION),
149                    ));
150                }
151                None => {
152                    return Err(io::Error::new(io::ErrorKind::InvalidData, format!("Extractor version missing in manifest {:?}", v_manifest_file)));
153                }
154            }
155            (
156                search_dir.to_path_buf(),
157                Some(OpenManifestInfo {
158                    path: v_manifest_file,
159                    mtime,
160                    len,
161                    ino,
162                    hash,
163                    generation: Some(manifest.generation),
164                    active_variant_id: manifest.active_variant_id,
165                    dependency_shards: manifest.dependency_shards,
166                    workspace_root: if !manifest.workspace_root.is_empty() { Some(PathBuf::from(manifest.workspace_root)) } else { None },
167                    sysroot_cas_key: manifest.sysroot_cas_key,
168                }),
169            )
170        } else {
171            (search_dir.to_path_buf(), None)
172        };
173        Ok(res)
174    }
175
176    /// Auto-discovers .ridx indices starting from current directory up to root or target/ridx.
177    pub fn auto_discover() -> io::Result<Self> {
178        let cur = std::env::current_dir()?;
179        Self::auto_discover_with(std::env::var("RIDX_INDEX_DIR").ok().as_deref(), &cur)
180    }
181
182    /// Auto-discovers .ridx indices using explicit environment and working directory parameters.
183    pub fn auto_discover_with(index_dir_env: Option<&str>, cur: &Path) -> io::Result<Self> {
184        if let Some(dir) = index_dir_env {
185            let p = PathBuf::from(dir);
186            if p.exists() {
187                return Self::open(p);
188            }
189        }
190
191        let mut candidates = vec![cur.join("target/ridx"), cur.join("../target/ridx")];
192        let mut nearest_pkg = None;
193        let mut enclosing_ws = None;
194        for anc in cur.ancestors() {
195            let cargo_toml = anc.join("Cargo.toml");
196            if cargo_toml.is_file() {
197                if nearest_pkg.is_none() {
198                    nearest_pkg = Some(anc.to_path_buf());
199                }
200                if let Ok(content) = fs::read_to_string(&cargo_toml) {
201                    if content.contains("[workspace]") {
202                        enclosing_ws = Some(anc.to_path_buf());
203                        break;
204                    }
205                }
206            }
207        }
208        if let Some(ws_root) = enclosing_ws.or(nearest_pkg) {
209            let ws_target = ws_root.join("target/ridx");
210            if !candidates.contains(&ws_target) {
211                candidates.push(ws_target);
212            }
213        }
214
215        let has_ridx_indicators = cur.join("ridx_manifest.json").is_file()
216            || cur.join("variant_manifest.json").is_file()
217            || fs::read_dir(cur).ok().map(|mut rd| rd.any(|e| e.map(|e| e.path().extension().is_some_and(|ext| ext == "ridx")).unwrap_or(false))).unwrap_or(false);
218        if has_ridx_indicators {
219            candidates.push(cur.to_path_buf());
220        }
221
222        for cand in candidates {
223            if cand.is_dir() {
224                if let Ok(ws) = Self::open(&cand) {
225                    return Ok(ws);
226                }
227            }
228        }
229
230        Err(io::Error::new(io::ErrorKind::NotFound, "Could not auto-discover target/ridx directory. Specify index path explicitly."))
231    }
232}
233
234pub(crate) fn collect_ridx_files(dir: &Path, files: &mut Vec<PathBuf>) -> io::Result<()> {
235    collect_ridx_files_bounded(dir, files, 0, 2)
236}
237
238fn collect_ridx_files_bounded(dir: &Path, files: &mut Vec<PathBuf>, depth: usize, max_depth: usize) -> io::Result<()> {
239    if depth > max_depth {
240        return Ok(());
241    }
242    for entry in fs::read_dir(dir)? {
243        let entry = entry?;
244        let p = entry.path();
245        if p.is_file() {
246            if p.extension().is_some_and(|ext| ext == "ridx") {
247                files.push(p);
248            }
249        } else if p.is_dir() {
250            if let Some(name) = p.file_name().and_then(|s| s.to_str()) {
251                if name.starts_with('.') || name == "variants" || name == "target" || name == "node_modules" || name == "vendor" {
252                    continue;
253                }
254            }
255            let _ = collect_ridx_files_bounded(&p, files, depth + 1, max_depth);
256        }
257    }
258    Ok(())
259}