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