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