-
Notifications
You must be signed in to change notification settings - Fork 894
/
manifest.rs
732 lines (648 loc) · 22.3 KB
/
manifest.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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
//! Rust distribution v2 manifests.
//!
//! This manifest describes the distributable artifacts for a single
//! release of Rust. They are toml files, typically downloaded from
//! e.g. static.rust-lang.org/dist/channel-rust-nightly.toml. They
//! describe where to download, for all platforms, each component of
//! the release, and their relationships to each other.
//!
//! Installers use this info to customize Rust installations.
//!
//! See tests/channel-rust-nightly-example.toml for an example.
//!
//! Docs: <https://forge.rust-lang.org/infra/channel-layout.html>
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::str::FromStr;
use anyhow::{anyhow, bail, Context, Result};
use serde::{Deserialize, Serialize};
use crate::{
dist::{config::Config, Profile, TargetTriple, ToolchainDesc},
errors::*,
toolchain::DistributableToolchain,
};
/// Used by the `installed_components` function
pub(crate) struct ComponentStatus {
pub component: Component,
pub name: String,
pub installed: bool,
pub available: bool,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct Manifest {
pub(crate) manifest_version: ManifestVersion,
pub date: String,
#[serde(default, rename = "pkg")]
pub packages: HashMap<String, Package>,
#[serde(default)]
pub renames: HashMap<String, Renamed>,
#[serde(default, skip_serializing)]
pub reverse_renames: HashMap<String, String>,
#[serde(default)]
pub profiles: HashMap<Profile, Vec<String>>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Renamed {
pub to: String,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Package {
pub version: String,
#[serde(rename = "target")]
pub targets: PackageTargets,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(from = "TargetsMap", into = "TargetsMap")]
pub enum PackageTargets {
Wildcard(TargetedPackage),
Targeted(HashMap<TargetTriple, TargetedPackage>),
}
#[derive(Deserialize, Serialize)]
#[serde(transparent)]
struct TargetsMap(HashMap<TargetTriple, TargetedPackage>);
impl From<TargetsMap> for PackageTargets {
fn from(mut map: TargetsMap) -> Self {
let wildcard = TargetTriple::new("*");
match (map.0.len(), map.0.entry(wildcard)) {
(1, Entry::Occupied(entry)) => Self::Wildcard(entry.remove()),
(_, _) => Self::Targeted(map.0),
}
}
}
impl From<PackageTargets> for TargetsMap {
fn from(targets: PackageTargets) -> Self {
match targets {
PackageTargets::Wildcard(tpkg) => {
let mut map = HashMap::new();
map.insert(TargetTriple::new("*"), tpkg);
Self(map)
}
PackageTargets::Targeted(tpkgs) => Self(tpkgs),
}
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(from = "Target", into = "Target")]
pub struct TargetedPackage {
#[serde(default)]
pub bins: Vec<HashedBinary>,
pub components: Vec<Component>,
}
#[derive(Debug, Deserialize, Serialize)]
struct Target {
available: bool,
url: Option<String>,
hash: Option<String>,
xz_url: Option<String>,
xz_hash: Option<String>,
zst_url: Option<String>,
zst_hash: Option<String>,
components: Option<Vec<Component>>,
extensions: Option<Vec<Component>>,
}
impl From<Target> for TargetedPackage {
fn from(target: Target) -> Self {
let mut components = target.components.unwrap_or_default();
if let Some(extensions) = target.extensions {
components.extend(extensions.into_iter().map(|mut c| {
c.is_extension = true;
c
}));
}
let mut bins = Vec::new();
if !target.available {
return Self { bins, components };
}
if let (Some(url), Some(hash)) = (target.zst_url, target.zst_hash) {
bins.push(HashedBinary {
url,
hash,
compression: CompressionKind::ZStd,
});
}
if let (Some(url), Some(hash)) = (target.xz_url, target.xz_hash) {
bins.push(HashedBinary {
url,
hash,
compression: CompressionKind::XZ,
});
}
if let (Some(url), Some(hash)) = (target.url, target.hash) {
bins.push(HashedBinary {
url,
hash,
compression: CompressionKind::GZip,
});
}
Self { bins, components }
}
}
impl From<TargetedPackage> for Target {
fn from(tpkg: TargetedPackage) -> Self {
let (mut url, mut hash) = (None, None);
let (mut xz_url, mut xz_hash) = (None, None);
let (mut zst_url, mut zst_hash) = (None, None);
let available = !tpkg.bins.is_empty();
for bin in tpkg.bins {
match bin.compression {
CompressionKind::GZip => {
url = Some(bin.url);
hash = Some(bin.hash);
}
CompressionKind::XZ => {
xz_url = Some(bin.url);
xz_hash = Some(bin.hash);
}
CompressionKind::ZStd => {
zst_url = Some(bin.url);
zst_hash = Some(bin.hash);
}
}
}
let (mut components, mut extensions) =
(Vec::with_capacity(tpkg.components.len()), Vec::new());
for c in tpkg.components {
match c.is_extension {
true => &mut extensions,
false => &mut components,
}
.push(c);
}
Self {
available,
url,
hash,
xz_url,
xz_hash,
zst_url,
zst_hash,
components: Some(components),
extensions: Some(extensions),
}
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum CompressionKind {
GZip,
XZ,
ZStd,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HashedBinary {
pub url: String,
pub hash: String,
pub compression: CompressionKind,
}
#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialOrd, Serialize)]
pub struct Component {
pub pkg: String,
#[serde(with = "component_target")]
pub target: Option<TargetTriple>,
// Older Rustup distinguished between components (which are essential) and
// extensions (which are not).
#[serde(default)]
pub is_extension: bool,
}
impl PartialEq for Component {
fn eq(&self, other: &Self) -> bool {
self.pkg == other.pkg && self.target == other.target
}
}
impl Hash for Component {
fn hash<H>(&self, hasher: &mut H)
where
H: Hasher,
{
self.pkg.hash(hasher);
self.target.hash(hasher);
}
}
mod component_target {
use super::*;
use serde::{Deserialize, Deserializer, Serializer};
pub fn serialize<S: Serializer>(
target: &Option<TargetTriple>,
serializer: S,
) -> Result<S::Ok, S::Error> {
serializer.serialize_str(match target {
Some(t) => t,
None => "*",
})
}
pub fn deserialize<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<Option<TargetTriple>, D::Error> {
Ok(match Option::<String>::deserialize(deserializer)? {
Some(s) if s != "*" => Some(TargetTriple::new(s)),
_ => None,
})
}
}
impl Manifest {
pub fn parse(data: &str) -> Result<Self> {
let mut manifest = toml::from_str::<Self>(data).context("error parsing manifest")?;
for (from, to) in manifest.renames.iter() {
manifest.reverse_renames.insert(to.to.clone(), from.clone());
}
manifest.validate()?;
Ok(manifest)
}
pub fn stringify(self) -> anyhow::Result<String> {
Ok(toml::to_string(&self)?)
}
pub fn get_package(&self, name: &str) -> Result<&Package> {
self.packages
.get(name)
.ok_or_else(|| anyhow!(format!("package not found: '{name}'")))
}
pub(crate) fn get_rust_version(&self) -> Result<&str> {
self.get_package("rust").map(|p| &*p.version)
}
pub(crate) fn get_legacy_components(&self, target: &TargetTriple) -> Result<Vec<Component>> {
// Build a profile from the components/extensions.
let result = self
.get_package("rust")?
.get_target(Some(target))?
.components
.iter()
.filter(|c| !c.is_extension && c.target.as_ref().map(|t| t == target).unwrap_or(true))
.cloned()
.collect();
Ok(result)
}
pub fn get_profile_components(
&self,
profile: Profile,
target: &TargetTriple,
) -> Result<Vec<Component>> {
// An older manifest with no profiles section.
if self.profiles.is_empty() {
return self.get_legacy_components(target);
}
let profile = self
.profiles
.get(&profile)
.ok_or_else(|| anyhow!(format!("profile not found: '{profile}'")))?;
let rust_pkg = self.get_package("rust")?.get_target(Some(target))?;
let result = profile
.iter()
.map(|s| {
(
s,
rust_pkg.components.iter().find(|c| {
&c.pkg == s && c.target.as_ref().map(|t| t == target).unwrap_or(true)
}),
)
})
.filter(|(_, c)| c.is_some())
.map(|(s, c)| Component::new(s.to_owned(), c.and_then(|c| c.target.clone()), false))
.collect();
Ok(result)
}
fn validate_targeted_package(&self, tpkg: &TargetedPackage) -> Result<()> {
for c in tpkg.components.iter() {
let cpkg = self
.get_package(&c.pkg)
.with_context(|| RustupError::MissingPackageForComponent(c.short_name(self)))?;
let _ctpkg = cpkg
.get_target(c.target.as_ref())
.with_context(|| RustupError::MissingPackageForComponent(c.short_name(self)))?;
}
Ok(())
}
fn validate(&self) -> Result<()> {
// Every component mentioned must have an actual package to download
for pkg in self.packages.values() {
match pkg.targets {
PackageTargets::Wildcard(ref tpkg) => {
self.validate_targeted_package(tpkg)?;
}
PackageTargets::Targeted(ref tpkgs) => {
for tpkg in tpkgs.values() {
self.validate_targeted_package(tpkg)?;
}
}
}
}
// The target of any renames must be an actual package. The subject of
// renames is unconstrained.
for renamed in self.renames.values() {
let name = &renamed.to;
if !self.packages.contains_key(name) {
bail!(format!(
"server sent a broken manifest: missing package for the target of a rename {name}"
));
}
}
Ok(())
}
// If the component should be renamed by this manifest, then return a new
// component with the new name. If not, return `None`.
pub(crate) fn rename_component(&self, component: &Component) -> Option<Component> {
self.renames.get(&component.pkg).map(|r| {
let mut c = component.clone();
c.pkg.clone_from(&r.to);
c
})
}
/// Determine installed components from an installed manifest.
pub(crate) fn query_components(
&self,
desc: &ToolchainDesc,
config: &Config,
) -> Result<Vec<ComponentStatus>> {
// Return all optional components of the "rust" package for the
// toolchain's target triple.
let mut res = Vec::new();
let rust_pkg = self
.packages
.get("rust")
.expect("manifest should contain a rust package");
let targ_pkg = rust_pkg
.targets
.get(&desc.target)
.expect("installed manifest should have a known target");
for component in &targ_pkg.components {
let installed = component.contained_within(&config.components);
let component_target = TargetTriple::new(component.target());
// Get the component so we can check if it is available
let component_pkg = self
.get_package(component.short_name_in_manifest())
.unwrap_or_else(|_| {
panic!(
"manifest should contain component {}",
&component.short_name(self)
)
});
let component_target_pkg = component_pkg
.targets
.get(&component_target)
.expect("component should have target toolchain");
res.push(ComponentStatus {
component: component.clone(),
name: component.name(self),
installed,
available: component_target_pkg.available(),
});
}
res.sort_by(|a, b| a.component.cmp(&b.component));
Ok(res)
}
}
impl Package {
pub fn get_target(&self, target: Option<&TargetTriple>) -> Result<&TargetedPackage> {
match self.targets {
PackageTargets::Wildcard(ref tpkg) => Ok(tpkg),
PackageTargets::Targeted(ref tpkgs) => {
if let Some(t) = target {
tpkgs
.get(t)
.ok_or_else(|| anyhow!(format!("target '{t}' not found in channel. \
Perhaps check https://doc.rust-lang.org/nightly/rustc/platform-support.html for available targets")))
} else {
Err(anyhow!("no target specified"))
}
}
}
}
}
impl PackageTargets {
pub(crate) fn get<'a>(&'a self, target: &TargetTriple) -> Option<&'a TargetedPackage> {
match self {
Self::Wildcard(tpkg) => Some(tpkg),
Self::Targeted(tpkgs) => tpkgs.get(target),
}
}
pub fn get_mut<'a>(&'a mut self, target: &TargetTriple) -> Option<&'a mut TargetedPackage> {
match self {
Self::Wildcard(tpkg) => Some(tpkg),
Self::Targeted(tpkgs) => tpkgs.get_mut(target),
}
}
}
impl TargetedPackage {
pub fn available(&self) -> bool {
!self.bins.is_empty()
}
}
impl Component {
pub fn new(pkg: String, target: Option<TargetTriple>, is_extension: bool) -> Self {
Self {
pkg,
target,
is_extension,
}
}
pub(crate) fn try_new(
name: &str,
distributable: &DistributableToolchain<'_>,
fallback_target: Option<&TargetTriple>,
) -> Result<Self> {
let manifest = distributable.get_manifest()?;
for component_status in distributable.components()? {
let component = component_status.component;
if name == component.name_in_manifest() || name == component.name(&manifest) {
return Ok(component);
}
}
Ok(Component::new(
name.to_string(),
fallback_target.cloned(),
true,
))
}
pub(crate) fn wildcard(&self) -> Self {
Self {
pkg: self.pkg.clone(),
target: None,
is_extension: false,
}
}
pub(crate) fn name(&self, manifest: &Manifest) -> String {
let pkg = self.short_name(manifest);
if let Some(ref t) = self.target {
format!("{pkg}-{t}")
} else {
pkg
}
}
pub(crate) fn short_name(&self, manifest: &Manifest) -> String {
if let Some(from) = manifest.reverse_renames.get(&self.pkg) {
from.to_owned()
} else {
self.pkg.clone()
}
}
pub(crate) fn description(&self, manifest: &Manifest) -> String {
let pkg = self.short_name(manifest);
if let Some(ref t) = self.target {
format!("'{pkg}' for target '{t}'")
} else {
format!("'{pkg}'")
}
}
pub fn short_name_in_manifest(&self) -> &String {
&self.pkg
}
pub(crate) fn name_in_manifest(&self) -> String {
let pkg = self.short_name_in_manifest();
if let Some(ref t) = self.target {
format!("{pkg}-{t}")
} else {
pkg.to_string()
}
}
pub(crate) fn target(&self) -> String {
if let Some(t) = self.target.as_ref() {
t.to_string()
} else {
String::new()
}
}
pub(crate) fn contained_within(&self, components: &[Component]) -> bool {
if components.contains(self) {
// Yes, we're within the component set, move on
true
} else if self.target.is_none() {
// We weren't in the given component set, but we're a package
// which targets "*" and as such older rustups might have
// accidentally made us target specific due to a bug in profiles.
components
.iter()
// As such, if our target is None, it's sufficient to check pkg
.any(|other| other.pkg == self.pkg)
} else {
// As a last ditch effort, we're contained within the component
// set if the name matches and the other component's target
// is None
components
.iter()
.any(|other| other.pkg == self.pkg && other.target.is_none())
}
}
}
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub(crate) enum ManifestVersion {
#[serde(rename = "2")]
#[default]
V2,
}
impl ManifestVersion {
pub fn as_str(&self) -> &'static str {
match self {
Self::V2 => "2",
}
}
}
impl FromStr for ManifestVersion {
type Err = RustupError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"2" => Ok(Self::V2),
_ => Err(RustupError::UnsupportedVersion(s.to_owned())),
}
}
}
impl fmt::Display for ManifestVersion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
#[cfg(test)]
mod tests {
use crate::dist::manifest::Manifest;
use crate::dist::TargetTriple;
use crate::RustupError;
// Example manifest from https://public.etherpad-mozilla.org/p/Rust-infra-work-week
static EXAMPLE: &str = include_str!("manifest/tests/channel-rust-nightly-example.toml");
// From brson's live build-rust-manifest.py script
static EXAMPLE2: &str = include_str!("manifest/tests/channel-rust-nightly-example2.toml");
#[test]
fn parse_smoke_test() {
let x86_64_unknown_linux_gnu = TargetTriple::new("x86_64-unknown-linux-gnu");
let x86_64_unknown_linux_musl = TargetTriple::new("x86_64-unknown-linux-musl");
let pkg = Manifest::parse(EXAMPLE).unwrap();
pkg.get_package("rust").unwrap();
pkg.get_package("rustc").unwrap();
pkg.get_package("cargo").unwrap();
pkg.get_package("rust-std").unwrap();
pkg.get_package("rust-docs").unwrap();
let rust_pkg = pkg.get_package("rust").unwrap();
assert!(rust_pkg.version.contains("1.3.0"));
let rust_target_pkg = rust_pkg
.get_target(Some(&x86_64_unknown_linux_gnu))
.unwrap();
assert!(rust_target_pkg.available());
assert_eq!(rust_target_pkg.bins[0].url, "example.com");
assert_eq!(rust_target_pkg.bins[0].hash, "...");
let component = &rust_target_pkg.components[0];
assert_eq!(component.short_name_in_manifest(), "rustc");
assert_eq!(component.target.as_ref(), Some(&x86_64_unknown_linux_gnu));
let component = &rust_target_pkg.components[4];
assert_eq!(component.short_name_in_manifest(), "rust-std");
assert_eq!(component.target.as_ref(), Some(&x86_64_unknown_linux_musl));
let docs_pkg = pkg.get_package("rust-docs").unwrap();
let docs_target_pkg = docs_pkg
.get_target(Some(&x86_64_unknown_linux_gnu))
.unwrap();
assert_eq!(docs_target_pkg.bins[0].url, "example.com");
}
#[test]
fn renames() {
let manifest = Manifest::parse(EXAMPLE2).unwrap();
assert_eq!(1, manifest.renames.len());
assert_eq!(manifest.renames["cargo-old"].to, "cargo");
assert_eq!(1, manifest.reverse_renames.len());
assert_eq!(manifest.reverse_renames["cargo"], "cargo-old");
}
#[test]
fn parse_round_trip() {
let original = Manifest::parse(EXAMPLE).unwrap();
let serialized = original.clone().stringify().unwrap();
let new = Manifest::parse(&serialized).unwrap();
assert_eq!(original, new);
let original = Manifest::parse(EXAMPLE2).unwrap();
let serialized = original.clone().stringify().unwrap();
let new = Manifest::parse(&serialized).unwrap();
assert_eq!(original, new);
}
#[test]
fn validate_components_have_corresponding_packages() {
let manifest = r#"
manifest-version = "2"
date = "2015-10-10"
[pkg.rust]
version = "rustc 1.3.0 (9a92aaf19 2015-09-15)"
[pkg.rust.target.x86_64-unknown-linux-gnu]
available = true
url = "example.com"
hash = "..."
[[pkg.rust.target.x86_64-unknown-linux-gnu.components]]
pkg = "rustc"
target = "x86_64-unknown-linux-gnu"
[[pkg.rust.target.x86_64-unknown-linux-gnu.extensions]]
pkg = "rust-std"
target = "x86_64-unknown-linux-musl"
[pkg.rustc]
version = "rustc 1.3.0 (9a92aaf19 2015-09-15)"
[pkg.rustc.target.x86_64-unknown-linux-gnu]
available = true
url = "example.com"
hash = "..."
"#;
let err = Manifest::parse(manifest).unwrap_err();
match err.downcast::<RustupError>().unwrap() {
RustupError::MissingPackageForComponent(_) => {}
_ => panic!(),
}
}
// #248
#[test]
fn manifest_can_contain_unknown_targets() {
let manifest = EXAMPLE.replace("x86_64-unknown-linux-gnu", "mycpu-myvendor-myos");
assert!(Manifest::parse(&manifest).is_ok());
}
}