1use std::path::{Path, PathBuf};
12use std::process::Command;
13use std::time::Duration;
14
15pub const REPO: &str = match parse_repo(env!("CARGO_PKG_REPOSITORY")) {
18 Some(repo) => repo,
19 None => panic!(concat!(
20 "the build's repository field is not a GitHub URL: ",
21 env!("CARGO_PKG_REPOSITORY")
22 )),
23};
24
25pub const fn repo() -> &'static str {
27 REPO
28}
29
30pub const fn parse_repo(url: &str) -> Option<&str> {
34 let bytes = url.as_bytes();
35 let prefix = b"https://github.com/";
36 if bytes.len() < prefix.len() {
37 return None;
38 }
39 let mut i = 0;
40 while i < prefix.len() {
41 if bytes[i] != prefix[i] {
42 return None;
43 }
44 i += 1;
45 }
46
47 let mut end = bytes.len();
48 while end > prefix.len() && bytes[end - 1] == b'/' {
49 end -= 1;
50 }
51 if end >= prefix.len() + 4
52 && bytes[end - 4] == b'.'
53 && bytes[end - 3] == b'g'
54 && bytes[end - 2] == b'i'
55 && bytes[end - 1] == b't'
56 {
57 end -= 4;
58 while end > prefix.len() && bytes[end - 1] == b'/' {
59 end -= 1;
60 }
61 }
62
63 let start = prefix.len();
64 if end <= start {
65 return None;
66 }
67
68 let mut slash_count = 0;
69 let mut j = start;
70 let mut slash_idx = 0;
71 while j < end {
72 let b = bytes[j];
73 if b == b'/' {
74 slash_count += 1;
75 slash_idx = j;
76 } else if b.is_ascii_whitespace() {
77 return None;
78 }
79 j += 1;
80 }
81
82 if slash_count != 1 || slash_idx == start || slash_idx == end - 1 {
83 return None;
84 }
85
86 let (_, tail) = match bytes.split_at_checked(start) {
87 Some(pair) => pair,
88 None => return None,
89 };
90 let (target, _) = match tail.split_at_checked(end - start) {
91 Some(pair) => pair,
92 None => return None,
93 };
94 match std::str::from_utf8(target) {
95 Ok(s) => Some(s),
96 Err(_) => None,
97 }
98}
99
100pub fn asset_name() -> Option<&'static str> {
102 match (std::env::consts::OS, std::env::consts::ARCH) {
103 ("macos", "aarch64") => Some("blyte-aarch64-apple-darwin"),
104 ("macos", "x86_64") => Some("blyte-x86_64-apple-darwin"),
105 ("linux", "x86_64") => Some("blyte-x86_64-unknown-linux-musl"),
106 _ => None,
107 }
108}
109
110pub fn parse_version(s: &str) -> Option<(u64, u64, u64)> {
112 let mut parts = s.trim().trim_start_matches('v').split('.');
113 let v = (
114 parts.next()?.parse().ok()?,
115 parts.next()?.parse().ok()?,
116 parts
117 .next()?
118 .split(|c: char| !c.is_ascii_digit())
119 .next()?
120 .parse()
121 .ok()?,
122 );
123 Some(v)
124}
125
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128pub enum InstallMethod {
129 Cargo,
130 Binary,
131}
132
133const CRATES_IO_GIT_SOURCE: &str = "(registry+https://github.com/rust-lang/crates.io-index)";
134const CRATES_IO_SPARSE_SOURCE: &str = "(sparse+https://index.crates.io/)";
135
136pub fn install_method(exe: &Path, cargo_home: Option<&Path>) -> Result<InstallMethod, String> {
138 let Some(cargo_home) = cargo_home else {
139 return Ok(InstallMethod::Binary);
140 };
141 let Ok(canon_exe) = exe.canonicalize() else {
142 return Ok(InstallMethod::Binary);
143 };
144 let cargo_bin = cargo_home.join("bin").join("blyte");
145 let Ok(canon_cargo_bin) = cargo_bin.canonicalize() else {
146 return Ok(InstallMethod::Binary);
147 };
148 if canon_exe != canon_cargo_bin {
149 return Ok(InstallMethod::Binary);
150 }
151
152 let crates2 = cargo_home.join(".crates2.json");
153 let text = match std::fs::read_to_string(&crates2) {
154 Ok(t) => t,
155 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
156 return Err(format!(
157 "blyte is in {} but {} is missing, so how it was installed is unknown",
158 cargo_home.join("bin").display(),
159 crates2.display()
160 ));
161 }
162 Err(e) => {
163 return Err(format!("could not read {}: {e}", crates2.display()));
164 }
165 };
166 let json: serde_json::Value = serde_json::from_str(&text)
167 .map_err(|e| format!("could not parse {}: {e}", crates2.display()))?;
168 let installs = json
169 .get("installs")
170 .and_then(|v| v.as_object())
171 .ok_or_else(|| format!("{} has no installs object", crates2.display()))?;
172 let Some(key) = installs.keys().find(|k| k.starts_with("blyte ")) else {
173 return Err(format!(
174 "{} does not list blyte, so how it was installed is unknown",
175 crates2.display()
176 ));
177 };
178 if key.ends_with(CRATES_IO_GIT_SOURCE) || key.ends_with(CRATES_IO_SPARSE_SOURCE) {
179 return Ok(InstallMethod::Cargo);
180 }
181 let source = key
182 .split_once('(')
183 .and_then(|(_, rest)| rest.strip_suffix(')'))
184 .unwrap_or(key.as_str());
185 Err(format!(
186 "blyte was installed by cargo from {source}; update it with the cargo install command you used"
187 ))
188}
189
190fn cargo_home() -> Option<PathBuf> {
191 if let Some(dir) = std::env::var_os("CARGO_HOME").filter(|v| !v.is_empty()) {
192 return Some(PathBuf::from(dir));
193 }
194 std::env::var_os("HOME")
195 .filter(|v| !v.is_empty())
196 .map(|h| PathBuf::from(h).join(".cargo"))
197}
198
199fn api_base() -> String {
200 match std::env::var("BLYTE_UPDATE_API") {
201 Ok(v) if !v.is_empty() => v.trim_end_matches('/').to_string(),
202 _ => "https://api.github.com".to_string(),
203 }
204}
205
206fn download_base() -> String {
207 match std::env::var("BLYTE_UPDATE_DOWNLOAD") {
208 Ok(v) if !v.is_empty() => v.trim_end_matches('/').to_string(),
209 _ => "https://github.com".to_string(),
210 }
211}
212
213fn cargo_bin() -> String {
214 match std::env::var("BLYTE_CARGO") {
215 Ok(v) if !v.is_empty() => v,
216 _ => "cargo".to_string(),
217 }
218}
219
220fn latest_tag() -> Result<String, String> {
221 let repo = repo();
222 let url = format!("{}/repos/{repo}/releases/latest", api_base());
223 let agent = ureq::AgentBuilder::new()
224 .timeout(Duration::from_secs(30))
225 .build();
226 let resp = agent
227 .get(&url)
228 .set("User-Agent", "blyte")
229 .call()
230 .map_err(|e| format!("could not read the latest release of {repo}: {e}"))?;
231 let body: serde_json::Value = resp
232 .into_json()
233 .map_err(|e| format!("could not read the latest release of {repo}: {e}"))?;
234 let tag = body
235 .get("tag_name")
236 .and_then(|v| v.as_str())
237 .ok_or_else(|| format!("the latest release of {repo} has no tag_name"))?
238 .trim()
239 .to_string();
240 if parse_version(&tag).is_none() {
241 return Err(format!("unexpected release tag: {tag:?}"));
242 }
243 Ok(tag)
244}
245
246fn download_release(repo: &str, tag: &str, asset: &str, tmp: &Path) -> Result<(), String> {
247 let url = format!("{}/{repo}/releases/download/{tag}/{asset}", download_base());
248 let agent = ureq::AgentBuilder::new()
249 .timeout_connect(Duration::from_secs(30))
250 .timeout_read(Duration::from_secs(600))
251 .build();
252 let resp = match agent.get(&url).set("User-Agent", "blyte").call() {
253 Ok(r) => r,
254 Err(e) => {
255 let _ = std::fs::remove_file(tmp);
256 return Err(format!("download failed: {e}"));
257 }
258 };
259 let mut reader = resp.into_reader();
260 let mut file = match std::fs::File::create(tmp) {
261 Ok(f) => f,
262 Err(e) => {
263 let _ = std::fs::remove_file(tmp);
264 return Err(format!("download failed: {e}"));
265 }
266 };
267 if let Err(e) = std::io::copy(&mut reader, &mut file) {
268 drop(file);
269 let _ = std::fs::remove_file(tmp);
270 return Err(format!("download failed: {e}"));
271 }
272 Ok(())
273}
274
275fn current_exe() -> Result<PathBuf, String> {
278 let exe = std::env::current_exe()
279 .and_then(|p| p.canonicalize())
280 .map_err(|e| format!("cannot find this blyte binary: {e}"))?;
281 Ok(if exe.file_name().is_some_and(|n| n == "blyte.prev") {
282 exe.with_file_name("blyte")
283 } else {
284 exe
285 })
286}
287
288fn prev_path(exe: &Path) -> PathBuf {
289 exe.with_file_name("blyte.prev")
290}
291
292fn version_of(bin: &Path) -> Result<String, String> {
293 let out = Command::new(bin)
294 .arg("--version")
295 .output()
296 .map_err(|e| format!("failed to run --version: {e}"))?;
297 if !out.status.success() {
298 let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
299 if stderr.is_empty() {
300 return Err(format!("--version exited with {}", out.status));
301 }
302 return Err(format!("--version exited with {}: {stderr}", out.status));
303 }
304 let ver = String::from_utf8_lossy(&out.stdout).trim().to_string();
305 if ver.is_empty() {
306 return Err("--version produced empty output".to_string());
307 }
308 Ok(ver)
309}
310
311pub fn rollback(exe: &Path) -> Result<String, String> {
313 let prev = prev_path(exe);
314 if !prev.is_file() {
315 return Err(format!(
316 "no previous build to roll back to ({} is missing)",
317 prev.display()
318 ));
319 }
320 let swap = exe.with_file_name(".blyte-swap");
321 std::fs::rename(exe, &swap).map_err(|e| format!("rollback failed: {e}"))?;
322 std::fs::rename(&prev, exe).map_err(|e| format!("rollback failed: {e}"))?;
323 std::fs::rename(&swap, &prev).map_err(|e| format!("rollback failed: {e}"))?;
324 version_of(exe).map_err(|e| {
325 format!(
326 "rollback binary at {} could not be verified: {e}",
327 exe.display()
328 )
329 })
330}
331
332pub fn refresh_skills(new_exe: &Path, home: &Path) -> Vec<String> {
334 let mut lines = Vec::new();
335
336 struct HarnessConfig {
337 name: &'static str,
338 skill_dirs: Vec<PathBuf>,
339 instructions_file: PathBuf,
340 install_args: Vec<&'static str>,
341 }
342
343 let harnesses = [
344 HarnessConfig {
345 name: "Claude Code",
346 skill_dirs: vec![home.join(".claude/skills/blyte-implementer")],
347 instructions_file: home.join(".claude/CLAUDE.md"),
348 install_args: vec!["skill", "install", "--force"],
349 },
350 HarnessConfig {
351 name: "Codex",
352 skill_dirs: vec![
353 home.join(".agents/skills/blyte-implementer"),
354 home.join(".codex/skills/blyte-implementer"),
355 ],
356 instructions_file: home.join(".codex/AGENTS.md"),
357 install_args: vec!["skill", "install", "--force", "--harness", "codex"],
358 },
359 ];
360
361 for harness in harnesses {
362 let existing_skills: Vec<(PathBuf, PathBuf)> = harness
363 .skill_dirs
364 .iter()
365 .map(|d| (d.join("SKILL.md"), d.join(".blyte-installed")))
366 .filter(|(s, _)| s.exists())
367 .collect();
368
369 if existing_skills.is_empty() {
370 continue;
371 }
372
373 let mut first_edited: Option<PathBuf> = None;
374 for (skill_file, installed_file) in &existing_skills {
375 let is_unedited = match std::fs::read_to_string(skill_file) {
376 Ok(skill_text) => {
377 if installed_file.exists() {
378 std::fs::read_to_string(installed_file)
379 .map(|inst_text| inst_text == skill_text)
380 .unwrap_or(false)
381 } else {
382 skill_text == crate::skill::SKILL_MD
383 }
384 }
385 Err(_) => false,
386 };
387
388 if !is_unedited {
389 first_edited = Some(skill_file.clone());
390 break;
391 }
392 }
393
394 if let Some(edited_path) = first_edited {
395 lines.push(format!(
396 "skill not refreshed for {}: {} has been edited (run blyte skill install --force to replace it)",
397 harness.name,
398 edited_path.display()
399 ));
400 } else {
401 let default_on = std::fs::read_to_string(&harness.instructions_file)
402 .map(|t| t.contains("<!-- blyte:default -->"))
403 .unwrap_or(false);
404
405 let mut args = harness.install_args.clone();
406 if !default_on {
407 args.push("--no-default");
408 }
409
410 let out = Command::new(new_exe).args(&args).env("HOME", home).output();
411
412 match out {
413 Ok(o) if o.status.success() => {
414 lines.push(format!("skill refreshed for {}", harness.name));
415 for line in String::from_utf8_lossy(&o.stdout).lines() {
416 if line.starts_with("auto-compact:") {
417 lines.push(line.to_string());
418 }
419 }
420 }
421 Ok(o) => {
422 let stderr = String::from_utf8_lossy(&o.stderr);
423 let cause = stderr.lines().rev().map(str::trim).find(|l| !l.is_empty());
424 match cause {
425 Some(c) => lines.push(format!(
426 "skill not refreshed for {}: blyte skill install failed; run it by hand ({c})",
427 harness.name
428 )),
429 None => lines.push(format!(
430 "skill not refreshed for {}: blyte skill install failed; run it by hand",
431 harness.name
432 )),
433 }
434 }
435 Err(e) => {
436 lines.push(format!(
437 "skill not refreshed for {}: blyte skill install failed; run it by hand ({e})",
438 harness.name
439 ));
440 }
441 }
442 }
443 }
444
445 lines
446}
447
448fn update(check: bool) -> Result<(), String> {
449 let current = env!("CARGO_PKG_VERSION");
450 let tag = latest_tag()?;
451 let (now, latest) = (parse_version(current), parse_version(&tag));
452 println!(
453 "installed: blyte {current}\nlatest: blyte {}",
454 tag.trim_start_matches('v')
455 );
456 if latest <= now {
457 println!("blyte is up to date");
458 return Ok(());
459 }
460 if check {
461 println!("run `blyte update` to install it");
462 return Ok(());
463 }
464 let exe = current_exe()?;
465 let prev = prev_path(&exe);
466 let method = install_method(&exe, cargo_home().as_deref())?;
467 let new_version = match method {
468 InstallMethod::Cargo => {
469 std::fs::copy(&exe, &prev)
470 .map_err(|e| format!("could not keep the previous build: {e}"))?;
471 let status = Command::new(cargo_bin())
472 .args(["install", "blyte", "--locked"])
473 .status()
474 .map_err(|e| format!("could not run cargo: {e}"))?;
475 if !status.success() {
476 return Err("cargo install blyte --locked failed".to_string());
477 }
478 version_of(&exe)?
479 }
480 InstallMethod::Binary => {
481 let repo = repo();
482 let asset = asset_name().ok_or_else(|| {
483 format!(
484 "no release binary for {}-{}; build it with `cargo install --git https://github.com/{repo} blyte`",
485 std::env::consts::OS,
486 std::env::consts::ARCH
487 )
488 })?;
489 let tmp = exe.with_file_name(format!(".blyte-update-{}", std::process::id()));
490 download_release(repo, &tag, asset, &tmp)?;
491 #[cfg(unix)]
492 {
493 use std::os::unix::fs::PermissionsExt;
494 std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755))
495 .map_err(|e| format!("could not make the download executable: {e}"))?;
496 }
497 let Ok(new_version) = version_of(&tmp) else {
498 let _ = std::fs::remove_file(&tmp);
499 return Err(
500 "the downloaded binary does not run; the installed blyte is unchanged".into(),
501 );
502 };
503 std::fs::copy(&exe, &prev)
504 .map_err(|e| format!("could not keep the previous build: {e}"))?;
505 std::fs::rename(&tmp, &exe)
506 .map_err(|e| format!("could not replace {}: {e}", exe.display()))?;
507 new_version
508 }
509 };
510 println!(
511 "updated to {new_version}; the previous build is kept as {}",
512 prev.display()
513 );
514 println!("`blyte update --rollback` restores it");
515 if let Some(home) = std::env::var_os("HOME").map(PathBuf::from) {
516 for line in refresh_skills(&exe, &home) {
517 println!("{line}");
518 }
519 if !home.as_os_str().is_empty() {
520 crate::skill::warn_superseded(&home);
521 }
522 }
523 Ok(())
524}
525
526pub fn run(check: bool, rollback_requested: bool) -> i32 {
528 let result = if rollback_requested {
529 current_exe()
530 .and_then(|exe| rollback(&exe))
531 .map(|v| println!("rolled back to {v}"))
532 } else {
533 update(check)
534 };
535 match result {
536 Ok(()) => 0,
537 Err(e) => {
538 eprintln!("error: {e}");
539 1
540 }
541 }
542}
543
544#[cfg(test)]
545mod tests {
546 use super::*;
547
548 #[test]
549 fn parser_maps_github_urls_and_rejects_non_github() {
550 assert_eq!(
551 parse_repo("https://github.com/acme/blyte"),
552 Some("acme/blyte")
553 );
554 assert_eq!(
555 parse_repo("https://github.com/acme/blyte/"),
556 Some("acme/blyte")
557 );
558 assert_eq!(
559 parse_repo("https://github.com/acme/blyte.git"),
560 Some("acme/blyte")
561 );
562 assert_eq!(parse_repo("https://gitlab.com/acme/blyte"), None);
563 assert_eq!(repo(), parse_repo(env!("CARGO_PKG_REPOSITORY")).unwrap());
564 }
565
566 #[cfg(unix)]
567 #[test]
568 fn rollback_errors_when_version_check_fails() {
569 use std::os::unix::fs::PermissionsExt;
570
571 let dir = tempfile::tempdir().unwrap();
572 let exe = dir.path().join("blyte");
573 let prev = dir.path().join("blyte.prev");
574 std::fs::write(&exe, "#!/bin/sh\necho 'blyte 2.0.0'\n").unwrap();
575 std::fs::write(&prev, "#!/bin/sh\nexit 1\n").unwrap();
576 std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap();
577 std::fs::set_permissions(&prev, std::fs::Permissions::from_mode(0o755)).unwrap();
578
579 let err = rollback(&exe).unwrap_err();
580 assert!(err.contains("could not be verified"), "{err}");
581 assert!(err.contains(&exe.display().to_string()), "{err}");
582 }
583
584 #[test]
585 fn install_method_returns_binary_when_exe_elsewhere_or_no_cargo_home() {
586 let dir = tempfile::tempdir().unwrap();
587 let cargo_home = dir.path().join("cargo");
588 std::fs::create_dir_all(cargo_home.join("bin")).unwrap();
589 let elsewhere = dir.path().join("other/blyte");
590 std::fs::create_dir_all(elsewhere.parent().unwrap()).unwrap();
591 std::fs::write(&elsewhere, b"bin").unwrap();
592
593 assert_eq!(
594 install_method(&elsewhere, Some(&cargo_home)),
595 Ok(InstallMethod::Binary)
596 );
597 assert_eq!(install_method(&elsewhere, None), Ok(InstallMethod::Binary));
598
599 let cargo_bin = cargo_home.join("bin/blyte");
600 std::fs::write(&cargo_bin, b"other").unwrap();
601 assert_eq!(
602 install_method(&elsewhere, Some(&cargo_home)),
603 Ok(InstallMethod::Binary)
604 );
605 }
606
607 #[test]
608 fn install_method_detects_crates_io_git_registry() {
609 let dir = tempfile::tempdir().unwrap();
610 let exe = dir.path().join("bin/blyte");
611 std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
612 std::fs::write(&exe, b"bin").unwrap();
613 std::fs::write(
614 dir.path().join(".crates2.json"),
615 r#"{"installs":{"blyte 0.74.1 (registry+https://github.com/rust-lang/crates.io-index)":{}}}"#,
616 )
617 .unwrap();
618
619 assert_eq!(
620 install_method(&exe, Some(dir.path())),
621 Ok(InstallMethod::Cargo)
622 );
623 }
624
625 #[test]
626 fn install_method_detects_crates_io_sparse_registry() {
627 let dir = tempfile::tempdir().unwrap();
628 let exe = dir.path().join("bin/blyte");
629 std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
630 std::fs::write(&exe, b"bin").unwrap();
631 std::fs::write(
632 dir.path().join(".crates2.json"),
633 r#"{"installs":{"blyte 0.74.1 (sparse+https://index.crates.io/)":{}}}"#,
634 )
635 .unwrap();
636
637 assert_eq!(
638 install_method(&exe, Some(dir.path())),
639 Ok(InstallMethod::Cargo)
640 );
641 }
642
643 #[test]
644 fn install_method_rejects_git_install_source() {
645 let dir = tempfile::tempdir().unwrap();
646 let exe = dir.path().join("bin/blyte");
647 std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
648 std::fs::write(&exe, b"bin").unwrap();
649 std::fs::write(
650 dir.path().join(".crates2.json"),
651 r#"{"installs":{"blyte 0.74.1 (git+https://github.com/dnf0/blyte#abc)":{}}}"#,
652 )
653 .unwrap();
654
655 let err = install_method(&exe, Some(dir.path())).unwrap_err();
656 assert!(err.contains("installed by cargo from"), "{err}");
657 }
658
659 #[test]
660 fn install_method_errors_when_crates2_json_missing() {
661 let dir = tempfile::tempdir().unwrap();
662 let exe = dir.path().join("bin/blyte");
663 std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
664 std::fs::write(&exe, b"bin").unwrap();
665
666 let err = install_method(&exe, Some(dir.path())).unwrap_err();
667 assert!(err.contains("is missing"), "{err}");
668 }
669
670 #[test]
671 fn install_method_errors_when_crates2_json_does_not_list_blyte() {
672 let dir = tempfile::tempdir().unwrap();
673 let exe = dir.path().join("bin/blyte");
674 std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
675 std::fs::write(&exe, b"bin").unwrap();
676 std::fs::write(
677 dir.path().join(".crates2.json"),
678 r#"{"installs":{"blyte-agent 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)":{}}}"#,
679 )
680 .unwrap();
681
682 let err = install_method(&exe, Some(dir.path())).unwrap_err();
683 assert!(err.contains("does not list blyte"), "{err}");
684 }
685
686 #[test]
687 fn install_method_errors_when_crates2_json_unparseable_or_missing_installs() {
688 let dir = tempfile::tempdir().unwrap();
689 let exe = dir.path().join("bin/blyte");
690 std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
691 std::fs::write(&exe, b"bin").unwrap();
692 let crates2 = dir.path().join(".crates2.json");
693
694 std::fs::write(&crates2, "not json").unwrap();
695 let err = install_method(&exe, Some(dir.path())).unwrap_err();
696 assert!(err.contains(&crates2.display().to_string()), "{err}");
697
698 std::fs::write(&crates2, r#"{"other":{}}"#).unwrap();
699 let err = install_method(&exe, Some(dir.path())).unwrap_err();
700 assert!(err.contains(&crates2.display().to_string()), "{err}");
701 }
702}