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    pub async fn get_latest_remote_server_release_url(
478        os: &str,
479        arch: &str,
480        mut release_channel: ReleaseChannel,
481        cx: &mut AsyncAppContext,
482    ) -> Result<(String, String)> {
483        let this = cx.update(|cx| {
484            cx.default_global::<GlobalAutoUpdate>()
485                .0
486                .clone()
487                .ok_or_else(|| anyhow!("auto-update not initialized"))
488        })??;
489
490        if release_channel == ReleaseChannel::Dev {
491            release_channel = ReleaseChannel::Nightly;
492        }
493
494        let release = Self::get_latest_release(
495            &this,
496            "zed-remote-server",
497            os,
498            arch,
499            Some(release_channel),
500            cx,
501        )
502        .await?;
503
504        let update_request_body = build_remote_server_update_request_body(cx)?;
505        let body = serde_json::to_string(&update_request_body)?;
506
507        Ok((release.url, body))
508    }
509
510    async fn get_latest_release(
511        this: &Model<Self>,
512        asset: &str,
513        os: &str,
514        arch: &str,
515        release_channel: Option<ReleaseChannel>,
516        cx: &mut AsyncAppContext,
517    ) -> Result<JsonRelease> {
518        let client = this.read_with(cx, |this, _| this.http_client.clone())?;
519        let mut url_string = client.build_url(&format!(
520            "/api/releases/latest?asset={}&os={}&arch={}",
521            asset, os, arch
522        ));
523        if let Some(param) = release_channel.and_then(|c| c.release_query_param()) {
524            url_string += "&";
525            url_string += param;
526        }
527
528        let mut response = client.get(&url_string, Default::default(), true).await?;
529
530        let mut body = Vec::new();
531        response
532            .body_mut()
533            .read_to_end(&mut body)
534            .await
535            .context("error reading release")?;
536
537        if !response.status().is_success() {
538            Err(anyhow!(
539                "failed to fetch release: {:?}",
540                String::from_utf8_lossy(&body),
541            ))?;
542        }
543
544        serde_json::from_slice(body.as_slice()).with_context(|| {
545            format!(
546                "error deserializing release {:?}",
547                String::from_utf8_lossy(&body),
548            )
549        })
550    }
551
552    async fn update(this: Model<Self>, mut cx: AsyncAppContext) -> Result<()> {
553        let (client, current_version, release_channel) = this.update(&mut cx, |this, cx| {
554            this.status = AutoUpdateStatus::Checking;
555            cx.notify();
556            (
557                this.http_client.clone(),
558                this.current_version,
559                ReleaseChannel::try_global(cx),
560            )
561        })?;
562
563        let release =
564            Self::get_latest_release(&this, "zed", OS, ARCH, release_channel, &mut cx).await?;
565
566        let should_download = match *RELEASE_CHANNEL {
567            ReleaseChannel::Nightly => cx
568                .update(|cx| AppCommitSha::try_global(cx).map(|sha| release.version != sha.0))
569                .ok()
570                .flatten()
571                .unwrap_or(true),
572            _ => release.version.parse::<SemanticVersion>()? > current_version,
573        };
574
575        if !should_download {
576            this.update(&mut cx, |this, cx| {
577                this.status = AutoUpdateStatus::Idle;
578                cx.notify();
579            })?;
580            return Ok(());
581        }
582
583        this.update(&mut cx, |this, cx| {
584            this.status = AutoUpdateStatus::Downloading;
585            cx.notify();
586        })?;
587
588        let temp_dir = tempfile::Builder::new()
589            .prefix("zed-auto-update")
590            .tempdir()?;
591
592        let filename = match OS {
593            "macos" => Ok("Zed.dmg"),
594            "linux" => Ok("zed.tar.gz"),
595            _ => Err(anyhow!("not supported: {:?}", OS)),
596        }?;
597
598        anyhow::ensure!(
599            which("rsync").is_ok(),
600            "Aborting. Could not find rsync which is required for auto-updates."
601        );
602
603        let downloaded_asset = temp_dir.path().join(filename);
604        download_release(&downloaded_asset, release, client, &cx).await?;
605
606        this.update(&mut cx, |this, cx| {
607            this.status = AutoUpdateStatus::Installing;
608            cx.notify();
609        })?;
610
611        let binary_path = match OS {
612            "macos" => install_release_macos(&temp_dir, downloaded_asset, &cx).await,
613            "linux" => install_release_linux(&temp_dir, downloaded_asset, &cx).await,
614            _ => Err(anyhow!("not supported: {:?}", OS)),
615        }?;
616
617        this.update(&mut cx, |this, cx| {
618            this.set_should_show_update_notification(true, cx)
619                .detach_and_log_err(cx);
620            this.status = AutoUpdateStatus::Updated { binary_path };
621            cx.notify();
622        })?;
623
624        Ok(())
625    }
626
627    fn set_should_show_update_notification(
628        &self,
629        should_show: bool,
630        cx: &AppContext,
631    ) -> Task<Result<()>> {
632        cx.background_executor().spawn(async move {
633            if should_show {
634                KEY_VALUE_STORE
635                    .write_kvp(
636                        SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string(),
637                        "".to_string(),
638                    )
639                    .await?;
640            } else {
641                KEY_VALUE_STORE
642                    .delete_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string())
643                    .await?;
644            }
645            Ok(())
646        })
647    }
648
649    fn should_show_update_notification(&self, cx: &AppContext) -> Task<Result<bool>> {
650        cx.background_executor().spawn(async move {
651            Ok(KEY_VALUE_STORE
652                .read_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY)?
653                .is_some())
654        })
655    }
656}
657
658async fn download_remote_server_binary(
659    target_path: &PathBuf,
660    release: JsonRelease,
661    client: Arc<HttpClientWithUrl>,
662    cx: &AsyncAppContext,
663) -> Result<()> {
664    let mut target_file = File::create(&target_path).await?;
665    let update_request_body = build_remote_server_update_request_body(cx)?;
666    let request_body = AsyncBody::from(serde_json::to_string(&update_request_body)?);
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    Ok(())
671}
672
673fn build_remote_server_update_request_body(cx: &AsyncAppContext) -> Result<UpdateRequestBody> {
674    let (installation_id, release_channel, telemetry_enabled, is_staff) = cx.update(|cx| {
675        let telemetry = Client::global(cx).telemetry().clone();
676        let is_staff = telemetry.is_staff();
677        let installation_id = telemetry.installation_id();
678        let release_channel =
679            ReleaseChannel::try_global(cx).map(|release_channel| release_channel.display_name());
680        let telemetry_enabled = TelemetrySettings::get_global(cx).metrics;
681
682        (
683            installation_id,
684            release_channel,
685            telemetry_enabled,
686            is_staff,
687        )
688    })?;
689
690    Ok(UpdateRequestBody {
691        installation_id,
692        release_channel,
693        telemetry: telemetry_enabled,
694        is_staff,
695        destination: "remote",
696    })
697}
698
699async fn download_release(
700    target_path: &Path,
701    release: JsonRelease,
702    client: Arc<HttpClientWithUrl>,
703    cx: &AsyncAppContext,
704) -> Result<()> {
705    let mut target_file = File::create(&target_path).await?;
706
707    let (installation_id, release_channel, telemetry_enabled, is_staff) = cx.update(|cx| {
708        let telemetry = Client::global(cx).telemetry().clone();
709        let is_staff = telemetry.is_staff();
710        let installation_id = telemetry.installation_id();
711        let release_channel =
712            ReleaseChannel::try_global(cx).map(|release_channel| release_channel.display_name());
713        let telemetry_enabled = TelemetrySettings::get_global(cx).metrics;
714
715        (
716            installation_id,
717            release_channel,
718            telemetry_enabled,
719            is_staff,
720        )
721    })?;
722
723    let request_body = AsyncBody::from(serde_json::to_string(&UpdateRequestBody {
724        installation_id,
725        release_channel,
726        telemetry: telemetry_enabled,
727        is_staff,
728        destination: "local",
729    })?);
730
731    let mut response = client.get(&release.url, request_body, true).await?;
732    smol::io::copy(response.body_mut(), &mut target_file).await?;
733    log::info!("downloaded update. path:{:?}", target_path);
734
735    Ok(())
736}
737
738async fn install_release_linux(
739    temp_dir: &tempfile::TempDir,
740    downloaded_tar_gz: PathBuf,
741    cx: &AsyncAppContext,
742) -> Result<PathBuf> {
743    let channel = cx.update(|cx| ReleaseChannel::global(cx).dev_name())?;
744    let home_dir = PathBuf::from(env::var("HOME").context("no HOME env var set")?);
745    let running_app_path = cx.update(|cx| cx.app_path())??;
746
747    let extracted = temp_dir.path().join("zed");
748    fs::create_dir_all(&extracted)
749        .await
750        .context("failed to create directory into which to extract update")?;
751
752    let output = Command::new("tar")
753        .arg("-xzf")
754        .arg(&downloaded_tar_gz)
755        .arg("-C")
756        .arg(&extracted)
757        .output()
758        .await?;
759
760    anyhow::ensure!(
761        output.status.success(),
762        "failed to extract {:?} to {:?}: {:?}",
763        downloaded_tar_gz,
764        extracted,
765        String::from_utf8_lossy(&output.stderr)
766    );
767
768    let suffix = if channel != "stable" {
769        format!("-{}", channel)
770    } else {
771        String::default()
772    };
773    let app_folder_name = format!("zed{}.app", suffix);
774
775    let from = extracted.join(&app_folder_name);
776    let mut to = home_dir.join(".local");
777
778    let expected_suffix = format!("{}/libexec/zed-editor", app_folder_name);
779
780    if let Some(prefix) = running_app_path
781        .to_str()
782        .and_then(|str| str.strip_suffix(&expected_suffix))
783    {
784        to = PathBuf::from(prefix);
785    }
786
787    let output = Command::new("rsync")
788        .args(["-av", "--delete"])
789        .arg(&from)
790        .arg(&to)
791        .output()
792        .await?;
793
794    anyhow::ensure!(
795        output.status.success(),
796        "failed to copy Zed update from {:?} to {:?}: {:?}",
797        from,
798        to,
799        String::from_utf8_lossy(&output.stderr)
800    );
801
802    Ok(to.join(expected_suffix))
803}
804
805async fn install_release_macos(
806    temp_dir: &tempfile::TempDir,
807    downloaded_dmg: PathBuf,
808    cx: &AsyncAppContext,
809) -> Result<PathBuf> {
810    let running_app_path = cx.update(|cx| cx.app_path())??;
811    let running_app_filename = running_app_path
812        .file_name()
813        .ok_or_else(|| anyhow!("invalid running app path"))?;
814
815    let mount_path = temp_dir.path().join("Zed");
816    let mut mounted_app_path: OsString = mount_path.join(running_app_filename).into();
817
818    mounted_app_path.push("/");
819    let output = Command::new("hdiutil")
820        .args(["attach", "-nobrowse"])
821        .arg(&downloaded_dmg)
822        .arg("-mountroot")
823        .arg(temp_dir.path())
824        .output()
825        .await?;
826
827    anyhow::ensure!(
828        output.status.success(),
829        "failed to mount: {:?}",
830        String::from_utf8_lossy(&output.stderr)
831    );
832
833    // Create an MacOsUnmounter that will be dropped (and thus unmount the disk) when this function exits
834    let _unmounter = MacOsUnmounter {
835        mount_path: mount_path.clone(),
836    };
837
838    let output = Command::new("rsync")
839        .args(["-av", "--delete"])
840        .arg(&mounted_app_path)
841        .arg(&running_app_path)
842        .output()
843        .await?;
844
845    anyhow::ensure!(
846        output.status.success(),
847        "failed to copy app: {:?}",
848        String::from_utf8_lossy(&output.stderr)
849    );
850
851    Ok(running_app_path)
852}