1use anyhow::{Context as _, Result, anyhow};
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!(auto_update, [Check, DismissErrorMessage, ViewReleaseNotes,]);
32
33#[derive(Serialize)]
34struct UpdateRequestBody {
35 installation_id: Option<Arc<str>>,
36 release_channel: Option<&'static str>,
37 telemetry: bool,
38 is_staff: Option<bool>,
39 destination: &'static str,
40}
41
42#[derive(Clone, PartialEq, Eq)]
43pub enum AutoUpdateStatus {
44 Idle,
45 Checking,
46 Downloading,
47 Installing,
48 Updated { binary_path: PathBuf },
49 Errored,
50}
51
52impl AutoUpdateStatus {
53 pub fn is_updated(&self) -> bool {
54 matches!(self, Self::Updated { .. })
55 }
56}
57
58pub struct AutoUpdater {
59 status: AutoUpdateStatus,
60 current_version: SemanticVersion,
61 http_client: Arc<HttpClientWithUrl>,
62 pending_poll: Option<Task<Option<()>>>,
63}
64
65#[derive(Deserialize, Debug)]
66pub struct JsonRelease {
67 pub version: String,
68 pub url: String,
69}
70
71struct MacOsUnmounter {
72 mount_path: PathBuf,
73}
74
75impl Drop for MacOsUnmounter {
76 fn drop(&mut self) {
77 let unmount_output = std::process::Command::new("hdiutil")
78 .args(["detach", "-force"])
79 .arg(&self.mount_path)
80 .output();
81
82 match unmount_output {
83 Ok(output) if output.status.success() => {
84 log::info!("Successfully unmounted the disk image");
85 }
86 Ok(output) => {
87 log::error!(
88 "Failed to unmount disk image: {:?}",
89 String::from_utf8_lossy(&output.stderr)
90 );
91 }
92 Err(error) => {
93 log::error!("Error while trying to unmount disk image: {:?}", error);
94 }
95 }
96 }
97}
98
99struct AutoUpdateSetting(bool);
100
101/// Whether or not to automatically check for updates.
102///
103/// Default: true
104#[derive(Clone, Copy, Default, JsonSchema, Deserialize, Serialize)]
105#[serde(transparent)]
106struct AutoUpdateSettingContent(bool);
107
108impl Settings for AutoUpdateSetting {
109 const KEY: Option<&'static str> = Some("auto_update");
110
111 type FileContent = Option<AutoUpdateSettingContent>;
112
113 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
114 let auto_update = [sources.server, sources.release_channel, sources.user]
115 .into_iter()
116 .find_map(|value| value.copied().flatten())
117 .unwrap_or(sources.default.ok_or_else(Self::missing_default)?);
118
119 Ok(Self(auto_update.0))
120 }
121
122 fn import_from_vscode(vscode: &settings::VsCodeSettings, current: &mut Self::FileContent) {
123 vscode.enum_setting("update.mode", current, |s| match s {
124 "none" | "manual" => Some(AutoUpdateSettingContent(false)),
125 _ => Some(AutoUpdateSettingContent(true)),
126 });
127 }
128}
129
130#[derive(Default)]
131struct GlobalAutoUpdate(Option<Entity<AutoUpdater>>);
132
133impl Global for GlobalAutoUpdate {}
134
135pub fn init(http_client: Arc<HttpClientWithUrl>, cx: &mut App) {
136 AutoUpdateSetting::register(cx);
137
138 cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
139 workspace.register_action(|_, action: &Check, window, cx| check(action, window, cx));
140
141 workspace.register_action(|_, action, _, cx| {
142 view_release_notes(action, cx);
143 });
144 })
145 .detach();
146
147 let version = release_channel::AppVersion::global(cx);
148 let auto_updater = cx.new(|cx| {
149 let updater = AutoUpdater::new(version, http_client);
150
151 let poll_for_updates = ReleaseChannel::try_global(cx)
152 .map(|channel| channel.poll_for_updates())
153 .unwrap_or(false);
154
155 if option_env!("ZED_UPDATE_EXPLANATION").is_none()
156 && env::var("ZED_UPDATE_EXPLANATION").is_err()
157 && poll_for_updates
158 {
159 let mut update_subscription = AutoUpdateSetting::get_global(cx)
160 .0
161 .then(|| updater.start_polling(cx));
162
163 cx.observe_global::<SettingsStore>(move |updater: &mut AutoUpdater, cx| {
164 if AutoUpdateSetting::get_global(cx).0 {
165 if update_subscription.is_none() {
166 update_subscription = Some(updater.start_polling(cx))
167 }
168 } else {
169 update_subscription.take();
170 }
171 })
172 .detach();
173 }
174
175 updater
176 });
177 cx.set_global(GlobalAutoUpdate(Some(auto_updater)));
178}
179
180pub fn check(_: &Check, window: &mut Window, cx: &mut App) {
181 if let Some(message) = option_env!("ZED_UPDATE_EXPLANATION") {
182 drop(window.prompt(
183 gpui::PromptLevel::Info,
184 "Zed was installed via a package manager.",
185 Some(message),
186 &["Ok"],
187 cx,
188 ));
189 return;
190 }
191
192 if let Ok(message) = env::var("ZED_UPDATE_EXPLANATION") {
193 drop(window.prompt(
194 gpui::PromptLevel::Info,
195 "Zed was installed via a package manager.",
196 Some(&message),
197 &["Ok"],
198 cx,
199 ));
200 return;
201 }
202
203 if !ReleaseChannel::try_global(cx)
204 .map(|channel| channel.poll_for_updates())
205 .unwrap_or(false)
206 {
207 return;
208 }
209
210 if let Some(updater) = AutoUpdater::get(cx) {
211 updater.update(cx, |updater, cx| updater.poll(cx));
212 } else {
213 drop(window.prompt(
214 gpui::PromptLevel::Info,
215 "Could not check for updates",
216 Some("Auto-updates disabled for non-bundled app."),
217 &["Ok"],
218 cx,
219 ));
220 }
221}
222
223pub fn view_release_notes(_: &ViewReleaseNotes, cx: &mut App) -> Option<()> {
224 let auto_updater = AutoUpdater::get(cx)?;
225 let release_channel = ReleaseChannel::try_global(cx)?;
226
227 match release_channel {
228 ReleaseChannel::Stable | ReleaseChannel::Preview => {
229 let auto_updater = auto_updater.read(cx);
230 let current_version = auto_updater.current_version;
231 let release_channel = release_channel.dev_name();
232 let path = format!("/releases/{release_channel}/{current_version}");
233 let url = &auto_updater.http_client.build_url(&path);
234 cx.open_url(url);
235 }
236 ReleaseChannel::Nightly => {
237 cx.open_url("https://github.com/zed-industries/zed/commits/nightly/");
238 }
239 ReleaseChannel::Dev => {
240 cx.open_url("https://github.com/zed-industries/zed/commits/main/");
241 }
242 }
243 None
244}
245
246#[cfg(not(target_os = "windows"))]
247struct InstallerDir(tempfile::TempDir);
248
249#[cfg(not(target_os = "windows"))]
250impl InstallerDir {
251 async fn new() -> Result<Self> {
252 Ok(Self(
253 tempfile::Builder::new()
254 .prefix("zed-auto-update")
255 .tempdir()?,
256 ))
257 }
258
259 fn path(&self) -> &Path {
260 self.0.path()
261 }
262}
263
264#[cfg(target_os = "windows")]
265struct InstallerDir(PathBuf);
266
267#[cfg(target_os = "windows")]
268impl InstallerDir {
269 async fn new() -> Result<Self> {
270 let installer_dir = std::env::current_exe()?
271 .parent()
272 .context("No parent dir for Zed.exe")?
273 .join("updates");
274 if smol::fs::metadata(&installer_dir).await.is_ok() {
275 smol::fs::remove_dir_all(&installer_dir).await?;
276 }
277 smol::fs::create_dir(&installer_dir).await?;
278 Ok(Self(installer_dir))
279 }
280
281 fn path(&self) -> &Path {
282 self.0.as_path()
283 }
284}
285
286impl AutoUpdater {
287 pub fn get(cx: &mut App) -> Option<Entity<Self>> {
288 cx.default_global::<GlobalAutoUpdate>().0.clone()
289 }
290
291 fn new(current_version: SemanticVersion, http_client: Arc<HttpClientWithUrl>) -> Self {
292 Self {
293 status: AutoUpdateStatus::Idle,
294 current_version,
295 http_client,
296 pending_poll: None,
297 }
298 }
299
300 pub fn start_polling(&self, cx: &mut Context<Self>) -> Task<Result<()>> {
301 cx.spawn(async move |this, cx| {
302 loop {
303 this.update(cx, |this, cx| this.poll(cx))?;
304 cx.background_executor().timer(POLL_INTERVAL).await;
305 }
306 })
307 }
308
309 pub fn poll(&mut self, cx: &mut Context<Self>) {
310 if self.pending_poll.is_some() || self.status.is_updated() {
311 return;
312 }
313
314 cx.notify();
315
316 self.pending_poll = Some(cx.spawn(async move |this, cx| {
317 let result = Self::update(this.upgrade()?, cx.clone()).await;
318 this.update(cx, |this, cx| {
319 this.pending_poll = None;
320 if let Err(error) = result {
321 log::error!("auto-update failed: error:{:?}", error);
322 this.status = AutoUpdateStatus::Errored;
323 cx.notify();
324 }
325 })
326 .ok()
327 }));
328 }
329
330 pub fn current_version(&self) -> SemanticVersion {
331 self.current_version
332 }
333
334 pub fn status(&self) -> AutoUpdateStatus {
335 self.status.clone()
336 }
337
338 pub fn dismiss_error(&mut self, cx: &mut Context<Self>) {
339 self.status = AutoUpdateStatus::Idle;
340 cx.notify();
341 }
342
343 // If you are packaging Zed and need to override the place it downloads SSH remotes from,
344 // you can override this function. You should also update get_remote_server_release_url to return
345 // Ok(None).
346 pub async fn download_remote_server_release(
347 os: &str,
348 arch: &str,
349 release_channel: ReleaseChannel,
350 version: Option<SemanticVersion>,
351 cx: &mut AsyncApp,
352 ) -> Result<PathBuf> {
353 let this = cx.update(|cx| {
354 cx.default_global::<GlobalAutoUpdate>()
355 .0
356 .clone()
357 .ok_or_else(|| anyhow!("auto-update not initialized"))
358 })??;
359
360 let release = Self::get_release(
361 &this,
362 "zed-remote-server",
363 os,
364 arch,
365 version,
366 Some(release_channel),
367 cx,
368 )
369 .await?;
370
371 let servers_dir = paths::remote_servers_dir();
372 let channel_dir = servers_dir.join(release_channel.dev_name());
373 let platform_dir = channel_dir.join(format!("{}-{}", os, arch));
374 let version_path = platform_dir.join(format!("{}.gz", release.version));
375 smol::fs::create_dir_all(&platform_dir).await.ok();
376
377 let client = this.read_with(cx, |this, _| this.http_client.clone())?;
378
379 if smol::fs::metadata(&version_path).await.is_err() {
380 log::info!(
381 "downloading zed-remote-server {os} {arch} version {}",
382 release.version
383 );
384 download_remote_server_binary(&version_path, release, client, cx).await?;
385 }
386
387 Ok(version_path)
388 }
389
390 pub async fn get_remote_server_release_url(
391 os: &str,
392 arch: &str,
393 release_channel: ReleaseChannel,
394 version: Option<SemanticVersion>,
395 cx: &mut AsyncApp,
396 ) -> Result<Option<(String, String)>> {
397 let this = cx.update(|cx| {
398 cx.default_global::<GlobalAutoUpdate>()
399 .0
400 .clone()
401 .ok_or_else(|| anyhow!("auto-update not initialized"))
402 })??;
403
404 let release = Self::get_release(
405 &this,
406 "zed-remote-server",
407 os,
408 arch,
409 version,
410 Some(release_channel),
411 cx,
412 )
413 .await?;
414
415 let update_request_body = build_remote_server_update_request_body(cx)?;
416 let body = serde_json::to_string(&update_request_body)?;
417
418 Ok(Some((release.url, body)))
419 }
420
421 async fn get_release(
422 this: &Entity<Self>,
423 asset: &str,
424 os: &str,
425 arch: &str,
426 version: Option<SemanticVersion>,
427 release_channel: Option<ReleaseChannel>,
428 cx: &mut AsyncApp,
429 ) -> Result<JsonRelease> {
430 let client = this.read_with(cx, |this, _| this.http_client.clone())?;
431
432 if let Some(version) = version {
433 let channel = release_channel.map(|c| c.dev_name()).unwrap_or("stable");
434
435 let url = format!("/api/releases/{channel}/{version}/{asset}-{os}-{arch}.gz?update=1",);
436
437 Ok(JsonRelease {
438 version: version.to_string(),
439 url: client.build_url(&url),
440 })
441 } else {
442 let mut url_string = client.build_url(&format!(
443 "/api/releases/latest?asset={}&os={}&arch={}",
444 asset, os, arch
445 ));
446 if let Some(param) = release_channel.and_then(|c| c.release_query_param()) {
447 url_string += "&";
448 url_string += param;
449 }
450
451 let mut response = client.get(&url_string, Default::default(), true).await?;
452 let mut body = Vec::new();
453 response.body_mut().read_to_end(&mut body).await?;
454
455 if !response.status().is_success() {
456 return Err(anyhow!(
457 "failed to fetch release: {:?}",
458 String::from_utf8_lossy(&body),
459 ));
460 }
461
462 serde_json::from_slice(body.as_slice()).with_context(|| {
463 format!(
464 "error deserializing release {:?}",
465 String::from_utf8_lossy(&body),
466 )
467 })
468 }
469 }
470
471 async fn get_latest_release(
472 this: &Entity<Self>,
473 asset: &str,
474 os: &str,
475 arch: &str,
476 release_channel: Option<ReleaseChannel>,
477 cx: &mut AsyncApp,
478 ) -> Result<JsonRelease> {
479 Self::get_release(this, asset, os, arch, None, release_channel, cx).await
480 }
481
482 async fn update(this: Entity<Self>, mut cx: AsyncApp) -> Result<()> {
483 let (client, current_version, release_channel) = this.update(&mut cx, |this, cx| {
484 this.status = AutoUpdateStatus::Checking;
485 cx.notify();
486 (
487 this.http_client.clone(),
488 this.current_version,
489 ReleaseChannel::try_global(cx),
490 )
491 })?;
492
493 let release =
494 Self::get_latest_release(&this, "zed", OS, ARCH, release_channel, &mut cx).await?;
495
496 let should_download = match *RELEASE_CHANNEL {
497 ReleaseChannel::Nightly => cx
498 .update(|cx| AppCommitSha::try_global(cx).map(|sha| release.version != sha.0))
499 .ok()
500 .flatten()
501 .unwrap_or(true),
502 _ => release.version.parse::<SemanticVersion>()? > current_version,
503 };
504
505 if !should_download {
506 this.update(&mut cx, |this, cx| {
507 this.status = AutoUpdateStatus::Idle;
508 cx.notify();
509 })?;
510 return Ok(());
511 }
512
513 this.update(&mut cx, |this, cx| {
514 this.status = AutoUpdateStatus::Downloading;
515 cx.notify();
516 })?;
517
518 let installer_dir = InstallerDir::new().await?;
519 let filename = match OS {
520 "macos" => Ok("Zed.dmg"),
521 "linux" => Ok("zed.tar.gz"),
522 "windows" => Ok("ZedUpdateInstaller.exe"),
523 _ => Err(anyhow!("not supported: {:?}", OS)),
524 }?;
525
526 #[cfg(not(target_os = "windows"))]
527 anyhow::ensure!(
528 which::which("rsync").is_ok(),
529 "Aborting. Could not find rsync which is required for auto-updates."
530 );
531
532 let downloaded_asset = installer_dir.path().join(filename);
533 download_release(&downloaded_asset, release, client, &cx).await?;
534
535 this.update(&mut cx, |this, cx| {
536 this.status = AutoUpdateStatus::Installing;
537 cx.notify();
538 })?;
539
540 let binary_path = match OS {
541 "macos" => install_release_macos(&installer_dir, downloaded_asset, &cx).await,
542 "linux" => install_release_linux(&installer_dir, downloaded_asset, &cx).await,
543 "windows" => install_release_windows(downloaded_asset).await,
544 _ => Err(anyhow!("not supported: {:?}", OS)),
545 }?;
546
547 this.update(&mut cx, |this, cx| {
548 this.set_should_show_update_notification(true, cx)
549 .detach_and_log_err(cx);
550 this.status = AutoUpdateStatus::Updated { binary_path };
551 cx.notify();
552 })?;
553
554 Ok(())
555 }
556
557 pub fn set_should_show_update_notification(
558 &self,
559 should_show: bool,
560 cx: &App,
561 ) -> Task<Result<()>> {
562 cx.background_spawn(async move {
563 if should_show {
564 KEY_VALUE_STORE
565 .write_kvp(
566 SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string(),
567 "".to_string(),
568 )
569 .await?;
570 } else {
571 KEY_VALUE_STORE
572 .delete_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string())
573 .await?;
574 }
575 Ok(())
576 })
577 }
578
579 pub fn should_show_update_notification(&self, cx: &App) -> Task<Result<bool>> {
580 cx.background_spawn(async move {
581 Ok(KEY_VALUE_STORE
582 .read_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY)?
583 .is_some())
584 })
585 }
586}
587
588async fn download_remote_server_binary(
589 target_path: &PathBuf,
590 release: JsonRelease,
591 client: Arc<HttpClientWithUrl>,
592 cx: &AsyncApp,
593) -> Result<()> {
594 let temp = tempfile::Builder::new().tempfile_in(remote_servers_dir())?;
595 let mut temp_file = File::create(&temp).await?;
596 let update_request_body = build_remote_server_update_request_body(cx)?;
597 let request_body = AsyncBody::from(serde_json::to_string(&update_request_body)?);
598
599 let mut response = client.get(&release.url, request_body, true).await?;
600 if !response.status().is_success() {
601 return Err(anyhow!(
602 "failed to download remote server release: {:?}",
603 response.status()
604 ));
605 }
606 smol::io::copy(response.body_mut(), &mut temp_file).await?;
607 smol::fs::rename(&temp, &target_path).await?;
608
609 Ok(())
610}
611
612fn build_remote_server_update_request_body(cx: &AsyncApp) -> Result<UpdateRequestBody> {
613 let (installation_id, release_channel, telemetry_enabled, is_staff) = cx.update(|cx| {
614 let telemetry = Client::global(cx).telemetry().clone();
615 let is_staff = telemetry.is_staff();
616 let installation_id = telemetry.installation_id();
617 let release_channel =
618 ReleaseChannel::try_global(cx).map(|release_channel| release_channel.display_name());
619 let telemetry_enabled = TelemetrySettings::get_global(cx).metrics;
620
621 (
622 installation_id,
623 release_channel,
624 telemetry_enabled,
625 is_staff,
626 )
627 })?;
628
629 Ok(UpdateRequestBody {
630 installation_id,
631 release_channel,
632 telemetry: telemetry_enabled,
633 is_staff,
634 destination: "remote",
635 })
636}
637
638async fn download_release(
639 target_path: &Path,
640 release: JsonRelease,
641 client: Arc<HttpClientWithUrl>,
642 cx: &AsyncApp,
643) -> Result<()> {
644 let mut target_file = File::create(&target_path).await?;
645
646 let (installation_id, release_channel, telemetry_enabled, is_staff) = cx.update(|cx| {
647 let telemetry = Client::global(cx).telemetry().clone();
648 let is_staff = telemetry.is_staff();
649 let installation_id = telemetry.installation_id();
650 let release_channel =
651 ReleaseChannel::try_global(cx).map(|release_channel| release_channel.display_name());
652 let telemetry_enabled = TelemetrySettings::get_global(cx).metrics;
653
654 (
655 installation_id,
656 release_channel,
657 telemetry_enabled,
658 is_staff,
659 )
660 })?;
661
662 let request_body = AsyncBody::from(serde_json::to_string(&UpdateRequestBody {
663 installation_id,
664 release_channel,
665 telemetry: telemetry_enabled,
666 is_staff,
667 destination: "local",
668 })?);
669
670 let mut response = client.get(&release.url, request_body, true).await?;
671 smol::io::copy(response.body_mut(), &mut target_file).await?;
672 log::info!("downloaded update. path:{:?}", target_path);
673
674 Ok(())
675}
676
677async fn install_release_linux(
678 temp_dir: &InstallerDir,
679 downloaded_tar_gz: PathBuf,
680 cx: &AsyncApp,
681) -> Result<PathBuf> {
682 let channel = cx.update(|cx| ReleaseChannel::global(cx).dev_name())?;
683 let home_dir = PathBuf::from(env::var("HOME").context("no HOME env var set")?);
684 let running_app_path = cx.update(|cx| cx.app_path())??;
685
686 let extracted = temp_dir.path().join("zed");
687 fs::create_dir_all(&extracted)
688 .await
689 .context("failed to create directory into which to extract update")?;
690
691 let output = Command::new("tar")
692 .arg("-xzf")
693 .arg(&downloaded_tar_gz)
694 .arg("-C")
695 .arg(&extracted)
696 .output()
697 .await?;
698
699 anyhow::ensure!(
700 output.status.success(),
701 "failed to extract {:?} to {:?}: {:?}",
702 downloaded_tar_gz,
703 extracted,
704 String::from_utf8_lossy(&output.stderr)
705 );
706
707 let suffix = if channel != "stable" {
708 format!("-{}", channel)
709 } else {
710 String::default()
711 };
712 let app_folder_name = format!("zed{}.app", suffix);
713
714 let from = extracted.join(&app_folder_name);
715 let mut to = home_dir.join(".local");
716
717 let expected_suffix = format!("{}/libexec/zed-editor", app_folder_name);
718
719 if let Some(prefix) = running_app_path
720 .to_str()
721 .and_then(|str| str.strip_suffix(&expected_suffix))
722 {
723 to = PathBuf::from(prefix);
724 }
725
726 let output = Command::new("rsync")
727 .args(["-av", "--delete"])
728 .arg(&from)
729 .arg(&to)
730 .output()
731 .await?;
732
733 anyhow::ensure!(
734 output.status.success(),
735 "failed to copy Zed update from {:?} to {:?}: {:?}",
736 from,
737 to,
738 String::from_utf8_lossy(&output.stderr)
739 );
740
741 Ok(to.join(expected_suffix))
742}
743
744async fn install_release_macos(
745 temp_dir: &InstallerDir,
746 downloaded_dmg: PathBuf,
747 cx: &AsyncApp,
748) -> Result<PathBuf> {
749 let running_app_path = cx.update(|cx| cx.app_path())??;
750 let running_app_filename = running_app_path
751 .file_name()
752 .ok_or_else(|| anyhow!("invalid running app path"))?;
753
754 let mount_path = temp_dir.path().join("Zed");
755 let mut mounted_app_path: OsString = mount_path.join(running_app_filename).into();
756
757 mounted_app_path.push("/");
758 let output = Command::new("hdiutil")
759 .args(["attach", "-nobrowse"])
760 .arg(&downloaded_dmg)
761 .arg("-mountroot")
762 .arg(temp_dir.path())
763 .output()
764 .await?;
765
766 anyhow::ensure!(
767 output.status.success(),
768 "failed to mount: {:?}",
769 String::from_utf8_lossy(&output.stderr)
770 );
771
772 // Create an MacOsUnmounter that will be dropped (and thus unmount the disk) when this function exits
773 let _unmounter = MacOsUnmounter {
774 mount_path: mount_path.clone(),
775 };
776
777 let output = Command::new("rsync")
778 .args(["-av", "--delete"])
779 .arg(&mounted_app_path)
780 .arg(&running_app_path)
781 .output()
782 .await?;
783
784 anyhow::ensure!(
785 output.status.success(),
786 "failed to copy app: {:?}",
787 String::from_utf8_lossy(&output.stderr)
788 );
789
790 Ok(running_app_path)
791}
792
793async fn install_release_windows(downloaded_installer: PathBuf) -> Result<PathBuf> {
794 let output = Command::new(downloaded_installer)
795 .arg("/verysilent")
796 .arg("/update=true")
797 .arg("!desktopicon")
798 .arg("!quicklaunchicon")
799 .output()
800 .await?;
801 anyhow::ensure!(
802 output.status.success(),
803 "failed to start installer: {:?}",
804 String::from_utf8_lossy(&output.stderr)
805 );
806 Ok(std::env::current_exe()?)
807}
808
809pub fn check_pending_installation() -> bool {
810 let Some(installer_path) = std::env::current_exe()
811 .ok()
812 .and_then(|p| p.parent().map(|p| p.join("updates")))
813 else {
814 return false;
815 };
816
817 // The installer will create a flag file after it finishes updating
818 let flag_file = installer_path.join("versions.txt");
819 if flag_file.exists() {
820 if let Some(helper) = installer_path
821 .parent()
822 .map(|p| p.join("tools\\auto_update_helper.exe"))
823 {
824 let _ = std::process::Command::new(helper).spawn();
825 return true;
826 }
827 }
828 false
829}