1use std::fmt::Write as _;
5use std::fs::{self, File};
6use std::io::Read;
7use std::path::{Path, PathBuf};
8use std::process;
9use std::sync::atomic::{AtomicU64, Ordering};
10
11use anyhow::{Context, bail};
12
13use super::git_ops;
14use crate::parser::Screenshot;
15
16pub const SCREENSHOTS_BRANCH: &str = "orch/screenshots";
18
19const MAX_IMAGES: usize = 12;
20const MAX_IMAGE_BYTES: u64 = 10 * 1024 * 1024;
21const IMAGE_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp"];
22const LOCAL_REF: &str = "refs/orch/screenshots";
23const PUSH_ATTEMPTS: u32 = 5;
24static INDEX_SEQ: AtomicU64 = AtomicU64::new(0);
25
26#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct Prepared {
29 pub source: PathBuf,
30 pub branch_path: String,
31 pub caption: String,
32}
33
34fn safe_name(name: &str) -> String {
36 let cleaned: String = name
37 .chars()
38 .map(|c| {
39 if c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_' {
40 c
41 } else {
42 '-'
43 }
44 })
45 .collect();
46 cleaned.trim_start_matches('.').to_string()
47}
48
49pub fn prepare(
51 shots: &[Screenshot],
52 base: &Path,
53 roots: &[PathBuf],
54 pr_number: u64,
55) -> (Vec<Prepared>, Vec<String>) {
56 let mut prepared = Vec::new();
57 let mut skipped = Vec::new();
58
59 for shot in shots {
60 if prepared.len() >= MAX_IMAGES {
61 skipped.push(format!("{}: more than {MAX_IMAGES} screenshots", shot.path));
62 continue;
63 }
64 match check_image(&shot.path, base, roots) {
65 Ok(source) => {
66 let name = source
67 .file_name()
68 .map(|n| safe_name(&n.to_string_lossy()))
69 .unwrap_or_default();
70 prepared.push(Prepared {
71 branch_path: format!("pr-{pr_number}/{}-{name}", prepared.len() + 1),
72 source,
73 caption: shot.caption.clone(),
74 });
75 }
76 Err(e) => skipped.push(format!("{}: {e}", shot.path)),
77 }
78 }
79 (prepared, skipped)
80}
81
82fn check_image(path: &str, base: &Path, roots: &[PathBuf]) -> anyhow::Result<PathBuf> {
83 let joined = base.join(path.trim());
84 let source = fs::canonicalize(&joined).context("file not found")?;
85 if !roots.iter().any(|root| source.starts_with(root)) {
86 bail!("outside the worktree");
87 }
88 let is_image = source
89 .extension()
90 .and_then(|e| e.to_str())
91 .is_some_and(|e| IMAGE_EXTENSIONS.contains(&e.to_ascii_lowercase().as_str()));
92 if !is_image {
93 bail!("not an image file");
94 }
95 let meta = fs::metadata(&source).context("unreadable")?;
96 if !meta.is_file() || meta.len() == 0 || meta.len() > MAX_IMAGE_BYTES {
97 bail!("empty or larger than {} MB", MAX_IMAGE_BYTES / 1024 / 1024);
98 }
99 let mut head = [0u8; 12];
100 let read = File::open(&source)
101 .and_then(|mut f| f.read(&mut head))
102 .context("unreadable")?;
103 if !has_image_header(&head[..read]) {
104 bail!("not an image file");
105 }
106 Ok(source)
107}
108
109fn has_image_header(head: &[u8]) -> bool {
110 head.starts_with(b"\x89PNG\r\n\x1a\n")
111 || head.starts_with(&[0xFF, 0xD8, 0xFF])
112 || head.starts_with(b"GIF8")
113 || (head.starts_with(b"RIFF") && head.get(8..12) == Some(b"WEBP"))
114}
115
116fn one_line(text: &str) -> String {
117 text.split_whitespace()
118 .collect::<Vec<_>>()
119 .join(" ")
120 .replace(['[', ']'], "")
121}
122
123pub fn build_comment(
125 repo: &str,
126 commit: &str,
127 images: &[Prepared],
128 note: Option<&str>,
129 skipped: &[String],
130) -> String {
131 let mut body = String::from("## Screenshots\n");
132 for (i, image) in images.iter().enumerate() {
133 let caption = one_line(&image.caption);
134 let alt = if caption.is_empty() {
135 format!("Screenshot {}", i + 1)
136 } else {
137 caption.clone()
138 };
139 let url = format!(
140 "https://github.com/{repo}/blob/{commit}/{}?raw=true",
141 image.branch_path
142 );
143 body.push('\n');
144 if !caption.is_empty() {
145 let _ = writeln!(body, "**{caption}**\n");
146 }
147 let _ = writeln!(body, "");
148 }
149 if !skipped.is_empty() {
150 body.push_str("\nSkipped:\n");
151 for reason in skipped {
152 let _ = writeln!(body, "- {}", one_line(reason));
153 }
154 }
155 if let Some(note) = note.map(str::trim).filter(|n| !n.is_empty()) {
156 let _ = write!(body, "\n> {}\n", one_line(note));
157 }
158 body
159}
160
161pub fn build_unpublished_comment(note: Option<&str>, skipped: &[String]) -> String {
163 let mut body = String::from("## Screenshots\n\nThe screenshots could not be published.\n");
164 if !skipped.is_empty() {
165 body.push_str("\nSkipped:\n");
166 for reason in skipped {
167 let _ = writeln!(body, "- {}", one_line(reason));
168 }
169 }
170 if let Some(note) = note.map(str::trim).filter(|n| !n.is_empty()) {
171 let _ = write!(body, "\n> {}\n", one_line(note));
172 }
173 body
174}
175
176async fn git_out(dir: &Path, index: Option<&Path>, args: &[&str]) -> anyhow::Result<String> {
177 let mut cmd = git_ops::git().await;
178 cmd.arg("-C").arg(dir).args(args);
179 if let Some(index) = index {
180 cmd.env("GIT_INDEX_FILE", index);
181 }
182 cmd.env("GIT_AUTHOR_NAME", "orch")
183 .env("GIT_AUTHOR_EMAIL", "orch@localhost")
184 .env("GIT_COMMITTER_NAME", "orch")
185 .env("GIT_COMMITTER_EMAIL", "orch@localhost");
186 let out = git_ops::sanitize_git_output(cmd.output_with_context().await?);
187 if !out.status.success() {
188 bail!(
189 "git {} failed: {}",
190 args.first().copied().unwrap_or(""),
191 String::from_utf8_lossy(&out.stderr).trim()
192 );
193 }
194 Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
195}
196
197pub async fn allowed_roots(worktree: &Path) -> Vec<PathBuf> {
199 let mut roots = Vec::new();
200 if let Ok(root) = fs::canonicalize(worktree) {
201 roots.push(root);
202 }
203 if let Ok(dir) = git_out(worktree, None, &["rev-parse", "--absolute-git-dir"]).await
204 && let Ok(dir) = fs::canonicalize(dir)
205 {
206 roots.push(dir);
207 }
208 roots
209}
210
211pub async fn publish(
214 worktree: &Path,
215 images: &[Prepared],
216 pr_number: u64,
217) -> anyhow::Result<String> {
218 if images.is_empty() {
219 bail!("no images to publish");
220 }
221 let git_dir = git_out(worktree, None, &["rev-parse", "--absolute-git-dir"]).await?;
222 let index = PathBuf::from(git_dir).join(format!(
223 "orch-screenshots-index-{}-{}-{pr_number}",
224 process::id(),
225 INDEX_SEQ.fetch_add(1, Ordering::Relaxed)
226 ));
227 let result = push_images(worktree, &index, images, pr_number).await;
228 let _ = fs::remove_file(&index);
229 result
230}
231
232async fn push_images(
233 worktree: &Path,
234 index: &Path,
235 images: &[Prepared],
236 pr_number: u64,
237) -> anyhow::Result<String> {
238 let mut blobs = Vec::with_capacity(images.len());
239 for image in images {
240 let source = image.source.to_string_lossy();
241 let blob = git_out(worktree, None, &["hash-object", "-w", "--", &source]).await?;
242 blobs.push((blob, image.branch_path.clone()));
243 }
244
245 let mut last_nff = None;
246 for attempt in 1..=PUSH_ATTEMPTS {
247 match push_once(worktree, index, &blobs, pr_number).await {
248 Ok(commit) => return Ok(commit),
249 Err(e) if push_lost_the_remote_tip(&e) => {
250 tracing::warn!(
251 attempt,
252 err = %e,
253 "screenshot push was not a fast-forward, fetching again"
254 );
255 last_nff = Some(e);
256 }
257 Err(e) => return Err(e),
258 }
259 }
260 Err(last_nff.unwrap_or_else(|| anyhow::anyhow!("screenshot push failed")))
261}
262
263async fn fetch_parent(worktree: &Path) -> anyhow::Result<Option<String>> {
264 let fetch_spec = format!("+refs/heads/{SCREENSHOTS_BRANCH}:{LOCAL_REF}");
265 match git_out(worktree, None, &["fetch", "origin", &fetch_spec]).await {
266 Ok(_) => Ok(Some(
267 git_out(worktree, None, &["rev-parse", "--verify", LOCAL_REF])
268 .await
269 .context("screenshots branch ref missing after a successful fetch")?,
270 )),
271 Err(e) if git_ops::is_missing_remote_ref_error(&e) => Ok(None),
272 Err(e) => Err(e),
274 }
275}
276
277fn push_lost_the_remote_tip(err: &anyhow::Error) -> bool {
278 let s = err.to_string();
279 let lower = s.to_ascii_lowercase();
280 lower.contains("non-fast-forward")
281 || s.contains("! [rejected]")
282 || lower.contains("fetch first")
283 || lower.contains("reference already exists")
284 || lower.contains("cannot lock ref")
285}
286
287async fn push_once(
288 worktree: &Path,
289 index: &Path,
290 blobs: &[(String, String)],
291 pr_number: u64,
292) -> anyhow::Result<String> {
293 let parent = fetch_parent(worktree).await?;
294 if let Some(parent) = &parent {
295 git_out(worktree, Some(index), &["read-tree", parent]).await?;
296 } else {
297 git_out(worktree, Some(index), &["read-tree", "--empty"]).await?;
298 }
299 for (blob, path) in blobs {
300 let entry = format!("100644,{blob},{path}");
301 git_out(
302 worktree,
303 Some(index),
304 &["update-index", "--add", "--cacheinfo", &entry],
305 )
306 .await?;
307 }
308 let tree = git_out(worktree, Some(index), &["write-tree"]).await?;
309 let message = format!("Screenshots for PR #{pr_number}");
310 let mut args = vec!["commit-tree", tree.as_str(), "-m", message.as_str()];
311 if let Some(parent) = &parent {
312 args.extend(["-p", parent.as_str()]);
313 }
314 let commit = git_out(worktree, None, &args).await?;
315 let refspec = format!("{commit}:refs/heads/{SCREENSHOTS_BRANCH}");
316 git_out(worktree, None, &["push", "origin", &refspec]).await?;
317 Ok(commit)
318}
319
320#[cfg(test)]
321mod tests {
322 use std::process::Command as StdCommand;
323 use std::slice;
324
325 use super::git_ops;
326 use super::*;
327
328 const PNG_HEADER: &[u8] = b"\x89PNG\r\n\x1a\n";
329
330 fn shot(path: &str, caption: &str) -> Screenshot {
331 Screenshot {
332 path: path.into(),
333 caption: caption.into(),
334 }
335 }
336
337 fn git_run(dir: &Path, args: &[&str]) -> String {
338 let out = StdCommand::new("git")
339 .arg("-C")
340 .arg(dir)
341 .args(args)
342 .env("GIT_CONFIG_GLOBAL", "/dev/null")
343 .output()
344 .unwrap();
345 assert!(out.status.success(), "git {args:?}: {out:?}");
346 String::from_utf8_lossy(&out.stdout).trim().to_string()
347 }
348
349 #[test]
350 fn git_error_strips_url_credentials() {
351 let raw = "error: failed to push some refs to 'https://x-access-token:test-secret-1234567890abcdef@github.com/o/r.git'";
352 let msg = format!("git push failed: {}", git_ops::sanitize_push_error(raw));
353 assert!(!msg.contains("test-secret-1234567890abcdef"));
354 assert!(msg.contains("://***@github.com"));
355 }
356
357 #[test]
358 fn comment_links_images_to_the_commit() {
359 let images = vec![
360 Prepared {
361 source: PathBuf::from("/x/home.png"),
362 branch_path: "pr-7/1-home.png".into(),
363 caption: "Home, desktop".into(),
364 },
365 Prepared {
366 source: PathBuf::from("/x/phone.png"),
367 branch_path: "pr-7/2-phone.png".into(),
368 caption: String::new(),
369 },
370 ];
371 let body = build_comment(
372 "owner/repo",
373 "abc123",
374 &images,
375 Some("ui-screenshot skill missing"),
376 &[],
377 );
378 assert!(body.starts_with("## Screenshots"));
379 assert!(body.contains("**Home, desktop**"));
380 assert!(body.contains(
381 ""
382 ));
383 assert!(body.contains(
384 ""
385 ));
386 assert!(body.contains("> ui-screenshot skill missing"));
387 }
388
389 #[test]
390 fn note_comment_has_no_images() {
391 let body = build_comment(
392 "owner/repo",
393 "",
394 &[],
395 Some("no browser, the screenshot could not be taken"),
396 &[],
397 );
398 assert!(!body.contains("!["));
399 assert!(body.contains("> no browser"));
400 }
401
402 #[test]
403 fn unpublished_comment_says_the_images_never_landed() {
404 let body = build_unpublished_comment(
405 Some("ui-screenshot skill missing"),
406 &["shot.png: empty or larger than 10 MB".into()],
407 );
408 assert!(body.starts_with("## Screenshots"));
409 assert!(body.contains("The screenshots could not be published."));
410 assert!(!body.contains("!["));
411 assert!(body.contains("Skipped:"));
412 assert!(body.contains("shot.png: empty or larger than 10 MB"));
413 assert!(body.contains("> ui-screenshot skill missing"));
414 }
415
416 #[test]
417 fn push_lost_the_remote_tip_detects_a_diverged_or_raced_create() {
418 let nff = anyhow::anyhow!("git push failed: ! [rejected] a -> a (non-fast-forward)");
419 assert!(push_lost_the_remote_tip(&nff));
420 assert!(push_lost_the_remote_tip(&anyhow::anyhow!(
421 "git push failed: ! [rejected] a -> a (fetch first)"
422 )));
423 assert!(push_lost_the_remote_tip(&anyhow::anyhow!(
424 "git push failed: remote: error: cannot lock ref 'refs/heads/orch/screenshots': reference already exists\n ! [remote rejected] a -> orch/screenshots (reference already exists)"
425 )));
426 assert!(!push_lost_the_remote_tip(&anyhow::anyhow!(
427 "git push failed: remote: fatal error in commit_refs\n ! [remote rejected] a -> a (pre-receive hook declined)"
428 )));
429 }
430
431 #[test]
432 fn prepare_keeps_images_inside_the_roots_only() {
433 let tmp = tempfile::tempdir().unwrap();
434 let root = fs::canonicalize(tmp.path()).unwrap();
435 fs::write(root.join("a b.png"), PNG_HEADER).unwrap();
436 fs::write(root.join("notes.txt"), b"text").unwrap();
437 fs::write(root.join("fake.png"), b"not an image at all").unwrap();
438 let outside = tempfile::tempdir().unwrap();
439 fs::write(outside.path().join("secret.png"), PNG_HEADER).unwrap();
440
441 let shots = vec![
442 shot("a b.png", "A"),
443 shot("notes.txt", "B"),
444 shot("fake.png", "F"),
445 shot("missing.png", "C"),
446 shot(&outside.path().join("secret.png").to_string_lossy(), "D"),
447 shot("../secret.png", "E"),
448 ];
449 let (prepared, skipped) = prepare(&shots, &root, slice::from_ref(&root), 9);
450
451 assert_eq!(prepared.len(), 1);
452 assert_eq!(prepared[0].branch_path, "pr-9/1-a-b.png");
453 assert_eq!(skipped.len(), 5);
454 }
455
456 #[tokio::test]
457 async fn publish_pushes_a_branch_the_worktree_never_sees() {
458 let tmp = tempfile::tempdir().unwrap();
459 let origin = tmp.path().join("origin.git");
460 let clone = tmp.path().join("clone");
461 git_run(tmp.path(), &["init", "--bare", "-q", "origin.git"]);
462 git_run(tmp.path(), &["init", "-q", "-b", "main", "clone"]);
463 git_run(&clone, &["config", "user.email", "t@t"]);
464 git_run(&clone, &["config", "user.name", "t"]);
465 git_run(
466 &clone,
467 &["remote", "add", "origin", &origin.to_string_lossy()],
468 );
469 fs::write(clone.join("f"), "x").unwrap();
470 git_run(&clone, &["add", "f"]);
471 git_run(&clone, &["commit", "-qm", "init"]);
472 let head_before = git_run(&clone, &["rev-parse", "HEAD"]);
473
474 let shot_path = clone.join("home.png");
475 fs::write(&shot_path, PNG_HEADER).unwrap();
476 let roots = vec![fs::canonicalize(&clone).unwrap()];
477 let (images, _) = prepare(&[shot("home.png", "Home")], &clone, &roots, 3);
478 let first = publish(&clone, &images, 3).await.unwrap();
479
480 fs::write(&shot_path, b"\x89PNG\r\n\x1a\nsecond").unwrap();
481 let (images, _) = prepare(&[shot("home.png", "Home")], &clone, &roots, 4);
482 let second = publish(&clone, &images, 4).await.unwrap();
483
484 assert_ne!(first, second);
485 let tip = format!("refs/heads/{SCREENSHOTS_BRANCH}");
486 assert_eq!(git_run(&origin, &["rev-parse", &tip]), second);
487 assert_eq!(
488 git_run(&origin, &["rev-parse", &format!("{second}^")]),
489 first
490 );
491 let files = git_run(&origin, &["ls-tree", "-r", "--name-only", &second]);
492 assert!(files.contains("pr-3/1-home.png"), "{files}");
493 assert!(files.contains("pr-4/1-home.png"), "{files}");
494 assert_eq!(git_run(&clone, &["rev-parse", "HEAD"]), head_before);
495 assert_eq!(
496 git_run(&clone, &["branch", "--list", SCREENSHOTS_BRANCH]),
497 ""
498 );
499 }
500
501 fn init_origin_and_clone(tmp: &Path) -> (PathBuf, PathBuf) {
502 let origin = tmp.join("origin.git");
503 let clone = tmp.join("clone");
504 git_run(tmp, &["init", "--bare", "-q", "origin.git"]);
505 git_run(tmp, &["init", "-q", "-b", "main", "clone"]);
506 git_run(&clone, &["config", "user.email", "t@t"]);
507 git_run(&clone, &["config", "user.name", "t"]);
508 git_run(
509 &clone,
510 &["remote", "add", "origin", &origin.to_string_lossy()],
511 );
512 fs::write(clone.join("f"), "x").unwrap();
513 git_run(&clone, &["add", "f"]);
514 git_run(&clone, &["commit", "-qm", "init"]);
515 (origin, clone)
516 }
517
518 fn write_hook(origin: &Path, body: &str) {
519 let hook = origin.join("hooks/pre-receive");
520 fs::write(&hook, body).unwrap();
521 let status = StdCommand::new("chmod")
522 .arg("+x")
523 .arg(&hook)
524 .status()
525 .unwrap();
526 assert!(status.success(), "chmod +x {hook:?}");
527 }
528
529 fn screenshots_tip(origin: &Path) -> String {
530 git_run(
531 origin,
532 &["rev-parse", &format!("refs/heads/{SCREENSHOTS_BRANCH}")],
533 )
534 }
535
536 fn screenshots_files(origin: &Path, commit: &str) -> String {
537 git_run(origin, &["ls-tree", "-r", "--name-only", commit])
538 }
539
540 fn screenshots_branch_exists(origin: &Path) -> bool {
541 StdCommand::new("git")
542 .arg("-C")
543 .arg(origin)
544 .args([
545 "show-ref",
546 "--verify",
547 "--quiet",
548 &format!("refs/heads/{SCREENSHOTS_BRANCH}"),
549 ])
550 .env("GIT_CONFIG_GLOBAL", "/dev/null")
551 .status()
552 .unwrap()
553 .success()
554 }
555
556 #[tokio::test]
557 async fn publish_retries_when_two_worktrees_push_together() {
558 let tmp = tempfile::tempdir().unwrap();
559 let (origin, clone) = init_origin_and_clone(tmp.path());
560 let other = tmp.path().join("other");
561 git_run(
562 &clone,
563 &["worktree", "add", "-q", &other.to_string_lossy(), "HEAD"],
564 );
565 write_hook(&origin, "#!/bin/sh\nsleep 0.2\n");
566
567 fs::write(clone.join("a.png"), PNG_HEADER).unwrap();
568 fs::write(other.join("b.png"), PNG_HEADER).unwrap();
569 let roots_a = allowed_roots(&clone).await;
570 let roots_b = allowed_roots(&other).await;
571 let (images_a, _) = prepare(&[shot("a.png", "A")], &clone, &roots_a, 3);
572 let (images_b, _) = prepare(&[shot("b.png", "B")], &other, &roots_b, 4);
573
574 let (first, second) =
575 tokio::join!(publish(&clone, &images_a, 3), publish(&other, &images_b, 4),);
576 let first = first.expect("first worktree publish");
577 let second = second.expect("second worktree publish");
578 assert_ne!(first, second);
579
580 let tip = screenshots_tip(&origin);
581 let files = screenshots_files(&origin, &tip);
582 assert!(files.contains("pr-3/1-a.png"), "{files}");
583 assert!(files.contains("pr-4/1-b.png"), "{files}");
584 let log = git_run(
585 &origin,
586 &[
587 "log",
588 "--format=%H",
589 &format!("refs/heads/{SCREENSHOTS_BRANCH}"),
590 ],
591 );
592 assert!(log.contains(&first), "{log}");
593 assert!(log.contains(&second), "{log}");
594 }
595
596 #[tokio::test]
597 async fn publish_skips_a_root_commit_when_fetch_fails() {
598 let tmp = tempfile::tempdir().unwrap();
599 let (origin, clone) = init_origin_and_clone(tmp.path());
600 let missing = tmp.path().join("missing.git");
601 git_run(
602 &clone,
603 &["remote", "set-url", "origin", &missing.to_string_lossy()],
604 );
605 git_run(
606 &clone,
607 &[
608 "remote",
609 "set-url",
610 "--push",
611 "origin",
612 &origin.to_string_lossy(),
613 ],
614 );
615
616 fs::write(clone.join("home.png"), PNG_HEADER).unwrap();
617 let roots = vec![fs::canonicalize(&clone).unwrap()];
618 let (images, _) = prepare(&[shot("home.png", "Home")], &clone, &roots, 3);
619 let err = publish(&clone, &images, 3).await.unwrap_err();
620 assert!(
621 !git_ops::is_missing_remote_ref_error(&err),
622 "fetch failed for a reason other than a missing branch: {err}"
623 );
624 assert!(
625 !screenshots_branch_exists(&origin),
626 "a root commit must not be pushed when fetch failed"
627 );
628 }
629
630 #[tokio::test]
631 async fn publish_stops_after_non_fast_forward_retries() {
632 let tmp = tempfile::tempdir().unwrap();
633 let (origin, clone) = init_origin_and_clone(tmp.path());
634 write_hook(
635 &origin,
636 "#!/bin/sh\necho 'error: non-fast-forward' >&2\nexit 1\n",
637 );
638
639 fs::write(clone.join("home.png"), PNG_HEADER).unwrap();
640 let roots = vec![fs::canonicalize(&clone).unwrap()];
641 let (images, _) = prepare(&[shot("home.png", "Home")], &clone, &roots, 3);
642 let err = publish(&clone, &images, 3).await.unwrap_err();
643 assert!(
644 err.to_string()
645 .to_ascii_lowercase()
646 .contains("non-fast-forward"),
647 "{err}"
648 );
649 assert!(!screenshots_branch_exists(&origin));
650 }
651}