-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubmodule.rs
More file actions
1077 lines (957 loc) · 36 KB
/
submodule.rs
File metadata and controls
1077 lines (957 loc) · 36 KB
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
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Git submodule support for bare repositories.
//!
//! This module provides functionality to detect and fetch submodule contents
//! from bare repositories without a working directory.
//!
//! # How Submodules Work in Git
//!
//! Submodules are tracked in two places:
//! 1. `.gitmodules` file - maps submodule names to URLs and paths
//! 2. Tree entries with mode `160000` - point to specific commits in submodule repos
//!
//! # Security
//!
//! - Each submodule is fetched using the same credential callbacks
//! - Submodule URLs are validated before fetching
//! - No source files are written to disk (bare repos only)
use git2::{ObjectType, Oid, Repository, TreeWalkMode, TreeWalkResult};
use std::collections::{HashMap, HashSet};
use tracing::{debug, trace, warn};
use super::auth::{sanitize_url_for_logging, validate_url};
use super::clone::{fetch_bare, FetchOptions2, FetchResult};
use super::error::Git2Error;
/// Git tree mode for submodule entries (commit references).
const SUBMODULE_MODE: i32 = 0o160_000;
/// Information about a submodule parsed from `.gitmodules`.
#[derive(Debug, Clone)]
pub struct SubmoduleInfo {
/// Submodule name (section name in .gitmodules)
pub name: String,
/// Path where the submodule is located in the tree
pub path: String,
/// URL to fetch the submodule from
pub url: String,
/// Branch to track (optional, defaults to default branch)
pub branch: Option<String>,
}
/// A submodule entry found in the tree.
#[derive(Debug, Clone)]
pub struct SubmoduleEntry {
/// Path in the tree where this submodule is located
pub path: String,
/// Commit SHA that the parent repo expects
pub commit: Oid,
/// URL to fetch from (from .gitmodules)
pub url: String,
}
/// Result of fetching a submodule.
pub struct FetchedSubmodule {
/// The submodule entry information
pub entry: SubmoduleEntry,
/// The fetched repository (bare)
pub fetch_result: FetchResult,
/// Recursively fetched child submodules (if any).
pub children: Vec<Self>,
}
/// Filter for submodule paths based on include/exclude glob patterns.
///
/// Exclude patterns take precedence over include patterns.
/// If no include patterns are set, all paths match (unless excluded).
pub struct SubmoduleFilter {
/// Compiled include patterns.
include: Vec<glob::Pattern>,
/// Compiled exclude patterns.
exclude: Vec<glob::Pattern>,
}
impl SubmoduleFilter {
/// Creates a new filter from optional include and exclude pattern slices.
///
/// Invalid patterns are logged and skipped.
#[must_use]
pub fn new(include: Option<&[String]>, exclude: Option<&[String]>) -> Self {
let include = include
.unwrap_or(&[])
.iter()
.filter_map(|p| match glob::Pattern::new(p) {
Ok(pat) => Some(pat),
Err(e) => {
warn!(pattern = %p, error = %e, "invalid submodule include pattern, skipping");
None
}
})
.collect();
let exclude = exclude
.unwrap_or(&[])
.iter()
.filter_map(|p| match glob::Pattern::new(p) {
Ok(pat) => Some(pat),
Err(e) => {
warn!(pattern = %p, error = %e, "invalid submodule exclude pattern, skipping");
None
}
})
.collect();
Self { include, exclude }
}
/// Returns `true` if the given path passes the filter.
///
/// A path is accepted if:
/// 1. It does NOT match any exclude pattern, AND
/// 2. Either no include patterns are set, or it matches at least one.
#[must_use]
pub fn matches(&self, path: &str) -> bool {
// Exclude takes precedence
if self.exclude.iter().any(|p| p.matches(path)) {
return false;
}
// If no include patterns, everything matches
if self.include.is_empty() {
return true;
}
// Must match at least one include pattern
self.include.iter().any(|p| p.matches(path))
}
}
/// Parse the `.gitmodules` file content into submodule info.
///
/// The format is INI-like:
/// ```text
/// [submodule "name"]
/// path = some/path
/// url = https://github.com/owner/repo
/// branch = main
/// ```
///
/// # Arguments
///
/// * `content` - Raw content of the `.gitmodules` file
///
/// # Returns
///
/// A map from submodule path to `SubmoduleInfo`.
#[must_use]
pub fn parse_gitmodules(content: &[u8]) -> HashMap<String, SubmoduleInfo> {
let mut result = HashMap::new();
let Ok(text) = std::str::from_utf8(content) else {
return result;
};
let mut current_name: Option<String> = None;
let mut current_path: Option<String> = None;
let mut current_url: Option<String> = None;
let mut current_branch: Option<String> = None;
for line in text.lines() {
let line = line.trim();
// Skip empty lines and comments
if line.is_empty() || line.starts_with('#') || line.starts_with(';') {
continue;
}
// Section header: [submodule "name"]
if line.starts_with('[') && line.ends_with(']') {
// Save previous submodule if complete
if let (Some(name), Some(path), Some(url)) =
(current_name.take(), current_path.take(), current_url.take())
{
result.insert(
path.clone(),
SubmoduleInfo {
name,
path,
url,
branch: current_branch.take(),
},
);
}
// Parse new section name - use strip methods for safe slicing
let inner = line
.strip_prefix('[')
.and_then(|s| s.strip_suffix(']'))
.unwrap_or("");
if let Some(name) = inner.strip_prefix("submodule \"") {
if let Some(name) = name.strip_suffix('"') {
current_name = Some(name.to_string());
}
}
continue;
}
// Key-value pairs
if let Some((key, value)) = line.split_once('=') {
let key = key.trim();
let value = value.trim();
match key {
"path" => current_path = Some(value.to_string()),
"url" => current_url = Some(value.to_string()),
"branch" => current_branch = Some(value.to_string()),
_ => {} // Ignore unknown keys
}
}
}
// Don't forget the last submodule
if let (Some(name), Some(path), Some(url)) = (current_name, current_path, current_url) {
result.insert(
path.clone(),
SubmoduleInfo {
name,
path,
url,
branch: current_branch,
},
);
}
result
}
/// Find all submodule entries in a git tree.
///
/// Submodules appear in the tree with mode `160000` (commit mode).
///
/// # Arguments
///
/// * `repo` - The repository containing the tree
/// * `commit_id` - The commit whose tree to search
/// * `gitmodules` - Parsed `.gitmodules` info (path -> `SubmoduleInfo`)
///
/// # Returns
///
/// A list of submodule entries found in the tree.
///
/// # Errors
///
/// Returns `Git2Error` if the commit or tree cannot be found.
#[allow(clippy::implicit_hasher)] // We only use std HashMap internally
pub fn find_submodule_entries(
repo: &Repository,
commit_id: Oid,
gitmodules: &HashMap<String, SubmoduleInfo>,
) -> Result<Vec<SubmoduleEntry>, Git2Error> {
let commit = repo
.find_commit(commit_id)
.map_err(|e| Git2Error::Git2(format!("failed to find commit: {e}")))?;
let tree = commit
.tree()
.map_err(|e| Git2Error::Git2(format!("failed to get tree: {e}")))?;
let mut entries = Vec::new();
tree.walk(TreeWalkMode::PreOrder, |dir, entry| {
// Check if this is a submodule entry (mode 160000)
if entry.filemode() == SUBMODULE_MODE && entry.kind() == Some(ObjectType::Commit) {
// git2 0.21: `TreeEntry::name()` returns `Result` (UTF-8 check);
// `Err` means a non-UTF-8 name, which we skip as before.
let Ok(name) = entry.name() else {
return TreeWalkResult::Ok;
};
let path = if dir.is_empty() {
name.to_string()
} else {
format!("{dir}{name}")
};
// Look up URL from gitmodules
if let Some(info) = gitmodules.get(&path) {
trace!(path = %path, commit = %entry.id(), "found submodule entry");
entries.push(SubmoduleEntry {
path,
commit: entry.id(),
url: info.url.clone(),
});
} else {
warn!(path = %path, "submodule entry found but not in .gitmodules");
}
}
TreeWalkResult::Ok
})
.map_err(|e| Git2Error::Git2(format!("failed to walk tree: {e}")))?;
debug!(count = entries.len(), "found submodule entries");
Ok(entries)
}
/// Get the `.gitmodules` file content from a tree.
///
/// # Arguments
///
/// * `repo` - The repository
/// * `commit_id` - The commit to read from
///
/// # Returns
///
/// The raw content of `.gitmodules`, or `None` if not present.
#[must_use]
pub fn get_gitmodules_content(repo: &Repository, commit_id: Oid) -> Option<Vec<u8>> {
let commit = repo.find_commit(commit_id).ok()?;
let tree = commit.tree().ok()?;
// Look for .gitmodules in the root
let entry = tree.get_name(".gitmodules")?;
if entry.kind() != Some(ObjectType::Blob) {
return None;
}
let blob = repo.find_blob(entry.id()).ok()?;
Some(blob.content().to_vec())
}
/// Fetch a single submodule.
///
/// # Arguments
///
/// * `entry` - The submodule entry to fetch
///
/// # Returns
///
/// The fetched submodule with its repository.
///
/// # Errors
///
/// Returns `Git2Error` if URL validation or fetch fails.
pub fn fetch_submodule(
entry: &SubmoduleEntry,
proxy_url: Option<&str>,
) -> Result<FetchedSubmodule, Git2Error> {
debug!(
url = %sanitize_url_for_logging(&entry.url),
path = %entry.path,
commit = %entry.commit,
"fetching submodule"
);
// Validate URL
validate_url(&entry.url)?;
// Fetch the submodule at the specific commit
// We don't specify a branch since we want a specific commit
let fetch_opts = FetchOptions2 {
branch: None,
depth: None,
progress: None, // Submodule fetch progress is reported at higher level
proxy_url: proxy_url.map(String::from),
};
let fetch_result = fetch_bare(&entry.url, Some(fetch_opts))?;
// Verify the expected commit exists
if fetch_result.repo.find_commit(entry.commit).is_err() {
return Err(Git2Error::Git2(format!(
"submodule commit {} not found in fetched repo",
entry.commit
)));
}
Ok(FetchedSubmodule {
entry: entry.clone(),
fetch_result,
children: Vec::new(),
})
}
/// Fetch all submodules for a repository.
///
/// Delegates to the internal recursive fetcher with the provided configuration.
/// Submodules at each depth level are fetched in parallel, up to
/// `max_concurrent` threads.
///
/// # Arguments
///
/// * `repo` - The parent repository (bare)
/// * `commit_id` - The commit whose submodules to fetch
/// * `proxy_url` - Optional proxy URL for network operations
/// * `max_depth` - Maximum recursion depth (1 = top-level only)
/// * `max_failures` - Maximum number of failures before stopping
/// * `max_concurrent` - Maximum number of submodules fetched in parallel
/// * `filter` - Filter for include/exclude patterns
///
/// # Returns
///
/// A list of successfully fetched submodules. Failed submodules are logged but skipped.
///
/// # Errors
///
/// Returns `Git2Error` if reading the tree fails.
pub fn fetch_all_submodules(
repo: &Repository,
commit_id: Oid,
proxy_url: Option<&str>,
max_depth: u32,
max_failures: usize,
max_concurrent: usize,
filter: &SubmoduleFilter,
) -> Result<Vec<FetchedSubmodule>, Git2Error> {
let mut visited_urls: HashSet<String> = HashSet::new();
let mut failure_count: usize = 0;
fetch_submodules_recursive(
repo,
commit_id,
proxy_url,
1, // current depth starts at 1
max_depth,
max_failures,
max_concurrent,
filter,
&mut visited_urls,
&mut failure_count,
)
}
/// Normalise a URL for cycle detection.
///
/// Strips trailing `.git` suffix and trailing slashes so that
/// `https://example.com/repo.git` and `https://example.com/repo` are
/// treated as the same repository.
fn normalise_url_for_cycle_detection(url: &str) -> String {
let mut normalised = url.to_lowercase();
normalised = normalised.trim_end_matches('/').to_string();
if std::path::Path::new(&normalised)
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("git"))
{
// Remove the ".git" suffix (4 bytes)
normalised.truncate(normalised.len() - 4);
}
normalised
}
/// Recursively fetch submodules up to a given depth.
///
/// This function:
/// 1. Reads `.gitmodules` from the given commit's tree
/// 2. Filters entries through the `SubmoduleFilter` and checks for cycles
/// 3. Fetches eligible entries in parallel batches of `max_concurrent`
/// 4. Tracks failure count and stops early when `max_failures` is reached
/// 5. For each successful fetch, recursively fetches child submodules
/// sequentially (children need mutable `visited_urls` and `failure_count`)
///
/// # Errors
///
/// Returns `Git2Error` if reading the tree fails.
#[allow(clippy::too_many_arguments)]
#[allow(clippy::too_many_lines)] // Parallel batch logic + recursion is naturally verbose
fn fetch_submodules_recursive(
repo: &Repository,
commit_id: Oid,
proxy_url: Option<&str>,
current_depth: u32,
max_depth: u32,
max_failures: usize,
max_concurrent: usize,
filter: &SubmoduleFilter,
visited_urls: &mut HashSet<String>,
failure_count: &mut usize,
) -> Result<Vec<FetchedSubmodule>, Git2Error> {
// Get .gitmodules content
let Some(gitmodules_content) = get_gitmodules_content(repo, commit_id) else {
debug!("no .gitmodules found, no submodules to fetch");
return Ok(Vec::new());
};
// Parse .gitmodules
let gitmodules = parse_gitmodules(&gitmodules_content);
if gitmodules.is_empty() {
debug!(".gitmodules is empty or invalid");
return Ok(Vec::new());
}
debug!(
count = gitmodules.len(),
depth = current_depth,
"parsed .gitmodules"
);
// Find submodule entries in tree
let entries = find_submodule_entries(repo, commit_id, &gitmodules)?;
let total_entries = entries.len();
// Phase 1: Filter entries and check cycles (sequential — needs mutable visited_urls)
let mut eligible_entries = Vec::new();
for entry in entries {
if *failure_count >= max_failures {
warn!(
failure_count = *failure_count,
max_failures = max_failures,
"max submodule failures reached, skipping remaining submodules"
);
break;
}
if !filter.matches(&entry.path) {
debug!(path = %entry.path, "submodule excluded by filter");
continue;
}
let normalised = normalise_url_for_cycle_detection(&entry.url);
if !visited_urls.insert(normalised) {
warn!(
path = %entry.path,
url = %sanitize_url_for_logging(&entry.url),
"submodule URL cycle detected, skipping"
);
continue;
}
eligible_entries.push(entry);
}
// Phase 2: Fetch in parallel batches
let mut fetched = Vec::new();
let batch_size = max_concurrent.max(1);
for batch in eligible_entries.chunks(batch_size) {
if *failure_count >= max_failures {
warn!(
failure_count = *failure_count,
max_failures = max_failures,
"max submodule failures reached, skipping remaining batches"
);
break;
}
let results: Vec<Result<FetchedSubmodule, Git2Error>> = std::thread::scope(|s| {
// Collect handles first so all threads run concurrently.
// Without the intermediate Vec, spawn-then-join would be
// evaluated lazily per element, making fetches sequential.
#[allow(clippy::needless_collect)]
let handles: Vec<_> = batch
.iter()
.map(|entry| s.spawn(move || fetch_submodule(entry, proxy_url)))
.collect();
handles
.into_iter()
.map(|h| h.join().expect("submodule fetch thread panicked"))
.collect()
});
// Phase 3: Process results and recurse into children (sequential)
for (entry, result) in batch.iter().zip(results) {
match result {
Ok(mut submodule) => {
if current_depth < max_depth {
match fetch_submodules_recursive(
&submodule.fetch_result.repo,
submodule.entry.commit,
proxy_url,
current_depth + 1,
max_depth,
max_failures,
max_concurrent,
filter,
visited_urls,
failure_count,
) {
Ok(children) => {
submodule.children = children;
}
Err(e) => {
warn!(
path = %entry.path,
error = %e,
"failed to fetch child submodules"
);
// Child submodule tree failure does not count as
// a failure of this submodule itself.
}
}
}
fetched.push(submodule);
}
Err(e) => {
*failure_count += 1;
warn!(
path = %entry.path,
url = %sanitize_url_for_logging(&entry.url),
error = %e,
failure_count = *failure_count,
"failed to fetch submodule, skipping"
);
}
}
}
}
debug!(
total = total_entries,
fetched = fetched.len(),
depth = current_depth,
"submodule fetch complete"
);
Ok(fetched)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_gitmodules_basic() {
let content = br#"[submodule "lib/foo"]
path = lib/foo
url = https://github.com/owner/foo.git
[submodule "vendor/bar"]
path = vendor/bar
url = git@github.com:owner/bar.git
branch = develop
"#;
let result = parse_gitmodules(content);
assert_eq!(result.len(), 2);
let foo = result.get("lib/foo").unwrap();
assert_eq!(foo.name, "lib/foo");
assert_eq!(foo.path, "lib/foo");
assert_eq!(foo.url, "https://github.com/owner/foo.git");
assert!(foo.branch.is_none());
let bar = result.get("vendor/bar").unwrap();
assert_eq!(bar.name, "vendor/bar");
assert_eq!(bar.path, "vendor/bar");
assert_eq!(bar.url, "git@github.com:owner/bar.git");
assert_eq!(bar.branch, Some("develop".to_string()));
}
#[test]
fn parse_gitmodules_with_comments() {
let content = br#"# This is a comment
[submodule "lib"]
; Another comment
path = lib
url = https://example.com/lib.git
"#;
let result = parse_gitmodules(content);
assert_eq!(result.len(), 1);
let lib = result.get("lib").unwrap();
assert_eq!(lib.name, "lib");
assert_eq!(lib.url, "https://example.com/lib.git");
}
#[test]
fn parse_gitmodules_empty() {
let content = b"";
let result = parse_gitmodules(content);
assert!(result.is_empty());
}
#[test]
fn parse_gitmodules_invalid_utf8() {
let content = &[0xff, 0xfe, 0x00, 0x01];
let result = parse_gitmodules(content);
assert!(result.is_empty());
}
#[test]
fn parse_gitmodules_missing_url() {
let content = br#"[submodule "incomplete"]
path = some/path
"#;
let result = parse_gitmodules(content);
// Should not include submodule without URL
assert!(result.is_empty());
}
#[test]
fn parse_gitmodules_whitespace_handling() {
let content = br#"[submodule "spaced"]
path = path/with/spaces
url=https://example.com/repo.git
"#;
let result = parse_gitmodules(content);
assert_eq!(result.len(), 1);
let spaced = result.get("path/with/spaces").unwrap();
assert_eq!(spaced.path, "path/with/spaces");
assert_eq!(spaced.url, "https://example.com/repo.git");
}
#[test]
fn submodule_mode_constant() {
// Verify the octal mode is correct
assert_eq!(SUBMODULE_MODE, 0o160_000);
assert_eq!(SUBMODULE_MODE, 57344); // decimal equivalent
}
// =========================================================================
// SubmoduleFilter tests
// =========================================================================
#[test]
fn filter_empty_matches_all() {
let filter = SubmoduleFilter::new(None, None);
assert!(filter.matches("lib/foo"));
assert!(filter.matches("vendor/bar"));
assert!(filter.matches("anything"));
}
#[test]
fn filter_include_only() {
let include = vec!["lib/*".to_string(), "deps/core".to_string()];
let filter = SubmoduleFilter::new(Some(&include), None);
assert!(filter.matches("lib/foo"));
assert!(filter.matches("lib/bar"));
assert!(filter.matches("deps/core"));
assert!(!filter.matches("vendor/bar"));
assert!(!filter.matches("deps/other"));
}
#[test]
fn filter_exclude_only() {
let exclude = vec!["vendor/*".to_string()];
let filter = SubmoduleFilter::new(None, Some(&exclude));
assert!(filter.matches("lib/foo"));
assert!(filter.matches("deps/core"));
assert!(!filter.matches("vendor/bar"));
assert!(!filter.matches("vendor/something"));
}
#[test]
fn filter_exclude_takes_precedence() {
let include = vec!["lib/*".to_string(), "vendor/*".to_string()];
let exclude = vec!["vendor/*".to_string()];
let filter = SubmoduleFilter::new(Some(&include), Some(&exclude));
assert!(filter.matches("lib/foo"));
// vendor/* is in include but also in exclude — exclude wins
assert!(!filter.matches("vendor/bar"));
}
#[test]
fn filter_invalid_pattern_skipped() {
let include = vec!["[invalid".to_string(), "lib/*".to_string()];
let filter = SubmoduleFilter::new(Some(&include), None);
// The invalid pattern is skipped; "lib/*" still works
assert!(filter.matches("lib/foo"));
assert!(!filter.matches("src/main"));
}
#[test]
fn filter_empty_slices() {
let include: Vec<String> = vec![];
let exclude: Vec<String> = vec![];
let filter = SubmoduleFilter::new(Some(&include), Some(&exclude));
// Empty include = match all, empty exclude = exclude nothing
assert!(filter.matches("anything"));
}
// =========================================================================
// URL normalisation / cycle detection tests
// =========================================================================
#[test]
fn normalise_url_strips_git_suffix() {
assert_eq!(
normalise_url_for_cycle_detection("https://github.com/owner/repo.git"),
"https://github.com/owner/repo"
);
}
#[test]
fn normalise_url_strips_trailing_slash() {
assert_eq!(
normalise_url_for_cycle_detection("https://github.com/owner/repo/"),
"https://github.com/owner/repo"
);
}
#[test]
fn normalise_url_case_insensitive() {
assert_eq!(
normalise_url_for_cycle_detection("https://GitHub.COM/Owner/Repo.git"),
normalise_url_for_cycle_detection("https://github.com/owner/repo")
);
}
#[test]
fn cycle_detection_via_visited_set() {
let mut visited = HashSet::new();
let url_a = "https://github.com/owner/repo.git";
let url_b = "https://github.com/owner/repo";
let norm_a = normalise_url_for_cycle_detection(url_a);
let norm_b = normalise_url_for_cycle_detection(url_b);
assert!(visited.insert(norm_a));
// Same repo with different URL form — should be detected as a cycle
assert!(!visited.insert(norm_b));
}
/// Build a bare repo containing only a `.gitmodules` blob in the root tree.
///
/// Note: this does NOT create an actual submodule tree entry (mode 160000)
/// because that would require a valid submodule commit reachable from the
/// parent, which we cannot fabricate without a real fetch. Tests that need
/// to exercise the tree-walking code path with submodule entries should
/// build a more elaborate fixture.
fn build_repo_with_gitmodules_blob() -> (tempfile::TempDir, Oid) {
let temp = tempfile::TempDir::new().unwrap();
let commit_oid = {
let repo = Repository::init_bare(temp.path()).unwrap();
let gitmodules_content = b"[submodule \"vendor/lib\"]\n\
\tpath = vendor/lib\n\
\turl = https://github.com/example/lib.git\n";
let gitmodules_oid = repo.blob(gitmodules_content).unwrap();
let mut tb = repo.treebuilder(None).unwrap();
tb.insert(".gitmodules", gitmodules_oid, 0o100_644).unwrap();
let tree_oid = tb.write().unwrap();
let signature = git2::Signature::now("Test", "test@example.com").unwrap();
let tree = repo.find_tree(tree_oid).unwrap();
repo.commit(
Some("HEAD"),
&signature,
&signature,
"with .gitmodules",
&tree,
&[],
)
.unwrap()
};
(temp, commit_oid)
}
#[test]
fn get_gitmodules_content_returns_content() {
let (temp, commit_oid) = build_repo_with_gitmodules_blob();
let repo = Repository::open_bare(temp.path()).unwrap();
let content = get_gitmodules_content(&repo, commit_oid);
assert!(content.is_some());
let bytes = content.unwrap();
let text = String::from_utf8_lossy(&bytes);
assert!(text.contains("vendor/lib"));
assert!(text.contains("https://github.com/example/lib.git"));
}
#[test]
fn get_gitmodules_content_returns_none_for_repo_without_gitmodules() {
let temp = tempfile::TempDir::new().unwrap();
let commit_oid = {
let repo = Repository::init_bare(temp.path()).unwrap();
let blob = repo.blob(b"hi\n").unwrap();
let mut tb = repo.treebuilder(None).unwrap();
tb.insert("README.md", blob, 0o100_644).unwrap();
let tree_oid = tb.write().unwrap();
let signature = git2::Signature::now("Test", "test@example.com").unwrap();
let tree = repo.find_tree(tree_oid).unwrap();
repo.commit(Some("HEAD"), &signature, &signature, "msg", &tree, &[])
.unwrap()
};
let repo = Repository::open_bare(temp.path()).unwrap();
let content = get_gitmodules_content(&repo, commit_oid);
assert!(content.is_none());
}
#[test]
fn get_gitmodules_content_returns_none_for_invalid_commit() {
let temp = tempfile::TempDir::new().unwrap();
let repo = Repository::init_bare(temp.path()).unwrap();
let bogus_oid = Oid::from_str("0000000000000000000000000000000000000001").unwrap();
let content = get_gitmodules_content(&repo, bogus_oid);
assert!(content.is_none());
}
#[test]
fn find_submodule_entries_empty_when_no_submodules() {
let temp = tempfile::TempDir::new().unwrap();
let commit_oid = {
let repo = Repository::init_bare(temp.path()).unwrap();
let blob = repo.blob(b"hi\n").unwrap();
let mut tb = repo.treebuilder(None).unwrap();
tb.insert("README.md", blob, 0o100_644).unwrap();
let tree_oid = tb.write().unwrap();
let signature = git2::Signature::now("Test", "test@example.com").unwrap();
let tree = repo.find_tree(tree_oid).unwrap();
repo.commit(Some("HEAD"), &signature, &signature, "msg", &tree, &[])
.unwrap()
};
let repo = Repository::open_bare(temp.path()).unwrap();
let gitmodules = HashMap::new();
let entries = find_submodule_entries(&repo, commit_oid, &gitmodules).unwrap();
assert!(entries.is_empty());
}
#[test]
fn find_submodule_entries_detects_gitlink_in_tree() {
// A tree containing a real gitlink (mode 160000) exercises the
// `let Ok(name) = entry.name()` walk-callback branch that the
// no-submodule test above never reaches.
let temp = tempfile::TempDir::new().unwrap();
let repo = Repository::init_bare(temp.path()).unwrap();
let sig = git2::Signature::now("Test", "test@example.com").unwrap();
// A commit to serve as the gitlink target oid (lives in this same repo
// for the test; `find_submodule_entries` only reads the tree entry's
// id/name, never peels the target).
let blob = repo.blob(b"sub\n").unwrap();
let mut sub_tb = repo.treebuilder(None).unwrap();
sub_tb.insert("f.txt", blob, 0o100_644).unwrap();
let sub_tree = repo.find_tree(sub_tb.write().unwrap()).unwrap();
let gitlink_target = repo
.commit(None, &sig, &sig, "submodule commit", &sub_tree, &[])
.unwrap();
// Parent commit whose tree has a gitlink at the root path "sub".
let mut root_tb = repo.treebuilder(None).unwrap();
root_tb
.insert("sub", gitlink_target, SUBMODULE_MODE)
.unwrap();
let root_tree = repo.find_tree(root_tb.write().unwrap()).unwrap();
let commit_oid = repo
.commit(None, &sig, &sig, "root commit", &root_tree, &[])
.unwrap();
let mut gitmodules = HashMap::new();
gitmodules.insert(
"sub".to_string(),
SubmoduleInfo {
name: "sub".to_string(),
path: "sub".to_string(),
url: "https://example.com/sub.git".to_string(),
branch: None,
},
);
let entries = find_submodule_entries(&repo, commit_oid, &gitmodules).unwrap();
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].path, "sub");
assert_eq!(entries[0].commit, gitlink_target);
assert_eq!(entries[0].url, "https://example.com/sub.git");
}
#[test]
fn find_submodule_entries_gitlink_missing_from_gitmodules_is_skipped() {
// Same gitlink tree, but with an empty .gitmodules map: the entry is
// found in the tree (hitting the same walk branch) yet produces no
// `SubmoduleEntry` because there's no URL to fetch from.
let temp = tempfile::TempDir::new().unwrap();
let repo = Repository::init_bare(temp.path()).unwrap();
let sig = git2::Signature::now("Test", "test@example.com").unwrap();
let blob = repo.blob(b"sub\n").unwrap();
let mut sub_tb = repo.treebuilder(None).unwrap();
sub_tb.insert("f.txt", blob, 0o100_644).unwrap();
let sub_tree = repo.find_tree(sub_tb.write().unwrap()).unwrap();
let gitlink_target = repo
.commit(None, &sig, &sig, "submodule commit", &sub_tree, &[])
.unwrap();
let mut root_tb = repo.treebuilder(None).unwrap();
root_tb
.insert("sub", gitlink_target, SUBMODULE_MODE)
.unwrap();
let root_tree = repo.find_tree(root_tb.write().unwrap()).unwrap();
let commit_oid = repo
.commit(None, &sig, &sig, "root commit", &root_tree, &[])
.unwrap();
let gitmodules = HashMap::new();
let entries = find_submodule_entries(&repo, commit_oid, &gitmodules).unwrap();
assert!(entries.is_empty());
}
#[test]
fn find_submodule_entries_invalid_commit_returns_error() {
let temp = tempfile::TempDir::new().unwrap();
let repo = Repository::init_bare(temp.path()).unwrap();
let bogus_oid = Oid::from_str("0000000000000000000000000000000000000001").unwrap();
let gitmodules = HashMap::new();
let result = find_submodule_entries(&repo, bogus_oid, &gitmodules);
assert!(result.is_err());
}
#[test]
fn submodule_entry_struct_fields() {
let entry = SubmoduleEntry {
path: "vendor/x".to_string(),