Skip to main content

blyte_cli/
update.rs

1//! `blyte update`: replace this binary with the latest GitHub release (2026-09-30).
2//!
3//! Releases carry one static binary per platform (release-on-merge.yml). The repository is the
4//! `repository` field of the workspace Cargo.toml. The repository is private,
5//! so the download goes through the GitHub CLI (`gh`), which already holds the user's access;
6//! blyte handles no token. The new binary must run before it replaces the old one, the old one is
7//! kept beside it as `blyte.prev` (`blyte update --rollback` swaps them back), and every installed
8//! copy of the skill is refreshed when unedited, for every harness (2026-10-01).
9
10use std::path::{Path, PathBuf};
11use std::process::Command;
12
13/// The repository whose releases are installed. The repository is the `repository` field
14/// of the workspace Cargo.toml.
15pub 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
23/// The repository whose releases are installed (`owner/name`).
24pub const fn repo() -> &'static str {
25    REPO
26}
27
28/// Parse a GitHub repository URL into an `owner/name` pair, stripping a leading
29/// `https://github.com/` and any trailing `/` or `.git`. Returns `None` if the URL is not a
30/// valid GitHub repository URL.
31pub 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
98/// Alias for [`parse_repo`].
99pub const fn parse_repo_url(url: &str) -> Option<&str> {
100    parse_repo(url)
101}
102
103/// The release asset for this machine, or `None` where no binary is built.
104pub 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
113/// `v0.2.1` or `0.2.1` as `(0, 2, 1)`.
114pub 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/// The GitHub CLI; `BLYTE_GH` names another (the tests use a stand-in).
130fn gh() -> String {
131    std::env::var("BLYTE_GH").unwrap_or_else(|_| "gh".to_string())
132}
133
134fn latest_tag() -> Result<String, String> {
135    let repo = repo();
136    let out = Command::new(gh())
137        .args([
138            "release", "view", "--repo", repo, "--json", "tagName", "--jq", ".tagName",
139        ])
140        .output()
141        .map_err(|e| {
142            format!("could not run the GitHub CLI (gh): {e}; install it and run `gh auth login`")
143        })?;
144    if !out.status.success() {
145        return Err(format!(
146            "gh could not read the latest release of {repo}: {}",
147            String::from_utf8_lossy(&out.stderr).trim()
148        ));
149    }
150    let tag = String::from_utf8_lossy(&out.stdout).trim().to_string();
151    if parse_version(&tag).is_none() {
152        return Err(format!("unexpected release tag: {tag:?}"));
153    }
154    Ok(tag)
155}
156
157/// The installed binary: this one, or its `blyte` sibling when this is `blyte.prev` (so a rollback
158/// also works from the previous build).
159fn current_exe() -> Result<PathBuf, String> {
160    let exe = std::env::current_exe()
161        .and_then(|p| p.canonicalize())
162        .map_err(|e| format!("cannot find this blyte binary: {e}"))?;
163    Ok(if exe.file_name().is_some_and(|n| n == "blyte.prev") {
164        exe.with_file_name("blyte")
165    } else {
166        exe
167    })
168}
169
170fn prev_path(exe: &Path) -> PathBuf {
171    exe.with_file_name("blyte.prev")
172}
173
174fn version_of(bin: &Path) -> Result<String, String> {
175    let out = Command::new(bin)
176        .arg("--version")
177        .output()
178        .map_err(|e| format!("failed to run --version: {e}"))?;
179    if !out.status.success() {
180        let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
181        if stderr.is_empty() {
182            return Err(format!("--version exited with {}", out.status));
183        }
184        return Err(format!("--version exited with {}: {stderr}", out.status));
185    }
186    let ver = String::from_utf8_lossy(&out.stdout).trim().to_string();
187    if ver.is_empty() {
188        return Err("--version produced empty output".to_string());
189    }
190    Ok(ver)
191}
192
193/// Swap `exe` and `blyte.prev`.
194pub fn rollback(exe: &Path) -> Result<String, String> {
195    let prev = prev_path(exe);
196    if !prev.is_file() {
197        return Err(format!(
198            "no previous build to roll back to ({} is missing)",
199            prev.display()
200        ));
201    }
202    let swap = exe.with_file_name(".blyte-swap");
203    std::fs::rename(exe, &swap).map_err(|e| format!("rollback failed: {e}"))?;
204    std::fs::rename(&prev, exe).map_err(|e| format!("rollback failed: {e}"))?;
205    std::fs::rename(&swap, &prev).map_err(|e| format!("rollback failed: {e}"))?;
206    version_of(exe).map_err(|e| {
207        format!(
208            "rollback binary at {} could not be verified: {e}",
209            exe.display()
210        )
211    })
212}
213
214/// Refresh every installed skill copy with `new_exe` when unedited, keeping whether blyte is the default.
215pub fn refresh_skills(new_exe: &Path, home: &Path) -> Vec<String> {
216    let mut lines = Vec::new();
217
218    struct HarnessConfig {
219        name: &'static str,
220        skill_dirs: Vec<PathBuf>,
221        instructions_file: PathBuf,
222        install_args: Vec<&'static str>,
223    }
224
225    let harnesses = [
226        HarnessConfig {
227            name: "Claude Code",
228            skill_dirs: vec![home.join(".claude/skills/blyte-implementer")],
229            instructions_file: home.join(".claude/CLAUDE.md"),
230            install_args: vec!["skill", "install", "--force"],
231        },
232        HarnessConfig {
233            name: "Codex",
234            skill_dirs: vec![
235                home.join(".agents/skills/blyte-implementer"),
236                home.join(".codex/skills/blyte-implementer"),
237            ],
238            instructions_file: home.join(".codex/AGENTS.md"),
239            install_args: vec!["skill", "install", "--force", "--harness", "codex"],
240        },
241    ];
242
243    for harness in harnesses {
244        let existing_skills: Vec<(PathBuf, PathBuf)> = harness
245            .skill_dirs
246            .iter()
247            .map(|d| (d.join("SKILL.md"), d.join(".blyte-installed")))
248            .filter(|(s, _)| s.exists())
249            .collect();
250
251        if existing_skills.is_empty() {
252            continue;
253        }
254
255        let mut first_edited: Option<PathBuf> = None;
256        for (skill_file, installed_file) in &existing_skills {
257            let is_unedited = match std::fs::read_to_string(skill_file) {
258                Ok(skill_text) => {
259                    if installed_file.exists() {
260                        std::fs::read_to_string(installed_file)
261                            .map(|inst_text| inst_text == skill_text)
262                            .unwrap_or(false)
263                    } else {
264                        skill_text == crate::skill::SKILL_MD
265                    }
266                }
267                Err(_) => false,
268            };
269
270            if !is_unedited {
271                first_edited = Some(skill_file.clone());
272                break;
273            }
274        }
275
276        if let Some(edited_path) = first_edited {
277            lines.push(format!(
278                "skill not refreshed for {}: {} has been edited (run blyte skill install --force to replace it)",
279                harness.name,
280                edited_path.display()
281            ));
282        } else {
283            let default_on = std::fs::read_to_string(&harness.instructions_file)
284                .map(|t| t.contains("<!-- blyte:default -->"))
285                .unwrap_or(false);
286
287            let mut args = harness.install_args.clone();
288            if !default_on {
289                args.push("--no-default");
290            }
291
292            let out = Command::new(new_exe).args(&args).env("HOME", home).output();
293
294            match out {
295                Ok(o) if o.status.success() => {
296                    lines.push(format!("skill refreshed for {}", harness.name));
297                    for line in String::from_utf8_lossy(&o.stdout).lines() {
298                        if line.starts_with("auto-compact:") {
299                            lines.push(line.to_string());
300                        }
301                    }
302                }
303                Ok(o) => {
304                    let stderr = String::from_utf8_lossy(&o.stderr);
305                    let cause = stderr.lines().rev().map(str::trim).find(|l| !l.is_empty());
306                    match cause {
307                        Some(c) => lines.push(format!(
308                            "skill not refreshed for {}: blyte skill install failed; run it by hand ({c})",
309                            harness.name
310                        )),
311                        None => lines.push(format!(
312                            "skill not refreshed for {}: blyte skill install failed; run it by hand",
313                            harness.name
314                        )),
315                    }
316                }
317                Err(e) => {
318                    lines.push(format!(
319                        "skill not refreshed for {}: blyte skill install failed; run it by hand ({e})",
320                        harness.name
321                    ));
322                }
323            }
324        }
325    }
326
327    lines
328}
329
330fn update(check: bool) -> Result<(), String> {
331    let current = env!("CARGO_PKG_VERSION");
332    let tag = latest_tag()?;
333    let (now, latest) = (parse_version(current), parse_version(&tag));
334    println!(
335        "installed: blyte {current}\nlatest:    blyte {}",
336        tag.trim_start_matches('v')
337    );
338    if latest <= now {
339        println!("blyte is up to date");
340        return Ok(());
341    }
342    if check {
343        println!("run `blyte update` to install it");
344        return Ok(());
345    }
346    let repo = repo();
347    let asset = asset_name().ok_or_else(|| {
348        format!(
349            "no release binary for {}-{}; build it with `cargo install --git https://github.com/{repo} blyte`",
350            std::env::consts::OS,
351            std::env::consts::ARCH
352        )
353    })?;
354    let exe = current_exe()?;
355    let tmp = exe.with_file_name(format!(".blyte-update-{}", std::process::id()));
356    let out = Command::new(gh())
357        .args([
358            "release",
359            "download",
360            &tag,
361            "--repo",
362            repo,
363            "--pattern",
364            asset,
365            "--clobber",
366            "-O",
367        ])
368        .arg(&tmp)
369        .output()
370        .map_err(|e| format!("could not run the GitHub CLI (gh): {e}"))?;
371    if !out.status.success() || !tmp.is_file() {
372        let _ = std::fs::remove_file(&tmp);
373        return Err(format!(
374            "download failed: {}",
375            String::from_utf8_lossy(&out.stderr).trim()
376        ));
377    }
378    #[cfg(unix)]
379    {
380        use std::os::unix::fs::PermissionsExt;
381        std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755))
382            .map_err(|e| format!("could not make the download executable: {e}"))?;
383    }
384    let Ok(new_version) = version_of(&tmp) else {
385        let _ = std::fs::remove_file(&tmp);
386        return Err("the downloaded binary does not run; the installed blyte is unchanged".into());
387    };
388    let prev = prev_path(&exe);
389    std::fs::copy(&exe, &prev).map_err(|e| format!("could not keep the previous build: {e}"))?;
390    std::fs::rename(&tmp, &exe).map_err(|e| format!("could not replace {}: {e}", exe.display()))?;
391    println!(
392        "updated to {new_version}; the previous build is kept as {}",
393        prev.display()
394    );
395    println!("`blyte update --rollback` restores it");
396    if let Some(home) = std::env::var_os("HOME").map(PathBuf::from) {
397        for line in refresh_skills(&exe, &home) {
398            println!("{line}");
399        }
400        if !home.as_os_str().is_empty() {
401            crate::skill::warn_superseded(&home);
402        }
403    }
404    Ok(())
405}
406
407/// `blyte update [--check | --rollback]`; returns the process exit code.
408pub fn run(check: bool, rollback_requested: bool) -> i32 {
409    let result = if rollback_requested {
410        current_exe()
411            .and_then(|exe| rollback(&exe))
412            .map(|v| println!("rolled back to {v}"))
413    } else {
414        update(check)
415    };
416    match result {
417        Ok(()) => 0,
418        Err(e) => {
419            eprintln!("error: {e}");
420            1
421        }
422    }
423}
424
425#[cfg(test)]
426mod tests {
427    use super::*;
428
429    #[test]
430    fn parser_maps_github_urls_and_rejects_non_github() {
431        assert_eq!(
432            parse_repo("https://github.com/acme/blyte"),
433            Some("acme/blyte")
434        );
435        assert_eq!(
436            parse_repo("https://github.com/acme/blyte/"),
437            Some("acme/blyte")
438        );
439        assert_eq!(
440            parse_repo("https://github.com/acme/blyte.git"),
441            Some("acme/blyte")
442        );
443        assert_eq!(parse_repo("https://gitlab.com/acme/blyte"), None);
444        assert_eq!(repo(), parse_repo(env!("CARGO_PKG_REPOSITORY")).unwrap());
445    }
446
447    #[cfg(unix)]
448    #[test]
449    fn rollback_errors_when_version_check_fails() {
450        use std::os::unix::fs::PermissionsExt;
451
452        let dir = tempfile::tempdir().unwrap();
453        let exe = dir.path().join("blyte");
454        let prev = dir.path().join("blyte.prev");
455        std::fs::write(&exe, "#!/bin/sh\necho 'blyte 2.0.0'\n").unwrap();
456        std::fs::write(&prev, "#!/bin/sh\nexit 1\n").unwrap();
457        std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap();
458        std::fs::set_permissions(&prev, std::fs::Permissions::from_mode(0o755)).unwrap();
459
460        let err = rollback(&exe).unwrap_err();
461        assert!(err.contains("could not be verified"), "{err}");
462        assert!(err.contains(&exe.display().to_string()), "{err}");
463    }
464}