auto_update.rs

  1mod update_notification;
  2
  3use anyhow::{anyhow, Context, Result};
  4use client::{Client, TelemetrySettings};
  5use db::kvp::KEY_VALUE_STORE;
  6use db::RELEASE_CHANNEL;
  7use editor::{Editor, MultiBuffer};
  8use gpui::{
  9    actions, AppContext, AsyncAppContext, Context as _, Global, Model, ModelContext,
 10    SemanticVersion, SharedString, Task, View, ViewContext, VisualContext, WindowContext,
 11};
 12
 13use markdown_preview::markdown_preview_view::{MarkdownPreviewMode, MarkdownPreviewView};
 14use schemars::JsonSchema;
 15use serde::Deserialize;
 16use serde_derive::Serialize;
 17use smol::{fs, io::AsyncReadExt};
 18
 19use settings::{Settings, SettingsSources, SettingsStore};
 20use smol::{fs::File, process::Command};
 21
 22use http_client::{AsyncBody, HttpClient, HttpClientWithUrl};
 23use release_channel::{AppCommitSha, AppVersion, ReleaseChannel};
 24use std::{
 25    env::{
 26        self,
 27        consts::{ARCH, OS},
 28    },
 29    ffi::OsString,
 30    path::{Path, PathBuf},
 31    sync::Arc,
 32    time::Duration,
 33};
 34use update_notification::UpdateNotification;
 35use util::ResultExt;
 36use workspace::notifications::NotificationId;
 37use workspace::Workspace;
 38
 39const SHOULD_SHOW_UPDATE_NOTIFICATION_KEY: &str = "auto-updater-should-show-updated-notification";
 40const POLL_INTERVAL: Duration = Duration::from_secs(60 * 60);
 41
 42actions!(
 43    auto_update,
 44    [
 45        Check,
 46        DismissErrorMessage,
 47        ViewReleaseNotes,
 48        ViewReleaseNotesLocally
 49    ]
 50);
 51
 52#[derive(Serialize)]
 53struct UpdateRequestBody {
 54    installation_id: Option<Arc<str>>,
 55    release_channel: Option<&'static str>,
 56    telemetry: bool,
 57    is_staff: Option<bool>,
 58    destination: &'static str,
 59}
 60
 61#[derive(Clone, PartialEq, Eq)]
 62pub enum AutoUpdateStatus {
 63    Idle,
 64    Checking,
 65    Downloading,
 66    Installing,
 67    Updated { binary_path: PathBuf },
 68    Errored,
 69}
 70
 71impl AutoUpdateStatus {
 72    pub fn is_updated(&self) -> bool {
 73        matches!(self, Self::Updated { .. })
 74    }
 75}
 76
 77pub struct AutoUpdater {
 78    status: AutoUpdateStatus,
 79    current_version: SemanticVersion,
 80    http_client: Arc<HttpClientWithUrl>,
 81    pending_poll: Option<Task<Option<()>>>,
 82}
 83
 84#[derive(Deserialize)]
 85struct JsonRelease {
 86    version: String,
 87    url: String,
 88}
 89
 90struct MacOsUnmounter {
 91    mount_path: PathBuf,
 92}
 93
 94impl Drop for MacOsUnmounter {
 95    fn drop(&mut self) {
 96        let unmount_output = std::process::Command::new("hdiutil")
 97            .args(["detach", "-force"])
 98            .arg(&self.mount_path)
 99            .output();
100
101        match unmount_output {
102            Ok(output) if output.status.success() => {
103                log::info!("Successfully unmounted the disk image");
104            }
105            Ok(output) => {
106                log::error!(
107                    "Failed to unmount disk image: {:?}",
108                    String::from_utf8_lossy(&output.stderr)
109                );
110            }
111            Err(error) => {
112                log::error!("Error while trying to unmount disk image: {:?}", error);
113            }
114        }
115    }
116}
117
118struct AutoUpdateSetting(bool);
119
120/// Whether or not to automatically check for updates.
121///
122/// Default: true
123#[derive(Clone, Copy, Default, JsonSchema, Deserialize, Serialize)]
124#[serde(transparent)]
125struct AutoUpdateSettingContent(bool);
126
127impl Settings for AutoUpdateSetting {
128    const KEY: Option<&'static str> = Some("auto_update");
129
130    type FileContent = Option<AutoUpdateSettingContent>;
131
132    fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
133        let auto_update = [sources.release_channel, sources.user]
134            .into_iter()
135            .find_map(|value| value.copied().flatten())
136            .unwrap_or(sources.default.ok_or_else(Self::missing_default)?);
137
138        Ok(Self(auto_update.0))
139    }
140}
141
142#[derive(Default)]
143struct GlobalAutoUpdate(Option<Model<AutoUpdater>>);
144
145impl Global for GlobalAutoUpdate {}
146
147#[derive(Deserialize)]
148struct ReleaseNotesBody {
149    title: String,
150    release_notes: String,
151}
152
153pub fn init(http_client: Arc<HttpClientWithUrl>, cx: &mut AppContext) {
154    AutoUpdateSetting::register(cx);
155
156    cx.observe_new_views(|workspace: &mut Workspace, _cx| {
157        workspace.register_action(|_, action: &Check, cx| check(action, cx));
158
159        workspace.register_action(|_, action, cx| {
160            view_release_notes(action, cx);
161        });
162
163        workspace.register_action(|workspace, _: &ViewReleaseNotesLocally, cx| {
164            view_release_notes_locally(workspace, cx);
165        });
166    })
167    .detach();
168
169    let version = release_channel::AppVersion::global(cx);
170    let auto_updater = cx.new_model(|cx| {
171        let updater = AutoUpdater::new(version, http_client);
172
173        let poll_for_updates = ReleaseChannel::try_global(cx)
174            .map(|channel| channel.poll_for_updates())
175            .unwrap_or(false);
176
177        if option_env!("ZED_UPDATE_EXPLANATION").is_none()
178            && env::var("ZED_UPDATE_EXPLANATION").is_err()
179            && poll_for_updates
180        {
181            let mut update_subscription = AutoUpdateSetting::get_global(cx)
182                .0
183                .then(|| updater.start_polling(cx));
184
185            cx.observe_global::<SettingsStore>(move |updater, cx| {
186                if AutoUpdateSetting::get_global(cx).0 {
187                    if update_subscription.is_none() {
188                        update_subscription = Some(updater.start_polling(cx))
189                    }
190                } else {
191                    update_subscription.take();
192                }
193            })
194            .detach();
195        }
196
197        updater
198    });
199    cx.set_global(GlobalAutoUpdate(Some(auto_updater)));
200}
201
202pub fn check(_: &Check, cx: &mut WindowContext) {
203    if let Some(message) = option_env!("ZED_UPDATE_EXPLANATION") {
204        drop(cx.prompt(
205            gpui::PromptLevel::Info,
206            "Zed was installed via a package manager.",
207            Some(message),
208            &["Ok"],
209        ));
210        return;
211    }
212
213    if let Ok(message) = env::var("ZED_UPDATE_EXPLANATION") {
214        drop(cx.prompt(
215            gpui::PromptLevel::Info,
216            "Zed was installed via a package manager.",
217            Some(&message),
218            &["Ok"],
219        ));
220        return;
221    }
222
223    if !ReleaseChannel::try_global(cx)
224        .map(|channel| channel.poll_for_updates())
225        .unwrap_or(false)
226    {
227        return;
228    }
229
230    if let Some(updater) = AutoUpdater::get(cx) {
231        updater.update(cx, |updater, cx| updater.poll(cx));
232    } else {
233        drop(cx.prompt(
234            gpui::PromptLevel::Info,
235            "Could not check for updates",
236            Some("Auto-updates disabled for non-bundled app."),
237            &["Ok"],
238        ));
239    }
240}
241
242pub fn view_release_notes(_: &ViewReleaseNotes, cx: &mut AppContext) -> Option<()> {
243    let auto_updater = AutoUpdater::get(cx)?;
244    let release_channel = ReleaseChannel::try_global(cx)?;
245
246    match release_channel {
247        ReleaseChannel::Stable | ReleaseChannel::Preview => {
248            let auto_updater = auto_updater.read(cx);
249            let current_version = auto_updater.current_version;
250            let release_channel = release_channel.dev_name();
251            let path = format!("/releases/{release_channel}/{current_version}");
252            let url = &auto_updater.http_client.build_url(&path);
253            cx.open_url(url);
254        }
255        ReleaseChannel::Nightly => {
256            cx.open_url("https://github.com/zed-industries/zed/commits/nightly/");
257        }
258        ReleaseChannel::Dev => {
259            cx.open_url("https://github.com/zed-industries/zed/commits/main/");
260        }
261    }
262    None
263}
264
265fn view_release_notes_locally(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
266    let release_channel = ReleaseChannel::global(cx);
267    let version = AppVersion::global(cx).to_string();
268
269    let client = client::Client::global(cx).http_client();
270    let url = client.build_url(&format!(
271        "/api/release_notes/v2/{}/{}",
272        release_channel.dev_name(),
273        version
274    ));
275
276    let markdown = workspace
277        .app_state()
278        .languages
279        .language_for_name("Markdown");
280
281    workspace
282        .with_local_workspace(cx, move |_, cx| {
283            cx.spawn(|workspace, mut cx| async move {
284                let markdown = markdown.await.log_err();
285                let response = client.get(&url, Default::default(), true).await;
286                let Some(mut response) = response.log_err() else {
287                    return;
288                };
289
290                let mut body = Vec::new();
291                response.body_mut().read_to_end(&mut body).await.ok();
292
293                let body: serde_json::Result<ReleaseNotesBody> =
294                    serde_json::from_slice(body.as_slice());
295
296                if let Ok(body) = body {
297                    workspace
298                        .update(&mut cx, |workspace, cx| {
299                            let project = workspace.project().clone();
300                            let buffer = project.update(cx, |project, cx| {
301                                project.create_local_buffer("", markdown, cx)
302                            });
303                            buffer.update(cx, |buffer, cx| {
304                                buffer.edit([(0..0, body.release_notes)], None, cx)
305                            });
306                            let language_registry = project.read(cx).languages().clone();
307
308                            let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
309
310                            let tab_description = SharedString::from(body.title.to_string());
311                            let editor = cx.new_view(|cx| {
312                                Editor::for_multibuffer(buffer, Some(project), true, cx)
313                            });
314                            let workspace_handle = workspace.weak_handle();
315                            let view: View<MarkdownPreviewView> = MarkdownPreviewView::new(
316                                MarkdownPreviewMode::Default,
317                                editor,
318                                workspace_handle,
319                                language_registry,
320                                Some(tab_description),
321                                cx,
322                            );
323                            workspace.add_item_to_active_pane(
324                                Box::new(view.clone()),
325                                None,
326                                true,
327                                cx,
328                            );
329                            cx.notify();
330                        })
331                        .log_err();
332                }
333            })
334            .detach();
335        })
336        .detach();
337}
338
339pub fn notify_of_any_new_update(cx: &mut ViewContext<Workspace>) -> Option<()> {
340    let updater = AutoUpdater::get(cx)?;
341    let version = updater.read(cx).current_version;
342    let should_show_notification = updater.read(cx).should_show_update_notification(cx);
343
344    cx.spawn(|workspace, mut cx| async move {
345        let should_show_notification = should_show_notification.await?;
346        if should_show_notification {
347            workspace.update(&mut cx, |workspace, cx| {
348                workspace.show_notification(
349                    NotificationId::unique::<UpdateNotification>(),
350                    cx,
351                    |cx| cx.new_view(|_| UpdateNotification::new(version)),
352                );
353                updater
354                    .read(cx)
355                    .set_should_show_update_notification(false, cx)
356                    .detach_and_log_err(cx);
357            })?;
358        }
359        anyhow::Ok(())
360    })
361    .detach();
362
363    None
364}
365
366impl AutoUpdater {
367    pub fn get(cx: &mut AppContext) -> Option<Model<Self>> {
368        cx.default_global::<GlobalAutoUpdate>().0.clone()
369    }
370
371    fn new(current_version: SemanticVersion, http_client: Arc<HttpClientWithUrl>) -> Self {
372        Self {
373            status: AutoUpdateStatus::Idle,
374            current_version,
375            http_client,
376            pending_poll: None,
377        }
378    }
379
380    pub fn start_polling(&self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
381        cx.spawn(|this, mut cx| async move {
382            loop {
383                this.update(&mut cx, |this, cx| this.poll(cx))?;
384                cx.background_executor().timer(POLL_INTERVAL).await;
385            }
386        })
387    }
388
389    pub fn poll(&mut self, cx: &mut ModelContext<Self>) {
390        if self.pending_poll.is_some() || self.status.is_updated() {
391            return;
392        }
393
394        cx.notify();
395
396        self.pending_poll = Some(cx.spawn(|this, mut cx| async move {
397            let result = Self::update(this.upgrade()?, cx.clone()).await;
398            this.update(&mut cx, |this, cx| {
399                this.pending_poll = None;
400                if let Err(error) = result {
401                    log::error!("auto-update failed: error:{:?}", error);
402                    this.status = AutoUpdateStatus::Errored;
403                    cx.notify();
404                }
405            })
406            .ok()
407        }));
408    }
409
410    pub fn status(&self) -> AutoUpdateStatus {
411        self.status.clone()
412    }
413
414    pub fn dismiss_error(&mut self, cx: &mut ModelContext<Self>) {
415        self.status = AutoUpdateStatus::Idle;
416        cx.notify();
417    }
418
419    pub async fn get_latest_remote_server_release(
420        os: &str,
421        arch: &str,
422        mut release_channel: ReleaseChannel,
423        cx: &mut AsyncAppContext,
424    ) -> Result<PathBuf> {
425        let this = cx.update(|cx| {
426            cx.default_global::<GlobalAutoUpdate>()
427                .0
428                .clone()
429                .ok_or_else(|| anyhow!("auto-update not initialized"))
430        })??;
431
432        if release_channel == ReleaseChannel::Dev {
433            release_channel = ReleaseChannel::Nightly;
434        }
435
436        let release = Self::get_latest_release(
437            &this,
438            "zed-remote-server",
439            os,
440            arch,
441            Some(release_channel),
442            cx,
443        )
444        .await?;
445
446        let servers_dir = paths::remote_servers_dir();
447        let channel_dir = servers_dir.join(release_channel.dev_name());
448        let platform_dir = channel_dir.join(format!("{}-{}", os, arch));
449        let version_path = platform_dir.join(format!("{}.gz", release.version));
450        smol::fs::create_dir_all(&platform_dir).await.ok();
451
452        let client = this.read_with(cx, |this, _| this.http_client.clone())?;
453        if smol::fs::metadata(&version_path).await.is_err() {
454            log::info!("downloading zed-remote-server {os} {arch}");
455            download_remote_server_binary(&version_path, release, client, cx).await?;
456        }
457
458        Ok(version_path)
459    }
460
461    async fn get_latest_release(
462        this: &Model<Self>,
463        asset: &str,
464        os: &str,
465        arch: &str,
466        release_channel: Option<ReleaseChannel>,
467        cx: &mut AsyncAppContext,
468    ) -> Result<JsonRelease> {
469        let client = this.read_with(cx, |this, _| this.http_client.clone())?;
470        let mut url_string = client.build_url(&format!(
471            "/api/releases/latest?asset={}&os={}&arch={}",
472            asset, os, arch
473        ));
474        if let Some(param) = release_channel.and_then(|c| c.release_query_param()) {
475            url_string += "&";
476            url_string += param;
477        }
478
479        let mut response = client.get(&url_string, Default::default(), true).await?;
480
481        let mut body = Vec::new();
482        response
483            .body_mut()
484            .read_to_end(&mut body)
485            .await
486            .context("error reading release")?;
487
488        if !response.status().is_success() {
489            Err(anyhow!(
490                "failed to fetch release: {:?}",
491                String::from_utf8_lossy(&body),
492            ))?;
493        }
494
495        serde_json::from_slice(body.as_slice()).with_context(|| {
496            format!(
497                "error deserializing release {:?}",
498                String::from_utf8_lossy(&body),
499            )
500        })
501    }
502
503    async fn update(this: Model<Self>, mut cx: AsyncAppContext) -> Result<()> {
504        let (client, current_version, release_channel) = this.update(&mut cx, |this, cx| {
505            this.status = AutoUpdateStatus::Checking;
506            cx.notify();
507            (
508                this.http_client.clone(),
509                this.current_version,
510                ReleaseChannel::try_global(cx),
511            )
512        })?;
513
514        let release =
515            Self::get_latest_release(&this, "zed", OS, ARCH, release_channel, &mut cx).await?;
516
517        let should_download = match *RELEASE_CHANNEL {
518            ReleaseChannel::Nightly => cx
519                .update(|cx| AppCommitSha::try_global(cx).map(|sha| release.version != sha.0))
520                .ok()
521                .flatten()
522                .unwrap_or(true),
523            _ => release.version.parse::<SemanticVersion>()? > current_version,
524        };
525
526        if !should_download {
527            this.update(&mut cx, |this, cx| {
528                this.status = AutoUpdateStatus::Idle;
529                cx.notify();
530            })?;
531            return Ok(());
532        }
533
534        this.update(&mut cx, |this, cx| {
535            this.status = AutoUpdateStatus::Downloading;
536            cx.notify();
537        })?;
538
539        let temp_dir = tempfile::Builder::new()
540            .prefix("zed-auto-update")
541            .tempdir()?;
542
543        let filename = match OS {
544            "macos" => Ok("Zed.dmg"),
545            "linux" => Ok("zed.tar.gz"),
546            _ => Err(anyhow!("not supported: {:?}", OS)),
547        }?;
548        let downloaded_asset = temp_dir.path().join(filename);
549        download_release(&downloaded_asset, release, client, &cx).await?;
550
551        this.update(&mut cx, |this, cx| {
552            this.status = AutoUpdateStatus::Installing;
553            cx.notify();
554        })?;
555
556        let binary_path = match OS {
557            "macos" => install_release_macos(&temp_dir, downloaded_asset, &cx).await,
558            "linux" => install_release_linux(&temp_dir, downloaded_asset, &cx).await,
559            _ => Err(anyhow!("not supported: {:?}", OS)),
560        }?;
561
562        this.update(&mut cx, |this, cx| {
563            this.set_should_show_update_notification(true, cx)
564                .detach_and_log_err(cx);
565            this.status = AutoUpdateStatus::Updated { binary_path };
566            cx.notify();
567        })?;
568
569        Ok(())
570    }
571
572    fn set_should_show_update_notification(
573        &self,
574        should_show: bool,
575        cx: &AppContext,
576    ) -> Task<Result<()>> {
577        cx.background_executor().spawn(async move {
578            if should_show {
579                KEY_VALUE_STORE
580                    .write_kvp(
581                        SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string(),
582                        "".to_string(),
583                    )
584                    .await?;
585            } else {
586                KEY_VALUE_STORE
587                    .delete_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string())
588                    .await?;
589            }
590            Ok(())
591        })
592    }
593
594    fn should_show_update_notification(&self, cx: &AppContext) -> Task<Result<bool>> {
595        cx.background_executor().spawn(async move {
596            Ok(KEY_VALUE_STORE
597                .read_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY)?
598                .is_some())
599        })
600    }
601}
602
603async fn download_remote_server_binary(
604    target_path: &PathBuf,
605    release: JsonRelease,
606    client: Arc<HttpClientWithUrl>,
607    cx: &AsyncAppContext,
608) -> Result<()> {
609    let mut target_file = File::create(&target_path).await?;
610    let (installation_id, release_channel, telemetry_enabled, is_staff) = cx.update(|cx| {
611        let telemetry = Client::global(cx).telemetry().clone();
612        let is_staff = telemetry.is_staff();
613        let installation_id = telemetry.installation_id();
614        let release_channel =
615            ReleaseChannel::try_global(cx).map(|release_channel| release_channel.display_name());
616        let telemetry_enabled = TelemetrySettings::get_global(cx).metrics;
617
618        (
619            installation_id,
620            release_channel,
621            telemetry_enabled,
622            is_staff,
623        )
624    })?;
625    let request_body = AsyncBody::from(serde_json::to_string(&UpdateRequestBody {
626        installation_id,
627        release_channel,
628        telemetry: telemetry_enabled,
629        is_staff,
630        destination: "remote",
631    })?);
632
633    let mut response = client.get(&release.url, request_body, true).await?;
634    smol::io::copy(response.body_mut(), &mut target_file).await?;
635    Ok(())
636}
637
638async fn download_release(
639    target_path: &Path,
640    release: JsonRelease,
641    client: Arc<HttpClientWithUrl>,
642    cx: &AsyncAppContext,
643) -> Result<()> {
644    let mut target_file = File::create(&target_path).await?;
645
646    let (installation_id, release_channel, telemetry_enabled, is_staff) = cx.update(|cx| {
647        let telemetry = Client::global(cx).telemetry().clone();
648        let is_staff = telemetry.is_staff();
649        let installation_id = telemetry.installation_id();
650        let release_channel =
651            ReleaseChannel::try_global(cx).map(|release_channel| release_channel.display_name());
652        let telemetry_enabled = TelemetrySettings::get_global(cx).metrics;
653
654        (
655            installation_id,
656            release_channel,
657            telemetry_enabled,
658            is_staff,
659        )
660    })?;
661
662    let request_body = AsyncBody::from(serde_json::to_string(&UpdateRequestBody {
663        installation_id,
664        release_channel,
665        telemetry: telemetry_enabled,
666        is_staff,
667        destination: "local",
668    })?);
669
670    let mut response = client.get(&release.url, request_body, true).await?;
671    smol::io::copy(response.body_mut(), &mut target_file).await?;
672    log::info!("downloaded update. path:{:?}", target_path);
673
674    Ok(())
675}
676
677async fn install_release_linux(
678    temp_dir: &tempfile::TempDir,
679    downloaded_tar_gz: PathBuf,
680    cx: &AsyncAppContext,
681) -> Result<PathBuf> {
682    let channel = cx.update(|cx| ReleaseChannel::global(cx).dev_name())?;
683    let home_dir = PathBuf::from(env::var("HOME").context("no HOME env var set")?);
684    let running_app_path = cx.update(|cx| cx.app_path())??;
685
686    let extracted = temp_dir.path().join("zed");
687    fs::create_dir_all(&extracted)
688        .await
689        .context("failed to create directory into which to extract update")?;
690
691    let output = Command::new("tar")
692        .arg("-xzf")
693        .arg(&downloaded_tar_gz)
694        .arg("-C")
695        .arg(&extracted)
696        .output()
697        .await?;
698
699    anyhow::ensure!(
700        output.status.success(),
701        "failed to extract {:?} to {:?}: {:?}",
702        downloaded_tar_gz,
703        extracted,
704        String::from_utf8_lossy(&output.stderr)
705    );
706
707    let suffix = if channel != "stable" {
708        format!("-{}", channel)
709    } else {
710        String::default()
711    };
712    let app_folder_name = format!("zed{}.app", suffix);
713
714    let from = extracted.join(&app_folder_name);
715    let mut to = home_dir.join(".local");
716
717    let expected_suffix = format!("{}/libexec/zed-editor", app_folder_name);
718
719    if let Some(prefix) = running_app_path
720        .to_str()
721        .and_then(|str| str.strip_suffix(&expected_suffix))
722    {
723        to = PathBuf::from(prefix);
724    }
725
726    let output = Command::new("rsync")
727        .args(["-av", "--delete"])
728        .arg(&from)
729        .arg(&to)
730        .output()
731        .await?;
732
733    anyhow::ensure!(
734        output.status.success(),
735        "failed to copy Zed update from {:?} to {:?}: {:?}",
736        from,
737        to,
738        String::from_utf8_lossy(&output.stderr)
739    );
740
741    Ok(to.join(expected_suffix))
742}
743
744async fn install_release_macos(
745    temp_dir: &tempfile::TempDir,
746    downloaded_dmg: PathBuf,
747    cx: &AsyncAppContext,
748) -> Result<PathBuf> {
749    let running_app_path = cx.update(|cx| cx.app_path())??;
750    let running_app_filename = running_app_path
751        .file_name()
752        .ok_or_else(|| anyhow!("invalid running app path"))?;
753
754    let mount_path = temp_dir.path().join("Zed");
755    let mut mounted_app_path: OsString = mount_path.join(running_app_filename).into();
756
757    mounted_app_path.push("/");
758    let output = Command::new("hdiutil")
759        .args(["attach", "-nobrowse"])
760        .arg(&downloaded_dmg)
761        .arg("-mountroot")
762        .arg(temp_dir.path())
763        .output()
764        .await?;
765
766    anyhow::ensure!(
767        output.status.success(),
768        "failed to mount: {:?}",
769        String::from_utf8_lossy(&output.stderr)
770    );
771
772    // Create an MacOsUnmounter that will be dropped (and thus unmount the disk) when this function exits
773    let _unmounter = MacOsUnmounter {
774        mount_path: mount_path.clone(),
775    };
776
777    let output = Command::new("rsync")
778        .args(["-av", "--delete"])
779        .arg(&mounted_app_path)
780        .arg(&running_app_path)
781        .output()
782        .await?;
783
784    anyhow::ensure!(
785        output.status.success(),
786        "failed to copy app: {:?}",
787        String::from_utf8_lossy(&output.stderr)
788    );
789
790    Ok(running_app_path)
791}