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    match release_channel {
248        ReleaseChannel::Stable | ReleaseChannel::Preview => {
249            let auto_updater = auto_updater.read(cx);
250            let current_version = auto_updater.current_version;
251            let release_channel = release_channel.dev_name();
252            let path = format!("/releases/{release_channel}/{current_version}");
253            let url = &auto_updater.http_client.build_url(&path);
254            cx.open_url(url);
255        }
256        ReleaseChannel::Nightly => {
257            cx.open_url("https://github.com/zed-industries/zed/commits/nightly/");
258        }
259        ReleaseChannel::Dev => {
260            cx.open_url("https://github.com/zed-industries/zed/commits/main/");
261        }
262    }
263    None
264}
265
266fn view_release_notes_locally(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
267    let release_channel = ReleaseChannel::global(cx);
268    let version = AppVersion::global(cx).to_string();
269
270    let client = client::Client::global(cx).http_client();
271    let url = client.build_url(&format!(
272        "/api/release_notes/{}/{}",
273        release_channel.dev_name(),
274        version
275    ));
276
277    let markdown = workspace
278        .app_state()
279        .languages
280        .language_for_name("Markdown");
281
282    workspace
283        .with_local_workspace(cx, move |_, cx| {
284            cx.spawn(|workspace, mut cx| async move {
285                let markdown = markdown.await.log_err();
286                let response = client.get(&url, Default::default(), true).await;
287                let Some(mut response) = response.log_err() else {
288                    return;
289                };
290
291                let mut body = Vec::new();
292                response.body_mut().read_to_end(&mut body).await.ok();
293
294                let body: serde_json::Result<ReleaseNotesBody> =
295                    serde_json::from_slice(body.as_slice());
296
297                if let Ok(body) = body {
298                    workspace
299                        .update(&mut cx, |workspace, cx| {
300                            let project = workspace.project().clone();
301                            let buffer = project.update(cx, |project, cx| {
302                                project.create_local_buffer("", markdown, cx)
303                            });
304                            buffer.update(cx, |buffer, cx| {
305                                buffer.edit([(0..0, body.release_notes)], None, cx)
306                            });
307                            let language_registry = project.read(cx).languages().clone();
308
309                            let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
310
311                            let tab_description = SharedString::from(body.title.to_string());
312                            let editor = cx.new_view(|cx| {
313                                Editor::for_multibuffer(buffer, Some(project), true, cx)
314                            });
315                            let workspace_handle = workspace.weak_handle();
316                            let view: View<MarkdownPreviewView> = MarkdownPreviewView::new(
317                                MarkdownPreviewMode::Default,
318                                editor,
319                                workspace_handle,
320                                language_registry,
321                                Some(tab_description),
322                                cx,
323                            );
324                            workspace.add_item_to_active_pane(
325                                Box::new(view.clone()),
326                                None,
327                                true,
328                                cx,
329                            );
330                            cx.notify();
331                        })
332                        .log_err();
333                }
334            })
335            .detach();
336        })
337        .detach();
338}
339
340pub fn notify_of_any_new_update(cx: &mut ViewContext<Workspace>) -> Option<()> {
341    let updater = AutoUpdater::get(cx)?;
342    let version = updater.read(cx).current_version;
343    let should_show_notification = updater.read(cx).should_show_update_notification(cx);
344
345    cx.spawn(|workspace, mut cx| async move {
346        let should_show_notification = should_show_notification.await?;
347        if should_show_notification {
348            workspace.update(&mut cx, |workspace, cx| {
349                workspace.show_notification(
350                    NotificationId::unique::<UpdateNotification>(),
351                    cx,
352                    |cx| cx.new_view(|_| UpdateNotification::new(version)),
353                );
354                updater
355                    .read(cx)
356                    .set_should_show_update_notification(false, cx)
357                    .detach_and_log_err(cx);
358            })?;
359        }
360        anyhow::Ok(())
361    })
362    .detach();
363
364    None
365}
366
367impl AutoUpdater {
368    pub fn get(cx: &mut AppContext) -> Option<Model<Self>> {
369        cx.default_global::<GlobalAutoUpdate>().0.clone()
370    }
371
372    fn new(current_version: SemanticVersion, http_client: Arc<HttpClientWithUrl>) -> Self {
373        Self {
374            status: AutoUpdateStatus::Idle,
375            current_version,
376            http_client,
377            pending_poll: None,
378        }
379    }
380
381    pub fn start_polling(&self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
382        cx.spawn(|this, mut cx| async move {
383            loop {
384                this.update(&mut cx, |this, cx| this.poll(cx))?;
385                cx.background_executor().timer(POLL_INTERVAL).await;
386            }
387        })
388    }
389
390    pub fn poll(&mut self, cx: &mut ModelContext<Self>) {
391        if self.pending_poll.is_some() || self.status.is_updated() {
392            return;
393        }
394
395        cx.notify();
396
397        self.pending_poll = Some(cx.spawn(|this, mut cx| async move {
398            let result = Self::update(this.upgrade()?, cx.clone()).await;
399            this.update(&mut cx, |this, cx| {
400                this.pending_poll = None;
401                if let Err(error) = result {
402                    log::error!("auto-update failed: error:{:?}", error);
403                    this.status = AutoUpdateStatus::Errored;
404                    cx.notify();
405                }
406            })
407            .ok()
408        }));
409    }
410
411    pub fn status(&self) -> AutoUpdateStatus {
412        self.status.clone()
413    }
414
415    pub fn dismiss_error(&mut self, cx: &mut ModelContext<Self>) {
416        self.status = AutoUpdateStatus::Idle;
417        cx.notify();
418    }
419
420    pub async fn get_latest_remote_server_release(
421        os: &str,
422        arch: &str,
423        mut release_channel: ReleaseChannel,
424        cx: &mut AsyncAppContext,
425    ) -> Result<PathBuf> {
426        let this = cx.update(|cx| {
427            cx.default_global::<GlobalAutoUpdate>()
428                .0
429                .clone()
430                .ok_or_else(|| anyhow!("auto-update not initialized"))
431        })??;
432
433        if release_channel == ReleaseChannel::Dev {
434            release_channel = ReleaseChannel::Nightly;
435        }
436
437        let release = Self::get_latest_release(
438            &this,
439            "zed-remote-server",
440            os,
441            arch,
442            Some(release_channel),
443            cx,
444        )
445        .await?;
446
447        let servers_dir = paths::remote_servers_dir();
448        let channel_dir = servers_dir.join(release_channel.dev_name());
449        let platform_dir = channel_dir.join(format!("{}-{}", os, arch));
450        let version_path = platform_dir.join(format!("{}.gz", release.version));
451        smol::fs::create_dir_all(&platform_dir).await.ok();
452
453        let client = this.read_with(cx, |this, _| this.http_client.clone())?;
454        if smol::fs::metadata(&version_path).await.is_err() {
455            log::info!("downloading zed-remote-server {os} {arch}");
456            download_remote_server_binary(&version_path, release, client, cx).await?;
457        }
458
459        Ok(version_path)
460    }
461
462    async fn get_latest_release(
463        this: &Model<Self>,
464        asset: &str,
465        os: &str,
466        arch: &str,
467        release_channel: Option<ReleaseChannel>,
468        cx: &mut AsyncAppContext,
469    ) -> Result<JsonRelease> {
470        let client = this.read_with(cx, |this, _| this.http_client.clone())?;
471        let mut url_string = client.build_url(&format!(
472            "/api/releases/latest?asset={}&os={}&arch={}",
473            asset, os, arch
474        ));
475        if let Some(param) = release_channel.and_then(|c| c.release_query_param()) {
476            url_string += "&";
477            url_string += param;
478        }
479
480        let mut response = client.get(&url_string, Default::default(), true).await?;
481
482        let mut body = Vec::new();
483        response
484            .body_mut()
485            .read_to_end(&mut body)
486            .await
487            .context("error reading release")?;
488
489        if !response.status().is_success() {
490            Err(anyhow!(
491                "failed to fetch release: {:?}",
492                String::from_utf8_lossy(&body),
493            ))?;
494        }
495
496        serde_json::from_slice(body.as_slice()).with_context(|| {
497            format!(
498                "error deserializing release {:?}",
499                String::from_utf8_lossy(&body),
500            )
501        })
502    }
503
504    async fn update(this: Model<Self>, mut cx: AsyncAppContext) -> Result<()> {
505        let (client, current_version, release_channel) = this.update(&mut cx, |this, cx| {
506            this.status = AutoUpdateStatus::Checking;
507            cx.notify();
508            (
509                this.http_client.clone(),
510                this.current_version,
511                ReleaseChannel::try_global(cx),
512            )
513        })?;
514
515        let release =
516            Self::get_latest_release(&this, "zed", OS, ARCH, release_channel, &mut cx).await?;
517
518        let should_download = match *RELEASE_CHANNEL {
519            ReleaseChannel::Nightly => cx
520                .update(|cx| AppCommitSha::try_global(cx).map(|sha| release.version != sha.0))
521                .ok()
522                .flatten()
523                .unwrap_or(true),
524            _ => release.version.parse::<SemanticVersion>()? > current_version,
525        };
526
527        if !should_download {
528            this.update(&mut cx, |this, cx| {
529                this.status = AutoUpdateStatus::Idle;
530                cx.notify();
531            })?;
532            return Ok(());
533        }
534
535        this.update(&mut cx, |this, cx| {
536            this.status = AutoUpdateStatus::Downloading;
537            cx.notify();
538        })?;
539
540        let temp_dir = tempfile::Builder::new()
541            .prefix("zed-auto-update")
542            .tempdir()?;
543
544        let filename = match OS {
545            "macos" => Ok("Zed.dmg"),
546            "linux" => Ok("zed.tar.gz"),
547            _ => Err(anyhow!("not supported: {:?}", OS)),
548        }?;
549        let downloaded_asset = temp_dir.path().join(filename);
550        download_release(&downloaded_asset, release, client, &cx).await?;
551
552        this.update(&mut cx, |this, cx| {
553            this.status = AutoUpdateStatus::Installing;
554            cx.notify();
555        })?;
556
557        let binary_path = match OS {
558            "macos" => install_release_macos(&temp_dir, downloaded_asset, &cx).await,
559            "linux" => install_release_linux(&temp_dir, downloaded_asset, &cx).await,
560            _ => Err(anyhow!("not supported: {:?}", OS)),
561        }?;
562
563        this.update(&mut cx, |this, cx| {
564            this.set_should_show_update_notification(true, cx)
565                .detach_and_log_err(cx);
566            this.status = AutoUpdateStatus::Updated { binary_path };
567            cx.notify();
568        })?;
569
570        Ok(())
571    }
572
573    fn set_should_show_update_notification(
574        &self,
575        should_show: bool,
576        cx: &AppContext,
577    ) -> Task<Result<()>> {
578        cx.background_executor().spawn(async move {
579            if should_show {
580                KEY_VALUE_STORE
581                    .write_kvp(
582                        SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string(),
583                        "".to_string(),
584                    )
585                    .await?;
586            } else {
587                KEY_VALUE_STORE
588                    .delete_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string())
589                    .await?;
590            }
591            Ok(())
592        })
593    }
594
595    fn should_show_update_notification(&self, cx: &AppContext) -> Task<Result<bool>> {
596        cx.background_executor().spawn(async move {
597            Ok(KEY_VALUE_STORE
598                .read_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY)?
599                .is_some())
600        })
601    }
602}
603
604async fn download_remote_server_binary(
605    target_path: &PathBuf,
606    release: JsonRelease,
607    client: Arc<HttpClientWithUrl>,
608    cx: &AsyncAppContext,
609) -> Result<()> {
610    let mut target_file = File::create(&target_path).await?;
611    let (installation_id, release_channel, telemetry_enabled, is_staff) = cx.update(|cx| {
612        let telemetry = Client::global(cx).telemetry().clone();
613        let is_staff = telemetry.is_staff();
614        let installation_id = telemetry.installation_id();
615        let release_channel =
616            ReleaseChannel::try_global(cx).map(|release_channel| release_channel.display_name());
617        let telemetry_enabled = TelemetrySettings::get_global(cx).metrics;
618
619        (
620            installation_id,
621            release_channel,
622            telemetry_enabled,
623            is_staff,
624        )
625    })?;
626    let request_body = AsyncBody::from(serde_json::to_string(&UpdateRequestBody {
627        installation_id,
628        release_channel,
629        telemetry: telemetry_enabled,
630        is_staff,
631        destination: "remote",
632    })?);
633
634    let mut response = client.get(&release.url, request_body, true).await?;
635    smol::io::copy(response.body_mut(), &mut target_file).await?;
636    Ok(())
637}
638
639async fn download_release(
640    target_path: &Path,
641    release: JsonRelease,
642    client: Arc<HttpClientWithUrl>,
643    cx: &AsyncAppContext,
644) -> Result<()> {
645    let mut target_file = File::create(&target_path).await?;
646
647    let (installation_id, release_channel, telemetry_enabled, is_staff) = cx.update(|cx| {
648        let telemetry = Client::global(cx).telemetry().clone();
649        let is_staff = telemetry.is_staff();
650        let installation_id = telemetry.installation_id();
651        let release_channel =
652            ReleaseChannel::try_global(cx).map(|release_channel| release_channel.display_name());
653        let telemetry_enabled = TelemetrySettings::get_global(cx).metrics;
654
655        (
656            installation_id,
657            release_channel,
658            telemetry_enabled,
659            is_staff,
660        )
661    })?;
662
663    let request_body = AsyncBody::from(serde_json::to_string(&UpdateRequestBody {
664        installation_id,
665        release_channel,
666        telemetry: telemetry_enabled,
667        is_staff,
668        destination: "local",
669    })?);
670
671    let mut response = client.get(&release.url, request_body, true).await?;
672    smol::io::copy(response.body_mut(), &mut target_file).await?;
673    log::info!("downloaded update. path:{:?}", target_path);
674
675    Ok(())
676}
677
678async fn install_release_linux(
679    temp_dir: &tempfile::TempDir,
680    downloaded_tar_gz: PathBuf,
681    cx: &AsyncAppContext,
682) -> Result<PathBuf> {
683    let channel = cx.update(|cx| ReleaseChannel::global(cx).dev_name())?;
684    let home_dir = PathBuf::from(env::var("HOME").context("no HOME env var set")?);
685    let running_app_path = cx.update(|cx| cx.app_path())??;
686
687    let extracted = temp_dir.path().join("zed");
688    fs::create_dir_all(&extracted)
689        .await
690        .context("failed to create directory into which to extract update")?;
691
692    let output = Command::new("tar")
693        .arg("-xzf")
694        .arg(&downloaded_tar_gz)
695        .arg("-C")
696        .arg(&extracted)
697        .output()
698        .await?;
699
700    anyhow::ensure!(
701        output.status.success(),
702        "failed to extract {:?} to {:?}: {:?}",
703        downloaded_tar_gz,
704        extracted,
705        String::from_utf8_lossy(&output.stderr)
706    );
707
708    let suffix = if channel != "stable" {
709        format!("-{}", channel)
710    } else {
711        String::default()
712    };
713    let app_folder_name = format!("zed{}.app", suffix);
714
715    let from = extracted.join(&app_folder_name);
716    let mut to = home_dir.join(".local");
717
718    let expected_suffix = format!("{}/libexec/zed-editor", app_folder_name);
719
720    if let Some(prefix) = running_app_path
721        .to_str()
722        .and_then(|str| str.strip_suffix(&expected_suffix))
723    {
724        to = PathBuf::from(prefix);
725    }
726
727    let output = Command::new("rsync")
728        .args(["-av", "--delete"])
729        .arg(&from)
730        .arg(&to)
731        .output()
732        .await?;
733
734    anyhow::ensure!(
735        output.status.success(),
736        "failed to copy Zed update from {:?} to {:?}: {:?}",
737        from,
738        to,
739        String::from_utf8_lossy(&output.stderr)
740    );
741
742    Ok(to.join(expected_suffix))
743}
744
745async fn install_release_macos(
746    temp_dir: &tempfile::TempDir,
747    downloaded_dmg: PathBuf,
748    cx: &AsyncAppContext,
749) -> Result<PathBuf> {
750    let running_app_path = cx.update(|cx| cx.app_path())??;
751    let running_app_filename = running_app_path
752        .file_name()
753        .ok_or_else(|| anyhow!("invalid running app path"))?;
754
755    let mount_path = temp_dir.path().join("Zed");
756    let mut mounted_app_path: OsString = mount_path.join(running_app_filename).into();
757
758    mounted_app_path.push("/");
759    let output = Command::new("hdiutil")
760        .args(["attach", "-nobrowse"])
761        .arg(&downloaded_dmg)
762        .arg("-mountroot")
763        .arg(temp_dir.path())
764        .output()
765        .await?;
766
767    anyhow::ensure!(
768        output.status.success(),
769        "failed to mount: {:?}",
770        String::from_utf8_lossy(&output.stderr)
771    );
772
773    // Create an MacOsUnmounter that will be dropped (and thus unmount the disk) when this function exits
774    let _unmounter = MacOsUnmounter {
775        mount_path: mount_path.clone(),
776    };
777
778    let output = Command::new("rsync")
779        .args(["-av", "--delete"])
780        .arg(&mounted_app_path)
781        .arg(&running_app_path)
782        .output()
783        .await?;
784
785    anyhow::ensure!(
786        output.status.success(),
787        "failed to copy app: {:?}",
788        String::from_utf8_lossy(&output.stderr)
789    );
790
791    Ok(running_app_path)
792}