1use crate::config::{state_dir, EnvFn, Track, UpdateCheck, UpdateConfig};
22use crate::error::{Error, Result};
23use crate::http::{self, Reach};
24use serde::{Deserialize, Serialize};
25use std::fmt;
26use std::path::{Path, PathBuf};
27use std::time::Duration;
28
29pub const MARKER_FILE: &str = "install.json";
30pub const CACHE_FILE: &str = "update.json";
31
32pub const DEFAULT_LATEST_URL: &str = "https://api.github.com/repos/mmhorda/eclipse/commits/main";
37
38pub const DEVELOP_LATEST_URL: &str = "https://api.github.com/repos/mmhorda/eclipse/commits/develop";
41
42fn latest_question(cfg: &UpdateConfig) -> (&str, Reach) {
46 match cfg.remote.as_deref() {
47 Some(remote) => (remote, Reach::Anywhere),
48 None => match cfg.track {
49 Track::Release => (DEFAULT_LATEST_URL, Reach::Public),
50 Track::Develop => (DEVELOP_LATEST_URL, Reach::Public),
51 },
52 }
53}
54
55pub const DEFAULT_RELEASES_URL: &str =
59 "https://api.github.com/repos/mmhorda/eclipse/releases/latest";
60
61pub const TARBALL_SUFFIX: &str = "-x86_64-unknown-linux-gnu.tar.gz";
64
65pub const SUMS_NAME: &str = "SHA256SUMS";
67
68const MAX_RELEASE_BYTES: usize = 64 * 1024;
71
72pub const RELEASE_TIMEOUT: Duration = Duration::from_secs(20);
74
75pub const CHECK_TIMEOUT: Duration = Duration::from_secs(2);
77
78const MAX_ANSWER_BYTES: usize = 8 * 1024;
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
82#[serde(rename_all = "lowercase")]
83pub enum Channel {
84 Source,
86 Release,
89}
90
91impl Channel {
92 pub fn label(self) -> &'static str {
93 match self {
94 Channel::Source => "source",
95 Channel::Release => "release",
96 }
97 }
98}
99
100#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
104pub struct Version {
105 pub major: u64,
106 pub minor: u64,
107 pub patch: u64,
108}
109
110impl Version {
111 pub fn parse(text: &str) -> Option<Version> {
113 let text = text.trim();
114 let text = text.strip_prefix('v').unwrap_or(text);
115 let mut parts = text.split('.');
116 let major = parts.next()?.parse().ok()?;
117 let minor = parts.next()?.parse().ok()?;
118 let patch = parts.next()?.split(['-', '+']).next()?.parse().ok()?;
121 if parts.next().is_some() {
122 return None;
123 }
124 Some(Version {
125 major,
126 minor,
127 patch,
128 })
129 }
130}
131
132impl fmt::Display for Version {
133 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134 write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
135 }
136}
137
138#[derive(Debug, Clone, PartialEq, Eq)]
141pub struct Release {
142 pub tag: String,
144 pub version: Version,
145 pub tarball_url: String,
146 pub tarball_name: String,
147 pub sums_url: String,
148 pub page: Option<String>,
150}
151
152pub fn parse_release(body: &str) -> std::result::Result<Release, String> {
156 let value: serde_json::Value =
157 serde_json::from_str(body).map_err(|e| format!("not a release object: {e}"))?;
158 let tag = value
159 .get("tag_name")
160 .and_then(|v| v.as_str())
161 .ok_or("the answer carries no tag_name")?
162 .trim()
163 .to_string();
164 let version =
165 Version::parse(&tag).ok_or_else(|| format!("tag {tag:?} is not vMAJOR.MINOR.PATCH"))?;
166 let assets = value
167 .get("assets")
168 .and_then(|v| v.as_array())
169 .ok_or("the answer carries no assets")?;
170 let find = |want: &dyn Fn(&str) -> bool| -> Option<(String, String)> {
171 assets.iter().find_map(|a| {
172 let name = a.get("name")?.as_str()?;
173 if !want(name) {
174 return None;
175 }
176 let url = a.get("browser_download_url")?.as_str()?.to_string();
177 Some((name.to_string(), url))
178 })
179 };
180 let (tarball_name, tarball_url) = find(&|n| n.ends_with(TARBALL_SUFFIX)).ok_or_else(|| {
181 format!(
182 "{tag} has no {TARBALL_SUFFIX} asset (it carries: {})",
183 asset_names(assets)
184 )
185 })?;
186 let sums_url = find(&|n| n == SUMS_NAME)
187 .map(|(_, url)| url)
188 .ok_or_else(|| {
189 format!("{tag} has no {SUMS_NAME} asset, so a download could not be checked")
190 })?;
191 Ok(Release {
192 tag,
193 version,
194 tarball_url,
195 tarball_name,
196 sums_url,
197 page: value
198 .get("html_url")
199 .and_then(|v| v.as_str())
200 .map(str::to_string),
201 })
202}
203
204fn asset_names(assets: &[serde_json::Value]) -> String {
205 let names: Vec<&str> = assets
206 .iter()
207 .filter_map(|a| a.get("name").and_then(|n| n.as_str()))
208 .collect();
209 if names.is_empty() {
210 "nothing".to_string()
211 } else {
212 names.join(", ")
213 }
214}
215
216#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
218pub struct InstallMarker {
219 pub channel: Channel,
220 pub prefix: PathBuf,
222 #[serde(default)]
226 pub workspace: Option<PathBuf>,
227 #[serde(default)]
230 pub commit: Option<String>,
231 pub installed_at: String,
233 #[serde(default)]
236 pub build: Option<String>,
237 #[serde(default)]
241 pub version: Option<String>,
242}
243
244impl InstallMarker {
245 pub fn path(env: EnvFn) -> Option<PathBuf> {
250 state_dir(env).map(|d| d.join(MARKER_FILE))
251 }
252
253 pub fn load(path: &Path) -> Result<Option<InstallMarker>> {
257 let text = match std::fs::read_to_string(path) {
258 Ok(t) => t,
259 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
260 Err(e) => return Err(Error::io(path, e)),
261 };
262 serde_json::from_str(&text)
263 .map(Some)
264 .map_err(|e| Error::Parse {
265 path: path.to_path_buf(),
266 message: format!("{e} (run install.sh again to rewrite it)"),
267 })
268 }
269}
270
271#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
273#[serde(default)]
274pub struct UpdateCache {
275 pub checked_at: u64,
278 pub latest: Option<String>,
280 pub notified: Option<String>,
282}
283
284impl UpdateCache {
285 pub fn load(path: &Path) -> UpdateCache {
287 std::fs::read_to_string(path)
288 .ok()
289 .and_then(|t| serde_json::from_str(&t).ok())
290 .unwrap_or_default()
291 }
292
293 pub fn save(&self, path: &Path) {
296 let Ok(text) = serde_json::to_string_pretty(self) else {
297 return;
298 };
299 if let Some(dir) = path.parent() {
300 if std::fs::create_dir_all(dir).is_err() {
301 return;
302 }
303 }
304 let tmp = path.with_extension(format!("json.{}.tmp", std::process::id()));
305 if std::fs::write(&tmp, text + "\n").is_err() || std::fs::rename(&tmp, path).is_err() {
306 let _ = std::fs::remove_file(&tmp);
307 }
308 }
309
310 pub fn is_due(&self, check: UpdateCheck, now_secs: u64) -> bool {
312 match check.period_secs() {
313 None => false,
314 Some(period) => now_secs.saturating_sub(self.checked_at) >= period,
315 }
316 }
317}
318
319pub fn parse_latest(body: &str) -> Option<String> {
321 let is_id = |s: &str| matches!(s.len(), 40 | 64) && s.bytes().all(|b| b.is_ascii_hexdigit());
322 let bare = body.trim();
323 if is_id(bare) {
324 return Some(bare.to_ascii_lowercase());
325 }
326 let value: serde_json::Value = serde_json::from_str(bare).ok()?;
327 let sha = value.get("sha")?.as_str()?.trim();
328 is_id(sha).then(|| sha.to_ascii_lowercase())
329}
330
331async fn get_body(
334 raw: &str,
335 reach: Reach,
336 accept: &str,
337 timeout: Duration,
338 cap: usize,
339) -> std::result::Result<String, String> {
340 let url = reqwest::Url::parse(raw).map_err(|e| format!("{raw:?}: {e}"))?;
341 let user_agent = format!("eclipse/{}", env!("CARGO_PKG_VERSION"));
342 let ask = async {
343 let mut resp = http::get(
344 &url,
345 timeout,
346 reach,
347 &[("Accept", accept), ("User-Agent", &user_agent)],
348 )
349 .await?;
350 if !resp.status().is_success() {
351 return Err(format!("{url} answered {}", resp.status()));
352 }
353 let mut body = Vec::new();
354 while let Some(chunk) = resp.chunk().await.map_err(|e| e.to_string())? {
355 body.extend_from_slice(&chunk);
356 if body.len() > cap {
357 return Err(format!(
361 "{url} answered more than {} KB, which is not a release list or a commit id; \
362 nothing was read",
363 cap / 1024
364 ));
365 }
366 }
367 Ok(String::from_utf8_lossy(&body).into_owned())
368 };
369 tokio::time::timeout(timeout, ask)
370 .await
371 .unwrap_or_else(|_| {
372 Err(format!(
373 "{url} did not answer within {} s",
374 timeout.as_secs()
375 ))
376 })
377}
378
379pub async fn fetch_latest(cfg: &UpdateConfig) -> std::result::Result<String, String> {
382 let (raw, reach) = latest_question(cfg);
383 let body = get_body(
384 raw,
385 reach,
386 "application/vnd.github.sha",
387 CHECK_TIMEOUT,
388 MAX_ANSWER_BYTES,
389 )
390 .await?;
391 parse_latest(&body).ok_or_else(|| format!("{raw} did not answer with a commit id"))
392}
393
394pub async fn fetch_release(cfg: &UpdateConfig) -> std::result::Result<Release, String> {
397 let (raw, reach) = match cfg.releases.as_deref() {
398 Some(r) => (r, Reach::Anywhere),
399 None => (DEFAULT_RELEASES_URL, Reach::Public),
400 };
401 let body = get_body(
402 raw,
403 reach,
404 "application/vnd.github+json",
405 RELEASE_TIMEOUT,
406 MAX_RELEASE_BYTES,
407 )
408 .await?;
409 parse_release(&body).map_err(|e| format!("{raw}: {e}"))
410}
411
412fn is_news(marker: &InstallMarker, installed: &str, latest: &str) -> bool {
419 if latest == installed {
420 return false;
421 }
422 let Some(workspace) = &marker.workspace else {
423 return true;
424 };
425 let contains = std::process::Command::new("git")
426 .arg("-C")
427 .arg(workspace)
428 .args(["merge-base", "--is-ancestor", latest, installed])
429 .stdin(std::process::Stdio::null())
430 .stdout(std::process::Stdio::null())
431 .stderr(std::process::Stdio::null())
432 .status()
433 .is_ok_and(|s| s.success());
434 !contains
435}
436
437#[derive(Debug, Clone, PartialEq, Eq)]
440enum Installed {
441 Commit(String),
443 Version(Version),
445}
446
447impl Installed {
448 fn of(marker: &InstallMarker) -> Option<Installed> {
449 match marker.channel {
450 Channel::Source => marker
451 .commit
452 .clone()
453 .filter(|c| !c.is_empty())
454 .map(Installed::Commit),
455 Channel::Release => marker
456 .version
457 .as_deref()
458 .and_then(Version::parse)
459 .map(Installed::Version),
460 }
461 }
462}
463
464#[derive(Debug, Clone, PartialEq, Eq)]
471pub struct Behind {
472 pub installed: String,
474 pub latest: String,
476}
477
478impl Behind {
479 pub fn shown_latest(&self) -> String {
482 Version::parse(&self.latest)
483 .map(|v| v.to_string())
484 .unwrap_or_else(|| self.latest.clone())
485 }
486
487 pub fn line(&self) -> String {
490 format!("↑ {} available · eclipse upgrade", self.shown_latest())
491 }
492}
493
494pub fn behind(marker: &InstallMarker, cache: &UpdateCache) -> Option<Behind> {
498 let latest = cache.latest.as_deref()?;
499 match Installed::of(marker)? {
500 Installed::Commit(commit) => is_news(marker, &commit, latest).then(|| Behind {
501 installed: short(&commit).to_string(),
502 latest: short(latest).to_string(),
503 }),
504 Installed::Version(version) => {
505 let newest = Version::parse(latest)?;
508 (newest > version).then(|| Behind {
509 installed: version.to_string(),
510 latest: latest.trim().to_string(),
511 })
512 }
513 }
514}
515
516pub const STALE_AFTER_SECS: u64 = 7 * 86_400;
520
521#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
523pub struct Snapshot {
524 pub installed: Option<String>,
526 pub latest: Option<String>,
528 pub behind: bool,
530 pub checked_at: u64,
532 pub channel: Option<Channel>,
533}
534
535#[derive(Debug, Clone, PartialEq, Eq)]
540pub struct Watch {
541 state: PathBuf,
542 cfg: UpdateConfig,
543}
544
545impl Watch {
546 pub fn for_env(env: EnvFn, cfg: &UpdateConfig) -> Option<Watch> {
549 if cfg.check == UpdateCheck::Off {
550 return None;
551 }
552 Some(Watch {
553 state: state_dir(env)?,
554 cfg: cfg.clone(),
555 })
556 }
557
558 pub fn at(state: PathBuf, cfg: &UpdateConfig) -> Watch {
561 Watch {
562 state,
563 cfg: cfg.clone(),
564 }
565 }
566
567 pub fn read(&self) -> Option<Behind> {
569 if self.cfg.check == UpdateCheck::Off {
570 return None;
571 }
572 let marker = InstallMarker::load(&self.state.join(MARKER_FILE))
573 .ok()
574 .flatten()?;
575 let cache = UpdateCache::load(&self.state.join(CACHE_FILE));
576 behind(&marker, &cache)
577 }
578
579 pub fn snapshot(&self, now_secs: u64) -> Snapshot {
582 if self.cfg.check == UpdateCheck::Off {
583 return Snapshot::default();
584 }
585 let marker = InstallMarker::load(&self.state.join(MARKER_FILE))
586 .ok()
587 .flatten();
588 let cache = UpdateCache::load(&self.state.join(CACHE_FILE));
589 let behind = marker.as_ref().and_then(|m| behind(m, &cache));
590 let fresh = now_secs.saturating_sub(cache.checked_at) <= STALE_AFTER_SECS;
591 Snapshot {
592 installed: behind
593 .as_ref()
594 .map(|b| b.installed.clone())
595 .or_else(|| marker.as_ref().and_then(installed_text)),
596 latest: behind
597 .as_ref()
598 .map(|b| b.latest.clone())
599 .or_else(|| cache.latest.clone()),
600 behind: behind.is_some() && fresh,
601 checked_at: cache.checked_at,
602 channel: marker.as_ref().map(|m| m.channel),
603 }
604 }
605}
606
607fn installed_text(marker: &InstallMarker) -> Option<String> {
610 match Installed::of(marker)? {
611 Installed::Commit(commit) => Some(short(&commit).to_string()),
612 Installed::Version(version) => Some(version.to_string()),
613 }
614}
615
616#[derive(Debug, Clone, PartialEq, Eq)]
619pub enum Outcome {
620 NotDue,
623 Current,
624 Behind(Behind),
625 Failed(String),
626}
627
628pub async fn refresh(state: &Path, cfg: &UpdateConfig) -> Outcome {
636 if cfg.check == UpdateCheck::Off {
637 return Outcome::NotDue;
638 }
639 let Ok(Some(marker)) = InstallMarker::load(&state.join(MARKER_FILE)) else {
640 return Outcome::NotDue;
641 };
642 let Some(installed) = Installed::of(&marker) else {
643 return Outcome::NotDue;
644 };
645 let cache_path = state.join(CACHE_FILE);
646 let mut cache = UpdateCache::load(&cache_path);
647 let now = crate::session::now_ms() / 1000;
648 if !cache.is_due(cfg.check, now) {
649 return match behind(&marker, &cache) {
650 Some(b) => Outcome::Behind(b),
651 None => Outcome::NotDue,
652 };
653 }
654 cache.checked_at = now;
657 cache.save(&cache_path);
658 match ask_and_cache(state, cfg, &installed).await {
659 Ok(_) => match behind(&marker, &UpdateCache::load(&cache_path)) {
660 Some(b) => Outcome::Behind(b),
661 None => Outcome::Current,
662 },
663 Err(why) => Outcome::Failed(why),
664 }
665}
666
667async fn ask_and_cache(
670 state: &Path,
671 cfg: &UpdateConfig,
672 installed: &Installed,
673) -> std::result::Result<String, String> {
674 let latest = match installed {
675 Installed::Version(_) => fetch_release(cfg).await.map(|release| release.tag),
676 Installed::Commit(_) => fetch_latest(cfg).await,
677 }?;
678 let path = state.join(CACHE_FILE);
681 let mut cache = UpdateCache::load(&path);
682 cache.latest = Some(latest.clone());
683 cache.save(&path);
684 Ok(latest)
685}
686
687pub fn rfc3339_utc(ms: u64) -> String {
690 let secs = ms / 1000;
691 let (y, m, d) = crate::cron::civil_from_days((secs / 86_400) as i64);
692 let rem = secs % 86_400;
693 format!(
694 "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z",
695 rem / 3600,
696 (rem % 3600) / 60,
697 rem % 60
698 )
699}
700
701fn short(id: &str) -> &str {
702 id.get(..7).unwrap_or(id)
703}
704
705#[derive(Default)]
708pub struct Check {
709 pub notice: Option<String>,
711 pub badge: Option<Behind>,
714 refresh: Option<tokio::task::JoinHandle<()>>,
715}
716
717impl Check {
718 pub fn idle() -> Check {
720 Check::default()
721 }
722
723 pub fn start(env: EnvFn, cfg: &UpdateConfig) -> Check {
727 if cfg.check == UpdateCheck::Off {
728 return Check::idle();
729 }
730 let Some(state) = state_dir(env) else {
731 return Check::idle();
732 };
733 let Ok(Some(marker)) = InstallMarker::load(&state.join(MARKER_FILE)) else {
734 return Check::idle();
735 };
736 let Some(installed) = Installed::of(&marker) else {
737 return Check::idle();
738 };
739 let cache_path = state.join(CACHE_FILE);
740 let mut cache = UpdateCache::load(&cache_path);
741
742 let badge = behind(&marker, &cache);
746 let mut notice = None;
747 if let Some(behind) = &badge {
748 if cache.latest.as_deref() != cache.notified.as_deref() {
749 notice = Some(format!(
750 "a newer eclipse is available ({}, installed {}): run `eclipse upgrade` \
751 \u{2014} this notice is `[update] check`, set it to \"off\" to stop it",
752 behind.latest, behind.installed
753 ));
754 cache.notified = cache.latest.clone();
755 }
756 }
757
758 let now = crate::session::now_ms() / 1000;
759 let due = cache.is_due(cfg.check, now);
760 if due {
761 cache.checked_at = now;
762 }
763 if notice.is_some() || due {
764 cache.save(&cache_path);
765 }
766
767 let refresh = due.then(|| {
768 let cfg = cfg.clone();
769 let state = state.clone();
770 tokio::spawn(async move {
771 let _ = ask_and_cache(&state, &cfg, &installed).await;
772 })
773 });
774 Check {
775 notice,
776 badge,
777 refresh,
778 }
779 }
780
781 pub async fn finish(self) {
785 if let Some(handle) = self.refresh {
786 let _ = tokio::time::timeout(RELEASE_TIMEOUT, handle).await;
787 }
788 }
789}
790
791#[cfg(test)]
792mod tests {
793 use super::*;
794 use std::io::{Read, Write};
795 use std::sync::atomic::{AtomicUsize, Ordering};
796 use std::sync::Arc;
797
798 const OLD: &str = "1111111111111111111111111111111111111111";
799 const NEW: &str = "2222222222222222222222222222222222222222";
800
801 fn serve(body: &'static str) -> (String, Arc<AtomicUsize>) {
803 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
804 let url = format!("http://{}/latest", listener.local_addr().unwrap());
805 let hits = Arc::new(AtomicUsize::new(0));
806 let counted = hits.clone();
807 std::thread::spawn(move || {
808 while let Ok((mut s, _)) = listener.accept() {
809 counted.fetch_add(1, Ordering::SeqCst);
810 let mut buf = [0u8; 2048];
811 let _ = s.read(&mut buf);
812 let _ = write!(
813 s,
814 "HTTP/1.1 200 OK\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
815 body.len()
816 );
817 }
818 });
819 (url, hits)
820 }
821
822 fn dead_url() -> String {
824 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
825 let url = format!("http://{}/latest", listener.local_addr().unwrap());
826 drop(listener);
827 url
828 }
829
830 fn installed(remote: &str, check: UpdateCheck) -> (tempfile::TempDir, UpdateConfig) {
832 let home = tempfile::tempdir().unwrap();
833 let state = home.path().join(".eclipse/state");
834 std::fs::create_dir_all(&state).unwrap();
835 std::fs::write(
836 state.join(MARKER_FILE),
837 format!(
838 r#"{{"channel":"source","prefix":"/x","commit":"{OLD}","installed_at":"2026-01-01T00:00:00Z"}}"#
839 ),
840 )
841 .unwrap();
842 let cfg = UpdateConfig {
843 check,
844 track: Track::Release,
845 remote: Some(remote.to_string()),
846 releases: None,
847 };
848 (home, cfg)
849 }
850
851 fn env_of(home: &Path) -> impl Fn(&str) -> Option<String> {
852 let home = home.to_string_lossy().into_owned();
853 move |k| (k == "HOME").then(|| home.clone())
854 }
855
856 async fn one_run(home: &Path, cfg: &UpdateConfig) -> Option<String> {
857 let env = env_of(home);
858 let check = Check::start(&env, cfg);
859 let notice = check.notice.clone();
860 check.finish().await;
861 notice
862 }
863
864 #[tokio::test]
865 async fn the_latest_commit_is_asked_once_per_period_and_the_notice_is_said_once() {
866 let (url, hits) = serve(NEW);
867 let (home, cfg) = installed(&url, UpdateCheck::Daily);
868
869 assert_eq!(one_run(home.path(), &cfg).await, None);
871 assert_eq!(hits.load(Ordering::SeqCst), 1);
872
873 let line = one_run(home.path(), &cfg).await.expect("a notice");
875 assert!(
876 line.contains("2222222") && line.contains("eclipse upgrade"),
877 "{line}"
878 );
879 assert!(
880 line.contains("off"),
881 "it says how to turn itself off: {line}"
882 );
883 assert_eq!(
884 hits.load(Ordering::SeqCst),
885 1,
886 "one request across two runs"
887 );
888
889 assert_eq!(one_run(home.path(), &cfg).await, None);
891 assert_eq!(hits.load(Ordering::SeqCst), 1);
892 }
893
894 #[tokio::test]
895 async fn a_server_that_is_down_is_silent_and_is_not_asked_again_within_the_period() {
896 let (home, cfg) = installed(&dead_url(), UpdateCheck::Daily);
897 assert_eq!(one_run(home.path(), &cfg).await, None);
898 let cache = UpdateCache::load(&home.path().join(".eclipse/state").join(CACHE_FILE));
899 assert!(cache.checked_at > 0, "the attempt is recorded");
900 assert_eq!(cache.latest, None);
901 assert!(!cache.is_due(UpdateCheck::Daily, cache.checked_at + 60));
902 assert_eq!(one_run(home.path(), &cfg).await, None);
903 }
904
905 #[tokio::test]
906 async fn an_answer_that_is_not_a_commit_id_is_never_cached_as_one() {
907 let (url, hits) = serve("<html>captive portal</html>");
908 let (home, cfg) = installed(&url, UpdateCheck::Daily);
909 assert_eq!(one_run(home.path(), &cfg).await, None);
910 assert_eq!(hits.load(Ordering::SeqCst), 1);
911 let cache = UpdateCache::load(&home.path().join(".eclipse/state").join(CACHE_FILE));
912 assert_eq!(cache.latest, None);
913 }
914
915 #[tokio::test]
916 async fn check_off_makes_no_request_and_writes_nothing() {
917 let (url, hits) = serve(NEW);
918 let (home, cfg) = installed(&url, UpdateCheck::Off);
919 assert_eq!(one_run(home.path(), &cfg).await, None);
920 assert_eq!(hits.load(Ordering::SeqCst), 0);
921 assert!(!home.path().join(".eclipse/state").join(CACHE_FILE).exists());
922 }
923
924 #[tokio::test]
925 async fn a_run_with_no_install_marker_makes_no_request() {
926 let (url, hits) = serve(NEW);
927 let home = tempfile::tempdir().unwrap();
928 let cfg = UpdateConfig {
929 check: UpdateCheck::Daily,
930 track: Track::Release,
931 remote: Some(url),
932 releases: None,
933 };
934 assert_eq!(one_run(home.path(), &cfg).await, None);
935 assert_eq!(
936 hits.load(Ordering::SeqCst),
937 0,
938 "nothing to compare with, nothing asked"
939 );
940 }
941
942 #[test]
943 fn a_commit_id_is_read_from_a_bare_body_or_a_json_sha_and_nothing_else() {
944 assert_eq!(parse_latest(&format!("{NEW}\n")).as_deref(), Some(NEW));
945 assert_eq!(
946 parse_latest(&format!(
947 r#"{{"sha":"{}","commit":{{}}}}"#,
948 NEW.to_uppercase()
949 ))
950 .as_deref(),
951 Some(NEW)
952 );
953 for bad in ["", "main", "abc123", r#"{"sha":"nope"}"#, "<html></html>"] {
954 assert_eq!(parse_latest(bad), None, "{bad:?}");
955 }
956 }
957
958 #[test]
961 fn the_commit_question_follows_the_tracks_branch_unless_a_remote_was_set() {
962 let asked = |track, remote: Option<&str>| {
963 let cfg = UpdateConfig {
964 check: UpdateCheck::Daily,
965 track,
966 remote: remote.map(str::to_string),
967 releases: None,
968 };
969 latest_question(&cfg).0.to_string()
970 };
971 assert_eq!(asked(Track::Release, None), DEFAULT_LATEST_URL);
972 assert_eq!(
973 asked(Track::Develop, None),
974 DEVELOP_LATEST_URL,
975 "a develop checkout is asked about develop, never about main"
976 );
977 assert!(DEVELOP_LATEST_URL.ends_with("/commits/develop"));
978 for track in [Track::Release, Track::Develop] {
979 assert_eq!(
980 asked(track, Some("http://mirror/latest")),
981 "http://mirror/latest",
982 "an explicit remote wins on either track"
983 );
984 }
985 }
986
987 #[test]
988 fn a_marker_that_is_missing_is_none_and_one_that_is_broken_names_its_file() {
989 let dir = tempfile::tempdir().unwrap();
990 let path = dir.path().join(MARKER_FILE);
991 assert_eq!(InstallMarker::load(&path).unwrap(), None);
992 std::fs::write(
993 &path,
994 r#"{"channel":"carrier-pigeon","prefix":"/x","installed_at":"t"}"#,
995 )
996 .unwrap();
997 let err = InstallMarker::load(&path).unwrap_err().to_string();
998 assert!(
999 err.contains("install.json") && err.contains("carrier-pigeon"),
1000 "{err}"
1001 );
1002 }
1003
1004 #[test]
1005 fn a_marker_from_a_tarball_install_has_no_commit_and_no_checkout() {
1006 let dir = tempfile::tempdir().unwrap();
1007 let path = dir.path().join(MARKER_FILE);
1008 std::fs::write(
1009 &path,
1010 r#"{"channel":"source","prefix":"/p","workspace":null,"commit":null,"installed_at":"2026-01-01T00:00:00Z"}"#,
1011 )
1012 .unwrap();
1013 let m = InstallMarker::load(&path).unwrap().unwrap();
1014 assert_eq!((m.commit, m.workspace), (None, None));
1015 }
1016
1017 fn git(dir: &Path, args: &[&str]) -> String {
1018 let out = std::process::Command::new("git")
1019 .arg("-C")
1020 .arg(dir)
1021 .args(["-c", "user.name=t", "-c", "user.email=t@t"])
1022 .args(args)
1023 .output()
1024 .unwrap();
1025 assert!(out.status.success(), "git {args:?}: {out:?}");
1026 String::from_utf8_lossy(&out.stdout).trim().to_string()
1027 }
1028
1029 #[test]
1030 fn a_release_version_is_three_numbers_and_orders_by_them() {
1031 assert_eq!(
1032 Version::parse("v0.2.1"),
1033 Some(Version {
1034 major: 0,
1035 minor: 2,
1036 patch: 1
1037 })
1038 );
1039 assert_eq!(Version::parse(" 0.10.0 ").unwrap().to_string(), "0.10.0");
1040 assert!(Version::parse("v0.10.0") > Version::parse("v0.9.9"));
1041 assert!(Version::parse("v1.0.0") > Version::parse("v0.99.99"));
1042 for bad in [
1043 "",
1044 "v",
1045 "1",
1046 "1.2",
1047 "1.2.3.4",
1048 "v1.two.3",
1049 "main",
1050 "v0.2.1-rc1.x",
1051 ] {
1052 assert_eq!(Version::parse(bad), None, "{bad:?}");
1053 }
1054 }
1055
1056 #[test]
1057 fn a_release_answer_names_the_linux_tarball_and_its_sums_or_says_what_it_carries() {
1058 let body = format!(
1059 r#"{{
1060 "tag_name": "v0.3.0",
1061 "html_url": "https://example.invalid/releases/v0.3.0",
1062 "assets": [
1063 {{"name": "eclipse-v0.3.0-aarch64-apple-darwin.tar.gz", "browser_download_url": "https://x/mac"}},
1064 {{"name": "eclipse-v0.3.0-x86_64-unknown-linux-gnu.tar.gz", "browser_download_url": "https://x/linux"}},
1065 {{"name": "{SUMS_NAME}", "browser_download_url": "https://x/sums"}}
1066 ]
1067 }}"#
1068 );
1069 let release = parse_release(&body).expect("a release");
1070 assert_eq!(release.version.to_string(), "0.3.0");
1071 assert_eq!(release.tarball_url, "https://x/linux");
1072 assert_eq!(release.sums_url, "https://x/sums");
1073 assert_eq!(
1074 release.page.as_deref(),
1075 Some("https://example.invalid/releases/v0.3.0")
1076 );
1077
1078 let missing = parse_release(
1081 r#"{"tag_name":"v0.3.0","assets":[{"name":"eclipse-v0.3.0-aarch64-apple-darwin.tar.gz","browser_download_url":"https://x/mac"}]}"#,
1082 )
1083 .unwrap_err();
1084 assert!(
1085 missing.contains("no") && missing.contains("darwin"),
1086 "{missing}"
1087 );
1088
1089 let bad_tag = parse_release(r#"{"tag_name":"nightly","assets":[]}"#).unwrap_err();
1091 assert!(bad_tag.contains("nightly"), "{bad_tag}");
1092 }
1093
1094 fn installed_release(version: &str, url: &str) -> (tempfile::TempDir, UpdateConfig) {
1097 let home = tempfile::tempdir().unwrap();
1098 let state = home.path().join(".eclipse/state");
1099 std::fs::create_dir_all(&state).unwrap();
1100 std::fs::write(
1101 state.join(MARKER_FILE),
1102 format!(
1103 r#"{{"channel":"release","prefix":"/x","workspace":null,"commit":null,"installed_at":"2026-01-01T00:00:00Z","build":"release","version":"{version}"}}"#
1104 ),
1105 )
1106 .unwrap();
1107 let cfg = UpdateConfig {
1108 check: UpdateCheck::Daily,
1109 track: Track::Release,
1110 remote: None,
1111 releases: Some(url.to_string()),
1112 };
1113 (home, cfg)
1114 }
1115
1116 #[tokio::test]
1117 async fn a_release_install_is_told_about_a_newer_tag_by_version_and_only_once() {
1118 let body: &'static str = Box::leak(
1119 format!(
1120 r#"{{"tag_name":"v0.3.0","assets":[{{"name":"eclipse-v0.3.0{TARBALL_SUFFIX}","browser_download_url":"https://x/linux"}},{{"name":"{SUMS_NAME}","browser_download_url":"https://x/sums"}}]}}"#
1121 )
1122 .into_boxed_str(),
1123 );
1124 let (url, hits) = serve(body);
1125 let (home, cfg) = installed_release("0.2.0", &url);
1126
1127 assert_eq!(one_run(home.path(), &cfg).await, None);
1129 assert_eq!(hits.load(Ordering::SeqCst), 1);
1130 let line = one_run(home.path(), &cfg).await.expect("a notice");
1131 assert!(
1132 line.contains("v0.3.0") && line.contains("0.2.0") && line.contains("eclipse upgrade"),
1133 "{line}"
1134 );
1135 assert_eq!(one_run(home.path(), &cfg).await, None, "said once");
1136 assert_eq!(hits.load(Ordering::SeqCst), 1);
1137 }
1138
1139 #[tokio::test]
1140 async fn a_release_install_on_the_newest_tag_is_silent() {
1141 let body: &'static str = Box::leak(
1142 format!(
1143 r#"{{"tag_name":"v0.2.0","assets":[{{"name":"eclipse-v0.2.0{TARBALL_SUFFIX}","browser_download_url":"https://x/linux"}},{{"name":"{SUMS_NAME}","browser_download_url":"https://x/sums"}}]}}"#
1144 )
1145 .into_boxed_str(),
1146 );
1147 let (url, _hits) = serve(body);
1148 let (home, cfg) = installed_release("0.2.0", &url);
1149 assert_eq!(one_run(home.path(), &cfg).await, None);
1150 assert_eq!(one_run(home.path(), &cfg).await, None, "never a notice");
1151 }
1152
1153 #[tokio::test]
1154 async fn a_release_marker_with_no_version_asks_nothing() {
1155 let (url, hits) = serve("{}");
1156 let home = tempfile::tempdir().unwrap();
1157 let state = home.path().join(".eclipse/state");
1158 std::fs::create_dir_all(&state).unwrap();
1159 std::fs::write(
1160 state.join(MARKER_FILE),
1161 r#"{"channel":"release","prefix":"/x","installed_at":"t"}"#,
1162 )
1163 .unwrap();
1164 let cfg = UpdateConfig {
1165 check: UpdateCheck::Daily,
1166 track: Track::Release,
1167 remote: None,
1168 releases: Some(url),
1169 };
1170 assert_eq!(one_run(home.path(), &cfg).await, None);
1171 assert_eq!(hits.load(Ordering::SeqCst), 0);
1172 }
1173
1174 #[test]
1175 fn a_commit_the_install_already_contains_is_not_news_and_one_it_has_never_seen_is() {
1176 let repo = tempfile::tempdir().unwrap();
1177 git(repo.path(), &["init", "-q"]);
1178 git(repo.path(), &["commit", "-q", "--allow-empty", "-m", "one"]);
1179 let first = git(repo.path(), &["rev-parse", "HEAD"]);
1180 git(repo.path(), &["commit", "-q", "--allow-empty", "-m", "two"]);
1181 let second = git(repo.path(), &["rev-parse", "HEAD"]);
1182 let marker = InstallMarker {
1183 channel: Channel::Source,
1184 prefix: "/x".into(),
1185 workspace: Some(repo.path().to_path_buf()),
1186 commit: Some(second.clone()),
1187 installed_at: "t".into(),
1188 build: None,
1189 version: None,
1190 };
1191 assert!(!is_news(&marker, &second, &second));
1192 assert!(
1193 !is_news(&marker, &second, &first),
1194 "an older commit is not an update"
1195 );
1196 assert!(is_news(&marker, &first, &second), "a newer one is");
1197 assert!(
1198 is_news(&marker, &second, NEW),
1199 "so is one this checkout has never seen"
1200 );
1201 }
1202
1203 fn release_body(tag: &str) -> &'static str {
1205 Box::leak(
1206 format!(
1207 r#"{{"tag_name":"{tag}","assets":[{{"name":"eclipse-{tag}{TARBALL_SUFFIX}","browser_download_url":"https://x/linux"}},{{"name":"{SUMS_NAME}","browser_download_url":"https://x/sums"}}]}}"#
1208 )
1209 .into_boxed_str(),
1210 )
1211 }
1212
1213 async fn one_run_check(home: &Path, cfg: &UpdateConfig) -> (Option<String>, Option<Behind>) {
1215 let env = env_of(home);
1216 let check = Check::start(&env, cfg);
1217 let seen = (check.notice.clone(), check.badge.clone());
1218 check.finish().await;
1219 seen
1220 }
1221
1222 fn state_of(home: &Path) -> PathBuf {
1223 home.join(".eclipse/state")
1224 }
1225
1226 fn rewrite_marker_version(home: &Path, version: &str) {
1228 std::fs::write(
1229 state_of(home).join(MARKER_FILE),
1230 format!(
1231 r#"{{"channel":"release","prefix":"/x","installed_at":"2026-01-01T00:00:00Z","version":"{version}"}}"#
1232 ),
1233 )
1234 .unwrap();
1235 }
1236
1237 fn write_cache(home: &Path, latest: &str, checked_at: u64) {
1238 let cache = UpdateCache {
1239 checked_at,
1240 latest: Some(latest.to_string()),
1241 notified: None,
1242 };
1243 cache.save(&state_of(home).join(CACHE_FILE));
1244 }
1245
1246 fn now_secs() -> u64 {
1247 crate::session::now_ms() / 1000
1248 }
1249
1250 #[tokio::test]
1253 async fn the_badge_lasts_across_runs_while_the_notice_is_only_said_once() {
1254 let (url, hits) = serve(release_body("v0.3.0"));
1255 let (home, cfg) = installed_release("0.2.0", &url);
1256
1257 assert_eq!(one_run_check(home.path(), &cfg).await, (None, None));
1259 assert_eq!(hits.load(Ordering::SeqCst), 1);
1260
1261 let (notice, badge) = one_run_check(home.path(), &cfg).await;
1263 assert!(
1264 notice.expect("a notice").contains("v0.3.0"),
1265 "the notice still names the tag"
1266 );
1267 let badge = badge.expect("a badge");
1268 assert_eq!(badge.installed, "0.2.0");
1269 assert_eq!(
1270 badge.line(),
1271 "↑ 0.3.0 available · eclipse upgrade",
1272 "one version, without the tag's v"
1273 );
1274
1275 let (notice, badge) = one_run_check(home.path(), &cfg).await;
1277 assert_eq!(notice, None, "a notice happens once per answer");
1278 assert!(
1279 badge.is_some(),
1280 "a badge lasts as long as the install is behind"
1281 );
1282 assert_eq!(hits.load(Ordering::SeqCst), 1, "neither run asked again");
1283 }
1284
1285 #[tokio::test]
1287 async fn the_badge_clears_when_the_install_reaches_the_new_version() {
1288 let (url, _hits) = serve(release_body("v0.3.0"));
1289 let (home, cfg) = installed_release("0.2.0", &url);
1290 assert_eq!(one_run_check(home.path(), &cfg).await, (None, None));
1291 assert!(one_run_check(home.path(), &cfg).await.1.is_some());
1292
1293 rewrite_marker_version(home.path(), "0.3.0");
1294 let env = env_of(home.path());
1295 let watch = Watch::for_env(&env, &cfg).expect("a watch");
1296 assert_eq!(watch.read(), None, "the upgrade is what clears it");
1297 }
1298
1299 #[test]
1301 fn a_source_install_badges_the_short_commit_it_has_never_seen() {
1302 let marker = InstallMarker {
1303 channel: Channel::Source,
1304 prefix: "/x".into(),
1305 workspace: None,
1306 commit: Some(OLD.into()),
1307 installed_at: "t".into(),
1308 build: None,
1309 version: None,
1310 };
1311 let cache = UpdateCache {
1312 checked_at: 1,
1313 latest: Some(NEW.into()),
1314 notified: Some(NEW.into()),
1315 };
1316 let badge = behind(&marker, &cache).expect("a badge");
1317 assert_eq!(badge.installed, "1111111");
1318 assert_eq!(badge.line(), "↑ 2222222 available · eclipse upgrade");
1319 }
1320
1321 #[tokio::test]
1324 async fn check_off_produces_no_badge_even_from_a_cached_answer() {
1325 let (home, mut cfg) = installed_release("0.2.0", "http://127.0.0.1:1/latest");
1326 write_cache(home.path(), "v0.3.0", now_secs());
1327 cfg.check = UpdateCheck::Off;
1328
1329 let env = env_of(home.path());
1330 assert!(Watch::for_env(&env, &cfg).is_none(), "nothing to watch");
1331 assert_eq!(Check::start(&env, &cfg).badge, None);
1332
1333 let snapshot = Watch::at(state_of(home.path()), &cfg).snapshot(now_secs());
1335 assert!(
1336 !snapshot.behind,
1337 "the answer is there and must not be shown"
1338 );
1339 assert_eq!(snapshot.latest, None);
1340 }
1341
1342 #[test]
1345 fn a_snapshot_stops_claiming_an_answer_older_than_a_week() {
1346 let (home, cfg) = installed_release("0.2.0", "http://127.0.0.1:1/latest");
1347 let now = now_secs();
1348 write_cache(home.path(), "v0.3.0", now - STALE_AFTER_SECS - 60);
1349
1350 let snapshot = Watch::at(state_of(home.path()), &cfg).snapshot(now);
1351 assert!(!snapshot.behind, "eight days old is not a claim to make");
1352 assert_eq!(snapshot.installed.as_deref(), Some("0.2.0"));
1353 assert_eq!(
1354 snapshot.latest.as_deref(),
1355 Some("v0.3.0"),
1356 "the number is still reported, it is the claim that is withheld"
1357 );
1358 assert_eq!(snapshot.channel, Some(Channel::Release));
1359
1360 write_cache(home.path(), "v0.3.0", now - 3600);
1362 let fresh = Watch::at(state_of(home.path()), &cfg).snapshot(now);
1363 assert!(fresh.behind);
1364 assert_eq!(fresh.checked_at, now - 3600);
1365 }
1366
1367 #[tokio::test]
1370 async fn a_scheduled_refresh_writes_the_cache_and_asks_once_a_period() {
1371 let (url, hits) = serve(release_body("v0.3.0"));
1372 let (home, cfg) = installed_release("0.2.0", &url);
1373 let state = state_of(home.path());
1374
1375 match refresh(&state, &cfg).await {
1376 Outcome::Behind(badge) => assert_eq!(badge.latest, "v0.3.0"),
1377 other => panic!("expected a badge, got {other:?}"),
1378 }
1379 assert_eq!(hits.load(Ordering::SeqCst), 1);
1380 let cache = UpdateCache::load(&state.join(CACHE_FILE));
1381 assert!(cache.checked_at > 0, "the attempt is recorded");
1382 assert_eq!(cache.latest.as_deref(), Some("v0.3.0"));
1383
1384 assert!(matches!(refresh(&state, &cfg).await, Outcome::Behind(_)));
1386 assert_eq!(hits.load(Ordering::SeqCst), 1, "one request per period");
1387 assert_eq!(
1388 Watch::at(state.clone(), &cfg).read().map(|b| b.latest),
1389 Some("v0.3.0".to_string()),
1390 "and the CLI's reader sees exactly what the gateway wrote"
1391 );
1392 }
1393
1394 #[tokio::test]
1397 async fn a_refresh_that_fails_reports_it_and_records_the_attempt() {
1398 let (home, cfg) = installed_release("0.2.0", &dead_url());
1399 let state = state_of(home.path());
1400 match refresh(&state, &cfg).await {
1401 Outcome::Failed(why) => assert!(!why.is_empty(), "{why}"),
1402 other => panic!("expected a failure, got {other:?}"),
1403 }
1404 let cache = UpdateCache::load(&state.join(CACHE_FILE));
1405 assert!(cache.checked_at > 0, "a failure is still an attempt");
1406 assert_eq!(cache.latest, None);
1407 assert!(
1408 matches!(refresh(&state, &cfg).await, Outcome::NotDue),
1409 "and the next tick inside the period asks nothing"
1410 );
1411 }
1412}