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 const fn parse_repo_url(url: &str) -> Option<&str> {
100 parse_repo(url)
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
129fn 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
157fn 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
181fn 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
197pub 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 ok = Command::new(new_exe)
276 .args(&args)
277 .env("HOME", home)
278 .output()
279 .map(|o| o.status.success())
280 .unwrap_or(false);
281
282 if ok {
283 lines.push(format!("skill refreshed for {}", harness.name));
284 } else {
285 lines.push(format!(
286 "skill not refreshed for {}: blyte skill install failed; run it by hand",
287 harness.name
288 ));
289 }
290 }
291 }
292
293 lines
294}
295
296fn update(check: bool) -> Result<(), String> {
297 let current = env!("CARGO_PKG_VERSION");
298 let tag = latest_tag()?;
299 let (now, latest) = (parse_version(current), parse_version(&tag));
300 println!(
301 "installed: blyte {current}\nlatest: blyte {}",
302 tag.trim_start_matches('v')
303 );
304 if latest <= now {
305 println!("blyte is up to date");
306 return Ok(());
307 }
308 if check {
309 println!("run `blyte update` to install it");
310 return Ok(());
311 }
312 let repo = repo();
313 let asset = asset_name().ok_or_else(|| {
314 format!(
315 "no release binary for {}-{}; build it with `cargo install --git https://github.com/{repo} blyte`",
316 std::env::consts::OS,
317 std::env::consts::ARCH
318 )
319 })?;
320 let exe = current_exe()?;
321 let tmp = exe.with_file_name(format!(".blyte-update-{}", std::process::id()));
322 let out = Command::new(gh())
323 .args([
324 "release",
325 "download",
326 &tag,
327 "--repo",
328 repo,
329 "--pattern",
330 asset,
331 "--clobber",
332 "-O",
333 ])
334 .arg(&tmp)
335 .output()
336 .map_err(|e| format!("could not run the GitHub CLI (gh): {e}"))?;
337 if !out.status.success() || !tmp.is_file() {
338 let _ = std::fs::remove_file(&tmp);
339 return Err(format!(
340 "download failed: {}",
341 String::from_utf8_lossy(&out.stderr).trim()
342 ));
343 }
344 #[cfg(unix)]
345 {
346 use std::os::unix::fs::PermissionsExt;
347 std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755))
348 .map_err(|e| format!("could not make the download executable: {e}"))?;
349 }
350 let Some(new_version) = version_of(&tmp) else {
351 let _ = std::fs::remove_file(&tmp);
352 return Err("the downloaded binary does not run; the installed blyte is unchanged".into());
353 };
354 let prev = prev_path(&exe);
355 std::fs::copy(&exe, &prev).map_err(|e| format!("could not keep the previous build: {e}"))?;
356 std::fs::rename(&tmp, &exe).map_err(|e| format!("could not replace {}: {e}", exe.display()))?;
357 println!(
358 "updated to {new_version}; the previous build is kept as {}",
359 prev.display()
360 );
361 println!("`blyte update --rollback` restores it");
362 if let Some(home) = std::env::var_os("HOME").map(PathBuf::from) {
363 for line in refresh_skills(&exe, &home) {
364 println!("{line}");
365 }
366 if !home.as_os_str().is_empty() {
367 crate::skill::warn_superseded(&home);
368 }
369 }
370 Ok(())
371}
372
373pub fn run(check: bool, rollback_requested: bool) -> i32 {
375 let result = if rollback_requested {
376 current_exe()
377 .and_then(|exe| rollback(&exe))
378 .map(|v| println!("rolled back to {v}"))
379 } else {
380 update(check)
381 };
382 match result {
383 Ok(()) => 0,
384 Err(e) => {
385 eprintln!("error: {e}");
386 1
387 }
388 }
389}
390
391#[cfg(test)]
392mod tests {
393 use super::*;
394
395 #[test]
396 fn parser_maps_github_urls_and_rejects_non_github() {
397 assert_eq!(
398 parse_repo("https://github.com/acme/blyte"),
399 Some("acme/blyte")
400 );
401 assert_eq!(
402 parse_repo("https://github.com/acme/blyte/"),
403 Some("acme/blyte")
404 );
405 assert_eq!(
406 parse_repo("https://github.com/acme/blyte.git"),
407 Some("acme/blyte")
408 );
409 assert_eq!(parse_repo("https://gitlab.com/acme/blyte"), None);
410 assert_eq!(repo(), parse_repo(env!("CARGO_PKG_REPOSITORY")).unwrap());
411 }
412}