Skip to main content

check_updates/
lib.rs

1use std::collections::HashSet;
2use std::path::PathBuf;
3use std::rc::Rc;
4
5use reqwest::Client;
6use semver::VersionReq;
7
8use crate::registry::*;
9
10mod package;
11mod registry;
12
13pub use package::{DepKind, Package, PackageVersion, Packages, Unit, Usage};
14
15type Purl = purl::GenericPurl<String>;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18pub enum RegistryCachePolicy {
19    PreferLocal,
20    #[default]
21    Refresh,
22    NoCache,
23}
24
25#[derive(Debug, Clone, Copy, Default)]
26pub struct Options {
27    pub registry_cache_policy: RegistryCachePolicy,
28}
29
30pub struct State {
31    client: Client,
32    root: Option<PathBuf>,
33    registry_cache_policy: RegistryCachePolicy,
34}
35
36impl State {
37    pub fn new(root: Option<PathBuf>, options: Options) -> Self {
38        let client = Client::builder()
39            .http2_adaptive_window(true)
40            .build()
41            .expect("failed to initialize HTTP client");
42        Self {
43            client,
44            root,
45            registry_cache_policy: options.registry_cache_policy,
46        }
47    }
48
49    pub fn client(&self) -> &Client {
50        &self.client
51    }
52
53    pub fn root(&self) -> Option<&PathBuf> {
54        self.root.as_ref()
55    }
56
57    pub fn registry_cache_policy(&self) -> RegistryCachePolicy {
58        self.registry_cache_policy
59    }
60}
61
62#[derive(Debug, thiserror::Error)]
63pub enum Error {
64    #[error("registry error: {0}")]
65    Registry(#[from] RegistryError),
66}
67
68pub struct CheckUpdates {
69    cargo: Registry,
70}
71
72impl CheckUpdates {
73    pub fn new(root: Option<PathBuf>) -> Self {
74        Self::with_options(root, Options::default())
75    }
76
77    pub fn with_options(root: Option<PathBuf>, options: Options) -> Self {
78        let state = Rc::new(State::new(root, options));
79        let cargo = CargoRegistry::new(state.clone());
80
81        Self {
82            cargo: cargo.into(),
83        }
84    }
85
86    pub async fn packages(&self) -> Result<Packages, Error> {
87        let mut res: Packages = Default::default();
88        // Track (unit, package_name, req, kind) to deduplicate while still
89        // preserving distinct dep sections in output.
90        let mut seen: HashSet<(Unit, String, String, DepKind)> = HashSet::new();
91        for package in self.cargo.packages().await? {
92            for usage in &package.usages {
93                // Wildcard requirements have nothing to update.
94                if usage.req == VersionReq::STAR {
95                    continue;
96                }
97                let key = (
98                    usage.unit.clone(),
99                    package.purl.name().to_string(),
100                    usage.req.to_string(),
101                    usage.kind,
102                );
103                if !seen.insert(key) {
104                    continue;
105                }
106                res.entry(usage.unit.clone()).or_default().push((
107                    usage.req.clone(),
108                    usage.kind,
109                    package.clone(),
110                ));
111            }
112        }
113        Ok(res)
114    }
115
116    /// Update the locally installed versions of the given packages to the one specified
117    pub fn update_versions<'a>(
118        &self,
119        packages: impl IntoIterator<Item = (&'a Usage, &'a Package, VersionReq)>,
120    ) -> Result<(), Error> {
121        self.cargo.update_versions(packages)?;
122        Ok(())
123    }
124}