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