auto_update.rs

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