blyte_cli/
update_notice.rs1use std::path::Path;
2use std::time::{Duration, SystemTime, UNIX_EPOCH};
3
4use serde::{Deserialize, Serialize};
5
6use crate::{registry, update};
7
8const DAY_SECS: u64 = 86_400;
9
10#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
11pub struct Cache {
12 pub checked_at: u64,
13 pub tag: Option<String>,
14 pub summary: Option<String>,
15 pub error: Option<String>,
16}
17
18pub fn summarize(body: &str) -> String {
19 let bullets: Vec<String> = body
20 .lines()
21 .filter_map(|l| l.trim().strip_prefix("- "))
22 .map(|b| b.replace("**", ""))
23 .collect();
24 if bullets.is_empty() {
25 return String::new();
26 }
27 let joined = bullets.join("; ");
28 if joined.len() > 200 {
29 let mut end = 200;
30 while !joined.is_char_boundary(end) {
31 end -= 1;
32 }
33 format!("{}…", &joined[..end])
34 } else {
35 joined
36 }
37}
38
39pub fn notice_line(current: &str, tag: &str, summary: &str) -> Option<String> {
40 let current_ver = update::parse_version(current)?;
41 let tag_ver = update::parse_version(tag)?;
42 if tag_ver <= current_ver {
43 return None;
44 }
45 let ver = tag.trim().strip_prefix('v').unwrap_or(tag.trim());
46 if summary.is_empty() {
47 Some(format!(
48 "blyte: {ver} is out (you have {current}). Run `blyte update`."
49 ))
50 } else {
51 Some(format!(
52 "blyte: {ver} is out (you have {current}): {summary}. Run `blyte update`."
53 ))
54 }
55}
56
57pub fn check(
58 state_dir: &Path,
59 current: &str,
60 now: u64,
61 fetch: impl FnOnce() -> Result<(String, String), String>,
62) -> Vec<String> {
63 let path = state_dir.join("latest-release.json");
64 let cached: Option<Cache> = std::fs::read_to_string(&path)
65 .ok()
66 .and_then(|s| serde_json::from_str(&s).ok());
67
68 if let Some(c) = &cached {
69 if now.saturating_sub(c.checked_at) < DAY_SECS {
70 let mut lines = Vec::new();
71 if let Some(tag) = c.tag.as_deref() {
72 let summary = c.summary.as_deref().unwrap_or("");
73 if let Some(line) = notice_line(current, tag, summary) {
74 lines.push(line);
75 }
76 }
77 return lines;
78 }
79 }
80
81 let prev_tag = cached.as_ref().and_then(|c| c.tag.clone());
82 let prev_summary = cached.as_ref().and_then(|c| c.summary.clone());
83
84 let fetched = fetch().and_then(|(tag, body)| {
85 if update::parse_version(&tag).is_none() {
86 Err(format!("unexpected tag {tag}"))
87 } else {
88 Ok((tag, body))
89 }
90 });
91
92 let mut lines = Vec::new();
93 let new_cache = match fetched {
94 Ok((tag, body)) => {
95 let summary = summarize(&body);
96 if let Some(line) = notice_line(current, &tag, &summary) {
97 lines.push(line);
98 }
99 Cache {
100 checked_at: now,
101 tag: Some(tag),
102 summary: Some(summary),
103 error: None,
104 }
105 }
106 Err(e) => {
107 lines.push(format!("blyte: could not check for a newer release: {e}"));
108 if let Some(tag) = prev_tag.as_deref() {
109 let summary = prev_summary.as_deref().unwrap_or("");
110 if let Some(line) = notice_line(current, tag, summary) {
111 lines.push(line);
112 }
113 }
114 Cache {
115 checked_at: now,
116 tag: prev_tag,
117 summary: prev_summary,
118 error: Some(e),
119 }
120 }
121 };
122
123 if let Err(e) = write_cache(state_dir, &path, &new_cache) {
124 lines.push(format!(
125 "blyte: could not save the release check to {}: {e}",
126 path.display()
127 ));
128 }
129
130 lines
131}
132
133fn write_cache(state_dir: &Path, path: &Path, cache: &Cache) -> std::io::Result<()> {
134 std::fs::create_dir_all(state_dir)?;
135 let json = serde_json::to_string(cache).map_err(std::io::Error::other)?;
136 std::fs::write(path, json)
137}
138
139pub fn print_notice() {
140 if std::env::var_os("BLYTE_NO_UPDATE_CHECK").is_some_and(|v| !v.is_empty()) {
141 return;
142 }
143 let Some(state_dir) = registry::state_dir() else {
144 eprintln!(
145 "blyte: could not check for a newer release: no state directory (set HOME or BLYTE_STATE_DIR)"
146 );
147 return;
148 };
149 let version = env!("CARGO_PKG_VERSION");
150 let now = match SystemTime::now().duration_since(UNIX_EPOCH) {
151 Ok(d) => d.as_secs(),
152 Err(e) => {
153 eprintln!("blyte: could not check for a newer release: system clock: {e}");
154 return;
155 }
156 };
157 let lines = check(&state_dir, version, now, || fetch_latest_release(version));
158 for line in lines {
159 eprintln!("{line}");
160 }
161}
162
163fn fetch_latest_release(version: &str) -> Result<(String, String), String> {
164 let url = format!(
165 "https://api.github.com/repos/{}/releases/latest",
166 update::REPO
167 );
168 let agent = ureq::AgentBuilder::new()
169 .timeout(Duration::from_secs(3))
170 .build();
171 let resp = match agent
172 .get(&url)
173 .set("User-Agent", &format!("blyte/{version}"))
174 .set("Accept", "application/vnd.github+json")
175 .call()
176 {
177 Ok(r) => r,
178 Err(ureq::Error::Status(code, _)) => return Err(format!("HTTP {code}")),
179 Err(ureq::Error::Transport(t)) => return Err(t.to_string()),
180 };
181 if resp.status() != 200 {
182 return Err(format!("HTTP {}", resp.status()));
183 }
184 let json: serde_json::Value = resp.into_json().map_err(|e| e.to_string())?;
185 let tag_name = json
186 .get("tag_name")
187 .and_then(|v| v.as_str())
188 .ok_or_else(|| "missing tag_name".to_string())?
189 .to_string();
190 let body = json
191 .get("body")
192 .and_then(|v| v.as_str())
193 .unwrap_or("")
194 .to_string();
195 Ok((tag_name, body))
196}