1use std::path::{Path, PathBuf};
11use std::process::Command;
12
13pub const REPO: &str = match parse_repo(env!("CARGO_PKG_REPOSITORY")) {
16 Some(repo) => repo,
17 None => panic!(concat!(
18 "the build's repository field is not a GitHub URL: ",
19 env!("CARGO_PKG_REPOSITORY")
20 )),
21};
22
23pub const fn repo() -> &'static str {
25 REPO
26}
27
28pub const fn parse_repo(url: &str) -> Option<&str> {
32 let bytes = url.as_bytes();
33 let prefix = b"https://github.com/";
34 if bytes.len() < prefix.len() {
35 return None;
36 }
37 let mut i = 0;
38 while i < prefix.len() {
39 if bytes[i] != prefix[i] {
40 return None;
41 }
42 i += 1;
43 }
44
45 let mut end = bytes.len();
46 while end > prefix.len() && bytes[end - 1] == b'/' {
47 end -= 1;
48 }
49 if end >= prefix.len() + 4
50 && bytes[end - 4] == b'.'
51 && bytes[end - 3] == b'g'
52 && bytes[end - 2] == b'i'
53 && bytes[end - 1] == b't'
54 {
55 end -= 4;
56 while end > prefix.len() && bytes[end - 1] == b'/' {
57 end -= 1;
58 }
59 }
60
61 let start = prefix.len();
62 if end <= start {
63 return None;
64 }
65
66 let mut slash_count = 0;
67 let mut j = start;
68 let mut slash_idx = 0;
69 while j < end {
70 let b = bytes[j];
71 if b == b'/' {
72 slash_count += 1;
73 slash_idx = j;
74 } else if b.is_ascii_whitespace() {
75 return None;
76 }
77 j += 1;
78 }
79
80 if slash_count != 1 || slash_idx == start || slash_idx == end - 1 {
81 return None;
82 }
83
84 let (_, tail) = match bytes.split_at_checked(start) {
85 Some(pair) => pair,
86 None => return None,
87 };
88 let (target, _) = match tail.split_at_checked(end - start) {
89 Some(pair) => pair,
90 None => return None,
91 };
92 match std::str::from_utf8(target) {
93 Ok(s) => Some(s),
94 Err(_) => None,
95 }
96}
97
98pub fn asset_name() -> Option<&'static str> {
100 match (std::env::consts::OS, std::env::consts::ARCH) {
101 ("macos", "aarch64") => Some("blyte-aarch64-apple-darwin"),
102 ("macos", "x86_64") => Some("blyte-x86_64-apple-darwin"),
103 ("linux", "x86_64") => Some("blyte-x86_64-unknown-linux-musl"),
104 _ => None,
105 }
106}
107
108pub fn parse_version(s: &str) -> Option<(u64, u64, u64)> {
110 let mut parts = s.trim().trim_start_matches('v').split('.');
111 let v = (
112 parts.next()?.parse().ok()?,
113 parts.next()?.parse().ok()?,
114 parts
115 .next()?
116 .split(|c: char| !c.is_ascii_digit())
117 .next()?
118 .parse()
119 .ok()?,
120 );
121 Some(v)
122}
123
124fn gh() -> String {
126 std::env::var("BLYTE_GH").unwrap_or_else(|_| "gh".to_string())
127}
128
129fn latest_tag() -> Result<String, String> {
130 let repo = repo();
131 let out = Command::new(gh())
132 .args([
133 "release", "view", "--repo", repo, "--json", "tagName", "--jq", ".tagName",
134 ])
135 .output()
136 .map_err(|e| {
137 format!("could not run the GitHub CLI (gh): {e}; install it and run `gh auth login`")
138 })?;
139 if !out.status.success() {
140 return Err(format!(
141 "gh could not read the latest release of {repo}: {}",
142 String::from_utf8_lossy(&out.stderr).trim()
143 ));
144 }
145 let tag = String::from_utf8_lossy(&out.stdout).trim().to_string();
146 if parse_version(&tag).is_none() {
147 return Err(format!("unexpected release tag: {tag:?}"));
148 }
149 Ok(tag)
150}
151
152fn current_exe() -> Result<PathBuf, String> {
155 let exe = std::env::current_exe()
156 .and_then(|p| p.canonicalize())
157 .map_err(|e| format!("cannot find this blyte binary: {e}"))?;
158 Ok(if exe.file_name().is_some_and(|n| n == "blyte.prev") {
159 exe.with_file_name("blyte")
160 } else {
161 exe
162 })
163}
164
165fn prev_path(exe: &Path) -> PathBuf {
166 exe.with_file_name("blyte.prev")
167}
168
169fn version_of(bin: &Path) -> Result<String, String> {
170 let out = Command::new(bin)
171 .arg("--version")
172 .output()
173 .map_err(|e| format!("failed to run --version: {e}"))?;
174 if !out.status.success() {
175 let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
176 if stderr.is_empty() {
177 return Err(format!("--version exited with {}", out.status));
178 }
179 return Err(format!("--version exited with {}: {stderr}", out.status));
180 }
181 let ver = String::from_utf8_lossy(&out.stdout).trim().to_string();
182 if ver.is_empty() {
183 return Err("--version produced empty output".to_string());
184 }
185 Ok(ver)
186}
187
188pub fn rollback(exe: &Path) -> Result<String, String> {
190 let prev = prev_path(exe);
191 if !prev.is_file() {
192 return Err(format!(
193 "no previous build to roll back to ({} is missing)",
194 prev.display()
195 ));
196 }
197 let swap = exe.with_file_name(".blyte-swap");
198 std::fs::rename(exe, &swap).map_err(|e| format!("rollback failed: {e}"))?;
199 std::fs::rename(&prev, exe).map_err(|e| format!("rollback failed: {e}"))?;
200 std::fs::rename(&swap, &prev).map_err(|e| format!("rollback failed: {e}"))?;
201 version_of(exe).map_err(|e| {
202 format!(
203 "rollback binary at {} could not be verified: {e}",
204 exe.display()
205 )
206 })
207}
208
209pub fn refresh_skills(new_exe: &Path, home: &Path) -> Vec<String> {
211 let mut lines = Vec::new();
212
213 struct HarnessConfig {
214 name: &'static str,
215 skill_dirs: Vec<PathBuf>,
216 instructions_file: PathBuf,
217 install_args: Vec<&'static str>,
218 }
219
220 let harnesses = [
221 HarnessConfig {
222 name: "Claude Code",
223 skill_dirs: vec![home.join(".claude/skills/blyte-implementer")],
224 instructions_file: home.join(".claude/CLAUDE.md"),
225 install_args: vec!["skill", "install", "--force"],
226 },
227 HarnessConfig {
228 name: "Codex",
229 skill_dirs: vec![
230 home.join(".agents/skills/blyte-implementer"),
231 home.join(".codex/skills/blyte-implementer"),
232 ],
233 instructions_file: home.join(".codex/AGENTS.md"),
234 install_args: vec!["skill", "install", "--force", "--harness", "codex"],
235 },
236 ];
237
238 for harness in harnesses {
239 let existing_skills: Vec<(PathBuf, PathBuf)> = harness
240 .skill_dirs
241 .iter()
242 .map(|d| (d.join("SKILL.md"), d.join(".blyte-installed")))
243 .filter(|(s, _)| s.exists())
244 .collect();
245
246 if existing_skills.is_empty() {
247 continue;
248 }
249
250 let mut first_edited: Option<PathBuf> = None;
251 for (skill_file, installed_file) in &existing_skills {
252 let is_unedited = match std::fs::read_to_string(skill_file) {
253 Ok(skill_text) => {
254 if installed_file.exists() {
255 std::fs::read_to_string(installed_file)
256 .map(|inst_text| inst_text == skill_text)
257 .unwrap_or(false)
258 } else {
259 skill_text == crate::skill::SKILL_MD
260 }
261 }
262 Err(_) => false,
263 };
264
265 if !is_unedited {
266 first_edited = Some(skill_file.clone());
267 break;
268 }
269 }
270
271 if let Some(edited_path) = first_edited {
272 lines.push(format!(
273 "skill not refreshed for {}: {} has been edited (run blyte skill install --force to replace it)",
274 harness.name,
275 edited_path.display()
276 ));
277 } else {
278 let default_on = std::fs::read_to_string(&harness.instructions_file)
279 .map(|t| t.contains("<!-- blyte:default -->"))
280 .unwrap_or(false);
281
282 let mut args = harness.install_args.clone();
283 if !default_on {
284 args.push("--no-default");
285 }
286
287 let out = Command::new(new_exe).args(&args).env("HOME", home).output();
288
289 match out {
290 Ok(o) if o.status.success() => {
291 lines.push(format!("skill refreshed for {}", harness.name));
292 for line in String::from_utf8_lossy(&o.stdout).lines() {
293 if line.starts_with("auto-compact:") {
294 lines.push(line.to_string());
295 }
296 }
297 }
298 Ok(o) => {
299 let stderr = String::from_utf8_lossy(&o.stderr);
300 let cause = stderr.lines().rev().map(str::trim).find(|l| !l.is_empty());
301 match cause {
302 Some(c) => lines.push(format!(
303 "skill not refreshed for {}: blyte skill install failed; run it by hand ({c})",
304 harness.name
305 )),
306 None => lines.push(format!(
307 "skill not refreshed for {}: blyte skill install failed; run it by hand",
308 harness.name
309 )),
310 }
311 }
312 Err(e) => {
313 lines.push(format!(
314 "skill not refreshed for {}: blyte skill install failed; run it by hand ({e})",
315 harness.name
316 ));
317 }
318 }
319 }
320 }
321
322 lines
323}
324
325fn update(check: bool) -> Result<(), String> {
326 let current = env!("CARGO_PKG_VERSION");
327 let tag = latest_tag()?;
328 let (now, latest) = (parse_version(current), parse_version(&tag));
329 println!(
330 "installed: blyte {current}\nlatest: blyte {}",
331 tag.trim_start_matches('v')
332 );
333 if latest <= now {
334 println!("blyte is up to date");
335 return Ok(());
336 }
337 if check {
338 println!("run `blyte update` to install it");
339 return Ok(());
340 }
341 let repo = repo();
342 let asset = asset_name().ok_or_else(|| {
343 format!(
344 "no release binary for {}-{}; build it with `cargo install --git https://github.com/{repo} blyte`",
345 std::env::consts::OS,
346 std::env::consts::ARCH
347 )
348 })?;
349 let exe = current_exe()?;
350 let tmp = exe.with_file_name(format!(".blyte-update-{}", std::process::id()));
351 let out = Command::new(gh())
352 .args([
353 "release",
354 "download",
355 &tag,
356 "--repo",
357 repo,
358 "--pattern",
359 asset,
360 "--clobber",
361 "-O",
362 ])
363 .arg(&tmp)
364 .output()
365 .map_err(|e| format!("could not run the GitHub CLI (gh): {e}"))?;
366 if !out.status.success() || !tmp.is_file() {
367 let _ = std::fs::remove_file(&tmp);
368 return Err(format!(
369 "download failed: {}",
370 String::from_utf8_lossy(&out.stderr).trim()
371 ));
372 }
373 #[cfg(unix)]
374 {
375 use std::os::unix::fs::PermissionsExt;
376 std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755))
377 .map_err(|e| format!("could not make the download executable: {e}"))?;
378 }
379 let Ok(new_version) = version_of(&tmp) else {
380 let _ = std::fs::remove_file(&tmp);
381 return Err("the downloaded binary does not run; the installed blyte is unchanged".into());
382 };
383 let prev = prev_path(&exe);
384 std::fs::copy(&exe, &prev).map_err(|e| format!("could not keep the previous build: {e}"))?;
385 std::fs::rename(&tmp, &exe).map_err(|e| format!("could not replace {}: {e}", exe.display()))?;
386 println!(
387 "updated to {new_version}; the previous build is kept as {}",
388 prev.display()
389 );
390 println!("`blyte update --rollback` restores it");
391 if let Some(home) = std::env::var_os("HOME").map(PathBuf::from) {
392 for line in refresh_skills(&exe, &home) {
393 println!("{line}");
394 }
395 if !home.as_os_str().is_empty() {
396 crate::skill::warn_superseded(&home);
397 }
398 }
399 Ok(())
400}
401
402pub fn run(check: bool, rollback_requested: bool) -> i32 {
404 let result = if rollback_requested {
405 current_exe()
406 .and_then(|exe| rollback(&exe))
407 .map(|v| println!("rolled back to {v}"))
408 } else {
409 update(check)
410 };
411 match result {
412 Ok(()) => 0,
413 Err(e) => {
414 eprintln!("error: {e}");
415 1
416 }
417 }
418}
419
420#[cfg(test)]
421mod tests {
422 use super::*;
423
424 #[test]
425 fn parser_maps_github_urls_and_rejects_non_github() {
426 assert_eq!(
427 parse_repo("https://github.com/acme/blyte"),
428 Some("acme/blyte")
429 );
430 assert_eq!(
431 parse_repo("https://github.com/acme/blyte/"),
432 Some("acme/blyte")
433 );
434 assert_eq!(
435 parse_repo("https://github.com/acme/blyte.git"),
436 Some("acme/blyte")
437 );
438 assert_eq!(parse_repo("https://gitlab.com/acme/blyte"), None);
439 assert_eq!(repo(), parse_repo(env!("CARGO_PKG_REPOSITORY")).unwrap());
440 }
441
442 #[cfg(unix)]
443 #[test]
444 fn rollback_errors_when_version_check_fails() {
445 use std::os::unix::fs::PermissionsExt;
446
447 let dir = tempfile::tempdir().unwrap();
448 let exe = dir.path().join("blyte");
449 let prev = dir.path().join("blyte.prev");
450 std::fs::write(&exe, "#!/bin/sh\necho 'blyte 2.0.0'\n").unwrap();
451 std::fs::write(&prev, "#!/bin/sh\nexit 1\n").unwrap();
452 std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap();
453 std::fs::set_permissions(&prev, std::fs::Permissions::from_mode(0o755)).unwrap();
454
455 let err = rollback(&exe).unwrap_err();
456 assert!(err.contains("could not be verified"), "{err}");
457 assert!(err.contains(&exe.display().to_string()), "{err}");
458 }
459}