-
Notifications
You must be signed in to change notification settings - Fork 208
/
Copy pathfakes.rs
559 lines (497 loc) · 17.9 KB
/
fakes.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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
use super::TestDatabase;
use crate::docbuilder::{BuildResult, DocCoverage};
use crate::error::Result;
use crate::index::api::{CrateData, CrateOwner, ReleaseData};
use crate::storage::{rustdoc_archive_path, source_archive_path, Storage};
use crate::utils::{Dependency, MetadataPackage, Target};
use anyhow::Context;
use chrono::{DateTime, Utc};
use postgres::Client;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use tracing::debug;
#[must_use = "FakeRelease does nothing until you call .create()"]
pub(crate) struct FakeRelease<'a> {
db: &'a TestDatabase,
storage: Arc<Storage>,
package: MetadataPackage,
builds: Vec<FakeBuild>,
/// name, content
source_files: Vec<(&'a str, &'a [u8])>,
/// name, content
rustdoc_files: Vec<(&'a str, &'a [u8])>,
doc_targets: Vec<String>,
default_target: Option<&'a str>,
registry_crate_data: CrateData,
registry_release_data: ReleaseData,
has_docs: bool,
has_examples: bool,
archive_storage: bool,
/// This stores the content, while `package.readme` stores the filename
readme: Option<&'a str>,
github_stats: Option<FakeGithubStats>,
doc_coverage: Option<DocCoverage>,
}
pub(crate) struct FakeBuild {
s3_build_log: Option<String>,
db_build_log: Option<String>,
build_time: Option<DateTime<Utc>>,
result: BuildResult,
}
const DEFAULT_CONTENT: &[u8] =
b"<html><head></head><body>default content for test/fakes</body></html>";
impl<'a> FakeRelease<'a> {
pub(super) fn new(db: &'a TestDatabase, storage: Arc<Storage>) -> Self {
FakeRelease {
db,
storage,
package: MetadataPackage {
id: "fake-package-id".into(),
name: "fake-package".into(),
version: "1.0.0".into(),
license: Some("MIT".into()),
repository: Some("https://git.example.com".into()),
homepage: Some("https://www.example.com".into()),
description: Some("Fake package".into()),
documentation: Some("https://docs.example.com".into()),
dependencies: vec![Dependency {
name: "fake-dependency".into(),
req: "^1.0.0".into(),
kind: None,
rename: None,
optional: false,
}],
targets: vec![Target::dummy_lib("fake_package".into(), None)],
readme: None,
keywords: vec!["fake".into(), "package".into()],
features: [
("default".into(), vec!["feature1".into(), "feature3".into()]),
("feature1".into(), Vec::new()),
("feature2".into(), vec!["feature1".into()]),
("feature3".into(), Vec::new()),
]
.iter()
.cloned()
.collect::<HashMap<String, Vec<String>>>(),
},
builds: vec![],
source_files: Vec::new(),
rustdoc_files: Vec::new(),
doc_targets: Vec::new(),
default_target: None,
registry_crate_data: CrateData { owners: Vec::new() },
registry_release_data: ReleaseData {
release_time: Utc::now(),
yanked: false,
downloads: 0,
},
has_docs: true,
has_examples: false,
readme: None,
github_stats: None,
doc_coverage: None,
archive_storage: false,
}
}
pub(crate) fn release_time(mut self, new: DateTime<Utc>) -> Self {
self.registry_release_data.release_time = new;
self
}
pub(crate) fn name(mut self, new: &str) -> Self {
self.package.name = new.into();
self.package.id = format!("{}-id", new);
self.package.targets[0].name = new.into();
self
}
pub(crate) fn version(mut self, new: &str) -> Self {
self.package.version = new.into();
self
}
pub(crate) fn repo(mut self, repo: impl Into<String>) -> Self {
self.package.repository = Some(repo.into());
self
}
/// Shortcut to add a single unsuccessful build with default data
// TODO: How should `has_docs` actually be handled?
pub(crate) fn build_result_failed(self) -> Self {
assert!(
self.builds.is_empty(),
"cannot use custom builds with build_result_failed"
);
Self {
has_docs: false,
builds: vec![FakeBuild::default().successful(false)],
..self
}
}
pub(crate) fn builds(self, builds: Vec<FakeBuild>) -> Self {
assert!(self.builds.is_empty());
assert!(!builds.is_empty());
Self { builds, ..self }
}
pub(crate) fn yanked(mut self, new: bool) -> Self {
self.registry_release_data.yanked = new;
self
}
pub(crate) fn archive_storage(mut self, new: bool) -> Self {
self.archive_storage = new;
self
}
/// Since we switched to LOL HTML, all data must have a valid <head> and <body>.
/// To avoid duplicating them in every test, this just makes up some content.
pub(crate) fn rustdoc_file(mut self, path: &'a str) -> Self {
self.rustdoc_files.push((path, DEFAULT_CONTENT));
self
}
pub(crate) fn rustdoc_file_with(mut self, path: &'a str, data: &'a [u8]) -> Self {
self.rustdoc_files.push((path, data));
self
}
pub(crate) fn source_file(mut self, path: &'a str, data: &'a [u8]) -> Self {
self.source_files.push((path, data));
self
}
pub(crate) fn default_target(mut self, target: &'a str) -> Self {
self = self.add_target(target);
self.default_target = Some(target);
self
}
pub(crate) fn add_target(mut self, target: &str) -> Self {
self.doc_targets.push(target.into());
self
}
pub(crate) fn binary(mut self, bin: bool) -> Self {
self.has_docs = !bin;
if bin {
for target in self.package.targets.iter_mut() {
target.crate_types = vec!["bin".into()];
}
}
self
}
pub(crate) fn keywords(mut self, keywords: Vec<String>) -> Self {
self.package.keywords = keywords;
self
}
pub(crate) fn add_platform<S: Into<String>>(mut self, platform: S) -> Self {
let platform = platform.into();
let name = self.package.targets[0].name.clone();
let target = Target::dummy_lib(name, Some(platform.clone()));
self.package.targets.push(target);
self.doc_targets.push(platform);
self
}
/// NOTE: this should be markdown. It will be rendered as HTML when served.
pub(crate) fn readme(mut self, content: &'a str) -> Self {
self.readme = Some(content);
self.source_file("README.md", content.as_bytes())
}
pub(crate) fn add_owner(mut self, owner: CrateOwner) -> Self {
self.registry_crate_data.owners.push(owner);
self
}
pub(crate) fn doc_coverage(self, doc_coverage: DocCoverage) -> Self {
Self {
doc_coverage: Some(doc_coverage),
..self
}
}
pub(crate) fn features(mut self, features: HashMap<String, Vec<String>>) -> Self {
self.package.features = features;
self
}
pub(crate) fn github_stats(
mut self,
repo: impl Into<String>,
stars: i32,
forks: i32,
issues: i32,
) -> Self {
self.github_stats = Some(FakeGithubStats {
repo: repo.into(),
stars,
forks,
issues,
});
self
}
pub(crate) fn documentation_url(mut self, documentation: Option<String>) -> Self {
self.package.documentation = documentation;
self
}
/// Returns the release_id
pub(crate) fn create(mut self) -> Result<i32> {
use std::fs;
use std::path::Path;
let package = self.package;
let db = self.db;
let mut rustdoc_files = self.rustdoc_files;
let storage = self.storage;
let archive_storage = self.archive_storage;
// Upload all source files as rustdoc files
// In real life, these would be highlighted HTML, but for testing we just use the files themselves.
for (source_path, data) in &self.source_files {
if let Some(src) = source_path.strip_prefix("src/") {
let mut updated = ["src", &package.name, src].join("/");
updated += ".html";
let source_html = format!(
"<html><head></head><body>{}</body></html>",
std::str::from_utf8(data).expect("invalid utf8")
);
rustdoc_files.push((
Box::leak(Box::new(updated)),
Box::leak(source_html.into_bytes().into_boxed_slice()),
));
}
}
#[derive(Debug)]
enum FileKind {
Rustdoc,
Sources,
}
let create_temp_dir = || {
tempfile::Builder::new()
.prefix("docs.rs-fake")
.tempdir()
.unwrap()
};
let store_files_into = |files: &[(&str, &[u8])], base_path: &Path| {
for (path, data) in files {
if path.starts_with('/') {
anyhow::bail!("absolute paths not supported");
}
// allow `src/main.rs`
if let Some(parent) = Path::new(path).parent() {
let path = base_path.join(parent);
fs::create_dir_all(&path)
.with_context(|| format!("failed to create {}", path.display()))?;
}
let file = base_path.join(path);
debug!("writing file {}", file.display());
fs::write(file, data)?;
}
Ok(())
};
let upload_files = |kind: FileKind, source_directory: &Path| {
debug!(
"adding directory {:?} from {}",
kind,
source_directory.display()
);
if archive_storage {
let (archive, public) = match kind {
FileKind::Rustdoc => {
(rustdoc_archive_path(&package.name, &package.version), true)
}
FileKind::Sources => {
(source_archive_path(&package.name, &package.version), false)
}
};
debug!("store in archive: {:?}", archive);
let (files_list, new_alg) = crate::db::add_path_into_remote_archive(
&storage,
&archive,
source_directory,
public,
)?;
let mut hm = HashSet::new();
hm.insert(new_alg);
Ok((files_list, hm))
} else {
let prefix = match kind {
FileKind::Rustdoc => "rustdoc",
FileKind::Sources => "sources",
};
crate::db::add_path_into_database(
&storage,
&format!("{}/{}/{}/", prefix, package.name, package.version),
source_directory,
)
}
};
debug!("before upload source");
let source_tmp = create_temp_dir();
store_files_into(&self.source_files, source_tmp.path())?;
let (source_meta, algs) = upload_files(FileKind::Sources, source_tmp.path())?;
debug!("added source files {}", source_meta);
// If the test didn't add custom builds, inject a default one
if self.builds.is_empty() {
self.builds.push(FakeBuild::default());
}
let last_build_result = &self.builds.last().unwrap().result;
if last_build_result.successful {
let index = [&package.name, "index.html"].join("/");
if package.is_library() && !rustdoc_files.iter().any(|(path, _)| path == &index) {
rustdoc_files.push((&index, DEFAULT_CONTENT));
}
let rustdoc_tmp = create_temp_dir();
let rustdoc_path = rustdoc_tmp.path();
// store default target files
store_files_into(&rustdoc_files, rustdoc_path)?;
debug!("added rustdoc files");
for target in &package.targets[1..] {
let platform = target.src_path.as_ref().unwrap();
let platform_dir = rustdoc_path.join(platform);
fs::create_dir(&platform_dir)?;
store_files_into(&rustdoc_files, &platform_dir)?;
debug!("added platform files for {}", platform);
}
let (rustdoc_meta, _) = upload_files(FileKind::Rustdoc, rustdoc_path)?;
debug!("uploaded rustdoc files: {}", rustdoc_meta);
}
let repository = match self.github_stats {
Some(stats) => Some(stats.create(&mut self.db.conn())?),
None => None,
};
let crate_tmp = create_temp_dir();
let crate_dir = crate_tmp.path();
if let Some(markdown) = self.readme {
fs::write(crate_dir.join("README.md"), markdown)?;
}
// Many tests rely on the default-target being linux, so it should not
// be set to docsrs_metadata::HOST_TARGET, because then tests fail on all
// non-linux platforms.
let default_target = self.default_target.unwrap_or("x86_64-unknown-linux-gnu");
let release_id = crate::db::add_package_into_database(
&mut db.conn(),
&package,
crate_dir,
last_build_result,
default_target,
source_meta,
self.doc_targets,
&self.registry_release_data,
self.has_docs,
self.has_examples,
algs,
repository,
archive_storage,
)?;
crate::db::update_crate_data_in_database(
&mut db.conn(),
&package.name,
&self.registry_crate_data,
)?;
for build in &self.builds {
build.create(&mut db.conn(), &storage, release_id, default_target)?;
}
if let Some(coverage) = self.doc_coverage {
crate::db::add_doc_coverage(&mut db.conn(), release_id, coverage)?;
}
Ok(release_id)
}
}
struct FakeGithubStats {
repo: String,
stars: i32,
forks: i32,
issues: i32,
}
impl FakeGithubStats {
fn create(&self, conn: &mut Client) -> Result<i32> {
let existing_count: i64 = conn
.query_one("SELECT COUNT(*) FROM repositories;", &[])?
.get(0);
let host_id = base64::encode(format!("FAKE ID {}", existing_count));
let data = conn.query_one(
"INSERT INTO repositories (host, host_id, name, description, last_commit, stars, forks, issues, updated_at)
VALUES ('github.com', $1, $2, 'Fake description!', NOW(), $3, $4, $5, NOW())
RETURNING id;",
&[&host_id, &self.repo, &self.stars, &self.forks, &self.issues],
)?;
Ok(data.get(0))
}
}
impl FakeBuild {
pub(crate) fn build_time(self, build_time: impl Into<DateTime<Utc>>) -> Self {
Self {
build_time: Some(build_time.into()),
..self
}
}
pub(crate) fn rustc_version(self, rustc_version: impl Into<String>) -> Self {
Self {
result: BuildResult {
rustc_version: rustc_version.into(),
..self.result
},
..self
}
}
pub(crate) fn docsrs_version(self, docsrs_version: impl Into<String>) -> Self {
Self {
result: BuildResult {
docsrs_version: docsrs_version.into(),
..self.result
},
..self
}
}
pub(crate) fn s3_build_log(self, build_log: impl Into<String>) -> Self {
Self {
s3_build_log: Some(build_log.into()),
..self
}
}
pub(crate) fn db_build_log(self, build_log: impl Into<String>) -> Self {
Self {
db_build_log: Some(build_log.into()),
..self
}
}
pub(crate) fn no_s3_build_log(self) -> Self {
Self {
s3_build_log: None,
..self
}
}
pub(crate) fn successful(self, successful: bool) -> Self {
Self {
result: BuildResult {
successful,
..self.result
},
..self
}
}
fn create(
&self,
conn: &mut Client,
storage: &Storage,
release_id: i32,
default_target: &str,
) -> Result<()> {
let build_id = crate::db::add_build_into_database(conn, release_id, &self.result)?;
if let Some(db_build_log) = self.db_build_log.as_deref() {
conn.query(
"UPDATE builds SET output = $2 WHERE id = $1",
&[&build_id, &db_build_log],
)?;
}
if let Some(build_time) = self.build_time.as_ref() {
conn.query(
"UPDATE builds SET build_time = $2 WHERE id = $1",
&[&build_id, &build_time],
)?;
}
if let Some(s3_build_log) = self.s3_build_log.as_deref() {
let path = format!("build-logs/{}/{}.txt", build_id, default_target);
storage.store_one(path, s3_build_log)?;
}
Ok(())
}
}
impl Default for FakeBuild {
fn default() -> Self {
Self {
s3_build_log: Some("It works!".into()),
db_build_log: None,
build_time: None,
result: BuildResult {
rustc_version: "rustc 2.0.0-nightly (000000000 1970-01-01)".into(),
docsrs_version: "docs.rs 1.0.0 (000000000 1970-01-01)".into(),
successful: true,
},
}
}
}