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) -> Option<String> {
175    let out = Command::new(bin).arg("--version").output().ok()?;
176    out.status
177        .success()
178        .then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
179}
180
181/// Swap `exe` and `blyte.prev`.
182fn rollback(exe: &Path) -> Result<String, String> {
183    let prev = prev_path(exe);
184    if !prev.is_file() {
185        return Err(format!(
186            "no previous build to roll back to ({} is missing)",
187            prev.display()
188        ));
189    }
190    let swap = exe.with_file_name(".blyte-swap");
191    std::fs::rename(exe, &swap).map_err(|e| format!("rollback failed: {e}"))?;
192    std::fs::rename(&prev, exe).map_err(|e| format!("rollback failed: {e}"))?;
193    std::fs::rename(&swap, &prev).map_err(|e| format!("rollback failed: {e}"))?;
194    Ok(version_of(exe).unwrap_or_else(|| "blyte (version unknown)".into()))
195}
196
197/// Refresh every installed skill copy with `new_exe` when unedited, keeping whether blyte is the default.
198pub fn refresh_skills(new_exe: &Path, home: &Path) -> Vec<String> {
199    let mut lines = Vec::new();
200
201    struct HarnessConfig {
202        name: &'static str,
203        skill_dirs: Vec<PathBuf>,
204        instructions_file: PathBuf,
205        install_args: Vec<&'static str>,
206    }
207
208    let harnesses = [
209        HarnessConfig {
210            name: "Claude Code",
211            skill_dirs: vec![home.join(".claude/skills/blyte-implementer")],
212            instructions_file: home.join(".claude/CLAUDE.md"),
213            install_args: vec!["skill", "install", "--force"],
214        },
215        HarnessConfig {
216            name: "Codex",
217            skill_dirs: vec![
218                home.join(".agents/skills/blyte-implementer"),
219                home.join(".codex/skills/blyte-implementer"),
220            ],
221            instructions_file: home.join(".codex/AGENTS.md"),
222            install_args: vec!["skill", "install", "--force", "--harness", "codex"],
223        },
224    ];
225
226    for harness in harnesses {
227        let existing_skills: Vec<(PathBuf, PathBuf)> = harness
228            .skill_dirs
229            .iter()
230            .map(|d| (d.join("SKILL.md"), d.join(".blyte-installed")))
231            .filter(|(s, _)| s.exists())
232            .collect();
233
234        if existing_skills.is_empty() {
235            continue;
236        }
237
238        let mut first_edited: Option<PathBuf> = None;
239        for (skill_file, installed_file) in &existing_skills {
240            let is_unedited = match std::fs::read_to_string(skill_file) {
241                Ok(skill_text) => {
242                    if installed_file.exists() {
243                        std::fs::read_to_string(installed_file)
244                            .map(|inst_text| inst_text == skill_text)
245                            .unwrap_or(false)
246                    } else {
247                        skill_text == crate::skill::SKILL_MD
248                    }
249                }
250                Err(_) => false,
251            };
252
253            if !is_unedited {
254                first_edited = Some(skill_file.clone());
255                break;
256            }
257        }
258
259        if let Some(edited_path) = first_edited {
260            lines.push(format!(
261                "skill not refreshed for {}: {} has been edited (run blyte skill install --force to replace it)",
262                harness.name,
263                edited_path.display()
264            ));
265        } else {
266            let default_on = std::fs::read_to_string(&harness.instructions_file)
267                .map(|t| t.contains("<!-- blyte:default -->"))
268                .unwrap_or(false);
269
270            let mut args = harness.install_args.clone();
271            if !default_on {
272                args.push("--no-default");
273            }
274
275            let out = Command::new(new_exe).args(&args).env("HOME", home).output();
276
277            match out {
278                Ok(o) if o.status.success() => {
279                    lines.push(format!("skill refreshed for {}", harness.name));
280                    for line in String::from_utf8_lossy(&o.stdout).lines() {
281                        if line.starts_with("auto-compact:") {
282                            lines.push(line.to_string());
283                        }
284                    }
285                }
286                Ok(o) => {
287                    let stderr = String::from_utf8_lossy(&o.stderr);
288                    let cause = stderr.lines().rev().map(str::trim).find(|l| !l.is_empty());
289                    match cause {
290                        Some(c) => lines.push(format!(
291                            "skill not refreshed for {}: blyte skill install failed; run it by hand ({c})",
292                            harness.name
293                        )),
294                        None => lines.push(format!(
295                            "skill not refreshed for {}: blyte skill install failed; run it by hand",
296                            harness.name
297                        )),
298                    }
299                }
300                Err(e) => {
301                    lines.push(format!(
302                        "skill not refreshed for {}: blyte skill install failed; run it by hand ({e})",
303                        harness.name
304                    ));
305                }
306            }
307        }
308    }
309
310    lines
311}
312
313fn update(check: bool) -> Result<(), String> {
314    let current = env!("CARGO_PKG_VERSION");
315    let tag = latest_tag()?;
316    let (now, latest) = (parse_version(current), parse_version(&tag));
317    println!(
318        "installed: blyte {current}\nlatest:    blyte {}",
319        tag.trim_start_matches('v')
320    );
321    if latest <= now {
322        println!("blyte is up to date");
323        return Ok(());
324    }
325    if check {
326        println!("run `blyte update` to install it");
327        return Ok(());
328    }
329    let repo = repo();
330    let asset = asset_name().ok_or_else(|| {
331        format!(
332            "no release binary for {}-{}; build it with `cargo install --git https://github.com/{repo} blyte`",
333            std::env::consts::OS,
334            std::env::consts::ARCH
335        )
336    })?;
337    let exe = current_exe()?;
338    let tmp = exe.with_file_name(format!(".blyte-update-{}", std::process::id()));
339    let out = Command::new(gh())
340        .args([
341            "release",
342            "download",
343            &tag,
344            "--repo",
345            repo,
346            "--pattern",
347            asset,
348            "--clobber",
349            "-O",
350        ])
351        .arg(&tmp)
352        .output()
353        .map_err(|e| format!("could not run the GitHub CLI (gh): {e}"))?;
354    if !out.status.success() || !tmp.is_file() {
355        let _ = std::fs::remove_file(&tmp);
356        return Err(format!(
357            "download failed: {}",
358            String::from_utf8_lossy(&out.stderr).trim()
359        ));
360    }
361    #[cfg(unix)]
362    {
363        use std::os::unix::fs::PermissionsExt;
364        std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755))
365            .map_err(|e| format!("could not make the download executable: {e}"))?;
366    }
367    let Some(new_version) = version_of(&tmp) else {
368        let _ = std::fs::remove_file(&tmp);
369        return Err("the downloaded binary does not run; the installed blyte is unchanged".into());
370    };
371    let prev = prev_path(&exe);
372    std::fs::copy(&exe, &prev).map_err(|e| format!("could not keep the previous build: {e}"))?;
373    std::fs::rename(&tmp, &exe).map_err(|e| format!("could not replace {}: {e}", exe.display()))?;
374    println!(
375        "updated to {new_version}; the previous build is kept as {}",
376        prev.display()
377    );
378    println!("`blyte update --rollback` restores it");
379    if let Some(home) = std::env::var_os("HOME").map(PathBuf::from) {
380        for line in refresh_skills(&exe, &home) {
381            println!("{line}");
382        }
383        if !home.as_os_str().is_empty() {
384            crate::skill::warn_superseded(&home);
385        }
386    }
387    Ok(())
388}
389
390/// `blyte update [--check | --rollback]`; returns the process exit code.
391pub fn run(check: bool, rollback_requested: bool) -> i32 {
392    let result = if rollback_requested {
393        current_exe()
394            .and_then(|exe| rollback(&exe))
395            .map(|v| println!("rolled back to {v}"))
396    } else {
397        update(check)
398    };
399    match result {
400        Ok(()) => 0,
401        Err(e) => {
402            eprintln!("error: {e}");
403            1
404        }
405    }
406}
407
408#[cfg(test)]
409mod tests {
410    use super::*;
411
412    #[test]
413    fn parser_maps_github_urls_and_rejects_non_github() {
414        assert_eq!(
415            parse_repo("https://github.com/acme/blyte"),
416            Some("acme/blyte")
417        );
418        assert_eq!(
419            parse_repo("https://github.com/acme/blyte/"),
420            Some("acme/blyte")
421        );
422        assert_eq!(
423            parse_repo("https://github.com/acme/blyte.git"),
424            Some("acme/blyte")
425        );
426        assert_eq!(parse_repo("https://gitlab.com/acme/blyte"), None);
427        assert_eq!(repo(), parse_repo(env!("CARGO_PKG_REPOSITORY")).unwrap());
428    }
429}