uv_distribution_types/
pip_index.rs

1//! Compatibility structs for converting between [`IndexUrl`] and [`Index`]. These structs are
2//! parsed and deserialized as [`IndexUrl`], but are stored as [`Index`] with the appropriate
3//! flags set.
4
5use serde::{Deserialize, Deserializer, Serialize};
6#[cfg(feature = "schemars")]
7use std::borrow::Cow;
8use std::path::Path;
9
10use crate::{Index, IndexUrl};
11
12macro_rules! impl_index {
13    ($name:ident, $from:expr) => {
14        #[derive(Debug, Clone, Eq, PartialEq)]
15        pub struct $name(Index);
16
17        impl $name {
18            pub fn relative_to(self, root_dir: &Path) -> Result<Self, crate::IndexUrlError> {
19                Ok(Self(self.0.relative_to(root_dir)?))
20            }
21        }
22
23        impl From<$name> for Index {
24            fn from(value: $name) -> Self {
25                value.0
26            }
27        }
28
29        impl From<Index> for $name {
30            fn from(value: Index) -> Self {
31                Self(value)
32            }
33        }
34
35        impl Serialize for $name {
36            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
37            where
38                S: serde::Serializer,
39            {
40                self.0.url().serialize(serializer)
41            }
42        }
43
44        impl<'de> Deserialize<'de> for $name {
45            fn deserialize<D>(deserializer: D) -> Result<$name, D::Error>
46            where
47                D: Deserializer<'de>,
48            {
49                IndexUrl::deserialize(deserializer).map($from).map(Self)
50            }
51        }
52
53        #[cfg(feature = "schemars")]
54        impl schemars::JsonSchema for $name {
55            fn schema_name() -> Cow<'static, str> {
56                IndexUrl::schema_name()
57            }
58
59            fn json_schema(
60                generator: &mut schemars::generate::SchemaGenerator,
61            ) -> schemars::Schema {
62                IndexUrl::json_schema(generator)
63            }
64        }
65    };
66}
67
68impl_index!(PipIndex, Index::from_index_url);
69impl_index!(PipExtraIndex, Index::from_extra_index_url);
70impl_index!(PipFindLinks, Index::from_find_links);