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
use std::collections::HashSet;

use anyhow::{Context, bail};
use colored::Colorize;

use crate::{
    channel::{
        Channel, Component, InstalledFile, MigrationStrategy, UserChannel, is_toolchain_deleted,
    },
    commands::{self, uninstall::uninstall_executable},
    config::Config,
    manifest::Manifest,
    options::{PathUpdate, UpdateOptions},
    version::Authority,
};

/// Updates installed toolchains
pub fn update(
    config: &Config,
    channel_type: Option<&UserChannel>,
    local_manifest: &mut Manifest,
    options: &UpdateOptions,
) -> anyhow::Result<()> {
    match channel_type {
        Some(UserChannel::Stable) => {
            let local_stable = local_manifest.get_latest_stable().context(
                "No stable version was found. To install it, try running:
midenup install stable
",
            )?;
            let upstream_stable = config
                .manifest
                .get_latest_stable()
                // NOTE: This means that there is no stable toolchain upstream.
                //
                // This is most likely an edge-case that shouldn't happen. If it does happen, it
                // probably means there's an error in midenup's parsing.
                .context("ERROR: No stable channel found in upstream")?;

            if upstream_stable.name > local_stable.name {
                let component_subset = if local_stable.is_partially_installed() {
                    Some(local_stable.components.clone())
                } else {
                    None
                };

                let channel_to_install = {
                    let components = upstream_stable
                        .components
                        .iter()
                        .filter(|comp| {
                            if let Some(component_subset) = &component_subset {
                                component_subset.contains(comp)
                            } else {
                                true
                            }
                        })
                        .cloned()
                        .collect();

                    Channel {
                        name: upstream_stable.name.clone(),
                        alias: upstream_stable.alias.clone(),
                        tags: local_stable.tags.clone(),
                        components,
                    }
                };

                commands::install(
                    config,
                    &channel_to_install,
                    local_manifest,
                    &((*options).into()),
                )?
            } else {
                println!("Nothing to update, you are all up to date");
            }
        },
        Some(UserChannel::Version(version)) => {
            // Check if any individual component changed since the last the manifest was synced
            let local_channel = local_manifest
                .get_channel(&UserChannel::Version(version.clone()))
                .context(format!("ERROR: No installed channel found with version {version}"))?
                .clone();

            let upstream_channel = config
                .manifest
                .get_channel(&UserChannel::Version(version.clone()))
                .context(format!(
                    "ERROR: Couldn't find a channel upstream with version {version}. Maybe it got \
                     removed."
                ))?;

            update_channel(config, &local_channel, upstream_channel, local_manifest, options)?
        },
        None => {
            // Update all toolchains
            let mut channels_to_update = Vec::new();
            for local_channel in local_manifest.get_channels() {
                let upstream_channel =
                    config.manifest.get_channels().find(|up_c| *up_c == local_channel);
                let Some(upstream_channel) = upstream_channel else {
                    // NOTE: A bit of an edge case. If the channel is present in the local manifest
                    // but not in upstream, then it probably either:
                    //
                    // - is a developer toolchain.
                    // - the upstream channel got removed from upstream (possibly for being too
                    //   old/deprecated/got rolled back)
                    continue;
                };
                channels_to_update.push((local_channel.clone(), upstream_channel.clone()));
            }

            for (local_channel, upstream_channel) in channels_to_update {
                update_channel(config, &local_channel, &upstream_channel, local_manifest, options)?;
            }
        },
        Some(UserChannel::Nightly) => todo!(),
        Some(UserChannel::Other(_)) => todo!(),
    }
    Ok(())
}

/// This function executes the actual update. It is in charge of "preparing the environmet" to then
/// call [`commands::install`]. Preparation primarily consists of:
///
/// - Uninstalling components (via `cargo uninstall`).
/// - Removing the installation indicator file.
///
/// The channel that is finally installed might differ slighltly from the upstream channel in the
/// following scenarios:
///
/// - A component is explicitely not updated. In that the case, the "old" component will be written
///   to the install.rs file to ensure consistency.
fn update_channel(
    config: &Config,
    local_channel: &Channel,
    upstream_channel: &Channel,
    local_manifest: &mut Manifest,
    options: &UpdateOptions,
) -> anyhow::Result<()> {
    let installed_toolchains_dir = config.midenup_home.join("toolchains");
    let toolchain_dir = installed_toolchains_dir.join(format!("{}", &local_channel.name));

    let mut channel_to_install = upstream_channel.clone();

    let comp_to_delete_with_motive = components_to_update(local_channel, &channel_to_install);

    if comp_to_delete_with_motive.is_empty() {
        println!("Toolchain {} is up to date", local_channel);
        return Ok(());
    }

    display_warnings(&comp_to_delete_with_motive, upstream_channel, options);

    let mut exes_to_uninstall = Vec::new();
    let mut libs_to_uninstall = Vec::new();
    for (component, motive) in comp_to_delete_with_motive {
        // If the component got added to the toolchain, then there's nothing to delete.
        if matches!(motive, UpdateMotive::Added) {
            continue;
        }
        match component.get_installed_file() {
            InstalledFile::Library { library_name, .. } => {
                let lib_path = toolchain_dir.join("lib").join(library_name);
                libs_to_uninstall.push(lib_path);
            },
            InstalledFile::Executable { .. } => {
                let executable_to_uninstall: Option<String> = match component.version {
                    Authority::Cargo { package, .. } => {
                        let package_name = package.unwrap_or(component.name.to_string());
                        Some(package_name)
                    },
                    Authority::Git { crate_name, .. } => Some(crate_name),
                    // Since uninstalling a component from the filesystem is potentially
                    // irreversible, we take special precautions before uninstalling them.
                    Authority::Path { crate_name, .. } => match options.path_update {
                        PathUpdate::Interactive => {
                            match handle_path_uninstall_interactive(crate_name)? {
                                InteractiveResult::Cancel => return Ok(()),
                                InteractiveResult::ComponentUpdate(update_decision) => {
                                    update_decision
                                },
                            }
                        },
                        PathUpdate::All => Some(crate_name),
                        PathUpdate::Off => None,
                    },
                };

                if let Some(executable_name) = executable_to_uninstall {
                    exes_to_uninstall.push(executable_name);
                } else {
                    // Case where the user wants to skip component update
                    let Some(component_to_install) =
                        channel_to_install.get_component_mut(&component.name)
                    else {
                        // This else case can occur when:
                        //
                        // - A user doesn't want to uninstall a component and
                        // - Said component is not present in the upstream channel, which means that
                        //   the component got removed from the toolchain entirely after the update.
                        continue;
                    };

                    // SAFETY: If the component is installed, it *must* be present on
                    // the local_channel.
                    let local_component =
                        local_channel.get_component(&component_to_install.name).unwrap();

                    *component_to_install = local_component.clone();
                }
            },
        }
    }

    // The update begins
    {
        // We remove the "installation-successful" file to trigger a re-installation.
        let installation_indicator = toolchain_dir.join("installation-successful");
        match std::fs::remove_file(&installation_indicator) {
            Ok(()) => (),
            // NOTE: If the installation indicator is not present, then it means that an update got
            // stopped mid way through. If that's the case, then this update run will bring the
            // toolchain back to a valid state.
            Err(e) if matches!(e.kind(), std::io::ErrorKind::NotFound) => (),
            Err(e) => bail!(format!(
                "Couldn't delete installation complete indicator in: {}because of {e}",
                &installation_indicator.display()
            )),
        }

        for lib in libs_to_uninstall {
            std::fs::remove_file(&lib).context(format!("Couldn't delete {}", lib.display()))?;
        }

        for exe in exes_to_uninstall {
            let result = uninstall_executable(exe, &toolchain_dir);
            match result {
                // If we fail to explicitely uninstall the executable, we simply keep going.
                // Failure in most cases originates from the "exe" not being found in the
                // `toolchain_dir`.  If the package is not found, then the new, updated, version can
                // simply be placed in the directory without any issues. This discrepancy can be
                // caused when an update is cut mid-way through.
                Err(commands::uninstall::UninstallError::FailedToUninstallPackage(name, ..)) => {
                    println!(
                        "INFO: Failed to uninstall old version of {name}. Proceeding regardless."
                    );
                    continue;
                },
                Err(err) => return Err(err)?,
                Ok(_) => continue,
            };
        }

        commands::install(config, &channel_to_install, local_manifest, &((*options).into()))?;

        // After removing the components, we check if we can remove the toolchain entirely.
        let is_entirely_removed = is_toolchain_deleted(&toolchain_dir);
        if is_entirely_removed {
            commands::uninstall(config, local_channel, local_manifest)?;
        };
    }
    Ok(())
}

enum InteractiveResult {
    /// Cancel the update all together. Useful for potential miss-clicks.
    Cancel,
    /// Wether to update the component or not.
    ComponentUpdate(Option<String>),
}

fn handle_path_uninstall_interactive(crate_name: String) -> anyhow::Result<InteractiveResult> {
    println!(
        "Would you like to update this component? (N/y/c)
   - N: no, skip this component
   - y: yes, update this component
   - c: cancel the update all-together (no changes will be applied)"
    );

    let mut input = String::new();
    std::io::stdin().read_line(&mut input).context("Failed to read input")?;
    let input = input.trim().to_ascii_lowercase();
    match input.as_str() {
        "y" => {
            println!("Updating {crate_name}");
            Ok(InteractiveResult::ComponentUpdate(Some(crate_name)))
        },
        "c" => {
            println!("Cancelling update, no changes will be applied.");
            Ok(InteractiveResult::Cancel)
        },
        _ => {
            println!("Skipping {crate_name}, it will not be updated");
            Ok(InteractiveResult::ComponentUpdate(None))
        },
    }
}

#[derive(Debug, Clone)]
pub enum UpdateMotive {
    /// This component was added to the toolchain and wasn't there before.
    Added,
    /// This component was removed and is no longer part of the toolchain.
    Removed,
    /// A newer version was released.
    NewerVersion,
    /// The entire channel was migrated.
    Migrated { strategy: MigrationStrategy },
}

/// This functions compares the Channel &older, with a newer channel [newer] and returns the list
/// of [Components] that need to be updated.
///
/// NOTE: A component can be marked for update in the following scenarios:
///
/// - The component got removed from the newer channel entirely and thus needs to be removed from
///   the system.
/// - A new component is present in the upstream manifest and thus needs to be installed.
/// - A newer version of a present component is released and thus an upgrade is due.
/// - An *older* version of a component is released and thus a downgrade is due.
/// - A components [Authority] got changed and thus needs to be removed and re-installed with the
///   new [Authority]
///
/// There is one notable exception to this rule which is when a channel is migrated into a different
/// channel. In that case, every component is marked for update.
pub fn components_to_update(older: &Channel, newer: &Channel) -> Vec<(Component, UpdateMotive)> {
    let new_channel: HashSet<&Component> = HashSet::from_iter(newer.components.iter());
    let current = HashSet::from_iter(older.components.iter());

    // This is the subset of new components present in the channel since last sync.
    //
    // NOTE: Equality between components is done via their name, see [Component::eq].
    let new_components = new_channel.difference(&current).map(|comp| (comp, UpdateMotive::Added));

    // This is the subset of old components that need to be removed.
    let old_components = current.difference(&new_channel).map(|comp| (comp, UpdateMotive::Removed));

    // These are the elements that are present in boths sets. We are only interested in those which
    // need updating.
    let components_to_update = current
        .iter()
        .filter(|comp| new_channel.contains(**comp))
        .filter_map(|current_component| {
            let new_component = new_channel.get(*current_component);
            match new_component {
                // This should't be possible, but if somehow the component is missing, then we
                // trigger an update for said component regardless.
                None => Some((current_component, UpdateMotive::Added)),
                // If the new channel was migrated, then every component should be deleted; unless
                // explicitely told otherwise by the users (for example in components which were
                // compile from a path at a given time).
                Some(new_component) => {
                    if let Some(strategy) = newer.migrated_into() {
                        Some((
                            current_component,
                            UpdateMotive::Migrated { strategy: strategy.clone() },
                        ))
                    } else if !current_component.is_up_to_date(new_component) {
                        Some((current_component, UpdateMotive::NewerVersion))
                    } else {
                        None
                    }
                },
            }
        });

    let components = new_components
        .chain(old_components)
        .chain(components_to_update)
        .map(|(comp, motive)| ((*comp).clone(), motive));

    Vec::from_iter(components)
}

fn display_warnings(
    components_with_motive: &[(Component, UpdateMotive)],
    newer: &Channel,
    options: &UpdateOptions,
) {
    let components_with_motive = components_with_motive.iter();

    // Warning for components installed from a PATH.
    {
        let components_from_path: Vec<String> = components_with_motive
            .clone()
            .filter_map(|(comp, _)| match &comp.version {
                Authority::Path { path, crate_name, .. } => Some((path, crate_name)),
                _ => None,
            })
            .map(|(path, crate_name)| {
                format!("- {} is installed from {}.\n", crate_name.bold(), path.display(),)
            })
            .collect();
        if !components_from_path.is_empty() {
            println!(
                "{}: The following elements are installed from a specific path in the filesystem.",
                "WARNING".yellow().bold(),
            );

            if matches!(options.path_update, PathUpdate::Off) {
                println!(
                    "
To make midenup update them all, pass the '--path-update=all' flag to `midenup update`.
Alternatively, pass the '--path-update=interactive' flag to interactively select which \
                     path-managed components to update.",
                );
            }
            for component_message in components_from_path {
                println!("{}", component_message);
            }
        }
    }

    // Warning for migrated components
    {
        let migrated_components: Vec<String> = components_with_motive
            .filter_map(|(component, motive)| match &motive {
                UpdateMotive::Migrated { strategy } => Some((component, strategy)),
                _ => None,
            })
            .map(|(component, strategy)| match strategy {
                MigrationStrategy::NameChange { old_channel } => {
                    format!("- {} from {} into {}", component.name, old_channel, newer)
                },
            })
            .collect();
        if !migrated_components.is_empty() {
            println!(
                "{}: The following elements are going to be migrated.",
                "WARNING".yellow().bold(),
            );

            for component_message in migrated_components {
                println!("{}", component_message);
            }
        }
    }
}