1use anyhow::{Context as _, Result};
2use client::{Client, TelemetrySettings};
3use db::RELEASE_CHANNEL;
4use db::kvp::KEY_VALUE_STORE;
5use gpui::{
6 App, AppContext as _, AsyncApp, Context, Entity, Global, SemanticVersion, Task, Window, actions,
7};
8use http_client::{AsyncBody, HttpClient, HttpClientWithUrl};
9use paths::remote_servers_dir;
10use release_channel::{AppCommitSha, ReleaseChannel};
11use serde::{Deserialize, Serialize};
12use settings::{Settings, SettingsContent, SettingsStore};
13use smol::{fs, io::AsyncReadExt};
14use smol::{fs::File, process::Command};
15use std::{
16 env::{
17 self,
18 consts::{ARCH, OS},
19 },
20 ffi::OsString,
21 path::{Path, PathBuf},
22 sync::Arc,
23 time::Duration,
24};
25use workspace::Workspace;
26
27const SHOULD_SHOW_UPDATE_NOTIFICATION_KEY: &str = "auto-updater-should-show-updated-notification";
28const POLL_INTERVAL: Duration = Duration::from_secs(60 * 60);
29
30actions!(
31 auto_update,
32 [
33 /// Checks for available updates.
34 Check,
35 /// Dismisses the update error message.
36 DismissErrorMessage,
37 /// Opens the release notes for the current version in a browser.
38 ViewReleaseNotes,
39 ]
40);
41
42#[derive(Serialize)]
43struct UpdateRequestBody {
44 installation_id: Option<Arc<str>>,
45 release_channel: Option<&'static str>,
46 telemetry: bool,
47 is_staff: Option<bool>,
48 destination: &'static str,
49}
50
51#[derive(Clone, Debug, PartialEq, Eq)]
52pub enum VersionCheckType {
53 Sha(AppCommitSha),
54 Semantic(SemanticVersion),
55}
56
57#[derive(Clone, PartialEq, Eq)]
58pub enum AutoUpdateStatus {
59 Idle,
60 Checking,
61 Downloading { version: VersionCheckType },
62 Installing { version: VersionCheckType },
63 Updated { version: VersionCheckType },
64 Errored,
65}
66
67impl AutoUpdateStatus {
68 pub fn is_updated(&self) -> bool {
69 matches!(self, Self::Updated { .. })
70 }
71}
72
73pub struct AutoUpdater {
74 status: AutoUpdateStatus,
75 current_version: SemanticVersion,
76 http_client: Arc<HttpClientWithUrl>,
77 pending_poll: Option<Task<Option<()>>>,
78 quit_subscription: Option<gpui::Subscription>,
79}
80
81#[derive(Deserialize, Clone, Debug)]
82pub struct JsonRelease {
83 pub version: String,
84 pub url: String,
85}
86
87struct MacOsUnmounter {
88 mount_path: PathBuf,
89}
90
91impl Drop for MacOsUnmounter {
92 fn drop(&mut self) {
93 let unmount_output = std::process::Command::new("hdiutil")
94 .args(["detach", "-force"])
95 .arg(&self.mount_path)
96 .output();
97
98 match unmount_output {
99 Ok(output) if output.status.success() => {
100 log::info!("Successfully unmounted the disk image");
101 }
102 Ok(output) => {
103 log::error!(
104 "Failed to unmount disk image: {:?}",
105 String::from_utf8_lossy(&output.stderr)
106 );
107 }
108 Err(error) => {
109 log::error!("Error while trying to unmount disk image: {:?}", error);
110 }
111 }
112 }
113}
114
115#[derive(Clone, Copy, Debug)]
116struct AutoUpdateSetting(bool);
117
118/// Whether or not to automatically check for updates.
119///
120/// Default: true
121impl Settings for AutoUpdateSetting {
122 fn from_defaults(content: &settings::SettingsContent, _cx: &mut App) -> Self {
123 debug_assert_eq!(content.auto_update.unwrap(), true);
124 Self(content.auto_update.unwrap())
125 }
126
127 fn refine(&mut self, content: &settings::SettingsContent, _cx: &mut App) {
128 if let Some(auto_update) = content.auto_update {
129 self.0 = auto_update;
130 }
131 }
132
133 fn import_from_vscode(_: &settings::VsCodeSettings, _: &mut SettingsContent) {
134 // We could match on vscode's update.mode here, but
135 // I think it's more important to have more people updating zed by default.
136 }
137}
138
139#[derive(Default)]
140struct GlobalAutoUpdate(Option<Entity<AutoUpdater>>);
141
142impl Global for GlobalAutoUpdate {}
143
144pub fn init(http_client: Arc<HttpClientWithUrl>, cx: &mut App) {
145 AutoUpdateSetting::register(cx);
146
147 cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
148 workspace.register_action(|_, action, window, cx| check(action, window, cx));
149
150 workspace.register_action(|_, action, _, cx| {
151 view_release_notes(action, cx);
152 });
153 })
154 .detach();
155
156 let version = release_channel::AppVersion::global(cx);
157 let auto_updater = cx.new(|cx| {
158 let updater = AutoUpdater::new(version, http_client, cx);
159
160 let poll_for_updates = ReleaseChannel::try_global(cx)
161 .map(|channel| channel.poll_for_updates())
162 .unwrap_or(false);
163
164 if option_env!("ZED_UPDATE_EXPLANATION").is_none()
165 && env::var("ZED_UPDATE_EXPLANATION").is_err()
166 && poll_for_updates
167 {
168 let mut update_subscription = AutoUpdateSetting::get_global(cx)
169 .0
170 .then(|| updater.start_polling(cx));
171
172 cx.observe_global::<SettingsStore>(move |updater: &mut AutoUpdater, cx| {
173 if AutoUpdateSetting::get_global(cx).0 {
174 if update_subscription.is_none() {
175 update_subscription = Some(updater.start_polling(cx))
176 }
177 } else {
178 update_subscription.take();
179 }
180 })
181 .detach();
182 }
183
184 updater
185 });
186 cx.set_global(GlobalAutoUpdate(Some(auto_updater)));
187}
188
189pub fn check(_: &Check, window: &mut Window, cx: &mut App) {
190 if let Some(message) = option_env!("ZED_UPDATE_EXPLANATION") {
191 drop(window.prompt(
192 gpui::PromptLevel::Info,
193 "Zed was installed via a package manager.",
194 Some(message),
195 &["Ok"],
196 cx,
197 ));
198 return;
199 }
200
201 if let Ok(message) = env::var("ZED_UPDATE_EXPLANATION") {
202 drop(window.prompt(
203 gpui::PromptLevel::Info,
204 "Zed was installed via a package manager.",
205 Some(&message),
206 &["Ok"],
207 cx,
208 ));
209 return;
210 }
211
212 if !ReleaseChannel::try_global(cx)
213 .map(|channel| channel.poll_for_updates())
214 .unwrap_or(false)
215 {
216 return;
217 }
218
219 if let Some(updater) = AutoUpdater::get(cx) {
220 updater.update(cx, |updater, cx| updater.poll(UpdateCheckType::Manual, cx));
221 } else {
222 drop(window.prompt(
223 gpui::PromptLevel::Info,
224 "Could not check for updates",
225 Some("Auto-updates disabled for non-bundled app."),
226 &["Ok"],
227 cx,
228 ));
229 }
230}
231
232pub fn view_release_notes(_: &ViewReleaseNotes, cx: &mut App) -> Option<()> {
233 let auto_updater = AutoUpdater::get(cx)?;
234 let release_channel = ReleaseChannel::try_global(cx)?;
235
236 match release_channel {
237 ReleaseChannel::Stable | ReleaseChannel::Preview => {
238 let auto_updater = auto_updater.read(cx);
239 let current_version = auto_updater.current_version;
240 let release_channel = release_channel.dev_name();
241 let path = format!("/releases/{release_channel}/{current_version}");
242 let url = &auto_updater.http_client.build_url(&path);
243 cx.open_url(url);
244 }
245 ReleaseChannel::Nightly => {
246 cx.open_url("https://github.com/zed-industries/zed/commits/nightly/");
247 }
248 ReleaseChannel::Dev => {
249 cx.open_url("https://github.com/zed-industries/zed/commits/main/");
250 }
251 }
252 None
253}
254
255#[cfg(not(target_os = "windows"))]
256struct InstallerDir(tempfile::TempDir);
257
258#[cfg(not(target_os = "windows"))]
259impl InstallerDir {
260 async fn new() -> Result<Self> {
261 Ok(Self(
262 tempfile::Builder::new()
263 .prefix("zed-auto-update")
264 .tempdir()?,
265 ))
266 }
267
268 fn path(&self) -> &Path {
269 self.0.path()
270 }
271}
272
273#[cfg(target_os = "windows")]
274struct InstallerDir(PathBuf);
275
276#[cfg(target_os = "windows")]
277impl InstallerDir {
278 async fn new() -> Result<Self> {
279 let installer_dir = std::env::current_exe()?
280 .parent()
281 .context("No parent dir for Zed.exe")?
282 .join("updates");
283 if smol::fs::metadata(&installer_dir).await.is_ok() {
284 smol::fs::remove_dir_all(&installer_dir).await?;
285 }
286 smol::fs::create_dir(&installer_dir).await?;
287 Ok(Self(installer_dir))
288 }
289
290 fn path(&self) -> &Path {
291 self.0.as_path()
292 }
293}
294
295pub enum UpdateCheckType {
296 Automatic,
297 Manual,
298}
299
300impl AutoUpdater {
301 pub fn get(cx: &mut App) -> Option<Entity<Self>> {
302 cx.default_global::<GlobalAutoUpdate>().0.clone()
303 }
304
305 fn new(
306 current_version: SemanticVersion,
307 http_client: Arc<HttpClientWithUrl>,
308 cx: &mut Context<Self>,
309 ) -> Self {
310 // On windows, executable files cannot be overwritten while they are
311 // running, so we must wait to overwrite the application until quitting
312 // or restarting. When quitting the app, we spawn the auto update helper
313 // to finish the auto update process after Zed exits. When restarting
314 // the app after an update, we use `set_restart_path` to run the auto
315 // update helper instead of the app, so that it can overwrite the app
316 // and then spawn the new binary.
317 let quit_subscription = Some(cx.on_app_quit(|_, _| async move {
318 #[cfg(target_os = "windows")]
319 finalize_auto_update_on_quit();
320 }));
321
322 cx.on_app_restart(|this, _| {
323 this.quit_subscription.take();
324 })
325 .detach();
326
327 Self {
328 status: AutoUpdateStatus::Idle,
329 current_version,
330 http_client,
331 pending_poll: None,
332 quit_subscription,
333 }
334 }
335
336 pub fn start_polling(&self, cx: &mut Context<Self>) -> Task<Result<()>> {
337 cx.spawn(async move |this, cx| {
338 loop {
339 this.update(cx, |this, cx| this.poll(UpdateCheckType::Automatic, cx))?;
340 cx.background_executor().timer(POLL_INTERVAL).await;
341 }
342 })
343 }
344
345 pub fn poll(&mut self, check_type: UpdateCheckType, cx: &mut Context<Self>) {
346 if self.pending_poll.is_some() {
347 return;
348 }
349
350 cx.notify();
351
352 self.pending_poll = Some(cx.spawn(async move |this, cx| {
353 let result = Self::update(this.upgrade()?, cx.clone()).await;
354 this.update(cx, |this, cx| {
355 this.pending_poll = None;
356 if let Err(error) = result {
357 this.status = match check_type {
358 // Be quiet if the check was automated (e.g. when offline)
359 UpdateCheckType::Automatic => {
360 log::info!("auto-update check failed: error:{:?}", error);
361 AutoUpdateStatus::Idle
362 }
363 UpdateCheckType::Manual => {
364 log::error!("auto-update failed: error:{:?}", error);
365 AutoUpdateStatus::Errored
366 }
367 };
368
369 cx.notify();
370 }
371 })
372 .ok()
373 }));
374 }
375
376 pub fn current_version(&self) -> SemanticVersion {
377 self.current_version
378 }
379
380 pub fn status(&self) -> AutoUpdateStatus {
381 self.status.clone()
382 }
383
384 pub fn dismiss_error(&mut self, cx: &mut Context<Self>) -> bool {
385 if self.status == AutoUpdateStatus::Idle {
386 return false;
387 }
388 self.status = AutoUpdateStatus::Idle;
389 cx.notify();
390 true
391 }
392
393 // If you are packaging Zed and need to override the place it downloads SSH remotes from,
394 // you can override this function. You should also update get_remote_server_release_url to return
395 // Ok(None).
396 pub async fn download_remote_server_release(
397 os: &str,
398 arch: &str,
399 release_channel: ReleaseChannel,
400 version: Option<SemanticVersion>,
401 cx: &mut AsyncApp,
402 ) -> Result<PathBuf> {
403 let this = cx.update(|cx| {
404 cx.default_global::<GlobalAutoUpdate>()
405 .0
406 .clone()
407 .context("auto-update not initialized")
408 })??;
409
410 let release = Self::get_release(
411 &this,
412 "zed-remote-server",
413 os,
414 arch,
415 version,
416 Some(release_channel),
417 cx,
418 )
419 .await?;
420
421 let servers_dir = paths::remote_servers_dir();
422 let channel_dir = servers_dir.join(release_channel.dev_name());
423 let platform_dir = channel_dir.join(format!("{}-{}", os, arch));
424 let version_path = platform_dir.join(format!("{}.gz", release.version));
425 smol::fs::create_dir_all(&platform_dir).await.ok();
426
427 let client = this.read_with(cx, |this, _| this.http_client.clone())?;
428
429 if smol::fs::metadata(&version_path).await.is_err() {
430 log::info!(
431 "downloading zed-remote-server {os} {arch} version {}",
432 release.version
433 );
434 download_remote_server_binary(&version_path, release, client, cx).await?;
435 }
436
437 Ok(version_path)
438 }
439
440 pub async fn get_remote_server_release_url(
441 os: &str,
442 arch: &str,
443 release_channel: ReleaseChannel,
444 version: Option<SemanticVersion>,
445 cx: &mut AsyncApp,
446 ) -> Result<Option<(String, String)>> {
447 let this = cx.update(|cx| {
448 cx.default_global::<GlobalAutoUpdate>()
449 .0
450 .clone()
451 .context("auto-update not initialized")
452 })??;
453
454 let release = Self::get_release(
455 &this,
456 "zed-remote-server",
457 os,
458 arch,
459 version,
460 Some(release_channel),
461 cx,
462 )
463 .await?;
464
465 let update_request_body = build_remote_server_update_request_body(cx)?;
466 let body = serde_json::to_string(&update_request_body)?;
467
468 Ok(Some((release.url, body)))
469 }
470
471 async fn get_release(
472 this: &Entity<Self>,
473 asset: &str,
474 os: &str,
475 arch: &str,
476 version: Option<SemanticVersion>,
477 release_channel: Option<ReleaseChannel>,
478 cx: &mut AsyncApp,
479 ) -> Result<JsonRelease> {
480 let client = this.read_with(cx, |this, _| this.http_client.clone())?;
481
482 if let Some(version) = version {
483 let channel = release_channel.map(|c| c.dev_name()).unwrap_or("stable");
484
485 let url = format!("/api/releases/{channel}/{version}/{asset}-{os}-{arch}.gz?update=1",);
486
487 Ok(JsonRelease {
488 version: version.to_string(),
489 url: client.build_url(&url),
490 })
491 } else {
492 let mut url_string = client.build_url(&format!(
493 "/api/releases/latest?asset={}&os={}&arch={}",
494 asset, os, arch
495 ));
496 if let Some(param) = release_channel.and_then(|c| c.release_query_param()) {
497 url_string += "&";
498 url_string += param;
499 }
500
501 let mut response = client.get(&url_string, Default::default(), true).await?;
502 let mut body = Vec::new();
503 response.body_mut().read_to_end(&mut body).await?;
504
505 anyhow::ensure!(
506 response.status().is_success(),
507 "failed to fetch release: {:?}",
508 String::from_utf8_lossy(&body),
509 );
510
511 serde_json::from_slice(body.as_slice()).with_context(|| {
512 format!(
513 "error deserializing release {:?}",
514 String::from_utf8_lossy(&body),
515 )
516 })
517 }
518 }
519
520 async fn get_latest_release(
521 this: &Entity<Self>,
522 asset: &str,
523 os: &str,
524 arch: &str,
525 release_channel: Option<ReleaseChannel>,
526 cx: &mut AsyncApp,
527 ) -> Result<JsonRelease> {
528 Self::get_release(this, asset, os, arch, None, release_channel, cx).await
529 }
530
531 async fn update(this: Entity<Self>, mut cx: AsyncApp) -> Result<()> {
532 let (client, installed_version, previous_status, release_channel) =
533 this.read_with(&cx, |this, cx| {
534 (
535 this.http_client.clone(),
536 this.current_version,
537 this.status.clone(),
538 ReleaseChannel::try_global(cx),
539 )
540 })?;
541
542 Self::check_dependencies()?;
543
544 this.update(&mut cx, |this, cx| {
545 this.status = AutoUpdateStatus::Checking;
546 log::info!("Auto Update: checking for updates");
547 cx.notify();
548 })?;
549
550 let fetched_release_data =
551 Self::get_latest_release(&this, "zed", OS, ARCH, release_channel, &mut cx).await?;
552 let fetched_version = fetched_release_data.clone().version;
553 let app_commit_sha = cx.update(|cx| AppCommitSha::try_global(cx).map(|sha| sha.full()));
554 let newer_version = Self::check_if_fetched_version_is_newer(
555 *RELEASE_CHANNEL,
556 app_commit_sha,
557 installed_version,
558 fetched_version,
559 previous_status.clone(),
560 )?;
561
562 let Some(newer_version) = newer_version else {
563 return this.update(&mut cx, |this, cx| {
564 let status = match previous_status {
565 AutoUpdateStatus::Updated { .. } => previous_status,
566 _ => AutoUpdateStatus::Idle,
567 };
568 this.status = status;
569 cx.notify();
570 });
571 };
572
573 this.update(&mut cx, |this, cx| {
574 this.status = AutoUpdateStatus::Downloading {
575 version: newer_version.clone(),
576 };
577 cx.notify();
578 })?;
579
580 let installer_dir = InstallerDir::new().await?;
581 let target_path = Self::target_path(&installer_dir).await?;
582 download_release(&target_path, fetched_release_data, client, &cx).await?;
583
584 this.update(&mut cx, |this, cx| {
585 this.status = AutoUpdateStatus::Installing {
586 version: newer_version.clone(),
587 };
588 cx.notify();
589 })?;
590
591 let new_binary_path = Self::install_release(installer_dir, target_path, &cx).await?;
592 if let Some(new_binary_path) = new_binary_path {
593 cx.update(|cx| cx.set_restart_path(new_binary_path))?;
594 }
595
596 this.update(&mut cx, |this, cx| {
597 this.set_should_show_update_notification(true, cx)
598 .detach_and_log_err(cx);
599 this.status = AutoUpdateStatus::Updated {
600 version: newer_version,
601 };
602 cx.notify();
603 })
604 }
605
606 fn check_if_fetched_version_is_newer(
607 release_channel: ReleaseChannel,
608 app_commit_sha: Result<Option<String>>,
609 installed_version: SemanticVersion,
610 fetched_version: String,
611 status: AutoUpdateStatus,
612 ) -> Result<Option<VersionCheckType>> {
613 let parsed_fetched_version = fetched_version.parse::<SemanticVersion>();
614
615 if let AutoUpdateStatus::Updated { version, .. } = status {
616 match version {
617 VersionCheckType::Sha(cached_version) => {
618 let should_download = fetched_version != cached_version.full();
619 let newer_version = should_download
620 .then(|| VersionCheckType::Sha(AppCommitSha::new(fetched_version)));
621 return Ok(newer_version);
622 }
623 VersionCheckType::Semantic(cached_version) => {
624 return Self::check_if_fetched_version_is_newer_non_nightly(
625 cached_version,
626 parsed_fetched_version?,
627 );
628 }
629 }
630 }
631
632 match release_channel {
633 ReleaseChannel::Nightly => {
634 let should_download = app_commit_sha
635 .ok()
636 .flatten()
637 .map(|sha| fetched_version != sha)
638 .unwrap_or(true);
639 let newer_version = should_download
640 .then(|| VersionCheckType::Sha(AppCommitSha::new(fetched_version)));
641 Ok(newer_version)
642 }
643 _ => Self::check_if_fetched_version_is_newer_non_nightly(
644 installed_version,
645 parsed_fetched_version?,
646 ),
647 }
648 }
649
650 fn check_dependencies() -> Result<()> {
651 #[cfg(not(target_os = "windows"))]
652 anyhow::ensure!(
653 which::which("rsync").is_ok(),
654 "Aborting. Could not find rsync which is required for auto-updates."
655 );
656 Ok(())
657 }
658
659 async fn target_path(installer_dir: &InstallerDir) -> Result<PathBuf> {
660 let filename = match OS {
661 "macos" => anyhow::Ok("Zed.dmg"),
662 "linux" => Ok("zed.tar.gz"),
663 "windows" => Ok("zed_editor_installer.exe"),
664 unsupported_os => anyhow::bail!("not supported: {unsupported_os}"),
665 }?;
666
667 Ok(installer_dir.path().join(filename))
668 }
669
670 async fn install_release(
671 installer_dir: InstallerDir,
672 target_path: PathBuf,
673 cx: &AsyncApp,
674 ) -> Result<Option<PathBuf>> {
675 match OS {
676 "macos" => install_release_macos(&installer_dir, target_path, cx).await,
677 "linux" => install_release_linux(&installer_dir, target_path, cx).await,
678 "windows" => install_release_windows(target_path).await,
679 unsupported_os => anyhow::bail!("not supported: {unsupported_os}"),
680 }
681 }
682
683 fn check_if_fetched_version_is_newer_non_nightly(
684 installed_version: SemanticVersion,
685 fetched_version: SemanticVersion,
686 ) -> Result<Option<VersionCheckType>> {
687 let should_download = fetched_version > installed_version;
688 let newer_version = should_download.then(|| VersionCheckType::Semantic(fetched_version));
689 Ok(newer_version)
690 }
691
692 pub fn set_should_show_update_notification(
693 &self,
694 should_show: bool,
695 cx: &App,
696 ) -> Task<Result<()>> {
697 cx.background_spawn(async move {
698 if should_show {
699 KEY_VALUE_STORE
700 .write_kvp(
701 SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string(),
702 "".to_string(),
703 )
704 .await?;
705 } else {
706 KEY_VALUE_STORE
707 .delete_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string())
708 .await?;
709 }
710 Ok(())
711 })
712 }
713
714 pub fn should_show_update_notification(&self, cx: &App) -> Task<Result<bool>> {
715 cx.background_spawn(async move {
716 Ok(KEY_VALUE_STORE
717 .read_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY)?
718 .is_some())
719 })
720 }
721}
722
723async fn download_remote_server_binary(
724 target_path: &PathBuf,
725 release: JsonRelease,
726 client: Arc<HttpClientWithUrl>,
727 cx: &AsyncApp,
728) -> Result<()> {
729 let temp = tempfile::Builder::new().tempfile_in(remote_servers_dir())?;
730 let mut temp_file = File::create(&temp).await?;
731 let update_request_body = build_remote_server_update_request_body(cx)?;
732 let request_body = AsyncBody::from(serde_json::to_string(&update_request_body)?);
733
734 let mut response = client.get(&release.url, request_body, true).await?;
735 anyhow::ensure!(
736 response.status().is_success(),
737 "failed to download remote server release: {:?}",
738 response.status()
739 );
740 smol::io::copy(response.body_mut(), &mut temp_file).await?;
741 smol::fs::rename(&temp, &target_path).await?;
742
743 Ok(())
744}
745
746fn build_remote_server_update_request_body(cx: &AsyncApp) -> Result<UpdateRequestBody> {
747 let (installation_id, release_channel, telemetry_enabled, is_staff) = cx.update(|cx| {
748 let telemetry = Client::global(cx).telemetry().clone();
749 let is_staff = telemetry.is_staff();
750 let installation_id = telemetry.installation_id();
751 let release_channel =
752 ReleaseChannel::try_global(cx).map(|release_channel| release_channel.display_name());
753 let telemetry_enabled = TelemetrySettings::get_global(cx).metrics;
754
755 (
756 installation_id,
757 release_channel,
758 telemetry_enabled,
759 is_staff,
760 )
761 })?;
762
763 Ok(UpdateRequestBody {
764 installation_id,
765 release_channel,
766 telemetry: telemetry_enabled,
767 is_staff,
768 destination: "remote",
769 })
770}
771
772async fn download_release(
773 target_path: &Path,
774 release: JsonRelease,
775 client: Arc<HttpClientWithUrl>,
776 cx: &AsyncApp,
777) -> Result<()> {
778 let mut target_file = File::create(&target_path).await?;
779
780 let (installation_id, release_channel, telemetry_enabled, is_staff) = cx.update(|cx| {
781 let telemetry = Client::global(cx).telemetry().clone();
782 let is_staff = telemetry.is_staff();
783 let installation_id = telemetry.installation_id();
784 let release_channel =
785 ReleaseChannel::try_global(cx).map(|release_channel| release_channel.display_name());
786 let telemetry_enabled = TelemetrySettings::get_global(cx).metrics;
787
788 (
789 installation_id,
790 release_channel,
791 telemetry_enabled,
792 is_staff,
793 )
794 })?;
795
796 let request_body = AsyncBody::from(serde_json::to_string(&UpdateRequestBody {
797 installation_id,
798 release_channel,
799 telemetry: telemetry_enabled,
800 is_staff,
801 destination: "local",
802 })?);
803
804 let mut response = client.get(&release.url, request_body, true).await?;
805 smol::io::copy(response.body_mut(), &mut target_file).await?;
806 log::info!("downloaded update. path:{:?}", target_path);
807
808 Ok(())
809}
810
811async fn install_release_linux(
812 temp_dir: &InstallerDir,
813 downloaded_tar_gz: PathBuf,
814 cx: &AsyncApp,
815) -> Result<Option<PathBuf>> {
816 let channel = cx.update(|cx| ReleaseChannel::global(cx).dev_name())?;
817 let home_dir = PathBuf::from(env::var("HOME").context("no HOME env var set")?);
818 let running_app_path = cx.update(|cx| cx.app_path())??;
819
820 let extracted = temp_dir.path().join("zed");
821 fs::create_dir_all(&extracted)
822 .await
823 .context("failed to create directory into which to extract update")?;
824
825 let output = Command::new("tar")
826 .arg("-xzf")
827 .arg(&downloaded_tar_gz)
828 .arg("-C")
829 .arg(&extracted)
830 .output()
831 .await?;
832
833 anyhow::ensure!(
834 output.status.success(),
835 "failed to extract {:?} to {:?}: {:?}",
836 downloaded_tar_gz,
837 extracted,
838 String::from_utf8_lossy(&output.stderr)
839 );
840
841 let suffix = if channel != "stable" {
842 format!("-{}", channel)
843 } else {
844 String::default()
845 };
846 let app_folder_name = format!("zed{}.app", suffix);
847
848 let from = extracted.join(&app_folder_name);
849 let mut to = home_dir.join(".local");
850
851 let expected_suffix = format!("{}/libexec/zed-editor", app_folder_name);
852
853 if let Some(prefix) = running_app_path
854 .to_str()
855 .and_then(|str| str.strip_suffix(&expected_suffix))
856 {
857 to = PathBuf::from(prefix);
858 }
859
860 let output = Command::new("rsync")
861 .args(["-av", "--delete"])
862 .arg(&from)
863 .arg(&to)
864 .output()
865 .await?;
866
867 anyhow::ensure!(
868 output.status.success(),
869 "failed to copy Zed update from {:?} to {:?}: {:?}",
870 from,
871 to,
872 String::from_utf8_lossy(&output.stderr)
873 );
874
875 Ok(Some(to.join(expected_suffix)))
876}
877
878async fn install_release_macos(
879 temp_dir: &InstallerDir,
880 downloaded_dmg: PathBuf,
881 cx: &AsyncApp,
882) -> Result<Option<PathBuf>> {
883 let running_app_path = cx.update(|cx| cx.app_path())??;
884 let running_app_filename = running_app_path
885 .file_name()
886 .with_context(|| format!("invalid running app path {running_app_path:?}"))?;
887
888 let mount_path = temp_dir.path().join("Zed");
889 let mut mounted_app_path: OsString = mount_path.join(running_app_filename).into();
890
891 mounted_app_path.push("/");
892 let output = Command::new("hdiutil")
893 .args(["attach", "-nobrowse"])
894 .arg(&downloaded_dmg)
895 .arg("-mountroot")
896 .arg(temp_dir.path())
897 .output()
898 .await?;
899
900 anyhow::ensure!(
901 output.status.success(),
902 "failed to mount: {:?}",
903 String::from_utf8_lossy(&output.stderr)
904 );
905
906 // Create an MacOsUnmounter that will be dropped (and thus unmount the disk) when this function exits
907 let _unmounter = MacOsUnmounter {
908 mount_path: mount_path.clone(),
909 };
910
911 let output = Command::new("rsync")
912 .args(["-av", "--delete"])
913 .arg(&mounted_app_path)
914 .arg(&running_app_path)
915 .output()
916 .await?;
917
918 anyhow::ensure!(
919 output.status.success(),
920 "failed to copy app: {:?}",
921 String::from_utf8_lossy(&output.stderr)
922 );
923
924 Ok(None)
925}
926
927async fn install_release_windows(downloaded_installer: PathBuf) -> Result<Option<PathBuf>> {
928 let output = Command::new(downloaded_installer)
929 .arg("/verysilent")
930 .arg("/update=true")
931 .arg("!desktopicon")
932 .arg("!quicklaunchicon")
933 .output()
934 .await?;
935 anyhow::ensure!(
936 output.status.success(),
937 "failed to start installer: {:?}",
938 String::from_utf8_lossy(&output.stderr)
939 );
940 // We return the path to the update helper program, because it will
941 // perform the final steps of the update process, copying the new binary,
942 // deleting the old one, and launching the new binary.
943 let helper_path = std::env::current_exe()?
944 .parent()
945 .context("No parent dir for Zed.exe")?
946 .join("tools\\auto_update_helper.exe");
947 Ok(Some(helper_path))
948}
949
950pub fn finalize_auto_update_on_quit() {
951 let Some(installer_path) = std::env::current_exe()
952 .ok()
953 .and_then(|p| p.parent().map(|p| p.join("updates")))
954 else {
955 return;
956 };
957
958 // The installer will create a flag file after it finishes updating
959 let flag_file = installer_path.join("versions.txt");
960 if flag_file.exists()
961 && let Some(helper) = installer_path
962 .parent()
963 .map(|p| p.join("tools\\auto_update_helper.exe"))
964 {
965 let mut command = std::process::Command::new(helper);
966 command.arg("--launch");
967 command.arg("false");
968 let _ = command.spawn();
969 }
970}
971
972#[cfg(test)]
973mod tests {
974 use super::*;
975
976 #[test]
977 fn test_stable_does_not_update_when_fetched_version_is_not_higher() {
978 let release_channel = ReleaseChannel::Stable;
979 let app_commit_sha = Ok(Some("a".to_string()));
980 let installed_version = SemanticVersion::new(1, 0, 0);
981 let status = AutoUpdateStatus::Idle;
982 let fetched_version = SemanticVersion::new(1, 0, 0);
983
984 let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
985 release_channel,
986 app_commit_sha,
987 installed_version,
988 fetched_version.to_string(),
989 status,
990 );
991
992 assert_eq!(newer_version.unwrap(), None);
993 }
994
995 #[test]
996 fn test_stable_does_update_when_fetched_version_is_higher() {
997 let release_channel = ReleaseChannel::Stable;
998 let app_commit_sha = Ok(Some("a".to_string()));
999 let installed_version = SemanticVersion::new(1, 0, 0);
1000 let status = AutoUpdateStatus::Idle;
1001 let fetched_version = SemanticVersion::new(1, 0, 1);
1002
1003 let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1004 release_channel,
1005 app_commit_sha,
1006 installed_version,
1007 fetched_version.to_string(),
1008 status,
1009 );
1010
1011 assert_eq!(
1012 newer_version.unwrap(),
1013 Some(VersionCheckType::Semantic(fetched_version))
1014 );
1015 }
1016
1017 #[test]
1018 fn test_stable_does_not_update_when_fetched_version_is_not_higher_than_cached() {
1019 let release_channel = ReleaseChannel::Stable;
1020 let app_commit_sha = Ok(Some("a".to_string()));
1021 let installed_version = SemanticVersion::new(1, 0, 0);
1022 let status = AutoUpdateStatus::Updated {
1023 version: VersionCheckType::Semantic(SemanticVersion::new(1, 0, 1)),
1024 };
1025 let fetched_version = SemanticVersion::new(1, 0, 1);
1026
1027 let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1028 release_channel,
1029 app_commit_sha,
1030 installed_version,
1031 fetched_version.to_string(),
1032 status,
1033 );
1034
1035 assert_eq!(newer_version.unwrap(), None);
1036 }
1037
1038 #[test]
1039 fn test_stable_does_update_when_fetched_version_is_higher_than_cached() {
1040 let release_channel = ReleaseChannel::Stable;
1041 let app_commit_sha = Ok(Some("a".to_string()));
1042 let installed_version = SemanticVersion::new(1, 0, 0);
1043 let status = AutoUpdateStatus::Updated {
1044 version: VersionCheckType::Semantic(SemanticVersion::new(1, 0, 1)),
1045 };
1046 let fetched_version = SemanticVersion::new(1, 0, 2);
1047
1048 let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1049 release_channel,
1050 app_commit_sha,
1051 installed_version,
1052 fetched_version.to_string(),
1053 status,
1054 );
1055
1056 assert_eq!(
1057 newer_version.unwrap(),
1058 Some(VersionCheckType::Semantic(fetched_version))
1059 );
1060 }
1061
1062 #[test]
1063 fn test_nightly_does_not_update_when_fetched_sha_is_same() {
1064 let release_channel = ReleaseChannel::Nightly;
1065 let app_commit_sha = Ok(Some("a".to_string()));
1066 let installed_version = SemanticVersion::new(1, 0, 0);
1067 let status = AutoUpdateStatus::Idle;
1068 let fetched_sha = "a".to_string();
1069
1070 let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1071 release_channel,
1072 app_commit_sha,
1073 installed_version,
1074 fetched_sha,
1075 status,
1076 );
1077
1078 assert_eq!(newer_version.unwrap(), None);
1079 }
1080
1081 #[test]
1082 fn test_nightly_does_update_when_fetched_sha_is_not_same() {
1083 let release_channel = ReleaseChannel::Nightly;
1084 let app_commit_sha = Ok(Some("a".to_string()));
1085 let installed_version = SemanticVersion::new(1, 0, 0);
1086 let status = AutoUpdateStatus::Idle;
1087 let fetched_sha = "b".to_string();
1088
1089 let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1090 release_channel,
1091 app_commit_sha,
1092 installed_version,
1093 fetched_sha.clone(),
1094 status,
1095 );
1096
1097 assert_eq!(
1098 newer_version.unwrap(),
1099 Some(VersionCheckType::Sha(AppCommitSha::new(fetched_sha)))
1100 );
1101 }
1102
1103 #[test]
1104 fn test_nightly_does_not_update_when_fetched_sha_is_same_as_cached() {
1105 let release_channel = ReleaseChannel::Nightly;
1106 let app_commit_sha = Ok(Some("a".to_string()));
1107 let installed_version = SemanticVersion::new(1, 0, 0);
1108 let status = AutoUpdateStatus::Updated {
1109 version: VersionCheckType::Sha(AppCommitSha::new("b".to_string())),
1110 };
1111 let fetched_sha = "b".to_string();
1112
1113 let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1114 release_channel,
1115 app_commit_sha,
1116 installed_version,
1117 fetched_sha,
1118 status,
1119 );
1120
1121 assert_eq!(newer_version.unwrap(), None);
1122 }
1123
1124 #[test]
1125 fn test_nightly_does_update_when_fetched_sha_is_not_same_as_cached() {
1126 let release_channel = ReleaseChannel::Nightly;
1127 let app_commit_sha = Ok(Some("a".to_string()));
1128 let installed_version = SemanticVersion::new(1, 0, 0);
1129 let status = AutoUpdateStatus::Updated {
1130 version: VersionCheckType::Sha(AppCommitSha::new("b".to_string())),
1131 };
1132 let fetched_sha = "c".to_string();
1133
1134 let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1135 release_channel,
1136 app_commit_sha,
1137 installed_version,
1138 fetched_sha.clone(),
1139 status,
1140 );
1141
1142 assert_eq!(
1143 newer_version.unwrap(),
1144 Some(VersionCheckType::Sha(AppCommitSha::new(fetched_sha)))
1145 );
1146 }
1147
1148 #[test]
1149 fn test_nightly_does_update_when_installed_versions_sha_cannot_be_retrieved() {
1150 let release_channel = ReleaseChannel::Nightly;
1151 let app_commit_sha = Ok(None);
1152 let installed_version = SemanticVersion::new(1, 0, 0);
1153 let status = AutoUpdateStatus::Idle;
1154 let fetched_sha = "a".to_string();
1155
1156 let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1157 release_channel,
1158 app_commit_sha,
1159 installed_version,
1160 fetched_sha.clone(),
1161 status,
1162 );
1163
1164 assert_eq!(
1165 newer_version.unwrap(),
1166 Some(VersionCheckType::Sha(AppCommitSha::new(fetched_sha)))
1167 );
1168 }
1169
1170 #[test]
1171 fn test_nightly_does_not_update_when_cached_update_is_same_as_fetched_and_installed_versions_sha_cannot_be_retrieved()
1172 {
1173 let release_channel = ReleaseChannel::Nightly;
1174 let app_commit_sha = Ok(None);
1175 let installed_version = SemanticVersion::new(1, 0, 0);
1176 let status = AutoUpdateStatus::Updated {
1177 version: VersionCheckType::Sha(AppCommitSha::new("b".to_string())),
1178 };
1179 let fetched_sha = "b".to_string();
1180
1181 let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1182 release_channel,
1183 app_commit_sha,
1184 installed_version,
1185 fetched_sha,
1186 status,
1187 );
1188
1189 assert_eq!(newer_version.unwrap(), None);
1190 }
1191
1192 #[test]
1193 fn test_nightly_does_update_when_cached_update_is_not_same_as_fetched_and_installed_versions_sha_cannot_be_retrieved()
1194 {
1195 let release_channel = ReleaseChannel::Nightly;
1196 let app_commit_sha = Ok(None);
1197 let installed_version = SemanticVersion::new(1, 0, 0);
1198 let status = AutoUpdateStatus::Updated {
1199 version: VersionCheckType::Sha(AppCommitSha::new("b".to_string())),
1200 };
1201 let fetched_sha = "c".to_string();
1202
1203 let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1204 release_channel,
1205 app_commit_sha,
1206 installed_version,
1207 fetched_sha.clone(),
1208 status,
1209 );
1210
1211 assert_eq!(
1212 newer_version.unwrap(),
1213 Some(VersionCheckType::Sha(AppCommitSha::new(fetched_sha)))
1214 );
1215 }
1216}