Skip to main content

lockdocs_core/upstream/
cache_entry.rs

1//! Read upstream cache entries and decide whether to refresh or retain them.
2
3use std::path::PathBuf;
4
5use anyhow::Result;
6
7use crate::{cache, Dep};
8
9use super::{Manifest, FORMAT};
10
11pub fn dir(dep: &Dep) -> PathBuf {
12    let safe = format!("{}@{}", dep.name, dep.version).replace(['/', '\\', ':'], "+");
13    cache::dir().join("upstream").join(dep.eco.as_str()).join(safe)
14}
15
16/// Was this copy made by an older lockdocs that downloaded less?
17pub fn stale(m: &Manifest) -> bool {
18    m.format < FORMAT
19}
20
21/// A prior explicit enrichment is also usable by automatic and offline queries.
22pub fn needs_refresh(m: &Manifest, explicit: bool) -> bool {
23    if explicit {
24        stale(m) || !m.docs_sites_checked
25    } else {
26        !compatible(m)
27    }
28}
29
30/// Oldest cache format whose commit was resolved from an exact release tag.
31/// Newer formats only differ in how the files were downloaded, so automatic
32/// and offline queries keep trusting them; `stale` still lets a fetch refresh.
33const MIN_TRUSTED_FORMAT: u32 = 4;
34
35fn compatible(m: &Manifest) -> bool {
36    m.format >= MIN_TRUSTED_FORMAT && (m.commit.is_some() || m.site.is_some() || m.files == 0)
37}
38
39/// A previous fetch (with or without files). Never touches the network.
40pub fn cached(dep: &Dep) -> Option<(PathBuf, Manifest)> {
41    let d = dir(dep);
42    let m: Manifest = serde_json::from_str(&std::fs::read_to_string(d.join(".lockdocs-upstream.json")).ok()?).ok()?;
43    Some((d, m))
44}
45
46pub(super) fn enrich_cached(prior: Option<(PathBuf, Manifest)>, explicit: bool, attempt: impl FnOnce() -> Result<Manifest>) -> Result<Manifest> {
47    if let Some((_, m)) = prior.as_ref().filter(|(_, m)| !needs_refresh(m, explicit)) {
48        return Ok(m.clone());
49    }
50    match attempt() {
51        Ok(m) => Ok(m),
52        Err(e) => match prior.filter(|(_, m)| compatible(m)) {
53            Some((_, mut m)) => {
54                m.note = Some(format!("upstream refresh failed: {e:#}; previous complete cache retained"));
55                Ok(m)
56            }
57            None => Err(e),
58        },
59    }
60}