-
Notifications
You must be signed in to change notification settings - Fork 585
/
version.rs
318 lines (280 loc) · 9.97 KB
/
version.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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
use std::collections::BTreeMap;
use chrono::NaiveDateTime;
use diesel::prelude::*;
use crate::util::errors::{cargo_err, AppResult};
use crate::models::{Crate, Dependency, User};
use crate::schema::*;
use crate::sql::split_part;
// Queryable has a custom implementation below
#[derive(Clone, Identifiable, Associations, Debug, Queryable, Deserialize, Serialize)]
#[diesel(belongs_to(Crate))]
pub struct Version {
pub id: i32,
pub crate_id: i32,
pub num: String,
pub updated_at: NaiveDateTime,
pub created_at: NaiveDateTime,
pub downloads: i32,
pub features: serde_json::Value,
pub yanked: bool,
pub license: Option<String>,
pub crate_size: Option<i32>,
pub published_by: Option<i32>,
pub checksum: String,
pub links: Option<String>,
pub rust_version: Option<String>,
}
#[derive(Insertable, Debug)]
#[diesel(table_name = versions, check_for_backend(diesel::pg::Pg))]
pub struct NewVersion {
crate_id: i32,
num: String,
features: serde_json::Value,
license: Option<String>,
crate_size: Option<i32>,
published_by: i32,
checksum: String,
links: Option<String>,
rust_version: Option<String>,
}
/// The highest version (semver order) and the most recently updated version.
/// Typically used for a single crate.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct TopVersions {
/// The "highest" version in terms of semver
pub highest: Option<semver::Version>,
/// The "highest" non-prerelease version
pub highest_stable: Option<semver::Version>,
/// The "newest" version in terms of publishing date
pub newest: Option<semver::Version>,
}
impl TopVersions {
/// Return both the newest (most recently updated) and the
/// highest version (in semver order) for a list of `Version` instances.
pub fn from_versions(versions: Vec<Version>) -> Self {
Self::from_date_version_pairs(versions.into_iter().map(|v| (v.created_at, v.num)))
}
/// Return both the newest (most recently updated) and the
/// highest version (in semver order) for a collection of date/version pairs.
pub fn from_date_version_pairs<T>(pairs: T) -> Self
where
T: IntoIterator<Item = (NaiveDateTime, String)>,
{
// filter out versions that we can't parse
let pairs: Vec<(NaiveDateTime, semver::Version)> = pairs
.into_iter()
.filter_map(|(date, version)| {
semver::Version::parse(&version)
.ok()
.map(|version| (date, version))
})
.collect();
let newest = pairs.iter().max().map(|(_, v)| v.clone());
let highest = pairs.iter().map(|(_, v)| v).max().cloned();
let highest_stable = pairs
.iter()
.map(|(_, v)| v)
.filter(|v| v.pre.is_empty())
.max()
.cloned();
Self {
highest,
highest_stable,
newest,
}
}
}
impl Version {
/// Returns (dependency, crate dependency name)
pub fn dependencies(&self, conn: &mut PgConnection) -> QueryResult<Vec<(Dependency, String)>> {
Dependency::belonging_to(self)
.inner_join(crates::table)
.select((dependencies::all_columns, crates::name))
.order((dependencies::optional, crates::name))
.load(conn)
}
pub fn record_readme_rendering(
version_id_: i32,
conn: &mut PgConnection,
) -> QueryResult<usize> {
use crate::schema::readme_renderings::dsl::*;
use diesel::dsl::now;
diesel::insert_into(readme_renderings)
.values(version_id.eq(version_id_))
.on_conflict(version_id)
.do_update()
.set(rendered_at.eq(now))
.execute(conn)
}
/// Gets the User who ran `cargo publish` for this version, if recorded.
/// Not for use when you have a group of versions you need the publishers for.
pub fn published_by(&self, conn: &mut PgConnection) -> Option<User> {
match self.published_by {
Some(pb) => users::table.find(pb).first(conn).ok(),
None => None,
}
}
}
impl NewVersion {
#[allow(clippy::too_many_arguments)]
pub fn new(
crate_id: i32,
num: &semver::Version,
features: &BTreeMap<String, Vec<String>>,
license: Option<String>,
license_file: Option<&str>,
crate_size: i32,
published_by: i32,
checksum: String,
links: Option<String>,
rust_version: Option<String>,
) -> AppResult<Self> {
let features = serde_json::to_value(features)?;
let mut new_version = NewVersion {
crate_id,
num: num.to_string(),
features,
license,
crate_size: Some(crate_size),
published_by,
checksum,
links,
rust_version,
};
new_version.validate_license(license_file)?;
Ok(new_version)
}
pub fn save(&self, conn: &mut PgConnection, published_by_email: &str) -> AppResult<Version> {
use crate::schema::versions::dsl::*;
use diesel::dsl::exists;
use diesel::{insert_into, select};
conn.transaction(|conn| {
let num_no_build = strip_build_metadata(&self.num);
let already_uploaded = versions
.filter(crate_id.eq(self.crate_id))
.filter(split_part(num, "+", 1).eq(num_no_build));
if select(exists(already_uploaded)).get_result(conn)? {
return Err(cargo_err(&format_args!(
"crate version `{}` is already uploaded",
num_no_build
)));
}
let version: Version = insert_into(versions).values(self).get_result(conn)?;
insert_into(versions_published_by::table)
.values((
versions_published_by::version_id.eq(version.id),
versions_published_by::email.eq(published_by_email),
))
.execute(conn)?;
Ok(version)
})
}
fn validate_license(&mut self, license_file: Option<&str>) -> AppResult<()> {
if let Some(ref license) = self.license {
validate_license_expr(license)?;
} else if license_file.is_some() {
// If no license is given, but a license file is given, flag this
// crate as having a nonstandard license. Note that we don't
// actually do anything else with license_file currently.
self.license = Some(String::from("non-standard"));
}
Ok(())
}
}
fn validate_license_expr(s: &str) -> AppResult<()> {
pub const PARSE_MODE: spdx::ParseMode = spdx::ParseMode {
allow_lower_case_operators: false,
allow_slash_as_or_operator: true,
allow_imprecise_license_names: false,
allow_postfix_plus_on_gpl: true,
};
spdx::Expression::parse_mode(s, PARSE_MODE).map_err(|_| {
cargo_err("unknown or invalid license expression; see http://opensource.org/licenses for options, and http://spdx.org/licenses/ for their identifiers")
})?;
Ok(())
}
fn strip_build_metadata(version: &str) -> &str {
version
.split_once('+')
.map(|parts| parts.0)
.unwrap_or(version)
}
#[cfg(test)]
mod tests {
use super::{validate_license_expr, TopVersions};
use chrono::NaiveDateTime;
#[track_caller]
fn date(str: &str) -> NaiveDateTime {
str.parse().unwrap()
}
#[track_caller]
fn version(str: &str) -> semver::Version {
semver::Version::parse(str).unwrap()
}
#[test]
fn top_versions_empty() {
let versions = vec![];
assert_eq!(
TopVersions::from_date_version_pairs(versions),
TopVersions {
highest: None,
highest_stable: None,
newest: None,
}
);
}
#[test]
fn top_versions_single() {
let versions = vec![(date("2020-12-03T12:34:56"), "1.0.0".into())];
assert_eq!(
TopVersions::from_date_version_pairs(versions),
TopVersions {
highest: Some(version("1.0.0")),
highest_stable: Some(version("1.0.0")),
newest: Some(version("1.0.0")),
}
);
}
#[test]
fn top_versions_prerelease() {
let versions = vec![(date("2020-12-03T12:34:56"), "1.0.0-beta.5".into())];
assert_eq!(
TopVersions::from_date_version_pairs(versions),
TopVersions {
highest: Some(version("1.0.0-beta.5")),
highest_stable: None,
newest: Some(version("1.0.0-beta.5")),
}
);
}
#[test]
fn top_versions_multiple() {
let versions = vec![
(date("2018-12-03T12:34:56"), "1.0.0".into()),
(date("2019-12-03T12:34:56"), "2.0.0-alpha.1".into()),
(date("2020-12-01T12:34:56"), "everything is broken".into()),
(date("2020-12-03T12:34:56"), "1.1.0".into()),
(date("2020-12-31T12:34:56"), "1.0.4".into()),
];
assert_eq!(
TopVersions::from_date_version_pairs(versions),
TopVersions {
highest: Some(version("2.0.0-alpha.1")),
highest_stable: Some(version("1.1.0")),
newest: Some(version("1.0.4")),
}
);
}
#[test]
fn licenses() {
assert_ok!(validate_license_expr("MIT"));
assert_ok!(validate_license_expr("MIT OR Apache-2.0"));
assert_ok!(validate_license_expr("MIT/Apache-2.0"));
assert_ok!(validate_license_expr("MIT AND Apache-2.0"));
assert_ok!(validate_license_expr("MIT OR (Apache-2.0 AND MIT)"));
assert_ok!(validate_license_expr("GPL-3.0+"));
let error = assert_err!(validate_license_expr("apache 2.0"));
let error = format!("{error}");
assert!(error.starts_with("unknown or invalid license expression; see http"));
}
}