1use crate::api_client::{ApiClient, CheckPoliciesRequest, SessionCheckData};
2use crate::credentials::resolve_credentials;
3use crate::resolution::{resolve_repo_by_name, ResolveRepoByNameError};
4use std::collections::HashSet;
5use std::fs;
6use std::path::Path;
7use std::process::Command;
8
9fn git_head_sha(project_root: &Path) -> Option<String> {
10 let out = Command::new("git")
11 .args(["rev-parse", "HEAD"])
12 .current_dir(project_root)
13 .output()
14 .ok()?;
15 if !out.status.success() {
16 return None;
17 }
18 let sha = String::from_utf8_lossy(&out.stdout).trim().to_string();
19 if sha.is_empty() {
20 None
21 } else {
22 Some(sha)
23 }
24}
25
26#[derive(Debug, PartialEq)]
28pub(crate) struct PushRef {
29 pub local_sha: String,
30 pub remote_sha: String,
31}
32
33fn is_zero_sha(sha: &str) -> bool {
34 !sha.is_empty() && sha.chars().all(|c| c == '0')
35}
36
37pub(crate) fn parse_push_refs(stdin: &str) -> Vec<PushRef> {
42 stdin
43 .lines()
44 .filter_map(|line| {
45 let mut parts = line.split_whitespace();
46 let _local_ref = parts.next()?;
47 let local_sha = parts.next()?;
48 let _remote_ref = parts.next()?;
49 let remote_sha = parts.next()?;
50 if is_zero_sha(local_sha) {
51 return None;
52 }
53 Some(PushRef {
54 local_sha: local_sha.to_string(),
55 remote_sha: remote_sha.to_string(),
56 })
57 })
58 .collect()
59}
60
61fn changed_files_for_refs(project_root: &Path, refs: &[PushRef]) -> Vec<String> {
65 let mut seen = HashSet::new();
66 let mut out = Vec::new();
67 for r in refs {
68 let base = if is_zero_sha(&r.remote_sha) {
72 match git_empty_tree_sha(project_root) {
73 Some(t) => t,
74 None => continue,
75 }
76 } else {
77 r.remote_sha.clone()
78 };
79 let out_bytes = Command::new("git")
80 .args([
81 "diff",
82 "--name-only",
83 "-z",
89 "--no-renames",
94 &format!("{base}..{}", r.local_sha),
95 ])
96 .current_dir(project_root)
97 .output();
98 let Ok(o) = out_bytes else { continue };
99 if !o.status.success() {
100 continue;
101 }
102 for p in split_nul_delimited_paths(&o.stdout) {
103 if seen.insert(p.clone()) {
104 out.push(p);
105 }
106 }
107 }
108 out
109}
110
111fn split_nul_delimited_paths(bytes: &[u8]) -> Vec<String> {
121 String::from_utf8_lossy(bytes)
122 .split('\0')
123 .filter(|p| !p.is_empty())
124 .map(|p| p.to_string())
125 .collect()
126}
127
128fn git_empty_tree_sha(project_root: &Path) -> Option<String> {
131 let out = Command::new("git")
132 .args(["hash-object", "-t", "tree", "/dev/null"])
133 .current_dir(project_root)
134 .output()
135 .ok()?;
136 if !out.status.success() {
137 return None;
138 }
139 let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
140 if s.is_empty() {
141 None
142 } else {
143 Some(s)
144 }
145}
146
147const STDIN_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
153
154fn read_with_timeout<F>(f: F, timeout: std::time::Duration) -> Option<String>
166where
167 F: FnOnce() -> Option<String> + Send + 'static,
168{
169 let (tx, rx) = std::sync::mpsc::channel();
170 std::thread::spawn(move || {
171 let _ = tx.send(f());
172 });
173 rx.recv_timeout(timeout).ok().flatten()
174}
175
176fn read_stdin_with_timeout(timeout: std::time::Duration) -> Option<String> {
184 use std::io::Read;
185 read_with_timeout(
186 || {
187 let mut buf = String::new();
188 std::io::stdin().read_to_string(&mut buf).ok().map(|_| buf)
189 },
190 timeout,
191 )
192}
193
194fn resolve_changed_paths(project_root: &Path) -> Option<Vec<String>> {
205 use std::io::IsTerminal;
206
207 if !std::io::stdin().is_terminal() {
213 if let Some(buf) = read_stdin_with_timeout(STDIN_READ_TIMEOUT) {
214 let refs = parse_push_refs(&buf);
215 if !refs.is_empty() {
216 let files = changed_files_for_refs(project_root, &refs);
226 return if files.is_empty() { None } else { Some(files) };
227 }
228 }
229 }
230
231 let out = Command::new("git")
235 .args([
236 "diff",
237 "--name-only",
238 "-z",
239 "--no-renames",
240 "@{upstream}..HEAD",
241 ])
242 .current_dir(project_root)
243 .output()
244 .ok()?;
245 if !out.status.success() {
246 return None;
247 }
248 let files = split_nul_delimited_paths(&out.stdout);
249 if files.is_empty() {
250 None
251 } else {
252 Some(files)
253 }
254}
255
256fn collect_session_data(session_dir: &Path) -> Option<SessionCheckData> {
257 let session_id = session_dir.file_name()?.to_string_lossy().to_string();
258
259 let events_path = session_dir.join("events.jsonl");
261 let mut files_modified = Vec::new();
262 let mut files_seen = HashSet::new();
263
264 if events_path.exists() {
265 if let Ok(content) = fs::read_to_string(&events_path) {
266 for line in content.lines() {
267 let event: serde_json::Value = match serde_json::from_str(line) {
268 Ok(v) => v,
269 Err(_) => continue,
270 };
271 if let Some(path) = event
272 .get("tool_input")
273 .and_then(|v| v.get("file_path"))
274 .and_then(|v| v.as_str())
275 {
276 if files_seen.insert(path.to_string()) {
277 files_modified.push(path.to_string());
278 }
279 }
280 }
281 }
282 }
283
284 let meta_path = session_dir.join("metadata.json");
286 let metadata: Option<serde_json::Value> = meta_path
287 .exists()
288 .then(|| fs::read_to_string(&meta_path).ok())
289 .flatten()
290 .and_then(|c| serde_json::from_str(&c).ok());
291
292 let transcript_path = metadata
293 .as_ref()
294 .and_then(|m| m.get("transcript_path"))
295 .and_then(|v| v.as_str())
296 .map(|s| s.to_string());
297
298 let mut tool_calls_map: std::collections::HashMap<String, i32> =
299 std::collections::HashMap::new();
300 let mut total_tool_calls: i32 = 0;
301
302 if let Some(path) = &transcript_path {
303 if let Ok(content) = fs::read_to_string(path) {
304 for line in content.lines() {
305 let entry: serde_json::Value = match serde_json::from_str(line) {
306 Ok(v) => v,
307 Err(_) => continue,
308 };
309
310 if entry.get("type").and_then(|v| v.as_str()) == Some("assistant") {
311 if let Some(content_arr) = entry
312 .get("message")
313 .and_then(|m| m.get("content"))
314 .and_then(|c| c.as_array())
315 {
316 for block in content_arr {
317 if block.get("type").and_then(|v| v.as_str()) == Some("tool_use") {
318 if let Some(name) = block.get("name").and_then(|v| v.as_str()) {
319 *tool_calls_map.entry(name.to_string()).or_insert(0) += 1;
320 total_tool_calls += 1;
321 }
322 }
323 }
324 }
325 }
326 }
327 }
328 }
329
330 let tool_calls = if tool_calls_map.is_empty() {
331 None
332 } else {
333 serde_json::to_value(&tool_calls_map).ok()
334 };
335
336 Some(SessionCheckData {
337 session_id,
338 tool_calls,
339 files_modified: if files_modified.is_empty() {
340 None
341 } else {
342 Some(files_modified)
343 },
344 total_tool_calls: if total_tool_calls > 0 {
345 Some(total_tool_calls)
346 } else {
347 None
348 },
349 })
350}
351
352pub fn select_worktree_sessions(
363 session_dirs: Vec<std::path::PathBuf>,
364 worktree_top: &str,
365) -> (Vec<std::path::PathBuf>, bool) {
366 let belongs = |dir: &std::path::Path| -> bool {
367 match fs::read_to_string(dir.join("origin")) {
368 Ok(s) => s.trim() == worktree_top, Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,
371 Err(_) => false,
376 }
377 };
378 let filtered: Vec<_> = session_dirs
379 .iter()
380 .filter(|d| belongs(d))
381 .cloned()
382 .collect();
383 if filtered.is_empty() && !session_dirs.is_empty() {
384 (session_dirs, true)
385 } else {
386 (filtered, false)
387 }
388}
389
390pub async fn check_policies(
401 project_root: &Path,
402 cwd: &Path,
403) -> Result<(), Box<dyn std::error::Error>> {
404 let (server_url, credential) = resolve_credentials(project_root)?;
405
406 let server_url = server_url
407 .ok_or("No server URL configured. Run `tracevault login --server-url=<url>` to set one.")?;
408
409 if credential.is_none() {
410 return Err(
411 "Not logged in. Run `tracevault login --server-url=<server_url>` to authenticate."
412 .into(),
413 );
414 }
415
416 let client = ApiClient::with_credential(&server_url, credential);
417
418 let repo = match resolve_repo_by_name(&client, project_root).await {
428 Ok(r) => r,
429 Err(ResolveRepoByNameError::ListFailed(e)) => {
430 return Err(connectivity_message(&e.to_string()).into());
431 }
432 Err(ResolveRepoByNameError::NotFound { repo_name }) => {
433 return Err(format!(
434 "Repo '{repo_name}' not found on server. Run `tracevault sync` first."
435 )
436 .into());
437 }
438 };
439
440 let sessions_dir = project_root.join(".tracevault").join("sessions");
442 let mut unpushed_dirs: Vec<std::path::PathBuf> = Vec::new();
443 if sessions_dir.exists() {
444 for entry in fs::read_dir(&sessions_dir)? {
445 let entry = entry?;
446 if !entry.file_type()?.is_dir() {
447 continue;
448 }
449 let session_dir = entry.path();
450 if session_dir.join(".pushed").exists() {
451 continue;
452 }
453 unpushed_dirs.push(session_dir);
454 }
455 }
456
457 let worktree_top = crate::paths::worktree_toplevel(cwd);
460 let (selected_dirs, fell_back) = select_worktree_sessions(unpushed_dirs, &worktree_top);
461 if fell_back {
462 eprintln!(
463 "Warning: no unpushed session matched this worktree by origin marker — \
464 checking all unpushed sessions to avoid skipping policy enforcement."
465 );
466 }
467
468 let mut sessions = Vec::new();
469 for session_dir in &selected_dirs {
470 if let Some(data) = collect_session_data(session_dir) {
471 sessions.push(data);
472 }
473 }
474
475 if sessions.is_empty() {
476 println!("No unpushed sessions to check.");
477 return Ok(());
478 }
479
480 println!("Checking {} session(s) against policies...", sessions.len());
481
482 let commit_sha = git_head_sha(cwd);
485 let changed_paths = resolve_changed_paths(cwd);
486 let result = client
487 .check_policies(
488 &repo.id,
489 CheckPoliciesRequest {
490 sessions,
491 commit_sha,
492 changed_paths,
493 },
494 )
495 .await
496 .map_err(|e| connectivity_message(&e.to_string()))?;
497
498 for r in &result.results {
500 let icon = match r.result.as_str() {
501 "pass" => "\x1b[32m✓\x1b[0m", "fail" if r.action == "block_push" => "\x1b[31m✗\x1b[0m", "fail" => "\x1b[33m!\x1b[0m", _ => " ",
505 };
506 println!(
507 " {} [{}] {} — {}",
508 icon, r.severity, r.rule_name, r.details
509 );
510 }
511
512 if result.blocked {
513 eprintln!("\n\x1b[31mPolicy check failed: push blocked.\x1b[0m");
514 std::process::exit(1);
515 } else if result.passed {
516 println!("\n\x1b[32mAll policy checks passed.\x1b[0m");
517 } else {
518 println!("\n\x1b[33mPolicy warnings found (push not blocked).\x1b[0m");
519 }
520
521 Ok(())
522}
523
524fn connectivity_message(raw: &str) -> String {
532 let lower = raw.to_ascii_lowercase();
533
534 if lower.contains("401") || lower.contains("unauthorized") {
537 return with_action(
538 raw,
539 "Session token may be expired. Run `tracevault login --server-url=<server_url>` to refresh.",
540 );
541 }
542 if lower.contains("403") || lower.contains("forbidden") {
545 return with_action(
546 raw,
547 "Your token is not authorized for this repo's policies. Confirm the token/service account has access and rerun `tracevault login`.",
548 );
549 }
550 if lower.contains("404") {
558 return with_action(
559 raw,
560 "This server may not recognize this endpoint yet — this can happen when the CLI is newer than the server. Confirm the server has been upgraded, or downgrade the CLI to match it.",
561 );
562 }
563 if is_server_error(&lower) {
566 return with_action(
567 raw,
568 "TraceVault server returned an error. The team has likely been paged; retry shortly.",
569 );
570 }
571 if lower.contains("dns")
574 || lower.contains("connect")
575 || lower.contains("timed out")
576 || lower.contains("timeout")
577 {
578 return with_action(
579 raw,
580 "Could not reach the TraceVault server. Check network and `server_url` in .tracevault/config.toml.",
581 );
582 }
583 format!("Policy check could not run: {raw}.")
585}
586
587fn with_action(raw: &str, action: &str) -> String {
589 format!("Policy check could not run: {raw}.\n → {action}")
590}
591
592fn is_server_error(lower: &str) -> bool {
597 lower.contains("internal")
598 || lower.contains("server error")
599 || ["500", "501", "502", "503", "504"]
600 .iter()
601 .any(|code| lower.contains(code))
602}
603
604#[cfg(test)]
605mod worktree_tests {
606 use super::select_worktree_sessions;
607 use std::path::PathBuf;
608
609 fn seed(tmp: &std::path::Path, id: &str, origin: Option<&str>) -> PathBuf {
610 let d = tmp.join(id);
611 std::fs::create_dir_all(&d).unwrap();
612 if let Some(o) = origin {
613 std::fs::write(d.join("origin"), o).unwrap();
614 }
615 d
616 }
617
618 #[test]
619 fn keeps_current_worktree_and_unmarked_excludes_other() {
620 let tmp = tempfile::tempdir().unwrap();
621 let mine = seed(tmp.path(), "mine", Some("/wt/here"));
622 let other = seed(tmp.path(), "other", Some("/wt/there"));
623 let legacy = seed(tmp.path(), "legacy", None);
624
625 let (kept, fell_back) = select_worktree_sessions(
626 vec![mine.clone(), other.clone(), legacy.clone()],
627 "/wt/here",
628 );
629
630 assert!(!fell_back);
631 assert!(kept.contains(&mine), "current worktree session kept");
632 assert!(
633 kept.contains(&legacy),
634 "unmarked legacy session kept (conservative)"
635 );
636 assert!(
637 !kept.contains(&other),
638 "other worktree's marked session excluded"
639 );
640 }
641
642 #[test]
643 fn excludes_session_with_unreadable_marker() {
644 let tmp = tempfile::tempdir().unwrap();
645 let mine = seed(tmp.path(), "mine", Some("/wt/here"));
646 let bad = tmp.path().join("bad");
649 std::fs::create_dir_all(bad.join("origin")).unwrap();
650
651 let (kept, fell_back) =
652 select_worktree_sessions(vec![mine.clone(), bad.clone()], "/wt/here");
653
654 assert!(!fell_back);
655 assert!(kept.contains(&mine), "current worktree session kept");
656 assert!(
657 !kept.contains(&bad),
658 "session with a present-but-unreadable marker must be excluded, not kept as legacy"
659 );
660 }
661
662 #[test]
663 fn falls_back_to_all_when_nothing_matches() {
664 let tmp = tempfile::tempdir().unwrap();
665 let a = seed(tmp.path(), "a", Some("/wt/there"));
666 let b = seed(tmp.path(), "b", Some("/wt/elsewhere"));
667
668 let (kept, fell_back) = select_worktree_sessions(vec![a.clone(), b.clone()], "/wt/here");
669
670 assert!(fell_back, "must flag fallback when filter matches nothing");
671 assert_eq!(
672 kept.len(),
673 2,
674 "never under-enforce: send all rather than zero"
675 );
676 }
677}
678
679#[cfg(test)]
680mod tests {
681 use super::connectivity_message;
682
683 #[test]
684 fn connectivity_message_suggests_login_on_401() {
685 let m = connectivity_message("Stream failed (401 Unauthorized): bad token");
686 assert!(
687 m.contains("tracevault login"),
688 "401 errors must surface the login hint; got: {m}"
689 );
690 }
691
692 #[test]
693 fn connectivity_message_suggests_login_on_unauthorized_text() {
694 let m = connectivity_message("Server returned: unauthorized request");
695 assert!(m.contains("tracevault login"));
696 }
697
698 #[test]
699 fn connectivity_message_suggests_network_check_on_dns_error() {
700 let m = connectivity_message("error sending request for url: dns error");
701 assert!(
702 m.to_lowercase().contains("network") || m.to_lowercase().contains("server_url"),
703 "DNS errors must surface a network hint; got: {m}"
704 );
705 }
706
707 #[test]
708 fn connectivity_message_suggests_network_check_on_connection_refused() {
709 let m = connectivity_message("connection refused");
710 assert!(m.to_lowercase().contains("network"));
711 }
712
713 #[test]
714 fn connectivity_message_falls_back_when_unrecognized() {
715 let m = connectivity_message("some weird new error shape we have not seen before");
716 assert!(m.contains("some weird new error shape"));
719 assert!(!m.contains("→")); }
721
722 #[test]
723 fn connectivity_message_does_not_collide_on_403() {
724 let m = connectivity_message("403 Forbidden");
725 assert!(
727 m.to_lowercase().contains("authorized"),
728 "403 should mention authorization; got: {m}"
729 );
730 }
731
732 #[test]
733 fn connectivity_message_flags_404_as_version_mismatch() {
734 let m = connectivity_message("Failed to list repos (404 Not Found): ");
739 assert!(
740 m.to_lowercase().contains("newer than the server")
741 || m.to_lowercase().contains("version mismatch"),
742 "404 should hint at a possible CLI/server version mismatch; got: {m}"
743 );
744 }
745
746 #[test]
747 fn connectivity_message_flags_500_as_server_error() {
748 let m = connectivity_message("Server returned 500 Internal Server Error: oops");
749 assert!(
750 m.to_lowercase().contains("server returned an error"),
751 "500 should surface the server-error hint; got: {m}"
752 );
753 }
754
755 #[test]
756 fn connectivity_message_flags_503_without_internal_text() {
757 let m = connectivity_message("Server returned 503 Service Unavailable: ");
760 assert!(
761 m.to_lowercase().contains("server returned an error"),
762 "503 should surface the server-error hint; got: {m}"
763 );
764 }
765
766 #[test]
767 fn connectivity_message_treats_504_as_server_not_network() {
768 let m = connectivity_message("Server returned 504 Gateway Timeout: ");
772 assert!(
773 m.to_lowercase().contains("server returned an error"),
774 "504 should be treated as a server error; got: {m}"
775 );
776 }
777}
778
779#[cfg(test)]
780mod push_ref_tests {
781 use super::{is_zero_sha, parse_push_refs};
782
783 #[test]
784 fn parses_a_single_ref_line() {
785 let refs = parse_push_refs("refs/heads/main abc123 refs/heads/main def456\n");
786 assert_eq!(refs.len(), 1);
787 assert_eq!(refs[0].local_sha, "abc123");
788 assert_eq!(refs[0].remote_sha, "def456");
789 }
790
791 #[test]
792 fn parses_multiple_refs() {
793 let refs = parse_push_refs(
794 "refs/heads/a 111 refs/heads/a 222\nrefs/heads/b 333 refs/heads/b 444\n",
795 );
796 assert_eq!(refs.len(), 2);
797 }
798
799 #[test]
800 fn parses_a_single_ref_line_without_trailing_newline() {
801 let refs = parse_push_refs("refs/heads/main abc123 refs/heads/main def456");
809 assert_eq!(refs.len(), 1);
810 assert_eq!(refs[0].local_sha, "abc123");
811 assert_eq!(refs[0].remote_sha, "def456");
812 }
813
814 #[test]
815 fn parses_multiple_refs_when_last_line_has_no_trailing_newline() {
816 let refs =
820 parse_push_refs("refs/heads/a 111 refs/heads/a 222\nrefs/heads/b 333 refs/heads/b 444");
821 assert_eq!(refs.len(), 2);
822 assert_eq!(refs[0].local_sha, "111");
823 assert_eq!(refs[1].local_sha, "333");
824 }
825
826 #[test]
827 fn skips_branch_deletions() {
828 let zeros = "0".repeat(40);
829 let line = format!("(delete) {zeros} refs/heads/gone abc123\n");
830 assert!(parse_push_refs(&line).is_empty());
831 }
832
833 #[test]
834 fn keeps_new_branches_whose_remote_sha_is_zero() {
835 let zeros = "0".repeat(40);
836 let line = format!("refs/heads/new abc123 refs/heads/new {zeros}\n");
837 let refs = parse_push_refs(&line);
838 assert_eq!(refs.len(), 1);
839 assert!(is_zero_sha(&refs[0].remote_sha));
840 }
841
842 #[test]
843 fn skips_malformed_lines_without_panicking() {
844 assert!(parse_push_refs("garbage\n\nalso garbage here\n").is_empty());
845 }
846
847 #[test]
848 fn zero_sha_detection_handles_sha256_length() {
849 assert!(is_zero_sha(&"0".repeat(64)));
850 assert!(!is_zero_sha("0000000000000000000000000000000000000001"));
851 assert!(!is_zero_sha(""));
852 }
853}
854
855#[cfg(test)]
875mod git_diff_tests {
876 use super::{changed_files_for_refs, git_empty_tree_sha, PushRef};
877 use crate::test_helpers::init_git_repo;
878 use std::path::Path;
879 use std::process::Command;
880
881 fn commit_file(dir: &Path, name: &str, content: &str) -> String {
885 std::fs::write(dir.join(name), content).unwrap();
886 let ok = Command::new("git")
887 .args(["-C", &dir.to_string_lossy(), "add", name])
888 .status()
889 .expect("git add failed")
890 .success();
891 assert!(ok, "git add must succeed");
892 let ok = Command::new("git")
893 .args([
894 "-C",
895 &dir.to_string_lossy(),
896 "commit",
897 "-m",
898 &format!("add {name}"),
899 ])
900 .status()
901 .expect("git commit failed")
902 .success();
903 assert!(ok, "git commit must succeed");
904 head_sha(dir)
905 }
906
907 fn head_sha(dir: &Path) -> String {
908 let out = Command::new("git")
909 .args(["-C", &dir.to_string_lossy(), "rev-parse", "HEAD"])
910 .output()
911 .expect("git rev-parse failed");
912 assert!(out.status.success());
913 String::from_utf8_lossy(&out.stdout).trim().to_string()
914 }
915
916 #[test]
917 fn two_dot_range_returns_only_the_newer_commits_files() {
918 let tmp = tempfile::tempdir().unwrap();
919 init_git_repo(tmp.path()); let sha1 = commit_file(tmp.path(), "a.txt", "a");
922 let sha2 = commit_file(tmp.path(), "b.txt", "b");
923
924 let refs = vec![PushRef {
925 local_sha: sha2,
926 remote_sha: sha1,
927 }];
928 let files = changed_files_for_refs(tmp.path(), &refs);
929
930 assert_eq!(files, vec!["b.txt".to_string()]);
935 }
936
937 #[test]
938 fn new_branch_zero_remote_sha_resolves_via_empty_tree() {
939 let tmp = tempfile::tempdir().unwrap();
940 init_git_repo(tmp.path());
941
942 commit_file(tmp.path(), "a.txt", "a");
943 let sha2 = commit_file(tmp.path(), "b.txt", "b");
944
945 let refs = vec![PushRef {
946 local_sha: sha2,
947 remote_sha: "0".repeat(40),
948 }];
949 let mut files = changed_files_for_refs(tmp.path(), &refs);
950 files.sort();
951
952 assert_eq!(files, vec!["a.txt".to_string(), "b.txt".to_string()]);
955 }
956
957 #[test]
958 fn identical_shas_yield_an_empty_file_list() {
959 let tmp = tempfile::tempdir().unwrap();
960 init_git_repo(tmp.path());
961 let sha = commit_file(tmp.path(), "a.txt", "a");
962
963 let refs = vec![PushRef {
964 local_sha: sha.clone(),
965 remote_sha: sha,
966 }];
967 let files = changed_files_for_refs(tmp.path(), &refs);
968
969 assert!(
970 files.is_empty(),
971 "a no-op push (same local and remote sha) must yield no files, got {files:?}"
972 );
973 }
974
975 #[test]
976 fn non_ascii_path_is_returned_raw_not_octal_quoted() {
977 let tmp = tempfile::tempdir().unwrap();
978 init_git_repo(tmp.path());
979 std::fs::create_dir_all(tmp.path().join("src")).unwrap();
980
981 let sha1 = commit_file(tmp.path(), "src/café.rs", "one");
982 let sha2 = commit_file(tmp.path(), "src/café.rs", "two");
983
984 let refs = vec![PushRef {
985 local_sha: sha2,
986 remote_sha: sha1,
987 }];
988 let files = changed_files_for_refs(tmp.path(), &refs);
989
990 assert_eq!(
996 files,
997 vec!["src/café.rs".to_string()],
998 "must be the raw UTF-8 path, not git's octal-quoted rendering; got {files:?}"
999 );
1000 }
1001
1002 #[test]
1003 fn path_containing_a_space_is_returned_intact() {
1004 let tmp = tempfile::tempdir().unwrap();
1005 init_git_repo(tmp.path());
1006 std::fs::create_dir_all(tmp.path().join("src")).unwrap();
1007
1008 let sha1 = commit_file(tmp.path(), "src/has space.rs", "one");
1009 let sha2 = commit_file(tmp.path(), "src/has space.rs", "two");
1010
1011 let refs = vec![PushRef {
1012 local_sha: sha2,
1013 remote_sha: sha1,
1014 }];
1015 let files = changed_files_for_refs(tmp.path(), &refs);
1016
1017 assert_eq!(files, vec!["src/has space.rs".to_string()]);
1018 }
1019
1020 #[test]
1021 fn rename_reports_both_source_and_destination() {
1022 let tmp = tempfile::tempdir().unwrap();
1023 init_git_repo(tmp.path());
1024 std::fs::create_dir_all(tmp.path().join("src")).unwrap();
1025 let sha1 = commit_file(tmp.path(), "src/plain.rs", "identical content");
1026
1027 let ok = Command::new("git")
1028 .args([
1029 "-C",
1030 &tmp.path().to_string_lossy(),
1031 "mv",
1032 "src/plain.rs",
1033 "src/renamed.rs",
1034 ])
1035 .status()
1036 .expect("git mv failed")
1037 .success();
1038 assert!(ok, "git mv must succeed");
1039 let ok = Command::new("git")
1040 .args([
1041 "-C",
1042 &tmp.path().to_string_lossy(),
1043 "commit",
1044 "-m",
1045 "rename plain.rs to renamed.rs",
1046 ])
1047 .status()
1048 .expect("git commit failed")
1049 .success();
1050 assert!(ok, "git commit must succeed");
1051 let sha2 = head_sha(tmp.path());
1052
1053 let refs = vec![PushRef {
1054 local_sha: sha2,
1055 remote_sha: sha1,
1056 }];
1057 let mut files = changed_files_for_refs(tmp.path(), &refs);
1058 files.sort();
1059
1060 assert_eq!(
1066 files,
1067 vec!["src/plain.rs".to_string(), "src/renamed.rs".to_string()],
1068 "a rename must surface BOTH the source and destination path; got {files:?}"
1069 );
1070 }
1071
1072 #[test]
1073 fn git_empty_tree_sha_is_the_well_known_constant() {
1074 let tmp = tempfile::tempdir().unwrap();
1075 init_git_repo(tmp.path());
1076
1077 let empty_tree =
1078 git_empty_tree_sha(tmp.path()).expect("git hash-object must resolve the empty tree");
1079 assert_eq!(empty_tree, "4b825dc642cb6eb9a060e54bf8d69288fbee4904");
1083 }
1084
1085 #[test]
1092 fn upstream_fallback_diff_fails_cleanly_with_no_upstream_configured() {
1093 let tmp = tempfile::tempdir().unwrap();
1094 init_git_repo(tmp.path());
1095 commit_file(tmp.path(), "a.txt", "a");
1096
1097 let out = Command::new("git")
1098 .args([
1099 "diff",
1100 "--name-only",
1101 "-z",
1102 "--no-renames",
1103 "@{upstream}..HEAD",
1104 ])
1105 .current_dir(tmp.path())
1106 .output()
1107 .expect("git diff must run");
1108
1109 assert!(
1110 !out.status.success(),
1111 "no upstream is configured, so this must fail rather than \
1112 silently resolve to something else"
1113 );
1114 }
1115
1116 #[test]
1120 fn upstream_fallback_diff_is_empty_when_upstream_matches_head() {
1121 let tmp = tempfile::tempdir().unwrap();
1122 init_git_repo(tmp.path());
1123 commit_file(tmp.path(), "a.txt", "a");
1124
1125 let branch_out = Command::new("git")
1126 .args(["symbolic-ref", "--short", "HEAD"])
1127 .current_dir(tmp.path())
1128 .output()
1129 .expect("git symbolic-ref must run");
1130 assert!(branch_out.status.success());
1131 let branch = String::from_utf8_lossy(&branch_out.stdout)
1132 .trim()
1133 .to_string();
1134
1135 for args in [
1139 vec!["branch", "tracking", &branch],
1140 vec!["branch", "--set-upstream-to=tracking", &branch],
1141 ] {
1142 let ok = Command::new("git")
1143 .args(&args)
1144 .current_dir(tmp.path())
1145 .status()
1146 .expect("git command must run")
1147 .success();
1148 assert!(ok, "git {args:?} must succeed");
1149 }
1150
1151 let out = Command::new("git")
1152 .args([
1153 "diff",
1154 "--name-only",
1155 "-z",
1156 "--no-renames",
1157 "@{upstream}..HEAD",
1158 ])
1159 .current_dir(tmp.path())
1160 .output()
1161 .expect("git diff must run");
1162
1163 assert!(out.status.success());
1164 assert!(
1165 out.stdout.is_empty(),
1166 "identical upstream/HEAD must diff to no files"
1167 );
1168 }
1169}
1170
1171#[cfg(test)]
1180mod read_with_timeout_tests {
1181 use super::read_with_timeout;
1182 use std::time::Duration;
1183
1184 #[test]
1185 fn returns_the_value_when_it_arrives_before_the_deadline() {
1186 let got = read_with_timeout(|| Some("hi".to_string()), Duration::from_secs(1));
1187 assert_eq!(got, Some("hi".to_string()));
1188 }
1189
1190 #[test]
1191 fn returns_none_when_the_closure_itself_returns_none() {
1192 let got = read_with_timeout(|| None, Duration::from_secs(1));
1193 assert_eq!(got, None);
1194 }
1195
1196 #[test]
1197 fn times_out_instead_of_hanging_on_a_closure_that_never_returns() {
1198 let start = std::time::Instant::now();
1203 let got = read_with_timeout(
1204 || {
1205 std::thread::sleep(Duration::from_secs(10));
1206 Some("too late".to_string())
1207 },
1208 Duration::from_millis(50),
1209 );
1210 assert_eq!(got, None, "must give up rather than wait for the closure");
1211 assert!(
1212 start.elapsed() < Duration::from_secs(1),
1213 "must return promptly on timeout, not block on the stalled closure; took {:?}",
1214 start.elapsed()
1215 );
1216 }
1217}