-
Notifications
You must be signed in to change notification settings - Fork 28
/
crates.rs
176 lines (148 loc) · 4.6 KB
/
crates.rs
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
use std::{fmt, str, task::Context, task::Poll};
use anyhow::{anyhow, Error};
use crates_index::{Crate, DependencyKind, Index};
use futures::FutureExt as _;
use hyper::service::Service;
use semver::{Version, VersionReq};
use serde::Deserialize;
use tokio::task::spawn_blocking;
use crate::{
models::crates::{CrateDep, CrateDeps, CrateName, CratePath, CrateRelease},
BoxFuture,
};
const CRATES_API_BASE_URI: &str = "https://crates.io/api/v1";
#[derive(Deserialize, Debug)]
struct RegistryPackageDep {
name: String,
req: VersionReq,
#[serde(default)]
kind: Option<String>,
#[serde(default)]
package: Option<String>,
}
#[derive(Deserialize, Debug)]
struct RegistryPackage {
vers: Version,
#[serde(default)]
deps: Vec<RegistryPackageDep>,
#[serde(default)]
yanked: bool,
}
fn convert_pkgs(krate: Crate) -> Result<QueryCrateResponse, Error> {
let name: CrateName = krate.name().parse()?;
let releases = krate
.versions()
.iter()
.map(|package| {
let mut deps = CrateDeps::default();
for dep in package.dependencies() {
let name = dep.crate_name().parse()?;
let req = VersionReq::parse(dep.requirement())?;
match dep.kind() {
DependencyKind::Normal => deps.main.insert(name, CrateDep::External(req)),
DependencyKind::Dev => deps.dev.insert(name, CrateDep::External(req)),
_ => None,
};
}
let version = Version::parse(package.version())?;
Ok(CrateRelease {
name: name.clone(),
version,
deps,
yanked: package.is_yanked(),
})
})
.collect::<Result<_, Error>>()?;
Ok(QueryCrateResponse { releases })
}
#[derive(Debug, Clone)]
pub struct QueryCrateResponse {
pub releases: Vec<CrateRelease>,
}
#[derive(Clone)]
pub struct QueryCrate {
index: Index,
}
impl QueryCrate {
pub fn new(index: Index) -> Self {
Self { index }
}
pub async fn query(index: Index, crate_name: CrateName) -> anyhow::Result<QueryCrateResponse> {
let crate_name2 = crate_name.clone();
let krate = spawn_blocking(move || index.crate_(crate_name2.as_ref()))
.await?
.ok_or_else(|| anyhow!("crate '{}' not found", crate_name.as_ref()))?;
convert_pkgs(krate)
}
}
impl fmt::Debug for QueryCrate {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("QueryCrate")
}
}
impl Service<CrateName> for QueryCrate {
type Response = QueryCrateResponse;
type Error = Error;
type Future = BoxFuture<Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, crate_name: CrateName) -> Self::Future {
let index = self.index.clone();
Self::query(index, crate_name).boxed()
}
}
#[derive(Deserialize)]
struct SummaryResponseDetail {
name: String,
max_version: Version,
}
#[derive(Deserialize)]
struct SummaryResponse {
most_downloaded: Vec<SummaryResponseDetail>,
}
fn convert_summary(response: SummaryResponse) -> Result<Vec<CratePath>, Error> {
response
.most_downloaded
.into_iter()
.map(|detail| {
let name = detail.name.parse()?;
Ok(CratePath {
name,
version: detail.max_version,
})
})
.collect()
}
#[derive(Clone, Default)]
pub struct GetPopularCrates {
client: reqwest::Client,
}
impl GetPopularCrates {
pub fn new(client: reqwest::Client) -> Self {
Self { client }
}
pub async fn query(client: reqwest::Client) -> anyhow::Result<Vec<CratePath>> {
let url = format!("{}/summary", CRATES_API_BASE_URI);
let res = client.get(&url).send().await?.error_for_status()?;
let summary: SummaryResponse = res.json().await?;
convert_summary(summary)
}
}
impl fmt::Debug for GetPopularCrates {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("GetPopularCrates")
}
}
impl Service<()> for GetPopularCrates {
type Response = Vec<CratePath>;
type Error = Error;
type Future = BoxFuture<Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, _req: ()) -> Self::Future {
let client = self.client.clone();
Self::query(client).boxed()
}
}