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