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