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