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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
use std::{
borrow::Cow,
collections::{BTreeMap, HashMap},
ffi::OsString,
fmt::{self, Display},
hash::Hash,
path::{Path, PathBuf},
};
use anyhow::{Context, bail};
use colored::Colorize;
use serde::{Deserialize, Serialize};
use sha2::Digest;
use crate::{
artifact::{Artifacts, TargetTriple},
config::Config,
profile::Profile,
toolchain::{Toolchain, ToolchainJustification},
utils,
version::{Authority, GitTarget},
};
/// Hash created to distinguish one installed channel from the another.
pub struct ChannelHash(String);
impl Display for ChannelHash {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
#[derive(Serialize, Deserialize, Debug, Clone, Hash)]
#[serde(untagged)]
pub enum MigrationStrategy {
NameChange { old_channel: semver::Version },
}
/// Tags used to identify special qualities of a specific channel.
#[derive(Serialize, Deserialize, Debug, Clone, Hash)]
#[serde(rename_all = "snake_case")]
pub enum Tags {
/// The channel is partially installed, i.e. only a subset of components
/// have been installed.
Partial,
/// The channel has been moved to a new channel or potentially even removed.
Migration {
#[serde(flatten)]
migration: MigrationStrategy,
},
}
/// Represents a specific release channel for a toolchain.
///
/// Different channels have different stability guarantees. See the specific details for the
/// channel you are interested in to learn more.
#[derive(Serialize, Deserialize, Debug, Clone, Hash)]
pub struct Channel {
/// Channels are identified by their name. The name corresponds to the channel's version.
/// The version can contain suffixes such as "-custom", "-beta".
pub name: semver::Version,
/// This is used to tag special channels. Most notably, the current "stable" channel is marked
/// with the [`ChannelAlias::Stable`] alias.
#[serde(skip_serializing_if = "Option::is_none")]
pub alias: Option<ChannelAlias>,
/// Set of tags used to denote a special characteristic about the channel.
///
/// Mainly used for locally installed channels.
#[serde(default)]
#[serde(skip_serializing_if = "Vec::is_empty")]
pub tags: Vec<Tags>,
/// The set of toolchain components available in this channel
pub components: Vec<Component>,
}
enum InstallationMotive {
ExplicitelySelected,
Dependency { comp_name: String },
}
impl Display for InstallationMotive {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
InstallationMotive::Dependency { comp_name } => {
write!(f, "is a depency of component {comp_name}")
},
InstallationMotive::ExplicitelySelected => {
write!(f, "was explictely selected for installation")
},
}
}
}
#[derive(Debug, Clone)]
pub enum UpstreamMatch {
/// The remote Channel is this Channel's upstream equivalent.
UpstreamCounterpart,
/// The remote Channel is this Channel's equivalent and got migrated.
Migrated(MigrationStrategy),
}
#[derive(Debug, Clone)]
pub struct UpstreamChannel {
pub channel: Channel,
pub upstream_match: UpstreamMatch,
}
impl UpstreamChannel {
pub fn new(channel: Channel, upstream_match: UpstreamMatch, config: &Config) -> Self {
let mut synced_channel = channel.clone();
synced_channel.sync(config);
UpstreamChannel { channel: synced_channel, upstream_match }
}
}
impl Channel {
pub fn new(
name: semver::Version,
alias: Option<ChannelAlias>,
components: Vec<Component>,
tags: Vec<Tags>,
) -> Self {
Self { name, alias, components, tags }
}
pub fn get_component(&self, name: impl AsRef<str>) -> Option<&Component> {
let name = name.as_ref();
self.components.iter().find(|c| c.name == name)
}
pub fn get_component_mut(&mut self, name: impl AsRef<str>) -> Option<&mut Component> {
let name = name.as_ref();
self.components.iter_mut().find(|c| c.name == name)
}
/// Is this channel a stable release? Does not imply that it has the `stable` alias.
///
/// To find out the latest stable [Channel], use [crate::manifest::Manifest::get_latest_stable].
pub fn is_stable(&self) -> bool {
self.alias.as_ref().is_none_or(|alias| matches!(alias, ChannelAlias::Stable))
}
pub fn is_nightly(&self) -> bool {
self.alias
.as_ref()
.is_some_and(|alias| matches!(alias, ChannelAlias::Nightly(_)))
}
/// Determines if the current toolchain was installed "partially", i.e., containing only a
/// subset of all the available components. This can be the case with `miden-toolchain.toml`.
pub fn is_partially_installed(&self) -> bool {
self.tags.iter().any(|tag| matches!(tag, Tags::Partial))
}
pub fn is_latest_nightly(&self) -> bool {
self.alias
.as_ref()
.is_some_and(|alias| matches!(alias, ChannelAlias::Nightly(None)))
}
pub fn get_channel_dir(&self, config: &Config) -> PathBuf {
let installed_toolchains_dir = config.midenup_home.join("toolchains");
installed_toolchains_dir.join(format!("{}", self.name))
}
pub fn content_hash(&self) -> ChannelHash {
use core::fmt::Write;
struct Sha256Hasher(sha2::Sha256);
impl core::hash::Hasher for Sha256Hasher {
fn finish(&self) -> u64 {
panic!("finish is intended to be left unused")
}
fn write(&mut self, bytes: &[u8]) {
self.0.update(bytes);
}
}
let mut h = Sha256Hasher(sha2::Sha256::new());
self.hash(&mut h);
let out = h.0.finalize();
let mut hex = String::with_capacity(64);
for byte in out {
write!(&mut hex, "{byte:02x}").expect("failed to write channel hash");
}
ChannelHash(hex)
}
/// Get all the aliases that the Channel is aware of
pub fn get_aliases(&self) -> HashMap<Alias, CliCommands> {
self.components.iter().fold(HashMap::new(), |mut acc, component| {
acc.extend(component.aliases.clone());
acc
})
}
/// Creates a "partial channel" from the original channel, given a toolchain "Partial" in this
/// context refers to the fact that the channel will not install all the available components,
/// but rather a subset.
pub fn create_subset(
&self,
current_toolchain: &Toolchain,
toolchain_justification: &ToolchainJustification,
) -> Option<Channel> {
let profile = current_toolchain.profile.unwrap_or_default();
let mut requested_components = Vec::new();
let mut components_to_install: Vec<Component> = Vec::new();
let mut components_not_found: HashMap<String, Vec<InstallationMotive>> = HashMap::new();
match profile {
Profile::Minimal => {
// Select components that are not marked "optional" from the manifest
requested_components.extend(
self.components
.iter()
.filter_map(|c| if c.optional { None } else { Some(c.name.as_ref()) }),
);
for extra_component in current_toolchain.components.iter() {
if !requested_components.contains(&extra_component.as_str()) {
requested_components.push(extra_component.as_str());
}
}
},
Profile::Complete => {
// Select all components from the manifest
requested_components.extend(self.components.iter().map(|c| c.name.as_ref()));
// We add any non-duplicate extra components here so that we can catch invalid
// components below
for extra_component in current_toolchain.components.iter() {
if !requested_components.contains(&extra_component.as_str()) {
requested_components.push(extra_component.as_str());
}
}
},
}
for component_name in requested_components {
let Some(component) = self.get_component(component_name) else {
// NOTE: In order to provide more helpful error messages, we collect all the missing
// components and return a single error message at the end.
components_not_found
.entry(component_name.to_string())
.or_default()
.push(InstallationMotive::ExplicitelySelected);
continue;
};
components_to_install.push(component.clone());
for depenency_name in &component.requires {
let Some(dependency) = self.get_component(depenency_name) else {
components_not_found.entry(depenency_name.to_string()).or_default().push(
InstallationMotive::Dependency { comp_name: component_name.to_string() },
);
continue;
};
components_to_install.push(dependency.clone());
}
}
if !components_not_found.is_empty() {
println!(
"{}: Some elements present in the current Toolchain are not present in the \
upstream channel: {}",
"WARNING".yellow().bold(),
self.name
);
println!();
for (missing_component_name, motive) in components_not_found {
let motives = motive
.iter()
.map(|motive| motive.to_string())
.collect::<Vec<String>>()
.join(" and ");
println!(
"- {missing_component_name}, which {motives}, is missing in upstream channel"
);
}
println!();
println!("These components will be ignored for the current install.");
println!();
// TODO: Add messages for the other justifications
#[allow(clippy::single_match)]
match toolchain_justification {
ToolchainJustification::MidenToolchainFile { path } => println!(
"Check the `miden_toolchain.toml` file in {} to see if any component is \
misspelled or got removed from upstream",
path.display()
),
_ => (),
}
}
let partial_channel = Channel {
name: self.name.clone(),
alias: self.alias.clone(),
tags: vec![Tags::Partial],
components: components_to_install,
};
Some(partial_channel)
}
/// Checks wheter the channel [other] is Self's upstream counterpart.
/// Currently this can happen in two scenarios:
/// - They share the same name (i.e. version).
/// - The upstream version is tagged as having being migrated from self's .
pub fn find_upstream_counterpart(&self, config: &Config) -> Option<UpstreamChannel> {
let upstream_manifest = &config.manifest;
let mut upstream_counterpart = None;
for upstream_channel in upstream_manifest.get_channels() {
// They share version
let equal_name = self.name == upstream_channel.name;
if equal_name {
let upstream_match = UpstreamMatch::UpstreamCounterpart;
upstream_counterpart =
Some(UpstreamChannel::new(upstream_channel.clone(), upstream_match, config));
break;
};
let was_migrated = upstream_channel.tags.iter().find_map(|tag| match tag {
Tags::Migration { migration } => match migration {
// A channel is only considered as "migrated" if it's
// current name matches the "old_channel" field of an
// upstream channel.
MigrationStrategy::NameChange { old_channel } => {
if old_channel == &self.name {
Some(migration)
} else {
None
}
},
},
_ => None,
});
if let Some(migration) = was_migrated {
let upstream_match = UpstreamMatch::Migrated(migration.clone());
upstream_counterpart =
Some(UpstreamChannel::new(upstream_channel.clone(), upstream_match, config));
break;
};
}
upstream_counterpart
}
// Syncs the channel to the latest changes
fn sync(&mut self, config: &Config) {
for comp in self.components.iter_mut() {
comp.sync(config);
}
}
}
impl Display for Channel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.alias {
Some(ChannelAlias::Stable) => write!(f, "stable ({})", self.name),
Some(ChannelAlias::Tag(tag)) => write!(f, "{}-{}", self.name, tag.as_ref()),
Some(ChannelAlias::Nightly(tag)) => {
let nightly_suffix =
tag.as_ref().map(|suffix| format!("-{}", suffix)).unwrap_or(String::from(""));
write!(f, "nightly-{}{}", self.name, nightly_suffix)
},
None => write!(f, "{}", self.name),
}
}
}
/// A special alias/tag that a channel can posses. For more information see [`Channel::alias`].
/// These are only used for locally installed [`Channel`]s.
#[derive(Serialize, Debug, PartialEq, Eq, Clone, Hash)]
#[serde(rename_all = "snake_case")]
pub enum ChannelAlias {
/// Represents `stable`. Only one [Channel] can be marked as `stable` at a time.
Stable,
/// Represents either `nightly` or `nightly-$SUFFIX`
Nightly(Option<Cow<'static, str>>),
/// An ad-hoc named alias for a channel. This can be used to tag custom channels with names such
/// as `0.15.0-stable`.
#[serde(untagged)]
Tag(Cow<'static, str>),
}
impl<'de> serde::de::Deserialize<'de> for ChannelAlias {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Unexpected;
use serde_untagged::UntaggedEnumVisitor;
UntaggedEnumVisitor::new()
.string(|s| {
s.parse::<ChannelAlias>().map_err(|err| {
serde::de::Error::invalid_value(Unexpected::Str(s), &err.to_string().as_str())
})
})
.deserialize(deserializer)
}
}
impl core::str::FromStr for ChannelAlias {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"stable" => Ok(Self::Stable),
"nightly" => Ok(Self::Nightly(None)),
tag => match tag.strip_prefix("nightly-") {
Some(suffix) => Ok(Self::Nightly(Some(Cow::Owned(suffix.to_string())))),
None => Ok(Self::Tag(Cow::Owned(tag.to_string()))),
},
}
}
}
/// Represents the file that the [Component] will install in the system.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum InstalledFile {
/// The component installs an executable.
#[serde(untagged)]
Executable {
#[serde(rename = "installed_executable")]
binary_name: String,
/// The component is executable (i.e. a CLI Binary) but it is *not* intended to be executed
/// on its own, rather only under aliases.
///
/// An example of this behavior is `cargo miden`, which is only intended to be executed
/// under the `miden new` and `miden build` aliases.
///
/// IMPORTANT: In order for alias_only to take effect, binary_name *must* also be specified
/// in the manifest.
#[serde(default)]
alias_only: bool,
},
/// The component installs a MaspLibrary.
#[serde(untagged)]
Library {
#[serde(rename = "installed_library")]
library_name: String,
/// This is the name of the struct which exposes the `Library::write_to_file()` function,
/// that is used to generate the associated `.masp` file.
library_struct: String,
},
}
impl InstalledFile {
pub fn get_library_struct(&self) -> Option<&str> {
match &self {
InstalledFile::Executable { .. } => None,
InstalledFile::Library { library_struct, .. } => Some(library_struct),
}
}
pub fn get_path_from(&self, toolchain_dir: &Path) -> PathBuf {
match &self {
exe @ InstalledFile::Executable { .. } => {
toolchain_dir.join("bin").join(exe.to_string())
},
lib @ InstalledFile::Library { .. } => toolchain_dir.join("lib").join(lib.to_string()),
}
}
}
impl Display for InstalledFile {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self {
InstalledFile::Executable {
binary_name: executable_name,
alias_only: _,
} => f.write_str(executable_name),
InstalledFile::Library { library_name, library_struct: _ } => f.write_str(library_name),
}
}
}
/// Represents each possible "word" variant that is passed to the command line.
///
/// These are used to resolve an [Alias] to its associated command.
#[derive(Serialize, Deserialize, Debug, Clone, Hash)]
#[serde(rename_all = "snake_case")]
pub enum CliCommand {
/// Resolve the command to a [Component]'s corresponding executable.
Executable,
/// Resolve the command to a toolchain library directory (`<toolchain>/lib`)
#[serde(rename = "lib_path")]
LibPath,
/// Resolve the command to a toolchain var directory (`<toolchain>/var`).
///
/// Optionally, it can contain a file name, which represents a file in `<toolchain>/var/<file>`.
// NOTE: Potentially in the future, we might want this to be an Optional field
#[serde(rename = "var_path")]
VarPath,
/// An argument that is passed verbatim, as is.
#[serde(untagged)]
Verbatim(String),
}
impl fmt::Display for CliCommand {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self {
CliCommand::Executable => write!(f, "executable"),
CliCommand::LibPath => write!(f, "lib_path"),
CliCommand::VarPath => write!(f, "var_path"),
CliCommand::Verbatim(word) => write!(f, "verbatim: {word}"),
}
}
}
pub fn resolve_command(
commands: &[CliCommand],
channel: &Channel,
component: &Component,
config: &Config,
) -> anyhow::Result<Vec<OsString>> {
let mut resolution = Vec::with_capacity(commands.len());
let mut commands = commands.iter();
while let Some(command) = commands.next() {
match command {
CliCommand::Executable => {
let name = &component.name;
let component = channel.get_component(name).with_context(|| {
format!(
"Component named {} is not present in toolchain version {}",
name, channel.name
)
})?;
resolution.push(OsString::from(component.get_cli_display()));
},
CliCommand::LibPath => {
let channel_dir = channel.get_channel_dir(config);
let toolchain_path = channel_dir.join("lib");
resolution.push(toolchain_path.into_os_string())
},
// The VarPath must be followed by a file name.
CliCommand::VarPath => {
let channel_dir = channel.get_channel_dir(config);
let toolchain_path = channel_dir.join("var");
let next_command =
commands.next().context("var_path needs to be followed by a path name")?;
let CliCommand::Verbatim(directory_name) = next_command else {
bail!(format!("After var_path a file is required. Got: {}", next_command))
};
let full_path = toolchain_path.join(directory_name);
resolution.push(full_path.into_os_string())
},
CliCommand::Verbatim(name) => resolution.push(OsString::from(name)),
}
}
Ok(resolution)
}
pub type Alias = String;
/// List of the commands that need to be run when [Alias] is called.
pub type CliCommands = Vec<CliCommand>;
/// An installable component of a toolchain
#[derive(Serialize, Deserialize, Debug, Clone, Hash)]
pub struct Component {
/// The canonical name of this toolchain component.
pub name: Cow<'static, str>,
/// The versioning authority for this component.
#[serde(flatten)]
pub version: Authority,
/// Indicates that this component is not required for a minimal toolchain
#[serde(default)]
#[serde(skip_serializing_if = "is_false")]
pub optional: bool,
/// Optional features to enable, if applicable, when installing this component.
#[serde(default)]
#[serde(skip_serializing_if = "Vec::is_empty")]
pub features: Vec<String>,
/// Other components that are required if this component is installed.
#[serde(default)]
#[serde(skip_serializing_if = "Vec::is_empty")]
pub requires: Vec<String>,
/// Commands used to call the [Component]'s associated executable.
///
/// IMPORTANT: This requires the [`Component::installed_file`] field to be an
/// [`InstalledFile::Executable`] either explicitly or implicitly.
#[serde(default)]
#[serde(skip_serializing_if = "Vec::is_empty")]
call_format: Vec<CliCommand>,
/// If not None, then this component requires a specific toolchain to compile.
#[serde(default)]
#[serde(skip_serializing_if = "Option::is_none")]
pub rustup_channel: Option<String>,
/// This field is used for crates that install files whose name is different than that of the
/// crate.
///
/// For instance: `miden-vm`'s executable is stored as 'miden'. This field indicates which type
/// of file the component will install.
///
/// IMPORTANT: If this field is missing from the manifest, then it means that the component
/// will install an executable that is named just like the crate. To access this value, use
/// [`Component::get_installed_file`].
#[serde(default)]
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(flatten)]
installed_file: Option<InstalledFile>,
/// A map that associates each alias to the corresponding command that needs to be executed.
///
/// NOTE: The list of commands that is resolved can have an "arbitrary" ordering: the
/// executable associated with this command is not forced to come in first.
///
/// Here's an example aliases entry in a manifest.json:
///
/// ```json
/// {
/// "name": "component-name",
/// "package": "component-package",
/// "version": "X.Y.Z",
/// "installed_executable": "miden-component",
/// "aliases": {
/// "alias1": [{"resolve": "component-name"}, {"verbatim": "argument"}],
/// "alias2": [{"verbatim": "cargo"}, {"resolve": "component-name"}, {"verbatim": "build"}]
/// }
/// },
/// ```
#[serde(default)]
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
pub aliases: BTreeMap<Alias, CliCommands>,
/// The file used by midenup's 'miden' to call the components executable.
///
/// If `None`, then the component's file will be saved as `miden <name>`. This distinction
/// exists mainly for components like `cargo-miden`, which differ in how they are called.
#[serde(default)]
#[serde(skip_serializing_if = "Option::is_none")]
symlink_name: Option<String>,
#[serde(default)]
#[serde(skip_serializing_if = "Vec::is_empty")]
pub initialization: Vec<String>,
/// Pre-built artifact.
#[serde(flatten)]
pub artifacts: Option<Artifacts>,
}
const fn is_false(value: &bool) -> bool {
!*value
}
impl Component {
pub fn new(name: impl Into<Cow<'static, str>>, version: Authority) -> Self {
Self {
name: name.into(),
version,
optional: false,
features: vec![],
requires: vec![],
call_format: vec![],
rustup_channel: None,
installed_file: None,
aliases: BTreeMap::new(),
symlink_name: None,
initialization: Vec::new(),
artifacts: None,
}
}
/// This method is used to check if the current [Component] is up to date with its upstream
/// equivalent.
///
/// This is used to check if they different in fields _besides_ the name. The [`Component::eq`]
/// implementation only tests name equality and is only used to check for components that got
/// added/removed.
///
/// WARNING: The idea behind this function is to early return when a
/// difference is found, and fallback to "UpToDate" if none are
/// found. Therefore, there should be *no* early returns that return
/// `UpToDate`, since they might skip a field that differes later on.
pub fn is_up_to_date(&self, upstream: &Self) -> bool {
match (&self.version, &upstream.version) {
(
Authority::Git {
repository_url: repository_url_a,
crate_name: crate_a,
target:
GitTarget::Branch {
name: name_a,
latest_revision: local_revision,
},
},
Authority::Git {
repository_url: repository_url_b,
crate_name: crate_b,
target:
GitTarget::Branch {
name: name_b,
latest_revision: upstream_revision,
},
},
) => {
if repository_url_a != repository_url_b {
return false;
}
if crate_a != crate_b {
return false;
}
if repository_url_a != repository_url_b {
return false;
}
if name_a != name_b {
return false;
}
match (local_revision, upstream_revision) {
(Some(local_revision), Some(upstream_revision)) => {
if *local_revision != *upstream_revision {
return false;
}
},
// If either is missing, trigger an update regardless.
_ => {
return false;
},
};
},
(
Authority::Path {
path: path_a,
crate_name: crate_name_a,
last_modification: last_modification_a,
},
Authority::Path {
path: path_b,
crate_name: crate_name_b,
last_modification: last_modification_b,
},
) => {
if *path_a != *path_b {
return false;
}
if *crate_name_a != *crate_name_b {
return false;
}
match (last_modification_a, last_modification_b) {
(Some(local_latest), Some(new_latest)) => {
if new_latest > local_latest {
return false;
}
},
// If anything failed, we simply mark the component as needing an update.
// The idea being that components installed from a path are skipped during
// updates by default and are only updated if the user explicitly passes the
// necessary flags.
_ => return false,
}
},
(
Authority::Cargo { package: package_a, version: version_a },
Authority::Cargo { package: package_b, version: version_b },
) => {
if package_a != package_b {
return false;
}
if version_a != version_b {
return false;
}
},
_ => {
// This case includes all the cases where the Authorities differ,
// which are never considered "up to date".
return false;
},
};
if self.features != upstream.features {
return false;
}
if self.requires != upstream.requires {
return false;
}
if self.rustup_channel != upstream.rustup_channel {
return false;
}
if self.installed_file != upstream.installed_file {
return false;
}
true
}
/// Returns the name of the executable corresponding to this component.
///
/// If the component does not specify the installed file name, that means that it installs and
/// executable named exactly like the crate.
pub fn get_installed_file(&self) -> InstalledFile {
if let Some(installed_file) = &self.installed_file {
installed_file.clone()
} else {
InstalledFile::Executable {
binary_name: self.name.to_string(),
// If not specified, all executable components are *not* alias_only
alias_only: false,
}
}
}
pub fn set_installed_file(&mut self, installed_file: Option<InstalledFile>) {
self.installed_file = installed_file;
}
/// Returns the string representation under which midenup calls a component.
pub fn get_cli_display(&self) -> String {
format!("miden {}", self.name)
}
/// Returns the name of symlink associated with a component.
pub fn get_symlink_name(&self) -> String {
if let Some(symlink_name) = &self.symlink_name {
symlink_name.clone()
} else {
format!("miden {}", self.name)
}
}
/// Returns the string representation under which midenup calls a component.
pub fn get_call_format(&self) -> Vec<CliCommand> {
if self.call_format.is_empty() {
vec![CliCommand::Executable]
} else {
self.call_format.clone()
}
}
/// Returns the URI for a given `target` (if available).
pub fn get_artifact_uri(&self, target: &TargetTriple) -> Option<String> {
self.artifacts.as_ref().and_then(|artifacts| artifacts.get_uri_for(target))
}
// Sync to the latest changes.
pub fn sync(&mut self, config: &Config) {
match &mut self.version {
Authority::Path {
path,
crate_name: _crate_name,
last_modification,
} => {
// If, for whatever reason, we fail to find the latest
// registered modification, we simply leave it empty. That does
// mean that an update will be triggered even if the component
// does not need it.
let path = if path.is_absolute() {
Cow::Borrowed(&*path)
} else {
Cow::Owned(config.working_directory.join(&*path))
};
let latest_registered_modification =
utils::fs::latest_modification(&path).ok().map(|modification| modification.0);
*last_modification = latest_registered_modification;
},
// NOTE: Components that are installed via git BRANCHES are a special case because we
// need to check if new commits have been pushed since the component was installed.
// When these components are installed, the lastest available commit hash is saved with
// them in the local manifest. We use this to check if an update is in order. Do note
// that the upstream manifest is not needed for these.
Authority::Git {
repository_url,
crate_name: _crate_name,
target,
} => {
match target {
GitTarget::Branch { name: branch_name, latest_revision } => {
// If, for whatever reason, we fail to find the latest hash, we
// simply leave it empty. That does mean that an update will be
// triggered even if the component does not need it.
let latest_upstream_revision =
utils::git::find_latest_hash(repository_url.as_str(), branch_name).ok();
*latest_revision = latest_upstream_revision;
},
GitTarget::Revision { hash: _hash } => {},
GitTarget::Tag { name: _name } => {},
}
},
Authority::Cargo { package: _package, version: _version } => {},
}
}
}
/// User-facing channel reference.
///
/// The main difference with this and [Channel] is the definition of "stable". The definition of
/// "stable" 'under the hood' is the lastest available non-nightly channel. If the user passes
/// [`UserChannel::Stable`] as the target channel, we then handle the mapping from it to the
/// underlying [Channel] representation.
#[derive(Serialize, Default, Debug, Clone)]
#[serde(rename_all = "snake_case")]
pub enum UserChannel {
#[default]
Stable,
Nightly,
#[serde(untagged)]
Version(semver::Version),
#[serde(untagged)]
Other(Cow<'static, str>),
}
impl Display for UserChannel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Version(version) => write!(f, "{version}"),
Self::Stable => f.write_str("stable"),
Self::Nightly => f.write_str("nightly"),
Self::Other(custom_name) => write!(f, "{custom_name}"),
}
}
}
impl<'de> serde::de::Deserialize<'de> for UserChannel {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Unexpected;
use serde_untagged::UntaggedEnumVisitor;
UntaggedEnumVisitor::new()
.string(|s| {
s.parse::<UserChannel>().map_err(|err| {
serde::de::Error::invalid_value(Unexpected::Str(s), &err.to_string().as_str())
})
})
.deserialize(deserializer)
}
}
impl core::str::FromStr for UserChannel {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
use anyhow::anyhow;
match s {
"stable" => Ok(Self::Stable),
"nightly" => Ok(Self::Nightly),
version => semver::Version::parse(version)
.map(Self::Version)
.map_err(|err| anyhow!("invalid channel version: {err}")),
}
}
}