1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
/// Shared test utilities for git repository testing.
///
/// Provides a clean API for creating and manipulating test repositories,
/// reducing boilerplate in test code.
use git2::{BranchType, Repository, Signature};
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use tempfile::TempDir;
/// Global mutex to serialize `in_dir` calls.
///
/// `std::env::set_current_dir` mutates process-global state, and Cargo runs
/// tests in parallel threads. Without serialization two concurrent `in_dir`
/// calls would corrupt each other's working directory.
static IN_DIR_LOCK: Mutex<()> = Mutex::new(());
/// A test repository wrapper with convenient helper methods.
pub struct TestRepo {
pub repo: Repository,
_dir: TempDir,
}
impl TestRepo {
/// Create a new test repository with an initial commit.
pub fn new() -> Self {
let dir = tempfile::tempdir().unwrap();
let repo = Repository::init(dir.path()).unwrap();
Self::configure_identity(&repo);
// Create an initial commit
{
let sig = Self::sig();
let tree_id = repo.index().unwrap().write_tree().unwrap();
let tree = repo.find_tree(tree_id).unwrap();
repo.commit(Some("HEAD"), &sig, &sig, "Initial commit", &tree, &[])
.unwrap();
}
TestRepo { repo, _dir: dir }
}
/// Create a test repository without any initial commit (empty).
pub fn new_empty() -> Self {
let dir = tempfile::tempdir().unwrap();
let repo = Repository::init(dir.path()).unwrap();
Self::configure_identity(&repo);
TestRepo { repo, _dir: dir }
}
/// Create a test repository with a remote (bare repo) and an integration branch.
///
/// Sets up:
/// - A bare "remote" repository at remote.git
/// - A cloned working repository
/// - An initial commit on the main branch
/// - An integration branch tracking origin/main
///
/// This mimics a typical development setup with an upstream remote.
pub fn new_with_remote() -> Self {
let dir = tempfile::tempdir().unwrap();
// Create a bare "remote"
let remote_path = dir.path().join("remote.git");
let remote_repo = Repository::init_bare(&remote_path).unwrap();
// Ensure HEAD points to main regardless of system default
remote_repo.set_head("refs/heads/main").unwrap();
// Create initial commit in the bare repo so it has a main branch
{
let sig = Self::sig();
let tree_id = {
let mut index = remote_repo.index().unwrap();
index.write_tree().unwrap()
};
let tree = remote_repo.find_tree(tree_id).unwrap();
remote_repo
.commit(Some("refs/heads/main"), &sig, &sig, "Initial", &tree, &[])
.unwrap();
}
// Clone it
let work_path = dir.path().join("work");
let repo = Repository::clone(remote_path.to_str().unwrap(), &work_path).unwrap();
Self::configure_identity(&repo);
// Create integration branch pointing at main, tracking origin/main
{
let head_commit = repo.head().unwrap().peel_to_commit().unwrap();
repo.branch("integration", &head_commit, false).unwrap();
repo.set_head("refs/heads/integration").unwrap();
// Set upstream tracking
let mut integration = repo.find_branch("integration", BranchType::Local).unwrap();
integration.set_upstream(Some("origin/main")).unwrap();
}
TestRepo { repo, _dir: dir }
}
/// Like `new_with_remote`, but stays on the `main` branch instead of
/// creating a separate `integration` branch. Useful for testing the
/// loose-commit path where the branch name must match the upstream's
/// local name.
pub fn new_on_main_with_remote() -> Self {
let dir = tempfile::tempdir().unwrap();
let remote_path = dir.path().join("remote.git");
let remote_repo = Repository::init_bare(&remote_path).unwrap();
remote_repo.set_head("refs/heads/main").unwrap();
{
let sig = Self::sig();
let tree_id = {
let mut index = remote_repo.index().unwrap();
index.write_tree().unwrap()
};
let tree = remote_repo.find_tree(tree_id).unwrap();
remote_repo
.commit(Some("refs/heads/main"), &sig, &sig, "Initial", &tree, &[])
.unwrap();
}
let work_path = dir.path().join("work");
let repo = Repository::clone(remote_path.to_str().unwrap(), &work_path).unwrap();
Self::configure_identity(&repo);
// After clone, HEAD is already on `main` tracking `origin/main`.
TestRepo { repo, _dir: dir }
}
/// Configure user identity in a repo so shell-invoked git commands work
/// even when no global git config is present.
fn configure_identity(repo: &Repository) {
let mut config = repo.config().unwrap();
config.set_str("user.name", "Test").unwrap();
config.set_str("user.email", "test@test.com").unwrap();
// Prevent git from opening an interactive editor in tests (e.g. for
// `git merge --continue` which is equivalent to `git commit`).
config.set_str("core.editor", "true").unwrap();
}
/// Get the signature used for commits.
fn sig() -> Signature<'static> {
Signature::now("Test", "test@test.com").unwrap()
}
/// Create a commit with a file.
///
/// # Arguments
/// * `message` - The commit message
/// * `filename` - The filename to create/modify
///
/// # Returns
/// The OID of the created commit
pub fn commit(&self, message: &str, filename: &str) -> git2::Oid {
let path = self.repo.workdir().unwrap().join(filename);
fs::write(&path, message).unwrap();
let mut index = self.repo.index().unwrap();
index.add_path(Path::new(filename)).unwrap();
index.write().unwrap();
let tree_id = index.write_tree().unwrap();
let tree = self.repo.find_tree(tree_id).unwrap();
let sig = Self::sig();
if let Ok(head) = self.repo.head() {
let parent = self.repo.find_commit(head.target().unwrap()).unwrap();
self.repo
.commit(Some("HEAD"), &sig, &sig, message, &tree, &[&parent])
.unwrap()
} else {
self.repo
.commit(Some("HEAD"), &sig, &sig, message, &tree, &[])
.unwrap()
}
}
/// Create a commit without changing files (using current tree).
///
/// # Arguments
/// * `message` - The commit message
///
/// # Returns
/// The OID of the created commit
pub fn commit_empty(&self, message: &str) -> git2::Oid {
let sig = Self::sig();
let tree_id = {
let mut index = self.repo.index().unwrap();
index.write_tree().unwrap()
};
let tree = self.repo.find_tree(tree_id).unwrap();
if let Ok(head) = self.repo.head() {
let parent = self.repo.find_commit(head.target().unwrap()).unwrap();
self.repo
.commit(Some("HEAD"), &sig, &sig, message, &tree, &[&parent])
.unwrap()
} else {
self.repo
.commit(Some("HEAD"), &sig, &sig, message, &tree, &[])
.unwrap()
}
}
/// Create a merge commit combining two parent commits.
///
/// # Arguments
/// * `message` - The commit message
/// * `parent1_oid` - OID of the first parent
/// * `parent2_oid` - OID of the second parent
///
/// # Returns
/// The OID of the merge commit
pub fn commit_merge(
&self,
message: &str,
parent1_oid: git2::Oid,
parent2_oid: git2::Oid,
) -> git2::Oid {
let sig = Self::sig();
let p1 = self.repo.find_commit(parent1_oid).unwrap();
let p2 = self.repo.find_commit(parent2_oid).unwrap();
let tree = self.repo.find_tree(p1.tree_id()).unwrap();
self.repo
.commit(Some("HEAD"), &sig, &sig, message, &tree, &[&p1, &p2])
.unwrap()
}
/// Get a commit relative to HEAD.
///
/// # Arguments
/// * `steps_back` - Number of steps back from HEAD (0 = HEAD, 1 = HEAD~1, etc.)
///
/// # Returns
/// The commit at the specified position
///
/// # Example
/// ```ignore
/// let head = test_repo.get_commit(0); // HEAD
/// let parent = test_repo.get_commit(1); // HEAD~1
/// let grandparent = test_repo.get_commit(2); // HEAD~2
/// ```
pub fn get_commit(&self, steps_back: usize) -> git2::Commit<'_> {
let mut commit = self.repo.head().unwrap().peel_to_commit().unwrap();
for _ in 0..steps_back {
commit = commit.parent(0).unwrap();
}
commit
}
/// Get the HEAD commit.
pub fn head_commit(&self) -> git2::Commit<'_> {
self.get_commit(0)
}
/// Get the commit message at a position relative to HEAD.
pub fn get_message(&self, steps_back: usize) -> String {
self.get_commit(steps_back)
.message()
.unwrap()
.trim()
.to_string()
}
/// Get the OID of a commit relative to HEAD.
pub fn get_oid(&self, steps_back: usize) -> git2::Oid {
self.get_commit(steps_back).id()
}
/// Create a branch at the current HEAD.
pub fn create_branch(&self, name: &str) -> git2::Branch<'_> {
let head_commit = self.head_commit();
self.repo.branch(name, &head_commit, false).unwrap()
}
/// Get the path to the working directory.
pub fn workdir(&self) -> PathBuf {
self.repo.workdir().unwrap().to_path_buf()
}
/// Run a closure with the current directory set to the repo's working directory.
///
/// Holds a global mutex so that concurrent test threads cannot corrupt
/// each other's process-wide cwd, and uses a drop guard to guarantee the
/// original directory is restored even if the closure panics.
pub fn in_dir<F, R>(&self, f: F) -> R
where
F: FnOnce() -> R,
{
let _lock = IN_DIR_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let restore = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
std::env::set_current_dir(self.workdir()).unwrap();
// Drop guard: restores cwd whether `f` returns normally or panics.
struct RestoreDir(PathBuf);
impl Drop for RestoreDir {
fn drop(&mut self) {
let _ = std::env::set_current_dir(&self.0);
}
}
let _guard = RestoreDir(restore);
f()
}
/// Run a closure with CWD set to the given path (must be inside the repo).
pub fn in_dir_path<F, R>(&self, path: &Path, f: F) -> R
where
F: FnOnce() -> R,
{
let _lock = IN_DIR_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let restore = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
std::env::set_current_dir(path).unwrap();
struct RestoreDir(PathBuf);
impl Drop for RestoreDir {
fn drop(&mut self) {
let _ = std::env::set_current_dir(&self.0);
}
}
let _guard = RestoreDir(restore);
f()
}
/// Switch HEAD to a branch and update the working directory.
pub fn switch_branch(&self, name: &str) {
self.repo.set_head(&format!("refs/heads/{}", name)).unwrap();
self.repo
.checkout_head(Some(git2::build::CheckoutBuilder::new().force()))
.unwrap();
}
/// Hard-reset the current branch to a specific commit.
pub fn reset_hard(&self, oid: git2::Oid) {
let commit = self.find_commit(oid);
self.repo
.reset(commit.as_object(), git2::ResetType::Hard, None)
.unwrap();
}
/// Force-update the working directory to match HEAD.
pub fn force_checkout(&self) {
self.repo
.checkout_head(Some(git2::build::CheckoutBuilder::new().force()))
.unwrap();
}
/// Create a branch at HEAD that tracks a remote upstream.
pub fn create_branch_tracking(&self, name: &str, upstream: &str) {
let mut branch = self.create_branch(name);
branch.set_upstream(Some(upstream)).unwrap();
}
/// Write content to a file in the working directory (without committing).
pub fn write_file(&self, filename: &str, content: &str) {
let path = self.workdir().join(filename);
fs::write(path, content).unwrap();
}
/// Read content from a file in the working directory.
pub fn read_file(&self, filename: &str) -> String {
let path = self.workdir().join(filename);
fs::read_to_string(path).unwrap()
}
/// Check if HEAD is on a branch.
pub fn is_on_branch(&self) -> bool {
self.repo.head().unwrap().is_branch()
}
/// Get the current branch name (shorthand).
pub fn current_branch_name(&self) -> String {
self.repo.head().unwrap().shorthand().unwrap().to_string()
}
/// Check if a branch exists.
pub fn branch_exists(&self, name: &str) -> bool {
self.repo.find_branch(name, BranchType::Local).is_ok()
}
/// Delete a local branch (including its tracking config).
pub fn delete_branch(&self, name: &str) {
let workdir = self.workdir();
crate::git::branch_delete(workdir.as_path(), name).unwrap();
}
/// Get the current HEAD commit OID.
pub fn head_oid(&self) -> git2::Oid {
self.repo.head().unwrap().target().unwrap()
}
/// Find a commit by OID.
pub fn find_commit(&self, oid: git2::Oid) -> git2::Commit<'_> {
self.repo.find_commit(oid).unwrap()
}
/// Create a branch at a specific commit.
///
/// # Arguments
/// * `name` - The branch name
/// * `oid` - The commit OID where the branch should point
pub fn create_branch_at_commit(&self, name: &str, oid: git2::Oid) -> git2::Branch<'_> {
let commit = self.find_commit(oid);
self.repo.branch(name, &commit, false).unwrap()
}
/// Get the target OID of a remote branch.
///
/// # Arguments
/// * `name` - The remote branch name (e.g., "origin/main")
///
/// # Returns
/// The OID that the remote branch points to
pub fn find_remote_branch_target(&self, name: &str) -> git2::Oid {
self.repo
.find_branch(name, BranchType::Remote)
.unwrap()
.get()
.target()
.unwrap()
}
/// Get the target OID of a branch.
///
/// # Arguments
/// * `name` - The branch name
///
/// # Returns
/// The OID that the branch points to
///
/// # Panics
/// Panics if the branch doesn't exist
pub fn get_branch_target(&self, name: &str) -> git2::Oid {
self.repo
.find_branch(name, BranchType::Local)
.unwrap()
.get()
.target()
.unwrap()
}
/// Set HEAD to a detached state at a specific commit.
///
/// # Arguments
/// * `oid` - The commit OID to detach HEAD to
pub fn set_detached_head(&self, oid: git2::Oid) {
self.repo.set_head_detached(oid).unwrap();
}
/// Set up a fake editor that replaces commit messages.
///
/// # Arguments
/// * `new_message` - The message that the fake editor will write
///
/// # Returns
/// The path to the editor script (for reference)
pub fn set_fake_editor(&self, new_message: &str) -> String {
// Git on Windows uses Git Bash, so we use the same shell command format for all platforms
let editor_script = format!("sh -c 'echo \"{}\" > \"$1\"' --", new_message);
// SAFETY: This is a test environment and we're setting a git-specific env var
// that won't affect other tests or the system
unsafe {
std::env::set_var("GIT_EDITOR", &editor_script);
}
editor_script
}
/// Get the path to the remote repository (if created with new_with_remote).
///
/// Returns None if the repository doesn't have a remote.git setup.
pub fn remote_path(&self) -> Option<PathBuf> {
let remote_path = self._dir.path().join("remote.git");
if remote_path.exists() {
Some(remote_path)
} else {
None
}
}
/// Add commits directly to the remote repository.
///
/// This is useful for simulating upstream changes.
///
/// # Arguments
/// * `messages` - Commit messages to add to the remote's main branch
///
/// # Returns
/// OID of the last commit added
pub fn add_remote_commits(&self, messages: &[&str]) -> git2::Oid {
let remote_path = self.remote_path().expect("No remote repository found");
let remote_repo = Repository::open_bare(&remote_path).unwrap();
let sig = Self::sig();
let mut last_oid = remote_repo
.find_branch("main", BranchType::Local)
.unwrap()
.get()
.target()
.unwrap();
for message in messages {
let parent = remote_repo.find_commit(last_oid).unwrap();
let tree = parent.tree().unwrap();
last_oid = remote_repo
.commit(
Some("refs/heads/main"),
&sig,
&sig,
message,
&tree,
&[&parent],
)
.unwrap();
}
last_oid
}
/// Simulate a cherry-pick of a local commit onto the remote's main branch.
///
/// Computes the diff between the local commit and its parent, then applies
/// those new/changed files on top of the remote tip's tree. This produces a
/// commit with the same patch-id as the original, so git rebase will
/// correctly detect it as a duplicate.
pub fn cherry_pick_to_remote(&self, local_oid: git2::Oid, message: &str) -> git2::Oid {
let remote_path = self.remote_path().expect("No remote repository found");
let remote_repo = Repository::open_bare(&remote_path).unwrap();
// Use a different committer to ensure the cherry-picked commit gets a
// different OID from the original (same patch-id, different commit hash).
let sig = Signature::now("Upstream", "upstream@test.com").unwrap();
let remote_tip = remote_repo
.find_branch("main", BranchType::Local)
.unwrap()
.get()
.target()
.unwrap();
let parent = remote_repo.find_commit(remote_tip).unwrap();
// Diff the local commit against its parent to find changed files
let local_commit = self.repo.find_commit(local_oid).unwrap();
let local_tree = local_commit.tree().unwrap();
let local_parent_tree = local_commit.parent(0).unwrap().tree().unwrap();
let diff = self
.repo
.diff_tree_to_tree(Some(&local_parent_tree), Some(&local_tree), None)
.unwrap();
// Start from the remote tip's tree and overlay changed files
let remote_parent_tree = parent.tree().unwrap();
let mut builder = remote_repo.treebuilder(Some(&remote_parent_tree)).unwrap();
diff.foreach(
&mut |delta, _| {
match delta.status() {
git2::Delta::Added | git2::Delta::Modified => {
let new_file = delta.new_file();
let path = new_file.path().unwrap().to_str().unwrap();
let blob = self.repo.find_blob(new_file.id()).unwrap();
let new_blob = remote_repo.blob(blob.content()).unwrap();
builder.insert(path, new_blob, 0o100644).unwrap();
}
git2::Delta::Deleted => {
let old_file = delta.old_file();
let path = old_file.path().unwrap().to_str().unwrap();
builder.remove(path).unwrap();
}
_ => {}
}
true
},
None,
None,
None,
)
.unwrap();
let tree_oid = builder.write().unwrap();
let tree = remote_repo.find_tree(tree_oid).unwrap();
remote_repo
.commit(
Some("refs/heads/main"),
&sig,
&sig,
message,
&tree,
&[&parent],
)
.unwrap()
}
/// Fetch from the remote repository.
///
/// Updates origin/* references in the working repository.
pub fn fetch_remote(&self) {
self.repo
.find_remote("origin")
.unwrap()
.fetch(&["main"], None, None)
.unwrap();
}
/// Create a branch at a specific commit hash.
pub fn create_branch_at(&self, name: &str, commit_hash: &str) {
crate::git::branch_create(self.workdir().as_path(), name, commit_hash).unwrap();
}
/// Merge a branch into the current branch with --no-ff.
pub fn merge_no_ff(&self, branch: &str) {
let outcome =
crate::git::merge_no_ff(self.workdir().as_path(), self.repo.path(), branch).unwrap();
assert!(
matches!(outcome, crate::git::MergeOutcome::Completed),
"merge_no_ff: expected Completed, got Conflicted"
);
}
/// Stage files in the working directory.
pub fn stage_files(&self, files: &[&str]) {
crate::git::stage_files(self.workdir().as_path(), files).unwrap();
}
/// Commit already-staged files with a message.
pub fn commit_staged(&self, message: &str) {
crate::git::commit(self.workdir().as_path(), message).unwrap();
}
/// Get the names of files that differ from HEAD.
pub fn diff_head_name_only(&self) -> String {
crate::git::diff_head_name_only(self.workdir().as_path()).unwrap()
}
/// Get the diff of a single commit.
pub fn diff_commit(&self, oid: &str) -> String {
crate::git::diff_commit(self.workdir().as_path(), oid).unwrap()
}
/// Set a git config value.
pub fn set_config(&self, key: &str, value: &str) {
crate::git::run_git(self.workdir().as_path(), &["config", key, value]).unwrap();
}
/// Get porcelain status output.
pub fn status_porcelain(&self) -> String {
crate::git::run_git_stdout(self.workdir().as_path(), &["status", "--porcelain"]).unwrap()
}
/// Rebase commits between `upstream` and HEAD onto `newbase` with --update-refs.
pub fn rebase_onto(&self, newbase: &str, upstream: &str) {
crate::git::rebase_onto(self.workdir().as_path(), newbase, upstream).unwrap();
}
/// Get all non-merge commit messages between HEAD and merge-base.
pub fn commit_messages(&self) -> Vec<String> {
let info = crate::core::repo::gather_repo_info(&self.repo, false, 1).unwrap();
info.commits.iter().map(|c| c.message.clone()).collect()
}
/// Get all branch names in the commit range.
pub fn branch_names(&self) -> Vec<String> {
let info = crate::core::repo::gather_repo_info(&self.repo, false, 1).unwrap();
info.branches.iter().map(|b| b.name.clone()).collect()
}
/// Get the commit summary at the tip of a branch.
pub fn branch_commit_summary(&self, name: &str) -> String {
let oid = self.get_branch_target(name);
let commit = self.find_commit(oid);
commit.summary().unwrap_or("").to_string()
}
/// Get the file paths changed in a commit.
pub fn commit_file_paths(&self, oid: git2::Oid) -> Vec<String> {
crate::core::repo::commit_file_paths(&self.repo, oid).unwrap()
}
/// Create a commit touching multiple files at once.
///
/// Each entry is a `(filename, content)` pair. Uses the git2 API
/// directly so it stays consistent with the single-file `commit()`.
pub fn commit_multi(&self, files: &[(&str, &str)], message: &str) -> git2::Oid {
for (filename, content) in files {
self.write_file(filename, content);
}
let mut index = self.repo.index().unwrap();
for (filename, _) in files {
index.add_path(Path::new(filename)).unwrap();
}
index.write().unwrap();
let tree_id = index.write_tree().unwrap();
let tree = self.repo.find_tree(tree_id).unwrap();
let sig = Self::sig();
if let Ok(head) = self.repo.head() {
let parent = self.repo.find_commit(head.target().unwrap()).unwrap();
self.repo
.commit(Some("HEAD"), &sig, &sig, message, &tree, &[&parent])
.unwrap()
} else {
self.repo
.commit(Some("HEAD"), &sig, &sig, message, &tree, &[])
.unwrap()
}
}
/// Assert that the working tree is clean (no diff from HEAD).
pub fn assert_working_tree_clean(&self) {
let diff = self.diff_head_name_only();
assert!(
diff.trim().is_empty(),
"working tree should be clean, but has: {}",
diff
);
}
}
/// Builder for creating test repositories with a fluent API.
///
/// # Example
/// ```ignore
/// let test_repo = TestRepoBuilder::new()
/// .commit("First commit", "file1.txt")
/// .commit("Second commit", "file2.txt")
/// .branch("feature")
/// .build();
/// ```
pub struct TestRepoBuilder {
repo: TestRepo,
}
impl TestRepoBuilder {
/// Create a new builder with an initial empty repository.
pub fn new() -> Self {
TestRepoBuilder {
repo: TestRepo::new_empty(),
}
}
/// Create a new builder with an initial commit.
pub fn with_initial_commit() -> Self {
TestRepoBuilder {
repo: TestRepo::new(),
}
}
/// Add a commit with a file.
pub fn commit(self, message: &str, filename: &str) -> Self {
self.repo.commit(message, filename);
self
}
/// Create a branch at the current HEAD.
pub fn branch(self, name: &str) -> Self {
self.repo.create_branch(name);
self
}
/// Build and return the test repository.
pub fn build(self) -> TestRepo {
self.repo
}
}
impl Default for TestRepoBuilder {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_repo_creation() {
let repo = TestRepo::new();
assert!(repo.is_on_branch());
assert_eq!(repo.get_message(0), "Initial commit");
}
#[test]
fn test_commit_and_get() {
let repo = TestRepo::new();
repo.commit("Second commit", "file2.txt");
repo.commit("Third commit", "file3.txt");
assert_eq!(repo.get_message(0), "Third commit");
assert_eq!(repo.get_message(1), "Second commit");
assert_eq!(repo.get_message(2), "Initial commit");
}
#[test]
fn test_builder_pattern() {
let repo = TestRepoBuilder::with_initial_commit()
.commit("Second", "file2.txt")
.commit("Third", "file3.txt")
.branch("feature")
.build();
assert_eq!(repo.get_message(0), "Third");
assert_eq!(repo.get_message(1), "Second");
// Verify branch was created
assert!(
repo.repo
.find_branch("feature", git2::BranchType::Local)
.is_ok()
);
}
#[test]
fn test_file_operations() {
let repo = TestRepo::new();
repo.write_file("test.txt", "hello");
assert_eq!(repo.read_file("test.txt"), "hello");
}
}