-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathprepare.rs
More file actions
553 lines (483 loc) · 17.5 KB
/
prepare.rs
File metadata and controls
553 lines (483 loc) · 17.5 KB
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
use crate::cmd::{Command, CommandError, ProcessLinesActions};
use crate::{Crate, Toolchain, Workspace, build::CratePatch};
use anyhow::Context as _;
use log::info;
use std::path::Path;
use toml::{
Value,
value::{Array, Table},
};
pub(crate) struct Prepare<'a> {
workspace: &'a Workspace,
toolchain: &'a Toolchain,
krate: &'a Crate,
source_dir: &'a Path,
patches: Vec<CratePatch>,
extra_cargo_args: Vec<String>,
}
impl<'a> Prepare<'a> {
pub(crate) fn new(
workspace: &'a Workspace,
toolchain: &'a Toolchain,
krate: &'a Crate,
source_dir: &'a Path,
patches: Vec<CratePatch>,
extra_cargo_args: Vec<String>,
) -> Self {
Self {
workspace,
toolchain,
krate,
source_dir,
patches,
extra_cargo_args,
}
}
pub(crate) fn prepare(&mut self) -> anyhow::Result<()> {
self.krate.copy_source_to(self.workspace, self.source_dir)?;
self.remove_override_files()?;
self.tweak_toml()?;
self.validate_manifest()?;
self.capture_lockfile()?;
self.fetch_deps()?;
Ok(())
}
fn validate_manifest(&self) -> anyhow::Result<()> {
info!(
"validating manifest of {} on toolchain {}",
self.krate, self.toolchain
);
// Skip crates missing a Cargo.toml
if !self.source_dir.join("Cargo.toml").is_file() {
return Err(PrepareError::MissingCargoToml.into());
}
let res = Command::new(self.workspace, self.toolchain.cargo())
.args(&["metadata", "--manifest-path", "Cargo.toml", "--no-deps"])
.args(&self.extra_cargo_args)
.cd(self.source_dir)
.log_output(false)
.run();
if res.is_err() {
return Err(PrepareError::InvalidCargoTomlSyntax.into());
}
Ok(())
}
fn remove_override_files(&self) -> anyhow::Result<()> {
let paths = [
&Path::new(".cargo").join("config"),
&Path::new(".cargo").join("config.toml"),
Path::new("rust-toolchain"),
Path::new("rust-toolchain.toml"),
];
for path in &paths {
let path = self.source_dir.join(path);
if path.exists() {
crate::utils::remove_file(&path)?;
info!("removed {}", path.display());
}
}
Ok(())
}
fn tweak_toml(&self) -> anyhow::Result<()> {
let path = self.source_dir.join("Cargo.toml");
let mut tweaker = TomlTweaker::new(self.krate, &path, &self.patches)?;
tweaker.tweak();
tweaker.save(&path)?;
Ok(())
}
fn capture_lockfile(&mut self) -> anyhow::Result<()> {
if self.source_dir.join("Cargo.lock").exists() {
info!(
"crate {} already has a lockfile, it will not be regenerated",
self.krate
);
return Ok(());
}
let mut cmd = Command::new(self.workspace, self.toolchain.cargo())
.args(&["generate-lockfile", "--manifest-path", "Cargo.toml"])
.args(&self.extra_cargo_args);
if !self.workspace.fetch_registry_index_during_builds() {
cmd = cmd
.args(&["-Zno-index-update"])
.env("__CARGO_TEST_CHANNEL_OVERRIDE_DO_NOT_USE_THIS", "nightly");
}
run_command(cmd.cd(self.source_dir))
}
fn fetch_deps(&mut self) -> anyhow::Result<()> {
fetch_deps(
self.workspace,
self.toolchain,
self.source_dir,
&[],
&self.extra_cargo_args,
)
}
}
pub(crate) fn fetch_deps(
workspace: &Workspace,
toolchain: &Toolchain,
source_dir: &Path,
fetch_build_std_targets: &[&str],
extra_cargo_args: &[String],
) -> anyhow::Result<()> {
let mut cmd = Command::new(workspace, toolchain.cargo())
.args(&["fetch", "--manifest-path", "Cargo.toml"])
.args(extra_cargo_args)
.cd(source_dir);
// Pass `-Zbuild-std` in case a build in the sandbox wants to use it;
// build-std has to have the source for libstd's dependencies available.
if !fetch_build_std_targets.is_empty() {
toolchain.add_component(workspace, "rust-src")?;
cmd = cmd.args(&["-Zbuild-std"]).env("RUSTC_BOOTSTRAP", "1");
}
for target in fetch_build_std_targets {
cmd = cmd.args(&["--target", target]);
}
run_command(cmd)
}
fn run_command(cmd: Command) -> anyhow::Result<()> {
let mut yanked_deps = false;
let mut missing_deps = false;
let mut broken_deps = false;
let mut broken_lockfile = false;
let mut process = |line: &str, _: &mut ProcessLinesActions| {
if line.contains("failed to select a version for the requirement") {
yanked_deps = true;
} else if line.contains("failed to load source for dependency")
|| line.contains("no matching package named")
|| line.contains("no matching package found")
|| line.contains("no matching package for override ")
|| (line.contains("The patch location ")
&& line.contains(" does not appear to contain any packages matching the name "))
{
missing_deps = true;
} else if line.contains("failed to parse manifest at")
|| line.contains("error: invalid table header")
|| (line.contains("error: unexpected ") && line.contains(", expected "))
|| line.contains("error: invalid type: ")
|| line.contains("error: cyclic feature dependency: feature ")
|| line.contains("error: cyclic package dependency: package ")
|| (line.contains("error: package collision in the lockfile: packages ")
&& line.contains(
" are different, but only one can be written to lockfile unambiguously",
))
{
broken_deps = true;
} else if line.contains("error: failed to parse lock file at")
|| line.contains(
"error: Attempting to resolve a dependency with more than one crate with links=",
)
{
broken_lockfile = true;
}
};
match cmd.process_lines(&mut process).run_capture() {
Ok(_) => Ok(()),
Err(CommandError::ExecutionFailed { status: _, stderr }) if yanked_deps => {
Err(PrepareError::YankedDependencies(stderr).into())
}
Err(CommandError::ExecutionFailed { status: _, stderr }) if missing_deps => {
Err(PrepareError::MissingDependencies(stderr).into())
}
Err(CommandError::ExecutionFailed { status: _, stderr }) if broken_deps => {
Err(PrepareError::BrokenDependencies(stderr).into())
}
Err(CommandError::ExecutionFailed { status: _, stderr }) if broken_lockfile => {
Err(PrepareError::InvalidCargoLock(stderr).into())
}
Err(err) => Err(err.into()),
}
}
struct TomlTweaker<'a> {
krate: &'a Crate,
table: Table,
dir: Option<&'a Path>,
patches: Vec<CratePatch>,
}
impl<'a> TomlTweaker<'a> {
pub fn new(
krate: &'a Crate,
cargo_toml: &'a Path,
patches: &[CratePatch],
) -> anyhow::Result<Self> {
let toml_content =
::std::fs::read_to_string(cargo_toml).context(PrepareError::MissingCargoToml)?;
let table: Table =
toml::from_str(&toml_content).context(PrepareError::InvalidCargoTomlSyntax)?;
let dir = cargo_toml.parent();
Ok(TomlTweaker {
krate,
table,
dir,
patches: patches.to_vec(),
})
}
#[cfg(test)]
fn new_with_table(krate: &'a Crate, table: Table, patches: &[CratePatch]) -> Self {
TomlTweaker {
krate,
table,
dir: None,
patches: patches.to_vec(),
}
}
pub fn tweak(&mut self) {
info!("started tweaking {}", self.krate);
self.remove_missing_items("example");
self.remove_missing_items("test");
self.remove_parent_workspaces();
self.remove_unwanted_cargo_features();
self.apply_patches();
info!("finished tweaking {}", self.krate);
}
#[allow(clippy::ptr_arg)]
fn test_existance(dir: &Path, value: &Array, folder: &str) -> Array {
value
.iter()
.filter_map(|t| t.as_table())
.filter_map(|t| {
t.get("name")
.and_then(Value::as_str)
.map(|n| (t, n.to_owned()))
})
.map(|(table, name)| {
let path = table.get("path").map_or_else(
|| dir.join(folder).join(name + ".rs"),
|path| dir.join(path.as_str().unwrap()),
);
(table, path)
})
.filter(|(_table, path)| path.exists())
.filter_map(|(table, _path)| Value::try_from(table).ok())
.collect()
}
fn remove_missing_items(&mut self, category: &str) {
let folder = &(String::from(category) + "s");
if let Some(dir) = self.dir
&& let Some(&mut Value::Array(ref mut array)) = self.table.get_mut(category)
{
let dim = array.len();
*(array) = Self::test_existance(dir, array, folder);
info!("removed {} missing {}", dim - array.len(), folder);
}
}
fn remove_parent_workspaces(&mut self) {
let krate = self.krate.to_string();
// Eliminate parent workspaces
if let Some(&mut Value::Table(ref mut package)) = self.table.get_mut("package")
&& package.remove("workspace").is_some()
{
info!("removed parent workspace from {krate}");
}
}
fn remove_unwanted_cargo_features(&mut self) {
let krate = self.krate.to_string();
// Remove the unwanted features from the main list
let mut has_publish_lockfile = false;
let mut has_default_run = false;
if let Some(&mut Value::Array(ref mut vec)) = self.table.get_mut("cargo-features") {
vec.retain(|key| {
if let Value::String(key) = key {
match key.as_str() {
"publish-lockfile" => has_publish_lockfile = true,
"default-run" => has_default_run = true,
_ => return true,
}
}
false
});
}
// Strip the 'publish-lockfile' key from [package]
if has_publish_lockfile {
info!("disabled cargo feature 'publish-lockfile' from {krate}");
if let Some(&mut Value::Table(ref mut package)) = self.table.get_mut("package") {
package.remove("publish-lockfile");
}
}
// Strip the 'default-run' key from [package]
if has_default_run {
info!("disabled cargo feature 'default-run' from {krate}");
if let Some(&mut Value::Table(ref mut package)) = self.table.get_mut("package") {
package.remove("default-run");
}
}
}
fn apply_patches(&mut self) {
if !self.patches.is_empty() {
let mut patch_table = self.table.get_mut("patch");
let patch_table = match patch_table {
Some(ref mut pt) => pt,
None => {
self.table
.insert("patch".to_string(), Value::Table(Table::new()));
self.table.get_mut("patch").unwrap()
}
};
let mut cratesio_table = patch_table.get_mut("crates-io");
let cratesio_table = match cratesio_table {
Some(ref mut cio) => cio,
None => {
patch_table
.as_table_mut()
.unwrap()
.insert("crates-io".to_string(), Value::Table(Table::new()));
patch_table.get_mut("crates-io").unwrap()
}
};
for patch in self.patches.iter().cloned() {
let (name, table) = match patch {
CratePatch::Git(patch) => {
let mut table = Table::new();
table.insert("git".into(), Value::String(patch.uri));
table.insert("branch".into(), Value::String(patch.branch));
(patch.name, table)
}
CratePatch::Path(patch) => {
let mut table = Table::new();
table.insert("path".into(), Value::String(patch.path.clone()));
(patch.name, table)
}
};
cratesio_table
.as_table_mut()
.unwrap()
.insert(name, Value::Table(table));
}
}
}
pub fn save(self, output_file: &Path) -> anyhow::Result<()> {
let crate_name = self.krate.to_string();
::std::fs::write(output_file, toml::to_string(&self.table)?.as_bytes())?;
info!(
"tweaked toml for {} written to {}",
crate_name,
output_file.to_string_lossy()
);
Ok(())
}
}
/// Error happened while preparing a crate for a build.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum PrepareError {
/// The git repository isn't publicly available.
#[error("can't fetch private git repositories")]
PrivateGitRepository,
/// The crate doesn't have a `Cargo.toml` in its source code.
#[error("missing Cargo.toml")]
MissingCargoToml,
/// The crate's Cargo.toml is invalid, either due to a TOML syntax error in it or cargo
/// rejecting it.
#[error("invalid Cargo.toml syntax")]
InvalidCargoTomlSyntax,
/// Something about the crates dependencies is invalid
#[error("broken dependencies: \n\n{0}")]
BrokenDependencies(String),
/// Some of this crate's dependencies were yanked, preventing Crater from fetching them.
#[error("the crate depends on yanked dependencies: \n\n{0}")]
YankedDependencies(String),
/// Some of the dependencies do not exist anymore.
#[error("the crate depends on missing dependencies: \n\n{0}")]
MissingDependencies(String),
/// cargo rejected (generating) the lockfile
#[error("the crate has a broken lockfile: \n\n{0}")]
InvalidCargoLock(String),
/// Uncategorized error
#[doc(hidden)]
#[error("uncategorized prepare error")]
Uncategorized,
}
#[cfg(test)]
mod tests {
use super::TomlTweaker;
use crate::build::{CratePatch, GitCratePatch, PathCratePatch};
use crate::crates::Crate;
use toml::toml;
#[test]
fn test_tweak_table_noop() {
let toml = toml! {
cargo-features = ["foobar"]
[package]
name = "foo"
version = "1.0"
};
let result = toml.clone();
let krate = Crate::local("/dev/null".as_ref());
let patches: Vec<CratePatch> = Vec::new();
let mut tweaker = TomlTweaker::new_with_table(&krate, toml, &patches);
tweaker.tweak();
assert_eq!(tweaker.table, result);
}
#[test]
fn test_tweak_table_changes() {
let toml = toml! {
cargo-features = ["foobar", "publish-lockfile", "default-run"]
[package]
name = "foo"
version = "1.0"
workspace = ".."
publish-lockfile = true
default-run = "foo"
[workspace]
members = []
};
let result = toml! {
cargo-features = ["foobar"]
[package]
name = "foo"
version = "1.0"
[workspace]
members = []
};
let krate = Crate::local("/dev/null".as_ref());
let patches: Vec<CratePatch> = Vec::new();
let mut tweaker = TomlTweaker::new_with_table(&krate, toml, &patches);
tweaker.tweak();
assert_eq!(tweaker.table, result);
}
#[test]
fn test_tweak_table_patches() {
let toml = toml! {
cargo-features = ["foobar"]
[package]
name = "foo"
version = "1.0"
[dependencies]
bar = "1.0"
[dev-dependencies]
baz = "1.0"
[target."cfg(unix)".dependencies]
quux = "1.0"
};
let result = toml! {
cargo-features = ["foobar"]
[package]
name = "foo"
version = "1.0"
[dependencies]
bar = "1.0"
[dev-dependencies]
baz = "1.0"
[target."cfg(unix)".dependencies]
quux = "1.0"
[patch.crates-io]
quux = { git = "https://git.example.com/quux", branch = "dev" }
baz = { path = "/path/to/baz" }
};
let krate = Crate::local("/dev/null".as_ref());
let patches = vec![
CratePatch::Git(GitCratePatch {
name: "quux".into(),
uri: "https://git.example.com/quux".into(),
branch: "dev".into(),
}),
CratePatch::Path(PathCratePatch {
name: "baz".into(),
path: "/path/to/baz".into(),
}),
];
let mut tweaker = TomlTweaker::new_with_table(&krate, toml, &patches);
tweaker.tweak();
assert_eq!(tweaker.table, result);
}
}