crates_index/
config.rs

1use crate::dirs::crate_prefix;
2use serde_derive::Deserialize;
3
4/// Global configuration of an index, reflecting the [contents of config.json](https://doc.rust-lang.org/cargo/reference/registries.html#index-format).
5#[derive(Clone, Debug, Deserialize)]
6pub struct IndexConfig {
7    /// Pattern for creating download URLs. Use [`IndexConfig::download_url`] instead.
8    pub dl: String,
9    /// Base URL for publishing, etc.
10    pub api: Option<String>,
11}
12
13impl IndexConfig {
14    /// Get the URL from where the specified package can be downloaded.
15    /// This method assumes the particular version is present in the registry,
16    /// and does not verify that it is.
17    #[must_use]
18    pub fn download_url(&self, name: &str, version: &str) -> Option<String> {
19        if !self.dl.contains("{crate}")
20            && !self.dl.contains("{version}")
21            && !self.dl.contains("{prefix}")
22            && !self.dl.contains("{lowerprefix}")
23        {
24            let mut new = String::with_capacity(self.dl.len() + name.len() + version.len() + 10);
25            new.push_str(&self.dl);
26            new.push('/');
27            new.push_str(name);
28            new.push('/');
29            new.push_str(version);
30            new.push_str("/download");
31            Some(new)
32        } else {
33            let mut prefix = String::with_capacity(5);
34            crate_prefix(&mut prefix, name, '/')?;
35            Some(
36                self.dl
37                    .replace("{crate}", name)
38                    .replace("{version}", version)
39                    .replace("{prefix}", &prefix)
40                    .replace("{lowerprefix}", &prefix.to_ascii_lowercase()),
41            )
42        }
43    }
44}