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