1use super::shipcheck::Shipcheck;
5use std::path::Path;
6use std::process::{Output, Stdio};
7
8use tokio::io::AsyncWriteExt;
9use tokio::process::Command;
10
11use crate::config;
12use crate::sys::cmd::CommandErrorContext;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum Tool {
16 Git,
17 Shipcheck,
18}
19
20impl Tool {
21 pub async fn detect(dir: &Path) -> Self {
24 if !dir.join("shipcheck.toml").exists() {
26 return Tool::Git;
27 }
28
29 match Shipcheck::detect(dir).await {
30 Shipcheck::Available => Tool::Shipcheck,
31 Shipcheck::Absent | Shipcheck::NotInstalled | Shipcheck::Outdated => Tool::Git,
32 }
33 }
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum When {
39 Tested,
41 Always,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum Outcome {
48 Committed {
49 skipped_oversized: Vec<String>,
51 },
52 Nothing {
53 skipped_oversized: Vec<String>,
54 },
55 Refused {
57 by: Tool,
58 reason: String,
59 },
60}
61
62pub(crate) const MAX_BLOB_BYTES: u64 = 100 * 1024 * 1024;
64
65pub(crate) fn oversized_commit_note(paths: &[String]) -> String {
67 format!(
68 "left files over GitHub's size limit out of the commit: {}",
69 paths.join(", ")
70 )
71}
72
73fn identity(agent: &str) -> (String, String) {
74 let name = config::get("git.name").unwrap_or_else(|_| format!("{agent}[bot]"));
75 let email = config::get("git.email")
76 .unwrap_or_else(|_| format!("{agent}[bot]@users.noreply.github.com"));
77 (name, email)
78}
79
80pub async fn git_commit(dir: &Path, message: &str, agent: &str) -> anyhow::Result<Output> {
82 let (name, email) = identity(agent);
83 Command::new("git")
84 .args(["-c", "commit.gpgsign=false", "commit", "-m", message])
85 .env("GIT_AUTHOR_NAME", &name)
86 .env("GIT_COMMITTER_NAME", &name)
87 .env("GIT_AUTHOR_EMAIL", &email)
88 .env("GIT_COMMITTER_EMAIL", &email)
89 .current_dir(dir)
90 .output_with_context()
91 .await
92}
93
94async fn shipcheck_commit(
95 dir: &Path,
96 bin: &Path,
97 message: &str,
98 agent: &str,
99) -> anyhow::Result<Outcome> {
100 let (name, email) = identity(agent);
101 let out = Command::new(bin)
102 .args(["commit", "-m", message])
103 .env("GIT_AUTHOR_NAME", &name)
104 .env("GIT_COMMITTER_NAME", &name)
105 .env("GIT_AUTHOR_EMAIL", &email)
106 .env("GIT_COMMITTER_EMAIL", &email)
107 .current_dir(dir)
108 .output_with_context()
109 .await?;
110 if out.status.success() {
111 return Ok(Outcome::Committed {
112 skipped_oversized: Vec::new(),
113 });
114 }
115
116 let why = String::from_utf8_lossy(&out.stderr).trim().to_string();
117 Ok(Outcome::Refused {
118 by: Tool::Shipcheck,
119 reason: format!("shipcheck commit refused, run `shipcheck run` first: {why}"),
120 })
121}
122
123pub async fn commit_all(
125 dir: &Path,
126 message: &str,
127 agent: &str,
128 when: When,
129) -> anyhow::Result<Outcome> {
130 let tool = Tool::detect(dir).await;
131 let bin = which::which("shipcheck").unwrap_or_else(|_| "shipcheck".into());
132 commit_with(dir, tool, &bin, message, agent, when).await
133}
134
135async fn commit_with(
136 dir: &Path,
137 tool: Tool,
138 shipcheck: &Path,
139 message: &str,
140 agent: &str,
141 when: When,
142) -> anyhow::Result<Outcome> {
143 if !has_changes(dir).await {
144 return Ok(Outcome::Nothing {
145 skipped_oversized: Vec::new(),
146 });
147 }
148
149 if tool == Tool::Shipcheck {
150 let outcome = shipcheck_commit(dir, shipcheck, message, agent).await?;
151 let Outcome::Refused { reason, .. } = &outcome else {
152 return Ok(outcome);
153 };
154 if when == When::Tested {
155 return Ok(outcome);
156 }
157
158 tracing::info!(reason = %reason, "committing untested work through git at the end of the session");
159 }
160
161 let add = Command::new("git")
162 .args(["add", "-A"])
163 .current_dir(dir)
164 .output_with_context()
165 .await?;
166 if !add.status.success() {
167 tracing::warn!("git add -A failed");
168 return Ok(Outcome::Refused {
169 by: Tool::Git,
170 reason: String::from_utf8_lossy(&add.stderr).trim().to_string(),
171 });
172 }
173
174 let skipped_oversized = unstage_oversized(dir, MAX_BLOB_BYTES).await?;
175 if !skipped_oversized.is_empty() {
176 tracing::warn!(
177 files = ?skipped_oversized,
178 "left files over GitHub's size limit out of the commit"
179 );
180 if !has_staged(dir).await {
181 return Ok(Outcome::Nothing { skipped_oversized });
182 }
183 }
184
185 let out = git_commit(dir, message, agent).await?;
186 if out.status.success() {
187 return Ok(Outcome::Committed { skipped_oversized });
188 }
189
190 let reason = String::from_utf8_lossy(&out.stderr).trim().to_string();
191 unstage(dir, &reason).await?;
192 Ok(Outcome::Refused {
193 by: Tool::Git,
194 reason,
195 })
196}
197
198async fn unstage_oversized(dir: &Path, limit: u64) -> anyhow::Result<Vec<String>> {
201 let raw = Command::new("git")
202 .args([
203 "diff",
204 "--cached",
205 "--raw",
206 "--full-index",
207 "--no-renames",
208 "-z",
209 "--diff-filter=AMT",
210 ])
211 .current_dir(dir)
212 .output_with_context()
213 .await?;
214 if !raw.status.success() {
215 return Ok(Vec::new());
216 }
217
218 let entries = parse_raw_diff(&String::from_utf8_lossy(&raw.stdout));
219 if entries.is_empty() {
220 return Ok(Vec::new());
221 }
222
223 let mut child = Command::new("git")
224 .args(["cat-file", "--batch-check=%(objectsize)"])
225 .current_dir(dir)
226 .stdin(Stdio::piped())
227 .stdout(Stdio::piped())
228 .stderr(Stdio::piped())
229 .kill_on_drop(true)
230 .spawn()?;
231 let mut input = entries
232 .iter()
233 .map(|(sha, _)| sha.as_str())
234 .collect::<Vec<_>>()
235 .join("\n");
236 input.push('\n');
237 {
238 let mut stdin = child
239 .stdin
240 .take()
241 .ok_or_else(|| anyhow::anyhow!("git cat-file stdin closed"))?;
242 stdin.write_all(input.as_bytes()).await?;
243 }
244
245 let sizes = child.wait_with_output().await?;
246 if !sizes.status.success() {
247 anyhow::bail!(
248 "git cat-file failed: {}",
249 String::from_utf8_lossy(&sizes.stderr).trim()
250 );
251 }
252
253 let oversized: Vec<String> = String::from_utf8_lossy(&sizes.stdout)
254 .lines()
255 .zip(&entries)
256 .filter(|(size, _)| size.trim().parse::<u64>().is_ok_and(|n| n > limit))
257 .map(|(_, (_, path))| path.clone())
258 .collect();
259 if oversized.is_empty() {
260 return Ok(oversized);
261 }
262
263 let restore = Command::new("git")
264 .args(["--literal-pathspecs", "restore", "--staged", "--"])
265 .args(&oversized)
266 .current_dir(dir)
267 .output_with_context()
268 .await?;
269 if !restore.status.success() {
270 anyhow::bail!(
271 "failed to unstage files over GitHub's size limit: {}",
272 String::from_utf8_lossy(&restore.stderr).trim()
273 );
274 }
275
276 Ok(oversized)
277}
278
279fn parse_raw_diff(out: &str) -> Vec<(String, String)> {
281 let mut fields = out.split('\0');
282 let mut entries = Vec::new();
283 while let (Some(meta), Some(path)) = (fields.next(), fields.next()) {
284 let parts: Vec<&str> = meta.trim_start_matches(':').split(' ').collect();
285 if let [_, mode, _, sha, _] = parts[..]
286 && mode != "160000"
287 {
288 entries.push((sha.to_string(), path.to_string()));
289 }
290 }
291 entries
292}
293
294async fn has_staged(dir: &Path) -> bool {
295 Command::new("git")
296 .args(["diff", "--cached", "--quiet"])
297 .current_dir(dir)
298 .status()
299 .await
300 .is_ok_and(|s| !s.success())
301}
302
303async fn unstage(dir: &Path, commit_err: &str) -> anyhow::Result<()> {
305 let restore = Command::new("git")
306 .args(["restore", "--staged", "."])
307 .current_dir(dir)
308 .output_with_context()
309 .await;
310 let restore_err = match restore {
311 Ok(o) if o.status.success() => return Ok(()),
312 Ok(o) => String::from_utf8_lossy(&o.stderr).trim().to_string(),
313 Err(e) => e.to_string(),
314 };
315 tracing::warn!(err = %restore_err, "git restore --staged failed, falling back to git reset HEAD -- .");
316 let reset = Command::new("git")
317 .args(["reset", "HEAD", "--", "."])
318 .current_dir(dir)
319 .output_with_context()
320 .await?;
321 if !reset.status.success() {
322 anyhow::bail!(
323 "git commit failed and cleanup failed (git restore --staged + git reset HEAD -- .): commit stderr: {commit_err}; restore: {restore_err}; reset stderr: {}",
324 String::from_utf8_lossy(&reset.stderr).trim()
325 );
326 }
327
328 Ok(())
329}
330
331pub async fn has_changes(dir: &Path) -> bool {
333 let diff = Command::new("git")
335 .args(["diff", "--quiet"])
336 .current_dir(dir)
337 .status()
338 .await;
339
340 let cached = Command::new("git")
341 .args(["diff", "--cached", "--quiet"])
342 .current_dir(dir)
343 .status()
344 .await;
345
346 let untracked = Command::new("git")
347 .args(["ls-files", "--others", "--exclude-standard"])
348 .current_dir(dir)
349 .output_with_context()
350 .await;
351
352 let has_diff = diff.is_ok_and(|s| !s.success());
353 let has_cached = cached.is_ok_and(|s| !s.success());
354 let has_untracked =
355 untracked.is_ok_and(|o| !String::from_utf8_lossy(&o.stdout).trim().is_empty());
356
357 has_diff || has_cached || has_untracked
358}
359
360#[cfg(test)]
361mod tests {
362 use serial_test::serial;
363 use std::env;
364 use std::fs;
365 use std::fs::Permissions;
366 use std::os::unix::fs::PermissionsExt;
367 use std::path::PathBuf;
368 use std::process;
369
370 use super::*;
371
372 fn git(dir: &Path, args: &[&str]) -> String {
373 let out = process::Command::new("git")
374 .args([
375 "-c",
376 "user.name=T",
377 "-c",
378 "user.email=t@t",
379 "-c",
380 "commit.gpgsign=false",
381 ])
382 .args(args)
383 .current_dir(dir)
384 .output()
385 .unwrap();
386 assert!(
387 out.status.success(),
388 "git {args:?}: {}",
389 String::from_utf8_lossy(&out.stderr)
390 );
391 String::from_utf8_lossy(&out.stdout).to_string()
392 }
393
394 fn repo() -> tempfile::TempDir {
395 let dir = tempfile::tempdir().unwrap();
396 git(dir.path(), &["init", "-b", "main"]);
397 fs::write(dir.path().join("base.txt"), "base").unwrap();
398 git(dir.path(), &["add", "base.txt"]);
399 git(dir.path(), &["commit", "-m", "base"]);
400 dir
401 }
402
403 fn fake_shipcheck(dir: &Path, ok: bool) -> PathBuf {
405 let bin = dir.join("shipcheck");
406 let body = if ok {
407 "#!/bin/sh\ngit add -A && git -c commit.gpgsign=false commit -q -m \"$3\"\n"
408 } else {
409 "#!/bin/sh\necho 'no passing result for this tree' >&2\nexit 1\n"
410 };
411 fs::write(&bin, body).unwrap();
412 fs::set_permissions(&bin, Permissions::from_mode(0o755)).unwrap();
413 bin
414 }
415
416 #[tokio::test]
417 #[serial(orch_home)]
418 async fn git_commits_every_change_and_reports_nothing_on_a_clean_tree() {
419 let orch = tempfile::tempdir().unwrap();
420 unsafe { env::set_var("ORCH_HOME", orch.path()) };
422 let dir = repo();
423 let missing = Path::new("/nonexistent/shipcheck");
424 fs::write(dir.path().join("a.txt"), "a").unwrap();
425 let out = commit_with(
426 dir.path(),
427 Tool::Git,
428 missing,
429 "step",
430 "claude",
431 When::Tested,
432 )
433 .await
434 .unwrap();
435 assert_eq!(
436 out,
437 Outcome::Committed {
438 skipped_oversized: vec![]
439 }
440 );
441 let (name, _) = identity("claude");
442 assert_eq!(
443 git(dir.path(), &["log", "-1", "--format=%s%n%an"]).trim(),
444 format!("step\n{name}")
445 );
446 let out = commit_with(
447 dir.path(),
448 Tool::Git,
449 missing,
450 "again",
451 "claude",
452 When::Tested,
453 )
454 .await
455 .unwrap();
456 assert_eq!(
457 out,
458 Outcome::Nothing {
459 skipped_oversized: vec![]
460 }
461 );
462 }
463
464 #[tokio::test]
465 async fn oversized_blobs_are_unstaged_and_the_rest_stays_staged() {
466 let dir = repo();
467 fs::write(dir.path().join("big file.db"), vec![0u8; 64]).unwrap();
468 fs::write(dir.path().join("small.txt"), "s").unwrap();
469 fs::write(dir.path().join("base.txt"), vec![1u8; 64]).unwrap();
470 git(dir.path(), &["add", "-A"]);
471 let skipped = unstage_oversized(dir.path(), 32).await.unwrap();
472 assert_eq!(
473 skipped,
474 vec!["base.txt".to_string(), "big file.db".to_string()]
475 );
476 assert_eq!(
477 git(dir.path(), &["diff", "--cached", "--name-only"]),
478 "small.txt\n"
479 );
480 assert!(has_staged(dir.path()).await);
481 assert!(unstage_oversized(dir.path(), 32).await.unwrap().is_empty());
482 }
483
484 #[tokio::test]
485 async fn a_tree_with_only_oversized_blobs_stages_nothing() {
486 let dir = repo();
487 fs::write(dir.path().join("big.db"), vec![0u8; 64]).unwrap();
488 git(dir.path(), &["add", "-A"]);
489 unstage_oversized(dir.path(), 32).await.unwrap();
490 assert!(!has_staged(dir.path()).await);
491 assert_eq!(git(dir.path(), &["status", "--porcelain"]), "?? big.db\n");
492 }
493
494 #[tokio::test]
495 async fn a_shipcheck_refusal_commits_nothing_and_leaves_the_tree() {
496 let dir = repo();
497 let bins = tempfile::tempdir().unwrap();
498 let bin = fake_shipcheck(bins.path(), false);
499 let head = git(dir.path(), &["rev-parse", "HEAD"]);
500 fs::write(dir.path().join("untested.txt"), "x").unwrap();
501 let out = commit_with(
502 dir.path(),
503 Tool::Shipcheck,
504 &bin,
505 "step",
506 "claude",
507 When::Tested,
508 )
509 .await
510 .unwrap();
511 match out {
512 Outcome::Refused { by, reason } => {
513 assert_eq!(by, Tool::Shipcheck);
514 assert!(reason.contains("shipcheck run"), "{reason}");
515 }
516 other => panic!("expected a refusal, got {other:?}"),
517 }
518 assert_eq!(git(dir.path(), &["rev-parse", "HEAD"]), head);
519 assert_eq!(
520 git(dir.path(), &["status", "--porcelain"]),
521 "?? untested.txt\n"
522 );
523 }
524
525 #[tokio::test]
526 async fn an_accepting_shipcheck_commits() {
527 let dir = repo();
528 let bins = tempfile::tempdir().unwrap();
529 let bin = fake_shipcheck(bins.path(), true);
530 fs::write(dir.path().join("tested.txt"), "x").unwrap();
531 let out = commit_with(
532 dir.path(),
533 Tool::Shipcheck,
534 &bin,
535 "tested step",
536 "claude",
537 When::Tested,
538 )
539 .await
540 .unwrap();
541 assert_eq!(
542 out,
543 Outcome::Committed {
544 skipped_oversized: vec![]
545 }
546 );
547 assert_eq!(
548 git(dir.path(), &["log", "-1", "--format=%s"]).trim(),
549 "tested step"
550 );
551 }
552
553 #[tokio::test]
554 async fn the_end_of_a_session_commits_untested_work_through_git() {
555 let dir = repo();
556 let bins = tempfile::tempdir().unwrap();
557 let bin = fake_shipcheck(bins.path(), false);
558 fs::write(dir.path().join("untested.txt"), "x").unwrap();
559 let out = commit_with(
560 dir.path(),
561 Tool::Shipcheck,
562 &bin,
563 "final",
564 "claude",
565 When::Always,
566 )
567 .await
568 .unwrap();
569 assert_eq!(
570 out,
571 Outcome::Committed {
572 skipped_oversized: vec![]
573 }
574 );
575 assert_eq!(git(dir.path(), &["status", "--porcelain"]), "");
576 assert_eq!(
577 git(dir.path(), &["log", "-1", "--format=%s"]).trim(),
578 "final"
579 );
580 }
581
582 #[test]
583 fn oversized_commit_note_lists_the_paths() {
584 assert_eq!(
585 oversized_commit_note(&["data/x.sqlite".to_string(), "a.bin".to_string()]),
586 "left files over GitHub's size limit out of the commit: data/x.sqlite, a.bin"
587 );
588 }
589
590 #[test]
591 fn parse_raw_diff_reads_blob_paths_and_skips_gitlinks() {
592 let out = ":100644 100644 oldsha newsha M\0src/a.rs\0\
593:000000 100644 0000000 blobsha A\0big file.db\0\
594:100644 160000 oldsha subsha T\0vendor/lib\0";
595 assert_eq!(
596 parse_raw_diff(out),
597 vec![
598 ("newsha".to_string(), "src/a.rs".to_string()),
599 ("blobsha".to_string(), "big file.db".to_string()),
600 ]
601 );
602 }
603}