Skip to main content

cli/
self_install.rs

1use anyhow::{Result, bail};
2
3use crate::config::{self, Config};
4#[cfg(unix)]
5use crate::privilege;
6use crate::update_check::{self, ReleaseChannel, UpdateStatus};
7use crate::{apps, colors, env, info, install_core, list, output, platform, shells, sys, version};
8
9pub async fn handle_update(
10    config: &Config,
11    target: Option<&str>,
12    diff: bool,
13    verbose: bool,
14    refresh_release: bool,
15) -> Result<()> {
16    if let Some(target) = target {
17        return info::handle_update_target(config, target).await;
18    }
19
20    let mut printed_update = if verbose {
21        Box::pin(list::handle_status_list(config, diff)).await?;
22        println!();
23        true
24    } else {
25        Box::pin(list::handle_update_list(config, diff)).await?
26    };
27
28    let current = version::semver();
29    if verbose {
30        println!("Checking for updates (current: {current})...");
31    }
32
33    let update_status = if refresh_release {
34        update_check::check_for_update_forced(config).await
35    } else {
36        update_check::check_for_update(config).await
37    };
38
39    match update_status {
40        Ok(UpdateStatus::UpToDate) => {
41            if verbose {
42                println!(
43                    "{}",
44                    colors::green(&format!("shine {current} is up to date."))
45                );
46            }
47        }
48        Ok(UpdateStatus::UpdateAvailable { latest }) => {
49            if printed_update && !verbose {
50                println!();
51            }
52            println!(
53                "{}",
54                colors::yellow(&format!(
55                    "A newer version of shine is available: {current} -> {latest}."
56                ))
57            );
58            println!("Run `shine self upgrade` to install it.");
59            printed_update = true;
60        }
61        Ok(UpdateStatus::UpdateRequired { latest }) => {
62            if printed_update && !verbose {
63                println!();
64            }
65            println!(
66                "{}",
67                colors::yellow(&format!(
68                    "A newer patch release of shine is available: {current} -> {latest}."
69                ))
70            );
71            println!("Run `shine self upgrade` to install it.");
72            printed_update = true;
73        }
74        Err(e) => {
75            eprintln!("{}", format_update_check_failure_warning(&e));
76        }
77    }
78
79    if !printed_update {
80        println!("{}", colors::dim("Nothing to update."));
81    }
82
83    Ok(())
84}
85
86fn format_update_check_failure_warning(err: &anyhow::Error) -> String {
87    colors::yellow_stderr(&format!("warning: skipped shine version check: {err}"))
88}
89
90pub async fn handle_self_upgrade(config: &Config, channel: Option<ReleaseChannel>) -> Result<()> {
91    let current = version::semver();
92    let selected_channel = channel.unwrap_or(ReleaseChannel::Stable);
93    let force_install = channel.is_some();
94    println!(
95        "Checking for {} upgrades (current: {current})...",
96        selected_channel.as_str()
97    );
98
99    match update_check::upgrade_to_release(config, selected_channel, force_install).await {
100        Ok(update_check::UpgradeResult::AlreadyUpToDate { channel, latest }) => {
101            println!(
102                "{}",
103                colors::green(&format!(
104                    "shine {current} is up to date on the {} channel ({latest}).",
105                    channel.as_str()
106                ))
107            );
108        }
109        Ok(update_check::UpgradeResult::Upgraded {
110            channel,
111            previous: _,
112            previous_display,
113            release_tag,
114            installed_version,
115            installed_path,
116        }) => {
117            println!(
118                "{}",
119                colors::green(&format_self_upgrade_message(
120                    channel,
121                    &previous_display,
122                    &installed_version,
123                    &release_tag,
124                ))
125            );
126            sync_self_install_dest(config, &installed_path).await;
127        }
128        Err(e) => {
129            update_check::invalidate_update_cache(config).await;
130            bail!("Upgrade failed: {e}");
131        }
132    }
133
134    Ok(())
135}
136
137fn format_self_upgrade_message(
138    channel: ReleaseChannel,
139    previous_display: &str,
140    installed_version: &str,
141    release_tag: &str,
142) -> String {
143    match channel {
144        ReleaseChannel::Stable => {
145            format!("Upgraded shine from {previous_display} to {installed_version}.")
146        }
147        ReleaseChannel::Preview => {
148            if previous_display.contains("-preview") {
149                format!(
150                    "Updated shine preview from {previous_display} to {installed_version} ({release_tag})."
151                )
152            } else {
153                format!(
154                    "Installed shine preview {installed_version} over stable {previous_display} ({release_tag})."
155                )
156            }
157        }
158    }
159}
160
161pub async fn handle_config_upgrade(
162    config: &Config,
163    target: Option<&str>,
164    verbose: bool,
165    prune_stale: bool,
166) -> Result<()> {
167    if let Some(target) = target {
168        return handle_config_target_upgrade(config, target, verbose, prune_stale).await;
169    }
170    if verbose {
171        println!("{}", colors::bold("Upgrading installed configs"));
172        config::print_presets_note(config);
173    }
174
175    let mut sep = if verbose {
176        output::SectionSeparator::new()
177    } else {
178        output::SectionSeparator::with_preamble(colors::bold("Upgrading installed configs"))
179    };
180
181    let env_report = Box::pin(env::upgrade::handle_upgrade(config, false, verbose)).await?;
182    let shell_report =
183        Box::pin(shells::handle_upgrade_installed(config, verbose, &mut sep)).await?;
184    let app_report = Box::pin(apps::handle_upgrade_installed_with_output(
185        config,
186        prune_stale,
187        verbose,
188        &mut sep,
189    ))
190    .await?;
191    let sys_report = Box::pin(sys::handle_upgrade_managed(config, verbose, &mut sep)).await?;
192
193    let updated = env_report.updated
194        + shell_report.updated_categories.len()
195        + usize::from(shell_report.path_changed)
196        + app_report.updated_categories
197        + sys_report.updated;
198    let user_modified = env_report.user_modified + app_report.user_modified;
199
200    let summary = config_upgrade_summary_parts(updated, user_modified, shell_report.link_conflicts);
201    if verbose || sep.has_printed() {
202        output::footer("Done", &summary);
203    } else {
204        println!("{}", colors::dim("Nothing to upgrade."));
205    }
206    for hint in &app_report.restart_hints {
207        println!("  {} {}", colors::symbol("!"), colors::yellow(hint));
208    }
209
210    if app_report.failed > 0 {
211        bail!(
212            "{} generated app configuration item(s) failed",
213            app_report.failed
214        );
215    }
216
217    if sys_report.failed > 0 {
218        bail!(
219            "{} managed system configuration item(s) failed",
220            sys_report.failed
221        );
222    }
223
224    Ok(())
225}
226
227async fn handle_config_target_upgrade(
228    config: &Config,
229    target: &str,
230    verbose: bool,
231    prune_stale: bool,
232) -> Result<()> {
233    use crate::shim::{PresetKind, resolve_preset_kind};
234
235    let target = target.trim();
236    if target.is_empty() {
237        bail!("upgrade target must not be empty");
238    }
239
240    let mut sep = if verbose {
241        println!("{}", colors::bold(&format!("Upgrading {target}")));
242        config::print_presets_note(config);
243        output::SectionSeparator::new()
244    } else {
245        output::SectionSeparator::with_preamble(colors::bold(&format!("Upgrading {target}")))
246    };
247
248    let (updated, user_modified, link_conflicts, failed, restart_hints) =
249        if let Some(item) = target.strip_prefix("sys/") {
250            if item.is_empty() || item.contains('/') {
251                bail!("invalid system target `{target}`; expected sys/<item>");
252            }
253            if prune_stale {
254                bail!("`--prune-stale` applies only to app targets");
255            }
256            let report = Box::pin(sys::handle_upgrade_managed_target(
257                config,
258                Some(item),
259                verbose,
260                &mut sep,
261            ))
262            .await?;
263            (report.updated, 0, 0, report.failed, Default::default())
264        } else {
265            let normalized = if let Some(rest) = target.strip_prefix("app/") {
266                let category = rest.split('/').next().unwrap_or_default();
267                format!("app/{category}")
268            } else if let Some(rest) = target.strip_prefix("shell/") {
269                let category = rest.split('/').next().unwrap_or_default();
270                format!("shell/{category}")
271            } else {
272                target.to_string()
273            };
274            let (kind, category) = resolve_preset_kind(config, &normalized).await?;
275            match kind {
276                PresetKind::App => {
277                    let report = Box::pin(apps::handle_upgrade_installed_target(
278                        config,
279                        Some(&category),
280                        prune_stale,
281                        verbose,
282                        &mut sep,
283                    ))
284                    .await?;
285                    (
286                        report.updated_categories,
287                        report.user_modified,
288                        0,
289                        report.failed,
290                        report.restart_hints,
291                    )
292                }
293                PresetKind::Shell => {
294                    if prune_stale {
295                        bail!("`--prune-stale` applies only to app targets");
296                    }
297                    let report = Box::pin(shells::handle_upgrade_installed_target(
298                        config,
299                        Some(&category),
300                        verbose,
301                        &mut sep,
302                    ))
303                    .await?;
304                    (
305                        report.updated_categories.len() + usize::from(report.path_changed),
306                        0,
307                        report.link_conflicts,
308                        0,
309                        Default::default(),
310                    )
311                }
312            }
313        };
314
315    let summary = config_upgrade_summary_parts(updated, user_modified, link_conflicts);
316    if verbose || sep.has_printed() {
317        output::footer("Done", &summary);
318    } else {
319        println!("{}", colors::dim("Nothing to upgrade."));
320    }
321    for hint in restart_hints {
322        println!("  {} {}", colors::symbol("!"), colors::yellow(&hint));
323    }
324    if failed > 0 {
325        bail!("{failed} managed configuration item(s) failed");
326    }
327    Ok(())
328}
329
330fn config_upgrade_summary_parts(
331    updated: usize,
332    user_modified: usize,
333    link_conflicts: usize,
334) -> Vec<String> {
335    let mut parts = Vec::new();
336    output::push_count(&mut parts, updated, colors::green, "updated");
337    output::push_count(
338        &mut parts,
339        user_modified,
340        colors::yellow,
341        "user-modified (kept)",
342    );
343    output::push_count(&mut parts, link_conflicts, colors::yellow, "link conflicts");
344    parts
345}
346
347/// After a successful self-upgrade, try to sync the new binary to the self-install destination.
348/// If the copy fails due to permissions, print a targeted hint instead of failing.
349async fn sync_self_install_dest(config: &Config, src: &std::path::Path) {
350    let dest = match &config.self_install_dest {
351        Some(d) => d,
352        None => return,
353    };
354    match sync_self_install_dest_from(src, dest).await {
355        Ok(SelfInstallSync::Synced) => println!(
356            "{}",
357            colors::green(&format!("Synced system copy at {}", dest.display()))
358        ),
359        Ok(SelfInstallSync::AlreadyCurrent) => {}
360        // Unix already tried `sudo` automatically inside `install_binary_with_elevation`;
361        // reaching here means it was declined or unavailable non-interactively. Windows has
362        // no such auto-elevation path, so it still needs the manual hint.
363        Err(e) if cfg!(windows) && has_io_error_kind(&e, std::io::ErrorKind::PermissionDenied) => {
364            let hint = format!(
365                "Installed copy at {} needs manual sync; rerun from an elevated terminal if needed.",
366                dest.display()
367            );
368            println!("{}", colors::yellow(&hint));
369        }
370        Err(e) => eprintln!(
371            "Warning: failed to sync system copy at {}: {e}",
372            dest.display()
373        ),
374    }
375}
376
377enum SelfInstallSync {
378    Synced,
379    AlreadyCurrent,
380}
381
382async fn sync_self_install_dest_from(
383    src: &std::path::Path,
384    dest: &std::path::Path,
385) -> Result<SelfInstallSync> {
386    if dest.exists() {
387        let canonical_src = src.canonicalize().unwrap_or_else(|_| src.to_path_buf());
388        let canonical_dest = dest.canonicalize().unwrap_or_else(|_| dest.to_path_buf());
389        if canonical_src == canonical_dest {
390            return Ok(SelfInstallSync::AlreadyCurrent);
391        }
392    }
393
394    install_binary_with_elevation(src, dest)
395        .await
396        .map(|()| SelfInstallSync::Synced)
397}
398
399fn has_io_error_kind(err: &anyhow::Error, kind: std::io::ErrorKind) -> bool {
400    err.chain().any(|cause| {
401        cause
402            .downcast_ref::<std::io::Error>()
403            .is_some_and(|io_err| io_err.kind() == kind)
404    })
405}
406
407pub async fn handle_self_install(
408    mut config: Config,
409    dest: Option<std::path::PathBuf>,
410) -> Result<()> {
411    use anyhow::{Context as _, bail};
412
413    let src = std::env::current_exe().context("failed to resolve current executable path")?;
414    let dest = match dest {
415        Some(dest) => dest,
416        None => platform::default_self_install_dest()?,
417    };
418
419    if dest.exists() {
420        let canonical_src = src.canonicalize().unwrap_or_else(|_| src.clone());
421        let canonical_dest = dest.canonicalize().unwrap_or_else(|_| dest.clone());
422        if canonical_src == canonical_dest {
423            let example = if cfg!(windows) {
424                r"C:\path\to\new\shine.exe self install"
425            } else {
426                "sudo /path/to/new/shine self install"
427            };
428            bail!(
429                "source and destination are the same binary: {}. Run the newer binary by full path, e.g. `{example}`, to overwrite this copy.",
430                dest.display()
431            );
432        }
433    }
434
435    install_binary_with_elevation(&src, &dest)
436        .await
437        .with_context(|| self_install_failure_hint(&dest))?;
438
439    // Remember where we installed so `shine self upgrade` can sync this copy automatically.
440    config.self_install_dest = Some(dest.clone());
441    config
442        .save()
443        .await
444        .context("failed to save self_install_dest to config")?;
445
446    println!(
447        "{}",
448        colors::green(&format!("installed to {}", dest.display()))
449    );
450    print_self_install_activation_hint(&dest);
451
452    Ok(())
453}
454
455fn self_install_failure_hint(dest: &std::path::Path) -> String {
456    format!("failed to copy to {}", dest.display())
457}
458
459fn print_self_install_activation_hint(dest: &std::path::Path) {
460    let Some(dir) = dest.parent() else {
461        return;
462    };
463    if platform::current_path_contains_dir(dir) {
464        println!(
465            "{}",
466            colors::dim("The install directory is already on PATH.")
467        );
468    } else {
469        println!(
470            "{}",
471            colors::yellow(&format!(
472                "Install directory is not on PATH: {}",
473                dir.display()
474            ))
475        );
476        println!("{}", colors::dim(&platform::path_install_hint(dir)));
477    }
478}
479
480fn install_binary_atomically(src: &std::path::Path, dest: &std::path::Path) -> Result<()> {
481    use anyhow::Context as _;
482
483    let parent = dest
484        .parent()
485        .with_context(|| format!("destination has no parent: {}", dest.display()))?;
486    std::fs::create_dir_all(parent)
487        .with_context(|| format!("failed to create destination dir: {}", parent.display()))?;
488
489    let temp = parent.join(format!(".shine-self-install-{}", uuid::Uuid::new_v4()));
490    std::fs::copy(src, &temp).with_context(|| {
491        format!(
492            "failed to stage binary from {} to {}",
493            src.display(),
494            temp.display()
495        )
496    })?;
497
498    #[cfg(unix)]
499    {
500        use std::os::unix::fs::PermissionsExt;
501        let mode = std::fs::metadata(src)
502            .map(|m| m.permissions().mode())
503            .unwrap_or(0o755);
504        std::fs::set_permissions(&temp, std::fs::Permissions::from_mode(mode))
505            .with_context(|| format!("failed to set permissions on {}", temp.display()))?;
506    }
507
508    match std::fs::rename(&temp, dest) {
509        Ok(()) => Ok(()),
510        Err(err) => {
511            let _ = std::fs::remove_file(&temp);
512            Err(err)
513                .with_context(|| format!("failed to replace {} with staged binary", dest.display()))
514        }
515    }
516}
517
518/// Installs the binary, auto-elevating via `sudo` on Unix if the plain copy
519/// fails because the destination isn't user-writable (e.g. `/usr/local/bin`
520/// owned by root). Mirrors the auto-elevation already used for privileged
521/// app-config writes in `apps/file_ops.rs::install_bytes_admin`, so the user
522/// is prompted once instead of being told to manually re-run with `sudo`.
523async fn install_binary_with_elevation(
524    src: &std::path::Path,
525    dest: &std::path::Path,
526) -> Result<()> {
527    match install_binary_atomically(src, dest) {
528        Ok(()) => Ok(()),
529        Err(e)
530            if !cfg!(windows)
531                && has_io_error_kind(&e, std::io::ErrorKind::PermissionDenied)
532                && !std::env::var("USER").is_ok_and(|user| user == "root") =>
533        {
534            let _lock = install_core::file_ops::admin_lock().await?;
535            install_binary_privileged(src, dest).await
536        }
537        Err(e) => Err(e),
538    }
539}
540
541#[cfg(unix)]
542async fn install_binary_privileged(src: &std::path::Path, dest: &std::path::Path) -> Result<()> {
543    use anyhow::Context as _;
544    use std::os::unix::fs::PermissionsExt;
545
546    if !privilege::ensure_admin(1).await? {
547        anyhow::bail!("administrator permission was not granted");
548    }
549
550    let parent = dest
551        .parent()
552        .with_context(|| format!("destination has no parent: {}", dest.display()))?;
553    let mode = std::fs::metadata(src)
554        .map(|m| m.permissions().mode())
555        .unwrap_or(0o755);
556
557    let status = install_core::file_ops::sudo_command()
558        .arg("mkdir")
559        .arg("-p")
560        .arg(parent)
561        .status()
562        .await
563        .context("failed to create privileged destination directory")?;
564    if !status.success() {
565        anyhow::bail!("administrator permission was not granted");
566    }
567
568    let status = install_core::file_ops::sudo_command()
569        .args(["install", "-m", &format!("{mode:o}"), "--"])
570        .arg(src)
571        .arg(dest)
572        .status()
573        .await
574        .context("failed to install shine binary with administrator privileges")?;
575    if !status.success() {
576        anyhow::bail!("failed to install shine binary with administrator privileges");
577    }
578
579    Ok(())
580}
581
582#[cfg(not(unix))]
583async fn install_binary_privileged(src: &std::path::Path, dest: &std::path::Path) -> Result<()> {
584    // No auto-elevation path on Windows: privileged binary copies go through
585    // an elevated terminal instead. Fall back to the plain unprivileged copy
586    // so the caller's original error surfaces if it still fails.
587    install_binary_atomically(src, dest)
588}
589
590#[cfg(test)]
591mod tests {
592    use super::*;
593
594    async fn make_temp_dir() -> std::path::PathBuf {
595        crate::test_support::make_temp_dir("shine-self-install-test").await
596    }
597
598    fn config_in(dir: &std::path::Path) -> Config {
599        crate::test_support::test_config(dir)
600    }
601
602    #[test]
603    fn install_binary_atomically_overwrites_existing_dest() {
604        let dir = std::env::temp_dir().join(format!("shine-self-install-{}", uuid::Uuid::new_v4()));
605        std::fs::create_dir_all(&dir).unwrap();
606        let src = dir.join("new-shine");
607        let dest = dir.join("shine");
608
609        std::fs::write(&src, b"new").unwrap();
610        std::fs::write(&dest, b"old").unwrap();
611
612        install_binary_atomically(&src, &dest).unwrap();
613
614        assert_eq!(std::fs::read(&dest).unwrap(), b"new");
615        std::fs::remove_dir_all(&dir).unwrap();
616    }
617
618    #[tokio::test]
619    async fn sync_self_install_dest_creates_missing_parent() {
620        let dir = std::env::temp_dir().join(format!("shine-self-sync-{}", uuid::Uuid::new_v4()));
621        let src = dir.join("new-shine");
622        let dest = dir.join("usr/local/bin/shine");
623
624        std::fs::create_dir_all(&dir).unwrap();
625        std::fs::write(&src, b"new").unwrap();
626
627        let outcome = sync_self_install_dest_from(&src, &dest).await.unwrap();
628
629        assert!(matches!(outcome, SelfInstallSync::Synced));
630        assert_eq!(std::fs::read(&dest).unwrap(), b"new");
631        std::fs::remove_dir_all(&dir).unwrap();
632    }
633
634    #[tokio::test]
635    async fn sync_self_install_dest_skips_current_exe_path() {
636        let dir = std::env::temp_dir().join(format!("shine-self-sync-{}", uuid::Uuid::new_v4()));
637        let src = dir.join("shine");
638
639        std::fs::create_dir_all(&dir).unwrap();
640        std::fs::write(&src, b"new").unwrap();
641
642        let outcome = sync_self_install_dest_from(&src, &src).await.unwrap();
643
644        assert!(matches!(outcome, SelfInstallSync::AlreadyCurrent));
645        assert_eq!(std::fs::read(&src).unwrap(), b"new");
646        std::fs::remove_dir_all(&dir).unwrap();
647    }
648
649    #[tokio::test]
650    async fn self_install_errors_when_source_is_destination() {
651        let dir = make_temp_dir().await;
652        let config = config_in(&dir);
653        let current = std::env::current_exe().unwrap();
654
655        let err = handle_self_install(config, Some(current))
656            .await
657            .unwrap_err();
658        assert!(
659            err.to_string()
660                .contains("source and destination are the same binary"),
661            "error should explain self-overwrite: {err:#}"
662        );
663
664        tokio::fs::remove_dir_all(&dir).await.unwrap();
665    }
666
667    #[test]
668    fn update_check_failure_warning_is_non_fatal_wording() {
669        let err = anyhow::anyhow!(
670            "GitHub stable release request failed: HTTP 403 Forbidden: API rate limit exceeded"
671        );
672        let warning = format_update_check_failure_warning(&err);
673
674        assert!(warning.contains("warning: skipped shine version check"));
675        assert!(warning.contains("HTTP 403 Forbidden"));
676        assert!(!warning.contains("Update check failed"));
677    }
678
679    #[test]
680    fn config_upgrade_summary_parts_includes_only_nonzero_counts() {
681        assert_eq!(
682            config_upgrade_summary_parts(2, 0, 0),
683            vec!["2 updated".to_string()]
684        );
685    }
686
687    #[test]
688    fn config_upgrade_summary_parts_empty_when_all_zero() {
689        assert!(config_upgrade_summary_parts(0, 0, 0).is_empty());
690    }
691
692    #[test]
693    fn config_upgrade_summary_parts_reports_actionable_counters() {
694        assert_eq!(
695            config_upgrade_summary_parts(1, 2, 3),
696            vec![
697                "1 updated".to_string(),
698                "2 user-modified (kept)".to_string(),
699                "3 link conflicts".to_string(),
700            ]
701        );
702    }
703
704    #[test]
705    fn format_self_upgrade_message_handles_stable_channel() {
706        assert_eq!(
707            format_self_upgrade_message(ReleaseChannel::Stable, "0.21.3", "0.21.4", "v0.21.4",),
708            "Upgraded shine from 0.21.3 to 0.21.4."
709        );
710    }
711
712    #[test]
713    fn format_self_upgrade_message_handles_stable_to_preview_install() {
714        assert_eq!(
715            format_self_upgrade_message(
716                ReleaseChannel::Preview,
717                "0.21.3",
718                "1.0.0-preview",
719                "preview",
720            ),
721            "Installed shine preview 1.0.0-preview over stable 0.21.3 (preview)."
722        );
723    }
724
725    #[test]
726    fn format_self_upgrade_message_handles_preview_to_preview_update() {
727        assert_eq!(
728            format_self_upgrade_message(
729                ReleaseChannel::Preview,
730                "1.0.0-preview",
731                "1.0.1-preview",
732                "preview",
733            ),
734            "Updated shine preview from 1.0.0-preview to 1.0.1-preview (preview)."
735        );
736    }
737}