midenup 0.2.0

The Miden toolchain manager
Documentation
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
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
use std::{ffi::OsString, path::PathBuf};

use anyhow::{Context, anyhow, bail};
use clap::{ArgAction, Args, FromArgMatches, Parser, Subcommand};
use midenup::{channel, commands, config, manifest, miden_wrapper, options};

pub use self::config::Config;

#[derive(Debug, Parser)]
#[command(name = "midenup")]
#[command(multicall(true))]
#[command(author, about = "The Miden toolchain installer", long_about = None)]
pub struct Midenup {
    #[command(subcommand)]
    behavior: Behavior,
}

#[derive(Debug, Subcommand)]
enum Behavior {
    /// The Miden toolchain installer
    Midenup {
        #[command(flatten)]
        config: GlobalArgs,
        #[command(subcommand)]
        command: Option<Commands>,
    },
    /// Invoke components of the current Miden toolchain
    #[command(external_subcommand)]
    Miden(Vec<OsString>),
}

#[derive(Debug, Subcommand)]

/// All the available Midenup Commands
enum Commands {
    /// Bootstrap the `midenup` environment.
    ///
    /// This initializes the `MIDEN_HOME` directory layout and configuration.
    Init,
    /// Install a Miden toolchain
    Install {
        /// The channel or version to install, e.g. `stable` or `0.15.0`
        #[arg(required(true), value_name = "CHANNEL", value_parser)]
        channel: channel::UserChannel,

        #[clap(flatten)]
        options: options::InstallationOptions,
    },
    /// Uninstall a Miden toolchain
    Uninstall {
        /// The channel or version to install, e.g. `stable` or `0.15.0`
        #[arg(required(true), value_name = "CHANNEL", value_parser)]
        channel: channel::UserChannel,
    },
    /// Show information about the midenup environment
    #[command(subcommand)]
    Show(commands::ShowCommand),
    /// Sets the current active miden toolchain for the current project.
    /// This creates a miden-toolchain.toml file in the present working directory.
    Set {
        /// The channel or version to set, e.g. `stable` or `0.15.0`
        #[arg(required(true), value_name = "CHANNEL", value_parser)]
        channel: channel::UserChannel,
    },
    /// Sets the system's default toolchain.
    ///
    /// Unlike `rustup`, midenup does *not* have a notion of directory
    /// overrides. Instead, the `midenup set` command can be used to configure a
    /// directory-specific toolchain.
    Override {
        /// The channel or version to set, e.g. `stable` or `0.15.0`
        #[arg(required(true), value_name = "CHANNEL", value_parser)]
        channel: channel::UserChannel,
    },
    /// Update your installed Miden toolchains.
    Update {
        /// `midenup update`'s behavior differs depending on the specified [CHANNEL]
        /// - If provided, updates only the specified channel.
        /// - If left blank, then midenup will check for updates in all the downloaded toolchains.
        /// - If [CHANNEL] = stable, then it will look for the newest available toolchain and set
        ///   that to be stable.
        #[clap(verbatim_doc_comment)]
        #[arg(value_name = "CHANNEL", value_parser)]
        channel: Option<channel::UserChannel>,

        #[clap(flatten)]
        options: options::UpdateOptions,
    },
}

const MIDENUP_MANIFEST_URI_ENV: &str = "MIDENUP_MANIFEST_URI";
/// Global configuration options for `midenup`
#[derive(Debug, Args)]
struct GlobalArgs {
    /// The location of the Miden toolchain root
    #[arg(long, hide(true), value_name = "DIR", env = "MIDENUP_HOME")]
    midenup_home: Option<PathBuf>,
    /// The URI from which we should load the global toolchain manifest
    #[arg(
        long,
        hide(true),
        value_name = "FILE",
        env = MIDENUP_MANIFEST_URI_ENV,
        default_value = manifest::Manifest::PUBLISHED_MANIFEST_URI
    )]
    manifest_uri: String,

    /// Determines wether the components are installed in debug mode. Useful for
    /// debugging and faster installations. This flag is only avaialble to
    /// `midenup`, not `miden`.
    #[clap(env = "MIDENUP_DEBUG_MODE", action = ArgAction::Set, default_value = "false", hide = true)]
    debug: bool,

    /// Display verbose output, mainly used during install.
    #[clap(short, long, action, default_value_t = false)]
    verbose: bool,

    // This flag needed to be implemented manually in order to use the
    // `display_version` function and circumvent `clap`'s default `--version`
    // output.
    /// Displays `midenup`'s version information.
    #[clap(short = 'V', long, action, default_value_t = false)]
    version: bool,
}

impl Commands {
    /// Execute the requested subcommand
    fn execute(
        &self,
        config: &config::Config,
        local_manifest: &mut manifest::Manifest,
    ) -> anyhow::Result<()> {
        match &self {
            Self::Init => commands::init(config),
            Self::Install { channel, options } => {
                let Some(channel) = config.manifest.get_channel(channel) else {
                    bail!("channel '{}' doesn't exist or is unavailable", channel);
                };
                commands::install(config, channel, local_manifest, options)
            },
            Self::Uninstall { channel, .. } => {
                let Some(channel) = config.manifest.get_channel(channel) else {
                    bail!("channel '{}' doesn't exist or is unavailable", channel);
                };
                commands::uninstall(config, channel, local_manifest)
            },
            Self::Update { channel, options } => {
                commands::update(config, channel.as_ref(), local_manifest, options)
            },
            Self::Show(cmd) => cmd.execute(config, local_manifest),
            Self::Set { channel } => commands::set(config, channel),
            Self::Override { channel } => commands::r#override(config, channel),
        }
    }
}

fn main() -> anyhow::Result<()> {
    curl::init();

    let cli = <Midenup as clap::CommandFactory>::command();
    let matches = cli.get_matches();
    let cli = Midenup::from_arg_matches(&matches).map_err(|err| err.exit()).unwrap();

    let config = match cli.behavior {
        Behavior::Miden(_) => {
            // Always respect XDG dirs if set
            let midenup_home = std::env::var_os("XDG_DATA_HOME")
                .map(PathBuf::from)
                .map(|dir| dir.join("midenup"))
                .or_else(|| dirs::data_dir().map(|dir| dir.join("midenup")))
                // If for whatever reason, we can't access the data dir, we fall
                // back to .local/share
                .or_else(|| {
                    std::env::home_dir()
                        .map(|home| home.join(".local").join("share"))
                })
                .ok_or_else(||
                            anyhow!("Failed to set midenup directory.\
                                     Consider setting a value for XDG_DATA_HOME in your shell's profile"
                            )
                )?;

            let manifest_uri = std::env::var(MIDENUP_MANIFEST_URI_ENV)
                .unwrap_or(manifest::Manifest::PUBLISHED_MANIFEST_URI.to_string());
            config::Config::init(midenup_home, manifest_uri, false)?
        },
        Behavior::Midenup { ref config, .. } => {
            let midenup_home = config
                .midenup_home
                .clone()
                .or_else(|| {
                    // Always respect XDG dirs if set
                    std::env::var_os("XDG_DATA_HOME")
                        .map(PathBuf::from)
                        .map(|dir| dir.join("midenup"))
                })
                .or_else(|| dirs::data_dir().map(|dir| dir.join("midenup")))
                // If for whatever reason, we can't access the data dir, we fall
                // back to .local/share
                .or_else(|| {
                    std::env::home_dir()
                        .map(|home| home.join(".local").join("share"))
                })
                .ok_or_else(||
                            anyhow!("Failed to set midenup directory.\
                                     Consider setting a value for XDG_DATA_HOME in your shell's profile"
                            )
                )?;

            config::Config::init(midenup_home, &config.manifest_uri, config.debug)?
        },
    };

    // Manifest that stores locally installed toolchains
    let mut local_manifest = {
        let local_manifest_path = config.midenup_home.join("manifest").with_extension("json");
        let local_manifest_uri = format!(
            "file://{}",
            local_manifest_path.to_str().context("Couldn't convert miden directory")?,
        );
        match manifest::Manifest::load_from(local_manifest_uri) {
            Ok(manifest) => Ok(manifest),
            Err(manifest::ManifestError::Empty | manifest::ManifestError::Missing(_)) => {
                Ok(manifest::Manifest::default())
            },
            Err(err) => Err(err),
        }
        .context("Error parsing local manifest")
    }?;

    let result = match cli.behavior {
        Behavior::Miden(argv) => miden_wrapper::miden_wrapper(argv, &config, &mut local_manifest),
        Behavior::Midenup {
            config: ref global_args,
            command: subcommand,
        } => {
            if global_args.version {
                println!("{}", miden_wrapper::display_version(&config));
                Ok(())
            } else if let Some(subcommand) = subcommand {
                subcommand.execute(&config, &mut local_manifest)
            } else {
                bail!("no subcommand provided. Run `midenup --help` for usage information.")
            }
        },
    };

    // After execution we check if need to update the midenup/opt symlink
    // This is done *after* execution because some commands change what the
    // active toolchain (update, set) and some remove the directory entirely
    // (uninstall)
    config.update_opt_symlinks(&config)?;

    result
}

#[cfg(test)]
mod tests {
    use std::{fs::OpenOptions, path::Path};

    use midenup::{
        channel::{self, InstalledFile},
        config, manifest, miden_wrapper, utils, version,
    };
    use tempdir::TempDir;

    use crate::*;

    #[macro_export]
    macro_rules! full_path_manifest {
        ($file:expr) => {
            concat!("file://", full_path!($file))
        };
    }

    #[macro_export]
    macro_rules! full_path {
        ($file:expr) => {
            concat!(env!("CARGO_MANIFEST_DIR"), "/", $file)
        };
    }

    type LocalManifest = manifest::Manifest;

    /// Simple auxiliary function to setup a midneup directory environment in tests.
    ///
    /// Additionally, it changes the PWD to a new temp dir to isolate test execution.
    fn test_setup(midenup_home: &Path, manifest_uri: &str) -> (LocalManifest, config::Config) {
        let local_manifest = {
            let local_manifest_path = midenup_home.join("manifest").with_extension("json");
            let local_manifest_uri = format!(
                "file://{}",
                local_manifest_path.to_str().expect("Couldn't convert miden directory"),
            );

            match manifest::Manifest::load_from(local_manifest_uri) {
                Ok(manifest) => Ok(manifest),
                Err(manifest::ManifestError::Empty | manifest::ManifestError::Missing(_)) => {
                    Ok(manifest::Manifest::default())
                },
                Err(err) => Err(err),
            }
            .unwrap_or_else(|_| {
                panic!("Failed to parse manifest {}", local_manifest_path.display())
            })
        };

        let config = config::Config::init(midenup_home.to_path_buf().clone(), manifest_uri, true)
            .unwrap_or_else(|err| {
                panic!(
                    "Failed to construct config from manifest {} and midenup_home at {}.
Error: {}",
                    manifest_uri,
                    midenup_home.display(),
                    err,
                )
            });

        (local_manifest, config)
    }

    // NOTE: We save this variables in this struct because if they ever go out of scope, the created
    // directory get deleted.
    struct TestEnvironment {
        #[allow(dead_code)]
        tmp_dir: TempDir,
        midenup_dir: PathBuf,
        #[allow(dead_code)]
        cargo_home: PathBuf,
        present_working_dir: PathBuf,
    }

    fn environment_setup(test_name: &str) -> TestEnvironment {
        let tmp_dir = tempdir::TempDir::new(&format!("midenup-{test_name}"))
            .expect("Couldn't create temp-dir");

        let tmp_present_working_directory = tmp_dir.path().join("test-working-directory");

        let tmp_midenup_home = tmp_dir.path().join("midenup");

        let tmp_cargo_home = tmp_dir.path().join("cargo");

        std::fs::create_dir(&tmp_present_working_directory).unwrap();

        // Set CARGO_HOME in order to not use the system's default `.cargo/bin` directory.
        unsafe {
            std::env::set_var("CARGO_HOME", &tmp_cargo_home);
        }

        std::env::set_current_dir(&tmp_present_working_directory).unwrap_or_else(|err| {
            panic!(
                "Failed to switch to {}, because of {err}",
                tmp_present_working_directory.display()
            )
        });

        TestEnvironment {
            tmp_dir,
            midenup_dir: tmp_midenup_home,
            cargo_home: tmp_cargo_home,
            present_working_dir: tmp_present_working_directory,
        }
    }

    fn get_full_command(argv: Vec<OsString>) -> String {
        argv.clone()
            .iter()
            .map(|arg| format!("{} ", arg.clone().into_string().unwrap()))
            .collect::<String>()
    }

    /// Integration test to check that installing and uninstalling works.
    ///
    /// Tries to install a toolchain under a [`channel::UserChannel`] (via the `stable` alias) and
    /// also specific versions explicitly.
    #[test]
    fn integration_install_uninstall_test() {
        let test_name = "integration_install_uninstall_test";
        let test_env = environment_setup(test_name);

        let tmp_home = test_env.midenup_dir;
        let cargo_home = test_env.cargo_home;
        let midenup_home = tmp_home.join("midenup");

        const FILE: &str = full_path_manifest!(
            "tests/data/integration_install_uninstall_test/channel-manifest.json"
        );
        let (mut local_manifest, config) = test_setup(&midenup_home, FILE);
        let toolchain_dir = midenup_home.join("toolchains");

        // We begin by initializing the midenup directory
        let command = Midenup::try_parse_from(["midenup", "init"]).unwrap();
        let Behavior::Midenup { command: Some(command), .. } = command.behavior else {
            panic!("Error while parsing test command. Expected Midneup Behavior, got Miden");
        };
        command.execute(&config, &mut local_manifest).expect("Failed to install stable");

        // We check that the basic midenup directory structure is present
        assert!(midenup_home.exists());
        assert!(toolchain_dir.exists());
        // The miden symlink should be in $CARGO_HOME/bin
        assert!(cargo_home.join("bin").join("miden").exists());

        // Now, we install stable
        let command = Midenup::try_parse_from(["midenup", "install", "stable"]).unwrap();
        let Behavior::Midenup { command: Some(command), .. } = command.behavior else {
            panic!("Error while parsing test command. Expected Midneup Behavior, got Miden");
        };

        // This should install version 0.16.0, since it's the latest available stable toolchain
        // present in FILE
        command.execute(&config, &mut local_manifest).expect("Failed to install stable");

        let latest_toolchain = toolchain_dir.join("0.16.0");
        assert!(latest_toolchain.exists());

        // Besides it should create the `stable` symlink
        let stable_dir = toolchain_dir.join("stable");
        assert!(stable_dir.exists());
        assert!(stable_dir.is_symlink());

        // Stable should point to 0.16.0
        let stable_toolchain =
            std::fs::read_link(&stable_dir).expect("Failed to read stable symlink");
        assert_eq!(stable_toolchain.file_name(), latest_toolchain.file_name());

        // Now we install a separate toolchain.
        let command = Midenup::try_parse_from(["midenup", "install", "0.15.0"]).unwrap();
        let Behavior::Midenup { command: Some(command), .. } = command.behavior else {
            panic!("Error while parsing test command. Expected Midenup Behavior, got Miden");
        };
        command.execute(&config, &mut local_manifest).expect("Failed to install stable");

        // This should install toolchain version 0.15.0.

        let older_toolchain = toolchain_dir.join("0.15.0");
        assert!(older_toolchain.exists());

        // Besides this new toolchain, all the other directories should still exists.
        assert!(stable_dir.exists());
        assert!(latest_toolchain.exists());

        let installed_toolchains = ["0.15.0", "0.16.0"].iter().map(|version| {
            semver::Version::parse(version)
                .unwrap_or_else(|_| panic!("Failed to turn {version} into semver::Version"))
        });

        // Besides creating the various directories, the local manifest should also reflect this
        // structure
        local_manifest
            .get_channels()
            .map(|channel| channel.name.clone())
            .eq(installed_toolchains);

        // Now, we'll uninstall 0.16.0.
        let command = Midenup::try_parse_from(["midenup", "uninstall", "0.16.0"]).unwrap();
        let Behavior::Midenup { command: Some(command), .. } = command.behavior else {
            panic!("Error while parsing test command. Expected Midneup Behavior, got Miden");
        };

        command.execute(&config, &mut local_manifest).expect("Failed to install stable");

        // Afterwards, both the 0.16.0 directory and the `stable` symlink should be deleted.
        // But, 0.15.0 should still remain
        assert!(!latest_toolchain.exists());
        assert!(!stable_dir.exists());
        assert!(older_toolchain.exists());

        // Similarly, the local manifest should now also reflect the that the older toolchain got
        // uninstalled
        let installed_toolchains = ["0.15.0"].iter().map(|version| {
            semver::Version::parse(version)
                .unwrap_or_else(|_| panic!("Failed to turn {version} into semver::Version"))
        });

        // Besides creating the various directories, the local manifest should also reflect this
        // structure
        local_manifest
            .get_channels()
            .map(|channel| channel.name.clone())
            .eq(installed_toolchains);
    }

    /// Checks that the `miden` utility is able to recognize when the currently active toolchain is
    /// not installed, and then installing it before executing the passed in command.
    #[test]
    fn integration_miden_test() {
        let test_name = "integration_miden_test";
        let test_env = environment_setup(test_name);

        let tmp_home = test_env.midenup_dir;
        let cargo_home = test_env.cargo_home;
        let midenup_home = tmp_home.join("midenup");

        // SIDENOTE: This tests uses a toolchain with version number 0.14.0. This
        // is simply used for testing purposes and is not a "real" toolchain.
        const FILE: &str =
            full_path_manifest!("tests/data/integration_miden_test/channel-manifest.json");

        let (mut local_manifest, config) = test_setup(&midenup_home, FILE);
        let toolchain_dir = midenup_home.join("toolchains");

        // By default, the active toolchain is the latest stable version. In the
        // case of the manifest present in FILE, that is version 0.16.0.
        let command = Midenup::try_parse_from(["miden", "client", "--version"]).unwrap();
        let Behavior::Miden(argv) = command.behavior else {
            panic!("Error while parsing test command. Expected Midne Behavior, got Midenup");
        };

        miden_wrapper::miden_wrapper(argv.clone(), &config, &mut local_manifest)
            .unwrap_or_else(|err| panic!("Failed to run: {} Error: {err}", get_full_command(argv)));

        // After this, `midenup` should:
        // 1. Recognize that the user wants to run a component
        // 2. Recognize that the active toolchain is not installed, and thus trigger an installation
        // 3. Before issuing the install, it should recognize that midenup hasn't been initialized
        //    and thus needs to be initialized.

        // midenup initialized check
        assert!(midenup_home.exists());
        assert!(toolchain_dir.exists());
        // The miden symlink should be in $CARGO_HOME/bin
        assert!(cargo_home.join("bin").join("miden").exists());

        // Stable toolchain installed check
        let latest_toolchain = toolchain_dir.join("0.16.0");
        assert!(latest_toolchain.exists());

        // Symlink check
        let stable_dir = toolchain_dir.join("stable");
        assert!(stable_dir.exists());
        assert!(stable_dir.is_symlink());

        // Global default

        // Now, we set a global default toolchain. This should change the current active toolchain
        // to 0.15.0.
        let command = Midenup::try_parse_from(["midenup", "override", "0.15.0"]).unwrap();
        let Behavior::Midenup { command: Some(command), .. } = command.behavior else {
            panic!("Error while parsing test command. Expected Midneup Behavior, got Miden");
        };
        command.execute(&config, &mut local_manifest).expect("Failed to install stable");

        // This should also trigger an install, since toolchain 0.15.0 is missing and is now the
        // active toolchain.
        let command = Midenup::try_parse_from(["miden", "client", "--version"]).unwrap();
        let Behavior::Miden(argv) = command.behavior else {
            panic!("Error while parsing test command. Expected Midne Behavior, got Midenup");
        };

        miden_wrapper::miden_wrapper(argv.clone(), &config, &mut local_manifest)
            .unwrap_or_else(|err| panic!("Failed to run: {} Error: {err}", get_full_command(argv)));

        let older_toolchain = toolchain_dir.join("0.15.0");
        assert!(older_toolchain.exists());

        // Directory only toolchain
        //
        // Now, we'll create a `miden-toolchain.toml` file. This will change the current active
        // toolchain. By default, the active toolchain is the latest stable version. In the case of
        // the manifest present in FILE, that is version 0.16.0.
        let command = Midenup::try_parse_from(["midenup", "set", "0.14.0"]).unwrap();
        let Behavior::Midenup { command: Some(command), .. } = command.behavior else {
            panic!("Error while parsing test command. Expected Midneup Behavior, got Miden");
        };
        command.execute(&config, &mut local_manifest).expect("Failed to install stable");

        // This should also trigger an install, since toolchain 0.14.0 is now missing
        let command = Midenup::try_parse_from(["miden", "client", "--version"]).unwrap();
        let Behavior::Miden(argv) = command.behavior else {
            panic!("Error while parsing test command. Expected Midne Behavior, got Midenup");
        };

        miden_wrapper::miden_wrapper(argv.clone(), &config, &mut local_manifest)
            .unwrap_or_else(|err| panic!("Failed to run: {} Error: {err}", get_full_command(argv)));

        let oldest_toolchain = toolchain_dir.join("0.14.0");
        assert!(oldest_toolchain.exists());

        // Afterwards, all of the newly installed toolchains should be present in the local
        // manifest.
        let installed_toolchains = ["0.14.0", "0.15.0", "0.16.0"].iter().map(|version| {
            semver::Version::parse(version)
                .unwrap_or_else(|_| panic!("Failed to turn {version} into semver::Version"))
        });

        // Besides creating the various directories, the local manifest should also reflect this
        // structure
        local_manifest
            .get_channels()
            .map(|channel| channel.name.clone())
            .eq(installed_toolchains);
    }

    /// Checks that the `miden` utility recognizes the existence of a `miden-toolchain.toml` file.
    ///
    /// This file contains the required toolchain for the current project, along with a list of
    /// required components. `miden` should be able to:
    ///
    /// - create said file
    /// - recognize the list of required components and install them
    /// - recognize if the list gets expanded and install the missing components
    #[test]
    fn integration_miden_toolchain_toml() {
        let test_name = "integration_miden_toolchain_toml";
        let test_env = environment_setup(test_name);

        let pwd = test_env.present_working_dir;

        let tmp_home = test_env.midenup_dir;
        let tmp_home_path = tmp_home;
        let midenup_home = tmp_home_path.join("midenup");

        const FILE: &str = full_path_manifest!(
            "tests/data/integration_miden_toolchain_toml/channel-manifest.json"
        );

        let (mut local_manifest, config) = test_setup(&midenup_home, FILE);

        // This should create a miden-toolchain.toml file that sets toolchain 0.16.0 as the active
        // one on the current project. Since the toolchain is not installed, the component list is
        // left empty.
        let command = Midenup::try_parse_from(["midenup", "set", "0.16.0"]).unwrap();
        let Behavior::Midenup { command: Some(command), .. } = command.behavior else {
            panic!("Error while parsing test command. Expected Midneup Behavior, got Miden");
        };
        command
            .execute(&config, &mut local_manifest)
            .expect("Failed to initialize midenup");

        // There should now be a `miden-toolchain.toml` file in the PWD.
        let miden_toolchain_file = pwd.join("miden-toolchain.toml");
        assert!(miden_toolchain_file.exists());

        // Now, we update the file to include the vm
        let toolchain_with_components =
            full_path!("tests/data/integration_miden_toolchain_toml/miden-toolchain-1.toml");
        std::fs::copy(toolchain_with_components, &miden_toolchain_file).unwrap();

        // `miden` should now install the components listed in the toolchain file.
        let command = Midenup::try_parse_from(["miden", "help", "toolchain"]).unwrap();
        let Behavior::Miden(argv) = command.behavior else {
            panic!("Error while parsing test command. Expected Miden Behavior, got Midenup");
        };
        miden_wrapper::miden_wrapper(argv.clone(), &config, &mut local_manifest)
            .unwrap_or_else(|err| panic!("Failed to run: {} Error: {err}", get_full_command(argv)));

        let toolchain_dir = midenup_home.join("toolchains");
        assert!(toolchain_dir.exists());

        let installed_channel =
            local_manifest.get_channel_by_name(&semver::Version::new(0, 16, 0)).unwrap();
        assert!(installed_channel.components.len() == 1);

        // Now, we'll add the miden compiler to the list.
        let toolchain_with_components =
            full_path!("tests/data/integration_miden_toolchain_toml/miden-toolchain-2.toml");
        std::fs::copy(toolchain_with_components, miden_toolchain_file).unwrap();

        // `miden` should now install:
        // - The compiler which was just added
        // - Both the standard library and transaction kernel libraris since they are a dependency
        //   for the compiler.
        let command = Midenup::try_parse_from(["miden", "help", "toolchain"]).unwrap();
        let Behavior::Miden(argv) = command.behavior else {
            panic!("Error while parsing test command. Expected Miden Behavior, got Midenup");
        };
        miden_wrapper::miden_wrapper(argv.clone(), &config, &mut local_manifest)
            .unwrap_or_else(|err| panic!("Failed to run: {} Error: {err}", get_full_command(argv)));

        let installed_channel = local_manifest
            .get_channel_by_name(&semver::Version::new(0, 16, 0))
            .unwrap()
            .clone();

        // VM, Compiler and both libraries
        assert_eq!(installed_channel.components.len(), 4);

        // Now, we try updating the installed toolchain. This should only update the installed
        // components and ignore the rest.
        let command = Midenup::try_parse_from(["midenup", "update", "stable"]).unwrap();
        let Behavior::Midenup { command: Some(command), .. } = command.behavior else {
            panic!("Error while parsing test command. Expected Midneup Behavior, got Miden");
        };
        command.execute(&config, &mut local_manifest).expect("Failed to install stable");

        // No components should have been added
        assert_eq!(installed_channel.components.len(), 4);

        // Finally, we attempt to install the entire stable toolchain, which should install the
        // remaining components.
        let command = Midenup::try_parse_from(["midenup", "install", "stable"]).unwrap();
        let Behavior::Midenup { command: Some(command), .. } = command.behavior else {
            panic!("Error while parsing test command. Expected Midneup Behavior, got Miden");
        };
        command.execute(&config, &mut local_manifest).expect("Failed to install stable");

        // Now, the entire toolchain should be installed
        let installed_channel =
            local_manifest.get_channel_by_name(&semver::Version::new(0, 16, 0)).unwrap();
        assert_eq!(installed_channel.components.len(), 6);
    }

    /// This tests checks that midenup's update behavior works correctly
    #[test]
    fn integration_update_test() {
        let test_name = "integration_update_test";
        let test_env = environment_setup(test_name);

        let tmp_home = test_env.midenup_dir;
        let midenup_home = tmp_home.join("midenup");

        // This manifest contains toolchain version 0.14.0 as its only toolchain
        //
        // WARNING: This test uses toolchain files which were created for testing purposes only.
        // For instance, they are lacking many components in order to save time.
        let manifest: &str =
            full_path_manifest!("tests/data/integration_update_test/channel-manifest-1.json");
        let (mut local_manifest, config) = test_setup(&midenup_home, manifest);
        let toolchain_dir = midenup_home.join("toolchains");

        // We begin by initializing the midenup directory
        let command = Midenup::try_parse_from(["midenup", "init"]).unwrap();
        let Behavior::Midenup { command: Some(command), .. } = command.behavior else {
            panic!("Error while parsing test command. Expected Midneup Behavior, got Miden");
        };
        command
            .execute(&config, &mut local_manifest)
            .expect("Failed to initialize midenup");

        // Now, we install stable. That is going to be version 0.14.0
        let command = Midenup::try_parse_from(["midenup", "install", "stable"]).unwrap();
        let Behavior::Midenup { command: Some(command), .. } = command.behavior else {
            panic!("Error while parsing test command. Expected Midneup Behavior, got Miden");
        };
        command.execute(&config, &mut local_manifest).expect("Failed to install stable");

        // Now, we re-generate the config with a newer manifest that contains version 0.15.0. This
        // is trying to emulate the release of a new stable version
        let manifest: &str =
            full_path_manifest!("tests/data/integration_update_test/channel-manifest-2.json");
        let (_, config) = test_setup(&midenup_home, manifest);

        // Now, we update stable. The stable symlink should point to version 0.15.0
        let command = Midenup::try_parse_from(["midenup", "update", "stable"]).unwrap();
        let Behavior::Midenup { command: Some(command), .. } = command.behavior else {
            panic!("Error while parsing test command. Expected Midneup Behavior, got Miden");
        };
        command.execute(&config, &mut local_manifest).expect("Failed to update stable");

        // The original toolchain should still exist
        let older_toolchain = toolchain_dir.join("0.14.0");
        assert!(older_toolchain.exists());

        // The newer toolchain should also now be installed
        let newer_toolchain = toolchain_dir.join("0.15.0");
        assert!(newer_toolchain.exists());

        // We check that the stable symlink still exits.
        let stable_dir = toolchain_dir.join("stable");
        assert!(stable_dir.exists());
        assert!(stable_dir.is_symlink());
        // The stable symlink should now point to the newer toolchain
        let stable_toolchain = std::fs::read_link(stable_dir.as_path())
            .expect("Couldn't obtain directory where the stable directory is pointing to");
        assert_eq!(stable_toolchain, newer_toolchain);

        // Now, we perform a "global" update. This performs an update on every *installed*
        // toolchain.
        //
        // The manifest file tests/data/integration_update_test/channel-manifest-3.json, besides
        // adding toolchain 0.16.0, also changed some fields on components from version 0.15.0.
        //
        // This update should perform the following changes:
        //
        // - Update 0.15.0's miden-vm to version 0.16.2.
        // - Remove base.masp from 0.15.0's toolchain dir.
        // - Downgrade 0.14.0's miden-vm.
        // - Add the miden-client to 0.14.0's toolchain dir
        // - Change 0.14.0's std's authority from Cargo to Git.
        //
        // However this should *not* update stable.
        let manifest: &str =
            full_path_manifest!("tests/data/integration_update_test/channel-manifest-3.json");
        let (_, config) = test_setup(&midenup_home, manifest);

        let command = Midenup::try_parse_from(["midenup", "update"]).unwrap();
        let Behavior::Midenup { command: Some(command), .. } = command.behavior else {
            panic!("Error while parsing test command. Expected Midneup Behavior, got Miden");
        };
        command
            .execute(&config, &mut local_manifest)
            .expect("Failed to perform global update");

        // We check that the stable symlink still exits and it is still pointing to 0.15.0.
        assert!(stable_dir.exists());
        assert!(stable_dir.is_symlink());

        // The stable symlink should now point to the newer toolchain
        let stable_toolchain = std::fs::read_link(stable_dir.as_path())
            .expect("Couldn't obtain directory where the stable directory is pointing to");
        assert_eq!(stable_toolchain, newer_toolchain);

        let toolchain_0_15_0 = toolchain_dir.join("0.15.0");
        let vm_exe_v15 = toolchain_0_15_0.join("bin").join("miden-vm");
        let command = std::process::Command::new(vm_exe_v15).arg("--version").output().unwrap();
        assert_eq!(String::from_utf8(command.stdout).unwrap(), "miden-vm 0.16.2\n");
        assert!(!toolchain_0_15_0.join("lib").join("base.masp").exists());

        let std_version = &local_manifest
            .get_channel(&channel::UserChannel::Version(semver::Version::new(0, 14, 0)))
            .expect("Couldn't find toolchain 0.14.0 in local manifest")
            .get_component("std")
            .expect("Couldn't find std library despite being listed in manifest.")
            .version;

        matches!(std_version, version::Authority::Git { .. });

        let toolchain_0_14_0 = toolchain_dir.join("0.14.0");
        let vm_exe_v14 = toolchain_0_14_0.join("bin").join("miden");
        let command = std::process::Command::new(vm_exe_v14).arg("--version").output().unwrap();
        assert_eq!(String::from_utf8(command.stdout).unwrap(), "Miden 0.13.0\n");
        let client_v14 = toolchain_0_14_0.join("bin").join("miden-client");
        assert!(client_v14.exists());

        // Now, we use the same manifest that we used previously to update the current stable
        // toolchain.
        let command = Midenup::try_parse_from(["midenup", "update", "stable"]).unwrap();
        let Behavior::Midenup { command: Some(command), .. } = command.behavior else {
            panic!("Error while parsing test command. Expected Midneup Behavior, got Miden");
        };
        command
            .execute(&config, &mut local_manifest)
            .expect("Failed to perform global update");

        let newest_toolchain = toolchain_dir.join("0.16.0");
        assert!(newest_toolchain.exists());

        // The stable symlink should now point to the newest toolchain
        let stable_toolchain = std::fs::read_link(stable_dir.as_path())
            .expect("Couldn't obtain directory where the stable directory is pointing to");
        assert_eq!(stable_toolchain, newest_toolchain);
    }

    /// Tries to install the "stable" toolchain from the present manifest.
    ///
    /// This differs from the test present in the .github directory which tries to install the
    /// stable toolchain from published manifest.
    #[test]
    fn integration_install_stable() {
        let test_name = "integration_install_stable";
        let test_env = environment_setup(test_name);

        let tmp_home = test_env.midenup_dir;
        let midenup_home = tmp_home.join("midenup");

        const FILE: &str = full_path_manifest!("manifest/channel-manifest.json");

        let (mut local_manifest, config) = test_setup(&midenup_home, FILE);

        let command = Midenup::try_parse_from(["midenup", "install", "stable"]).unwrap();
        let Behavior::Midenup { command: Some(command), .. } = command.behavior else {
            panic!("Error while parsing test command. Expected Midenup Behavior, got Miden");
        };
        command.execute(&config, &mut local_manifest).expect("Failed to install stable");

        // After install is executed, the local manifest should be present
        let manifest = midenup_home.join("manifest").with_extension("json");
        assert!(manifest.exists());

        let stable_dir = midenup_home.join("toolchains").join("stable");
        assert!(stable_dir.exists());
        assert!(stable_dir.is_symlink());

        let stable_channel = local_manifest
            .get_latest_stable()
            .expect("No stable channel found; despite having installed stable");

        // We test if the in-memory representation of the local manifest contains the stable alias
        assert_eq!(stable_channel.alias, Some(channel::ChannelAlias::Stable));

        // We read the filesystem again, to check that the "stable" alias was correclty saved
        assert_eq!(
            local_manifest
                .get_channels()
                .next()
                .expect(
                    "ERROR: The local_manifest in the filesystem has no alias, when it should \
                     have stable alias"
                )
                .alias
                .as_ref()
                .expect(
                    "ERROR: The installed stable toolchain should be marked as stable in the \
                     local manifest"
                ),
            &channel::ChannelAlias::Stable
        );
    }

    /// Validates that midenup manages to install components with [Authority]s different than
    /// [`version::Authority::Cargo`]. Besides installing these components, we verify that midenup
    /// manages to update them when needed.
    #[test]
    fn integration_install_from_non_cargo() {
        let test_name = "integration_install_from_non_cargo";
        let test_env = environment_setup(test_name);

        let miden_vm_clone_path = test_env.present_working_dir.join("miden_vm");
        {
            let miden_vm_repo = "https://github.com/0xMiden/miden-vm.git";
            // Commit corresponding to release number 0.16.4 of the miden-vm
            // See https://github.com/0xMiden/miden-vm/releases/tag/v0.16.4
            let vm_release_16 = "fc368686bd1e6e171a51a1a5b365ef5400e4b8d5";
            utils::git::clone_specific_revision(miden_vm_repo, vm_release_16, &miden_vm_clone_path)
                .unwrap();
        };
        let midenup_home = test_env.midenup_dir;

        // Initial manifest with a client tracked by version::Authority::Git::Revision
        let manifest: &str = full_path_manifest!(
            "tests/data/integration_install_from_non_cargo/channel-manifest-1.json"
        );
        let (mut local_manifest, config) = test_setup(&midenup_home, manifest);

        // We install stable
        let command = Midenup::try_parse_from(["midenup", "install", "stable"]).unwrap();
        let Behavior::Midenup { command: Some(command), .. } = command.behavior else {
            panic!("Error while parsing test command. Expected Midneup Behavior, got Miden");
        };
        command.execute(&config, &mut local_manifest).expect("Failed to install stable");

        let (time_when_installed, hash_when_installed) = {
            let stable_channel = local_manifest
                .get_latest_stable()
                .expect("No stable channel found; despite having installed stable")
                .clone();

            let vm_from_path = stable_channel.get_component("vm").unwrap();
            let last_modification = match vm_from_path.version {
                version::Authority::Path { last_modification, .. } => last_modification.unwrap(),
                _ => panic!(
                    "Failed to recognize miden_vm's Authority as Path, despite being installed \
                     like so."
                ),
            };

            let client_from_git = stable_channel.get_component("client").unwrap();
            let revision = match &client_from_git.version {
                version::Authority::Git {
                    target: version::GitTarget::Revision { hash },
                    ..
                } => hash.clone(),
                authority => panic!(
                    "Failed to recognize miden_client's Authority as Git, despite being installed \
                     like so. Found: {authority}"
                ),
            };

            (last_modification, revision)
        };

        // We call for an update, to check that midenup recognizes that no component needs to be
        // updated.
        let command = Midenup::try_parse_from(["midenup", "update"]).unwrap();
        let Behavior::Midenup { command: Some(command), .. } = command.behavior else {
            panic!("Error while parsing test command. Expected Midneup Behavior, got Miden");
        };
        command.execute(&config, &mut local_manifest).expect("Failed to update");
        let (new_time, new_revision) = {
            let stable_channel = local_manifest
                .get_latest_stable()
                .expect("No stable channel found; despite having installed stable")
                .clone();

            let vm_from_path = stable_channel.get_component("vm").unwrap();
            let last_modification = match vm_from_path.version {
                version::Authority::Path { last_modification, .. } => last_modification.unwrap(),
                _ => panic!(
                    "Failed to recognize miden_vm's Authority as Path, despite being installed \
                     like so."
                ),
            };

            let client_from_git = stable_channel.get_component("client").unwrap();
            let revision = match &client_from_git.version {
                version::Authority::Git {
                    target: version::GitTarget::Revision { hash },
                    ..
                } => hash.clone(),
                authority => panic!(
                    "Failed to recognize miden_client's Authority as Git, despite being installed \
                     like so. Found: {authority}"
                ),
            };

            (last_modification, revision)
        };

        // These two should be equal since no updates should have been triggered.
        assert_eq!(new_time, time_when_installed);
        assert_eq!(new_revision, hash_when_installed);

        // Now, we need to check if udpates are handled properly. First, we update the manifest to
        // trigger an update for the client which is managed by git and also we create a new file on
        // the miden-vm path to trigger an update.
        let manifest: &str = full_path_manifest!(
            "tests/data/integration_install_from_non_cargo/channel-manifest-2.json"
        );
        let (_, config) = test_setup(&midenup_home, manifest);
        {
            OpenOptions::new()
                .read(true)
                .write(true)
                .create(true)
                .truncate(false)
                .open(miden_vm_clone_path.join("miden-vm/").join("trigger-update"))
                .unwrap();
        }

        let command = Midenup::try_parse_from(["midenup", "update", "--path-update=all"]).unwrap();
        let Behavior::Midenup { command: Some(command), .. } = command.behavior else {
            panic!("Error while parsing test command. Expected Midneup Behavior, got Miden");
        };
        command.execute(&config, &mut local_manifest).expect("Failed to update");

        let (new_time, new_revision) = {
            let stable_channel = local_manifest
                .get_latest_stable()
                .expect("No stable channel found; despite having installed stable")
                .clone();

            let vm_from_path = stable_channel.get_component("vm").unwrap();
            let last_modification = match vm_from_path.version {
                version::Authority::Path { last_modification, .. } => last_modification.unwrap(),
                _ => panic!(
                    "Failed to recognize miden_vm's Authority as Path, despite being installed \
                     like so."
                ),
            };

            let client_from_git = stable_channel.get_component("client").unwrap();
            let revision = match &client_from_git.version {
                version::Authority::Git {
                    target: version::GitTarget::Revision { hash },
                    ..
                } => hash.clone(),
                authority => panic!(
                    "Failed to recognize miden_client's Authority as Git, despite being installed \
                     like so. Found: {authority}"
                ),
            };

            (last_modification, revision)
        };

        assert!(new_time > time_when_installed);
        assert_ne!(new_revision, hash_when_installed);
    }

    /// This 'midenc' component present in this manifest is lacking its required 'rustup_channel"
    /// and thus installation should fail.
    #[test]
    #[should_panic]
    fn midenup_catches_installation_failure() {
        let test_name = "midenup_catches_installation_failure";
        let test_env = environment_setup(test_name);

        let tmp_home = test_env.midenup_dir;
        let midenup_home = tmp_home.join("midenup");

        const FILE_PRE_UPDATE: &str = full_path_manifest!(
            "tests/data/unit_test_manifest_additional/manifest-uncompilable-midenc.json"
        );

        let (mut local_manifest, config) = test_setup(&midenup_home, FILE_PRE_UPDATE);

        let command = Midenup::try_parse_from(["midenup", "install", "stable"]).unwrap();
        let Behavior::Midenup { command: Some(command), .. } = command.behavior else {
            panic!("Error while parsing test command. Expected Midneup Behavior, got Miden");
        };
        command.execute(&config, &mut local_manifest).expect("Failed to install stable");
        // After install is executed, the local manifest should be present
        let manifest = midenup_home.join("manifest").with_extension("json");
        assert!(manifest.exists());
    }

    /// Integration test to check that migration works correctly:
    ///
    /// - Updating a toolchain with a migration tag installs into the NEW name directory and removes
    ///   the OLD directory.
    #[test]
    fn integration_migration_test() {
        let test_name = "integration_migration_test";
        let test_env = environment_setup(test_name);
        let tmp_home = test_env.midenup_dir;
        let midenup_home = tmp_home.join("midenup");
        let toolchain_dir = midenup_home.join("toolchains");

        // Load manifest 1 (channel "0.20.3", no migration tag)
        let manifest: &str =
            full_path_manifest!("tests/data/integration_migration_test/channel-manifest-1.json");
        let (mut local_manifest, config) = test_setup(&midenup_home, manifest);

        // Initialize midenup
        let command = Midenup::try_parse_from(["midenup", "init"]).unwrap();
        let Behavior::Midenup { command: Some(command), .. } = command.behavior else {
            panic!("Error while parsing test command. Expected Midenup Behavior, got Miden");
        };
        command
            .execute(&config, &mut local_manifest)
            .expect("Failed to initialize midenup");

        // Install stable (0.20.3)
        let command = Midenup::try_parse_from(["midenup", "install", "stable"]).unwrap();
        let Behavior::Midenup { command: Some(command), .. } = command.behavior else {
            panic!("Error while parsing test command. Expected Midenup Behavior, got Miden");
        };
        command.execute(&config, &mut local_manifest).expect("Failed to install stable");

        // Check that binaries are installed in the bin directory
        assert!(toolchain_dir.join("0.20.3").join("bin").join("miden-vm").exists());
        assert!(toolchain_dir.join("0.20.3").join("bin").join("miden-client").exists());
        // Check that libraries are installed in the lib directory
        assert!(toolchain_dir.join("0.20.3").join("lib").join("core.masp").exists());

        // Swap to manifest 2 (channel "0.13.0" with migration from "0.20.3")
        let manifest: &str =
            full_path_manifest!("tests/data/integration_migration_test/channel-manifest-2.json");
        let (_, config) = test_setup(&midenup_home, manifest);

        // Perform global update
        let command = Midenup::try_parse_from(["midenup", "update"]).unwrap();
        let Behavior::Midenup { command: Some(command), .. } = command.behavior else {
            panic!("Error while parsing test command. Expected Midenup Behavior, got Miden");
        };
        command
            .execute(&config, &mut local_manifest)
            .expect("Failed to perform global update");

        // Check 1: Components installed in 0.13.0 directory
        assert!(toolchain_dir.join("0.13.0").exists());
        assert!(toolchain_dir.join("0.13.0").join("installation-successful").exists());

        // Check 2: The 0.20.3 directory has been entirely deleted
        assert!(!toolchain_dir.join("0.20.3").exists());

        // Check 3: The stable symlink points to the new channel directory
        let stable_symlink = toolchain_dir.join("stable");
        assert!(stable_symlink.exists(), "stable symlink should exist after migration");
        let symlink_target =
            std::fs::read_link(&stable_symlink).expect("stable should be a symlink");
        assert_eq!(
            symlink_target,
            toolchain_dir.join("0.13.0"),
            "stable symlink should point to the migrated channel"
        );
    }

    #[test]
    /// Validates that every component present in the stable toolchain from the published manifest
    /// is able to be executed.
    ///
    /// This relies on every component respecting the --help flag, which is an assumption we already
    /// make in the miden_wrapper.rs file. This stems from the fact that the help command is
    /// generated automatically.
    ///
    /// [See here for details](https://docs.rs/clap/latest/clap/struct.Command.html#method.disable_help_flag)
    fn integration_test_components_are_runnable() {
        let test_name = "integration_test_components";
        let test_env = environment_setup(test_name);

        let tmp_home = test_env.midenup_dir;
        let midenup_home = tmp_home.join("midenup");

        const FILE: &str = full_path_manifest!("manifest/channel-manifest.json");
        let (mut local_manifest, config) = test_setup(&midenup_home, FILE);

        // Install the latest stable toolchain
        let command = Midenup::try_parse_from(["midenup", "install", "stable"]).unwrap();
        let Behavior::Midenup { command: Some(command), .. } = command.behavior else {
            panic!("Expected Midenup behavior, got Miden");
        };
        command.execute(&config, &mut local_manifest).expect("Failed to install stable");

        let stable_channel = local_manifest
            .get_latest_stable()
            .expect("No stable channel found after installing stable")
            .clone();

        println!("Installed: {}", stable_channel);

        // Verify each executable component is accessible and runnable
        for component in &stable_channel.components {
            let component_type = component.get_installed_file();
            // Skip libraries
            if matches!(component_type, InstalledFile::Library { .. }) {
                continue;
            }

            // Skip components not meant to be executed directly
            if matches!(component_type, InstalledFile::Executable { alias_only: true, .. }) {
                continue;
            }

            let argv: Vec<OsString> =
                vec!["miden".into(), "help".into(), component.name.as_ref().into()];

            miden_wrapper::miden_wrapper(argv, &config, &mut local_manifest).unwrap_or_else(
                |err| {
                    panic!(
                        "Component '{}' is not runnable through the 'miden' interface: {}",
                        component.name, err
                    )
                },
            );
        }
    }
}