1use std::io::Write;
14use std::path::Path;
15use std::process::{Command, Stdio};
16use std::sync::mpsc::{self, Receiver};
17use std::thread;
18use std::time::{Duration, Instant};
19
20use crate::remote::RemoteTarget;
21
22const RELEASES_URL: &str = "https://github.com/akivajp/rigtop/releases/download";
24const LATEST_URL: &str = "https://github.com/akivajp/rigtop/releases/latest";
26
27pub fn target_version() -> &'static str {
29 env!("CARGO_PKG_VERSION")
30}
31
32pub fn agent_is_older(agent_version: &str) -> bool {
35 match (
36 parse_version(agent_version),
37 parse_version(target_version()),
38 ) {
39 (Some(agent), Some(ours)) => agent < ours,
40 _ => false,
41 }
42}
43
44pub fn is_newer(version: &str) -> bool {
46 match (parse_version(version), parse_version(target_version())) {
47 (Some(other), Some(ours)) => other > ours,
48 _ => false,
49 }
50}
51
52fn parse_version(version: &str) -> Option<Vec<u64>> {
54 let core = version.split(['-', '+']).next()?;
55 core.split('.').map(|part| part.parse().ok()).collect()
56}
57
58fn agent_binary(agent_command: &str) -> Option<&str> {
61 agent_command
62 .split_whitespace()
63 .next()
64 .filter(|program| program.contains('/'))
65}
66
67fn shell_quote(text: &str) -> String {
69 format!("'{}'", text.replace('\'', r"'\''"))
70}
71
72pub fn update_script(version: &str, agent_command: &str) -> String {
75 script(version, agent_binary(agent_command))
76}
77
78pub fn self_update_script(version: &str, exe: &Path) -> String {
81 script(version, Some(&exe.to_string_lossy()))
82}
83
84fn script(version: &str, binary: Option<&str>) -> String {
86 let tag = shell_quote(&format!("v{version}"));
87 let url = shell_quote(&format!("{RELEASES_URL}/v{version}/install.sh"));
88 let find = match binary {
90 Some(path) => match path.strip_prefix("~/") {
91 Some(rest) => format!("bin=\"$HOME\"/{}", shell_quote(rest)),
92 None => format!("bin={}", shell_quote(path)),
93 },
94 None => "bin=$(command -v rigtop 2>/dev/null || true)\n\
96 [ -n \"$bin\" ] || [ ! -x \"$HOME/.cargo/bin/rigtop\" ] || bin=\"$HOME/.cargo/bin/rigtop\""
97 .to_owned(),
98 };
99 format!(
100 r#"set -eu
101{find}
102if [ -z "$bin" ] || [ ! -e "$bin" ]; then
103 echo "rigtop update: rigtop not found on this host" >&2
104 exit 1
105fi
106case "$bin" in
107 */.cargo/bin/*)
108 echo "rigtop update: $bin was installed with cargo; update it with: cargo install $(basename "$bin") --version {version} --locked" >&2
109 exit 1
110 ;;
111esac
112dir=$(dirname "$bin")
113if [ ! -w "$dir" ]; then
114 echo "rigtop update: $dir is not writable (a package manager's copy?); update it with the package manager or the .deb of v{version}" >&2
115 exit 1
116fi
117# Keep rigtop-gui only where it was installed.
118gui=--tui-only
119[ ! -x "$dir/rigtop-gui" ] || gui=
120script=$(mktemp)
121trap 'rm -f "$script"' EXIT
122if command -v curl >/dev/null 2>&1; then
123 curl -fsSL --retry 3 {url} -o "$script"
124elif command -v wget >/dev/null 2>&1; then
125 wget -q -O "$script" {url}
126else
127 echo "rigtop update: needs curl or wget" >&2
128 exit 1
129fi
130sh "$script" --version {tag} --bin-dir "$dir" $gui
131"#
132 )
133}
134
135pub fn unsupported_reason(os: &str) -> Option<String> {
138 os.starts_with("Windows").then(|| {
139 "on Windows, update rigtop there with `scoop update rigtop`, or with the zip \
140 from the releases page"
141 .to_owned()
142 })
143}
144
145pub fn self_update_unsupported() -> Option<String> {
148 cfg!(windows).then(|| {
149 "on Windows, quit rigtop and run `scoop update rigtop`, or replace it with the \
150 zip from the releases page"
151 .to_owned()
152 })
153}
154
155pub fn describe_self(version: &str) -> String {
157 format!(
158 "Update rigtop from {ours} to {version}? This downloads the v{version} release \
159 from GitHub, checks it and replaces the rigtop you are running (when it is in a \
160 directory you can write to; copies from cargo or a package manager are left \
161 alone). The new version runs after a restart.",
162 ours = target_version()
163 )
164}
165
166pub fn describe(host: &str, agent_version: &str) -> String {
168 format!(
169 "Update rigtop on {host} from {agent_version} to {version}? Over SSH, this \
170 downloads the v{version} release from GitHub, checks it and replaces the \
171 rigtop the agent runs (when it is in a directory you can write to; copies \
172 from cargo or a package manager are left alone). The connection then restarts.",
173 version = target_version()
174 )
175}
176
177pub struct UpdateJob {
179 result: Receiver<Result<String, String>>,
180}
181
182impl UpdateJob {
183 pub fn start(target: &RemoteTarget) -> Self {
185 let agent_command = target.args.last().cloned().unwrap_or_default();
186 let script = update_script(target_version(), &agent_command);
187 let mut args = target.args.clone();
189 if let Some(last) = args.last_mut() {
190 *last = "sh -s".to_owned();
191 }
192 Self::spawn(target.program.clone(), args, script)
193 }
194
195 pub fn start_self(version: &str, exe: &Path) -> Self {
199 let script = self_update_script(version, exe);
200 Self::spawn("sh".to_owned(), vec!["-s".to_owned()], script)
201 }
202
203 fn spawn(program: String, args: Vec<String>, script: String) -> Self {
204 let (tx, result) = mpsc::channel();
205 thread::Builder::new()
206 .name("rigtop-update".to_owned())
207 .spawn(move || {
208 let result = run_script(&program, &args, &script).map(|line| {
209 line.strip_prefix("rigtop install: done: ")
211 .map_or(line.clone(), str::to_owned)
212 });
213 let _ = tx.send(result);
214 })
215 .expect("spawn update thread");
216 Self { result }
217 }
218
219 pub fn poll(&self) -> Option<Result<String, String>> {
222 self.result.try_recv().ok()
223 }
224}
225
226pub const DEFAULT_CHECK_INTERVAL: Duration = Duration::from_secs(3600);
228
229pub struct ReleaseChecker {
231 interval: Duration,
232 next_check: Instant,
233 running: Option<Receiver<Result<String, String>>>,
234 newer: Option<String>,
236 fetch: fn() -> Result<String, String>,
237}
238
239impl ReleaseChecker {
240 pub fn new(interval: Duration) -> Self {
242 Self::with_fetch(interval, latest_release)
243 }
244
245 fn with_fetch(interval: Duration, fetch: fn() -> Result<String, String>) -> Self {
246 Self {
247 interval,
248 next_check: Instant::now(),
249 running: None,
250 newer: None,
251 fetch,
252 }
253 }
254
255 pub fn poll(&mut self) -> Option<&str> {
258 if let Some(running) = &self.running
259 && let Ok(result) = running.try_recv()
260 {
261 self.running = None;
262 if let Ok(version) = result
264 && is_newer(&version)
265 {
266 self.newer = Some(version);
267 }
268 }
269 if self.running.is_none() && Instant::now() >= self.next_check {
270 self.next_check = Instant::now() + self.interval;
271 let (tx, rx) = mpsc::channel();
272 let fetch = self.fetch;
273 let started = thread::Builder::new()
274 .name("rigtop-release-check".to_owned())
275 .spawn(move || {
276 let _ = tx.send(fetch());
277 });
278 if started.is_ok() {
279 self.running = Some(rx);
280 }
281 }
282 self.newer.as_deref()
283 }
284}
285
286pub fn latest_release() -> Result<String, String> {
289 let null = if cfg!(windows) { "NUL" } else { "/dev/null" };
290 let mut command = Command::new("curl");
291 command
292 .args([
293 "-fsSL",
294 "--max-time",
295 "30",
296 "-o",
297 null,
298 "-w",
299 "%{url_effective}",
300 ])
301 .arg(LATEST_URL)
302 .stdin(Stdio::null())
303 .stderr(Stdio::null());
304 #[cfg(windows)]
305 {
306 use std::os::windows::process::CommandExt;
307 command.creation_flags(0x0800_0000);
309 }
310 let output = command
311 .output()
312 .map_err(|err| format!("cannot run curl: {err}"))?;
313 if !output.status.success() {
314 return Err(format!("curl exited with {}", output.status));
315 }
316 version_from_release_url(&String::from_utf8_lossy(&output.stdout))
317 .ok_or_else(|| "no release found".to_owned())
318}
319
320fn version_from_release_url(url: &str) -> Option<String> {
322 let tag = url.trim().rsplit_once("/tag/")?.1;
323 let version = tag.strip_prefix('v')?;
324 parse_version(version).map(|_| version.to_owned())
325}
326
327fn run_script(program: &str, args: &[String], script: &str) -> Result<String, String> {
330 let mut command = Command::new(program);
331 command
332 .args(args)
333 .stdin(Stdio::piped())
334 .stdout(Stdio::piped())
335 .stderr(Stdio::piped());
336 #[cfg(windows)]
337 {
338 use std::os::windows::process::CommandExt;
339 command.creation_flags(0x0800_0000);
341 }
342 let mut child = command
343 .spawn()
344 .map_err(|err| format!("cannot start {program}: {err}"))?;
345 if let Some(mut stdin) = child.stdin.take() {
346 let _ = stdin.write_all(script.as_bytes());
348 }
349 let output = child
350 .wait_with_output()
351 .map_err(|err| format!("{program} failed: {err}"))?;
352 let last_line = |bytes: &[u8]| {
353 String::from_utf8_lossy(bytes)
354 .lines()
355 .rev()
356 .map(str::trim)
357 .find(|line| !line.is_empty())
358 .map(str::to_owned)
359 };
360 if output.status.success() {
361 Ok(last_line(&output.stdout).unwrap_or_else(|| "done".to_owned()))
362 } else {
363 Err(last_line(&output.stderr)
364 .or_else(|| last_line(&output.stdout))
365 .unwrap_or_else(|| format!("{program} exited with {}", output.status)))
366 }
367}
368
369#[cfg(test)]
370mod tests {
371 use super::*;
372
373 #[test]
374 fn versions_compare_by_number() {
375 assert_eq!(parse_version("0.10.1"), Some(vec![0, 10, 1]));
376 assert_eq!(parse_version("1.2.0-rc.1"), Some(vec![1, 2, 0]));
377 assert_eq!(parse_version(""), None);
378 assert!(agent_is_older("0.0.9"));
379 assert!(!agent_is_older(target_version()));
380 assert!(!agent_is_older("999.0.0"));
381 assert!(!agent_is_older(""), "unknown versions are not offered");
382 }
383
384 #[test]
385 fn newer_releases_are_found() {
386 assert_eq!(
387 version_from_release_url("https://github.com/akivajp/rigtop/releases/tag/v0.12.1\n"),
388 Some("0.12.1".to_owned())
389 );
390 assert_eq!(
391 version_from_release_url("https://github.com/akivajp/rigtop/releases"),
392 None
393 );
394 assert!(is_newer("999.0.0"));
395 assert!(!is_newer(target_version()));
396
397 let mut checker =
398 ReleaseChecker::with_fetch(Duration::from_secs(3600), || Ok("999.0.0".to_owned()));
399 let mut found = None;
401 for _ in 0..100 {
402 if let Some(version) = checker.poll() {
403 found = Some(version.to_owned());
404 break;
405 }
406 thread::sleep(Duration::from_millis(10));
407 }
408 assert_eq!(found.as_deref(), Some("999.0.0"));
409
410 let mut checker = ReleaseChecker::with_fetch(Duration::from_secs(3600), || {
411 Ok(target_version().to_owned())
412 });
413 checker.poll();
414 thread::sleep(Duration::from_millis(50));
415 assert!(checker.poll().is_none(), "the same version is not news");
416 }
417
418 #[test]
420 #[ignore]
421 fn latest_release_from_github() {
422 let version = latest_release().unwrap();
423 assert!(parse_version(&version).is_some(), "{version}");
424 }
425
426 #[test]
427 fn self_update_script_targets_the_running_program() {
428 let script = self_update_script("1.2.3", Path::new("/home/me/.local/bin/rigtop-gui"));
429 assert!(script.contains("bin='/home/me/.local/bin/rigtop-gui'"));
430 }
431
432 #[test]
433 fn windows_hosts_get_directions_instead() {
434 assert!(unsupported_reason("Windows 11 Pro").is_some());
435 assert!(unsupported_reason("Linux (Ubuntu 24.04)").is_none());
436 }
437
438 #[test]
439 fn script_uses_the_agent_command_path() {
440 assert!(update_script("1.2.3", "rigtop --agent").contains("command -v rigtop"));
441 let script = update_script("1.2.3", "/opt/my rig/rigtop --agent");
442 assert!(script.contains("bin='/opt/my'"));
444 let script = update_script("1.2.3", "~/bin/rigtop --agent");
445 assert!(script.contains(r#"bin="$HOME"/'bin/rigtop'"#));
446 assert!(
447 script.contains(
448 "'https://github.com/akivajp/rigtop/releases/download/v1.2.3/install.sh'"
449 )
450 );
451 assert!(script.contains("--version 'v1.2.3'"));
452 }
453
454 #[cfg(unix)]
457 #[test]
458 fn script_installs_next_to_the_running_rigtop() {
459 use std::fs;
460 use std::os::unix::fs::PermissionsExt;
461
462 let tmp = tempfile::tempdir().unwrap();
463 let bin = tmp.path().join("bin");
464 let tools = tmp.path().join("tools");
465 fs::create_dir_all(&bin).unwrap();
466 fs::create_dir_all(&tools).unwrap();
467 let executable = |path: &std::path::Path, text: &str| {
468 fs::write(path, text).unwrap();
469 fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap();
470 };
471 executable(&bin.join("rigtop"), "#!/bin/sh\n");
472 executable(
474 &tools.join("curl"),
475 "#!/bin/sh\nwhile [ $# -gt 1 ]; do [ \"$1\" = -o ] && out=$2; shift; done\n\
476 printf 'echo installed \"$@\"\\n' > \"$out\"\n",
477 );
478 let path = format!("{}:{}:/usr/bin:/bin", bin.display(), tools.display());
479 let run = |script: &str| {
480 run_script(
481 "env",
482 &[format!("PATH={path}"), "sh".to_owned(), "-s".to_owned()],
483 script,
484 )
485 };
486
487 let output = run(&update_script("1.2.3", "rigtop --agent")).unwrap();
488 assert_eq!(
489 output,
490 format!(
491 "installed --version v1.2.3 --bin-dir {} --tui-only",
492 bin.display()
493 )
494 );
495
496 fs::set_permissions(&bin, fs::Permissions::from_mode(0o555)).unwrap();
498 let result = run(&update_script("1.2.3", "rigtop --agent"));
499 fs::set_permissions(&bin, fs::Permissions::from_mode(0o755)).unwrap();
500 if let Err(error) = result {
502 assert!(error.contains("is not writable"), "{error}");
503 }
504
505 let cargo = tmp.path().join(".cargo/bin");
507 fs::create_dir_all(&cargo).unwrap();
508 executable(&cargo.join("rigtop"), "#!/bin/sh\n");
509 let command = format!("{}/rigtop --agent", cargo.display());
510 let error = run(&update_script("1.2.3", &command)).unwrap_err();
511 assert!(
512 error.contains("cargo install rigtop --version 1.2.3"),
513 "{error}"
514 );
515
516 executable(&bin.join("rigtop-gui"), "#!/bin/sh\n");
518 let output = run(&self_update_script("1.2.3", &bin.join("rigtop-gui"))).unwrap();
519 assert_eq!(
520 output,
521 format!("installed --version v1.2.3 --bin-dir {}", bin.display())
522 );
523
524 let error = run(&update_script("1.2.3", "/nowhere/rigtop --agent")).unwrap_err();
525 assert!(error.contains("not found"), "{error}");
526 }
527}