bv-index 0.1.37

Registry index trait and Git-backed implementation for biov
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
use std::fs;
use std::path::PathBuf;
use std::process::{Command, Stdio};

use bv_core::data::DataManifest;
use bv_core::error::{BvError, Result};
use bv_core::manifest::Manifest;
use semver::{Version, VersionReq};

use crate::backend::{IndexBackend, ToolSummary};

pub struct GitIndex {
    pub url: String,
    pub local_path: PathBuf,
}

impl GitIndex {
    pub fn new(url: impl Into<String>, local_path: impl Into<PathBuf>) -> Self {
        Self {
            url: url.into(),
            local_path: local_path.into(),
        }
    }

    /// Refresh only if the local clone is older than `ttl`.
    /// Returns `true` when an actual network fetch was performed.
    pub fn refresh_if_stale(&self, ttl: std::time::Duration) -> Result<bool> {
        let stamp = self.local_path.join(".bv-refresh");
        let is_fresh = stamp
            .metadata()
            .and_then(|m| m.modified())
            .ok()
            .and_then(|t| t.elapsed().ok())
            .map(|elapsed| elapsed < ttl)
            .unwrap_or(false);

        if is_fresh {
            return Ok(false);
        }

        self.git_refresh()?;
        self.touch_stamp();
        Ok(true)
    }

    /// True when the local clone exists and has been fetched at least once.
    pub fn is_available(&self) -> bool {
        self.local_path.join(".bv-refresh").exists() || self.local_path.join(".git").exists()
    }

    /// Path to the local clone of this registry.
    pub fn local_path(&self) -> &std::path::Path {
        &self.local_path
    }

    fn git_refresh(&self) -> Result<()> {
        if self.local_path.exists() {
            // Re-point the remote if the cached clone is from a different URL.
            // This handles users who had the old default registry cloned.
            self.maybe_update_remote()?;

            let out = Command::new("git")
                .args([
                    "-C",
                    &self.local_path.to_string_lossy(),
                    "pull",
                    "--ff-only",
                ])
                .env("GIT_TERMINAL_PROMPT", "0")
                .stdin(Stdio::null())
                .stdout(Stdio::null())
                .stderr(Stdio::piped())
                .output()?;
            if !out.status.success() {
                let msg = String::from_utf8_lossy(&out.stderr);
                return Err(BvError::IndexError(format!(
                    "git pull failed in {}: {}",
                    self.local_path.display(),
                    msg.trim()
                )));
            }
        } else {
            if let Some(parent) = self.local_path.parent() {
                fs::create_dir_all(parent)?;
            }
            let out = Command::new("git")
                .args([
                    "clone",
                    "--depth",
                    "1",
                    &self.url,
                    &self.local_path.to_string_lossy(),
                ])
                .env("GIT_TERMINAL_PROMPT", "0")
                .stdin(Stdio::null())
                .stdout(Stdio::null())
                .stderr(Stdio::piped())
                .output()?;
            if !out.status.success() {
                let msg = String::from_utf8_lossy(&out.stderr);
                return Err(BvError::IndexError(format!(
                    "git clone failed for '{}': {}",
                    self.url,
                    msg.trim()
                )));
            }
        }
        Ok(())
    }

    /// If the existing clone's remote URL doesn't match `self.url`, update it.
    fn maybe_update_remote(&self) -> Result<()> {
        let out = Command::new("git")
            .args([
                "-C",
                &self.local_path.to_string_lossy(),
                "remote",
                "get-url",
                "origin",
            ])
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .output()?;

        let current = String::from_utf8_lossy(&out.stdout).trim().to_string();
        if current != self.url {
            Command::new("git")
                .args([
                    "-C",
                    &self.local_path.to_string_lossy(),
                    "remote",
                    "set-url",
                    "origin",
                    &self.url,
                ])
                .stdin(Stdio::null())
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .status()?;
        }
        Ok(())
    }

    fn touch_stamp(&self) {
        let stamp = self.local_path.join(".bv-refresh");
        let _ = fs::write(&stamp, "");
    }
}

impl IndexBackend for GitIndex {
    fn name(&self) -> &str {
        "git"
    }

    fn refresh(&self) -> Result<()> {
        self.git_refresh()?;
        self.touch_stamp();
        Ok(())
    }

    fn get_manifest(&self, tool: &str, version: &VersionReq) -> Result<Manifest> {
        let tool_dir = self.local_path.join("tools").join(tool);
        if !tool_dir.exists() {
            return Err(BvError::IndexError(format!(
                "tool '{tool}' not found in registry"
            )));
        }

        let versions = self.list_versions(tool)?;
        if versions.is_empty() {
            return Err(BvError::IndexError(format!(
                "no versions of '{tool}' found in registry"
            )));
        }

        let best = versions
            .iter()
            .filter(|v| version.matches(v))
            .max()
            .ok_or_else(|| {
                BvError::IndexError(format!(
                    "no version of '{tool}' satisfies '{version}' (available: {})",
                    versions
                        .iter()
                        .map(|v| v.to_string())
                        .collect::<Vec<_>>()
                        .join(", ")
                ))
            })?;

        let manifest_path = tool_dir.join(format!("{best}.toml"));
        let s = fs::read_to_string(&manifest_path).map_err(|e| {
            BvError::IndexError(format!("could not read manifest for '{tool}@{best}': {e}"))
        })?;

        Manifest::from_toml_str(&s)
    }

    fn list_versions(&self, tool: &str) -> Result<Vec<Version>> {
        let tool_dir = self.local_path.join("tools").join(tool);
        if !tool_dir.exists() {
            return Err(BvError::IndexError(format!(
                "tool '{tool}' not found in registry"
            )));
        }

        let mut versions = Vec::new();
        let mut dropped: Vec<String> = Vec::new();
        for entry in fs::read_dir(&tool_dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.extension().is_some_and(|e| e == "toml")
                && let Some(stem) = path.file_stem().and_then(|s| s.to_str())
            {
                match stem.parse::<Version>() {
                    Ok(v) => versions.push(v),
                    Err(_) => dropped.push(stem.to_string()),
                }
            }
        }

        if !dropped.is_empty() {
            tracing::warn!(
                tool = %tool,
                dropped = ?dropped,
                "ignoring tool manifest files with non-semver names (expected MAJOR.MINOR.PATCH; \
                 calver like 2024.01.0 is not valid semver)"
            );
        }

        versions.sort();
        Ok(versions)
    }

    fn list_tools(&self) -> Result<Vec<ToolSummary>> {
        let tools_dir = self.local_path.join("tools");
        if !tools_dir.exists() {
            return Ok(vec![]);
        }

        let mut tools = Vec::new();
        for entry in fs::read_dir(&tools_dir)? {
            let entry = entry?;
            if !entry.file_type()?.is_dir() {
                continue;
            }

            let id = entry.file_name().to_string_lossy().to_string();
            let versions = self.list_versions(&id).unwrap_or_default();

            let latest_manifest = versions.last().and_then(|v| {
                let p = tools_dir.join(&id).join(format!("{v}.toml"));
                fs::read_to_string(p)
                    .ok()
                    .and_then(|s| Manifest::from_toml_str(&s).ok())
            });

            let description = latest_manifest
                .as_ref()
                .and_then(|m| m.tool.description.clone());
            let tier = latest_manifest
                .as_ref()
                .map(|m| m.tool.tier.clone())
                .unwrap_or_default();
            let deprecated = latest_manifest
                .as_ref()
                .map(|m| m.tool.deprecated)
                .unwrap_or(false);
            let input_types = latest_manifest
                .as_ref()
                .map(|m| m.tool.inputs.iter().map(|i| i.r#type.to_string()).collect())
                .unwrap_or_default();
            let output_types = latest_manifest
                .as_ref()
                .map(|m| {
                    m.tool
                        .outputs
                        .iter()
                        .map(|o| o.r#type.to_string())
                        .collect()
                })
                .unwrap_or_default();

            tools.push(ToolSummary {
                id,
                latest_version: versions.last().map(|v| v.to_string()).unwrap_or_default(),
                description,
                tier,
                deprecated,
                input_types,
                output_types,
            });
        }

        tools.sort_by(|a, b| a.id.cmp(&b.id));
        Ok(tools)
    }

    fn get_data_manifest(&self, dataset: &str, version: Option<&str>) -> Result<DataManifest> {
        let data_dir = self.local_path.join("data").join(dataset);
        if !data_dir.exists() {
            return Err(BvError::IndexError(format!(
                "dataset '{dataset}' not found in registry"
            )));
        }

        let ver = if let Some(v) = version {
            v.to_string()
        } else {
            let mut versions = self.list_data_versions(dataset)?;
            versions.sort();
            versions.into_iter().last().ok_or_else(|| {
                BvError::IndexError(format!("no versions of '{dataset}' found in registry"))
            })?
        };

        let manifest_path = data_dir.join(format!("{ver}.toml"));
        let s = fs::read_to_string(&manifest_path).map_err(|e| {
            BvError::IndexError(format!(
                "could not read data manifest for '{dataset}@{ver}': {e}"
            ))
        })?;

        DataManifest::from_toml_str(&s)
    }

    fn list_data_versions(&self, dataset: &str) -> Result<Vec<String>> {
        let data_dir = self.local_path.join("data").join(dataset);
        if !data_dir.exists() {
            return Err(BvError::IndexError(format!(
                "dataset '{dataset}' not found in registry"
            )));
        }

        let mut versions = Vec::new();
        let mut dropped: Vec<String> = Vec::new();
        for entry in fs::read_dir(&data_dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.extension().is_some_and(|e| e == "toml")
                && let Some(stem) = path.file_stem().and_then(|s| s.to_str())
            {
                if stem.parse::<Version>().is_ok() {
                    versions.push(stem.to_string());
                } else {
                    dropped.push(stem.to_string());
                }
            }
        }

        if !dropped.is_empty() {
            tracing::warn!(
                dataset = %dataset,
                dropped = ?dropped,
                "ignoring dataset manifest files with non-semver names (expected MAJOR.MINOR.PATCH; \
                 calver like 2024.01.0 is not valid semver)"
            );
        }

        versions.sort();
        Ok(versions)
    }

    fn list_datasets(&self) -> Result<Vec<String>> {
        let data_dir = self.local_path.join("data");
        if !data_dir.exists() {
            return Ok(Vec::new());
        }
        let mut ids = Vec::new();
        for entry in fs::read_dir(&data_dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir()
                && let Some(name) = path.file_name().and_then(|s| s.to_str())
            {
                ids.push(name.to_string());
            }
        }
        ids.sort();
        Ok(ids)
    }
}

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

    /// git pull/clone must never hang waiting for credentials.
    /// Verify GIT_TERMINAL_PROMPT=0 is set by trying to clone a nonexistent URL
    /// and confirming the process exits (rather than blocking on stdin).
    #[test]
    fn git_refresh_does_not_prompt_for_credentials() {
        let tmp = tempdir().unwrap();
        let index = GitIndex::new(
            "https://github.com/tejasprabhune/definitely-does-not-exist-bv-test",
            tmp.path().join("clone"),
        );
        // Must complete quickly (not hang on a credential prompt).
        let result = index.git_refresh();
        assert!(
            result.is_err(),
            "expected clone of nonexistent repo to fail"
        );
        let msg = result.unwrap_err().to_string();
        assert!(
            !msg.is_empty(),
            "expected a non-empty error message, not a silent hang"
        );
    }

    #[test]
    fn maybe_update_remote_fixes_stale_url() {
        let tmp = tempdir().unwrap();
        let repo_path = tmp.path().join("repo");

        // Initialise a bare local repo so we have a valid .git dir.
        Command::new("git")
            .args(["init", repo_path.to_str().unwrap()])
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .unwrap();
        Command::new("git")
            .args([
                "-C",
                repo_path.to_str().unwrap(),
                "remote",
                "add",
                "origin",
                "https://github.com/old-org/old-repo",
            ])
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .unwrap();

        let index = GitIndex::new(
            "https://github.com/tejasprabhune/bv-registry",
            repo_path.clone(),
        );
        index.maybe_update_remote().unwrap();

        let out = Command::new("git")
            .args([
                "-C",
                repo_path.to_str().unwrap(),
                "remote",
                "get-url",
                "origin",
            ])
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .output()
            .unwrap();
        let url = String::from_utf8_lossy(&out.stdout).trim().to_string();
        assert_eq!(url, "https://github.com/tejasprabhune/bv-registry");
    }

    #[test]
    fn list_versions_returns_only_valid_semver() {
        let tmp = tempdir().unwrap();
        let tool_dir = tmp.path().join("tools").join("tmalign");
        fs::create_dir_all(&tool_dir).unwrap();
        fs::write(tool_dir.join("1.2.3.toml"), "").unwrap();
        fs::write(tool_dir.join("20240303.toml"), "").unwrap();
        fs::write(tool_dir.join("2024.01.0.toml"), "").unwrap();

        let index = GitIndex::new("unused", tmp.path().to_path_buf());
        let versions = index.list_versions("tmalign").unwrap();

        assert_eq!(versions.len(), 1);
        assert_eq!(versions[0], Version::new(1, 2, 3));
    }

    #[test]
    fn list_data_versions_returns_only_valid_semver() {
        let tmp = tempdir().unwrap();
        let data_dir = tmp.path().join("data").join("uniref50");
        fs::create_dir_all(&data_dir).unwrap();
        fs::write(data_dir.join("0.1.0.toml"), "").unwrap();
        fs::write(data_dir.join("2024.01.0.toml"), "").unwrap();

        let index = GitIndex::new("unused", tmp.path().to_path_buf());
        let versions = index.list_data_versions("uniref50").unwrap();

        assert_eq!(versions, vec!["0.1.0".to_string()]);
    }
}