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