Skip to main content

grit_lib/
submodule_gitdir.rs

1//! Submodule gitdir paths when `extensions.submodulePathConfig` is enabled.
2//!
3//! Mirrors Git's `create_default_gitdir_config` / `validate_submodule_git_dir` logic
4//! enough for upstream tests (encoded paths, nesting checks, conflict resolution).
5
6use crate::git_path::CanonicalizeExt;
7use crate::worktree::WorktreeError;
8use std::collections::HashSet;
9use std::fs;
10use std::path::{Component, Path, PathBuf};
11
12use crate::config::{ConfigFile, ConfigScope};
13use crate::error::{Error, Result, SubmoduleError};
14use crate::hash;
15use crate::index::Index;
16use crate::objects::{ObjectId, ObjectKind};
17use crate::odb::Odb;
18
19/// Filesystem path to the separate git directory for a submodule under `super_git_dir`.
20///
21/// Matches Git `submodule_name_to_gitdir` with `extensions.submodulePathConfig` off: append
22/// `modules/<name>` by splitting only on `/` and `\\` (components like `..` are kept; no
23/// normalization).
24#[must_use]
25pub(crate) fn submodule_modules_git_dir(super_git_dir: &Path, submodule_relpath: &str) -> PathBuf {
26    let mut out = super_git_dir.to_path_buf();
27    out.push("modules");
28    for seg in submodule_relpath.split(['/', '\\']) {
29        if seg.is_empty() || seg == "." {
30            continue;
31        }
32        out.push(seg);
33    }
34    out
35}
36
37/// Returns whether `extensions.submodulePathConfig` is enabled in `git_dir/config`.
38///
39/// `git_dir` should be the repository directory that holds `config` (the common git directory when
40/// using linked worktrees).
41pub(crate) fn submodule_path_config_enabled(git_dir: &Path) -> bool {
42    let config_path = git_dir.join("config");
43    let Ok(content) = fs::read_to_string(&config_path) else {
44        return false;
45    };
46    let mut in_extensions = false;
47    for line in content.lines() {
48        let trimmed = line.trim();
49        if trimmed.starts_with('[') {
50            in_extensions = trimmed.eq_ignore_ascii_case("[extensions]");
51            continue;
52        }
53        if in_extensions {
54            if let Some((k, v)) = trimmed.split_once('=') {
55                if k.trim().eq_ignore_ascii_case("submodulepathconfig") {
56                    return parse_bool(v.trim());
57                }
58            }
59        }
60    }
61    false
62}
63
64fn parse_bool(s: &str) -> bool {
65    matches!(s.to_ascii_lowercase().as_str(), "true" | "yes" | "on" | "1")
66}
67
68fn is_rfc3986_unreserved(b: u8) -> bool {
69    b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~')
70}
71
72fn is_casefolding_rfc3986_unreserved(b: u8) -> bool {
73    matches!(b, b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~')
74}
75
76fn percent_encode(name: &str, pred: fn(u8) -> bool) -> String {
77    let mut out = String::new();
78    for &b in name.as_bytes() {
79        if pred(b) {
80            out.push(b as char);
81        } else {
82            out.push_str(&format!("%{:02x}", b));
83        }
84    }
85    out
86}
87
88/// Returns true if `path` looks like a git directory (`HEAD` and `objects/` exist).
89pub fn is_git_directory(path: &Path) -> bool {
90    path.join("HEAD").is_file() && path.join("objects").is_dir()
91}
92
93/// Whether `git_dir` is a usable Git directory, with the same rules as Git's repository
94/// discovery: a valid `HEAD` in `git_dir` (including linked-worktree admin dirs) and
95/// `objects/` + `refs/` in the common git directory (`commondir` when present).
96///
97/// Used for embedded-repository detection and to validate local remotes.
98#[must_use]
99pub(crate) fn is_valid_git_dir(git_dir: &Path) -> bool {
100    if !git_head_ref_valid(&git_dir.join("HEAD")) {
101        return false;
102    }
103    let object_store = crate::repo::common_git_dir_for_config(git_dir);
104    object_store.join("objects").is_dir() && object_store.join("refs").is_dir()
105}
106
107#[cfg(test)]
108mod embedded_git_dir_tests {
109    use super::*;
110    use std::fs;
111
112    #[test]
113    fn placeholder_dot_git_dir_is_not_a_repository() {
114        let tmp = tempfile::tempdir().unwrap();
115        let git = tmp.path().join(".git");
116        fs::create_dir_all(&git).unwrap();
117        assert!(!is_valid_git_dir(&git));
118    }
119
120    #[test]
121    fn minimal_init_layout_is_a_repository() {
122        let tmp = tempfile::tempdir().unwrap();
123        let git = tmp.path().join(".git");
124        fs::create_dir_all(git.join("objects")).unwrap();
125        fs::create_dir_all(git.join("refs/heads")).unwrap();
126        fs::write(git.join("HEAD"), "ref: refs/heads/main\n").unwrap();
127        assert!(is_valid_git_dir(&git));
128    }
129
130    #[test]
131    fn linked_worktree_admin_dir_uses_commondir_for_stores() {
132        let tmp = tempfile::tempdir().unwrap();
133        let common = tmp.path().join("repo.git");
134        fs::create_dir_all(common.join("objects")).unwrap();
135        fs::create_dir_all(common.join("refs/heads")).unwrap();
136        let admin = common.join("worktrees/linked");
137        fs::create_dir_all(&admin).unwrap();
138        fs::write(admin.join("HEAD"), "ref: refs/heads/main\n").unwrap();
139        fs::write(admin.join("commondir"), "../..\n").unwrap();
140        assert!(is_valid_git_dir(&admin));
141        assert!(
142            !admin.join("objects").is_dir(),
143            "admin dir must not need local objects/"
144        );
145    }
146}
147
148fn git_head_ref_valid(head_path: &Path) -> bool {
149    let Ok(meta) = fs::symlink_metadata(head_path) else {
150        return false;
151    };
152    if meta.file_type().is_symlink() {
153        if let Ok(target) = fs::read_link(head_path) {
154            return target.to_string_lossy().starts_with("refs/");
155        }
156        return false;
157    }
158    let Ok(content) = fs::read_to_string(head_path) else {
159        return false;
160    };
161    let trimmed = content.trim();
162    if let Some(rest) = trimmed.strip_prefix("ref:") {
163        return rest.trim().starts_with("refs/");
164    }
165    ObjectId::from_hex(trimmed).is_ok()
166}
167
168/// Rejects submodule paths that traverse symlinks (Git `validate_submodule_path`).
169///
170/// Path components follow Git `is_dir_sep`: on Unix only `/` separates; on Windows both `/`
171/// and `\` do. A carriage return in a single segment (e.g. `sub\r`) must not be split.
172pub fn validate_submodule_path(work_tree: &Path, rel: &str) -> Result<()> {
173    if rel.is_empty() {
174        return Err(Error::Worktree(WorktreeError::Submodule(
175            SubmoduleError::EmptyPath,
176        )));
177    }
178    let mut cur = work_tree.to_path_buf();
179    #[cfg(windows)]
180    let parts = rel.split(|c| c == '/' || c == '\\');
181    #[cfg(not(windows))]
182    let parts = rel.split('/');
183    for comp in parts.filter(|s| !s.is_empty()) {
184        cur.push(comp);
185        let meta = match fs::symlink_metadata(&cur) {
186            Ok(m) => m,
187            Err(_) => continue,
188        };
189        if meta.file_type().is_symlink() {
190            return Err(Error::Worktree(WorktreeError::Submodule(
191                SubmoduleError::SymlinkInPath {
192                    path: rel.to_owned(),
193                    component: comp.to_owned(),
194                },
195            )));
196        }
197    }
198    Ok(())
199}
200
201fn last_modules_segment(git_dir_abs: &Path) -> Option<String> {
202    let s = git_dir_abs.to_string_lossy();
203    let marker = "/modules/";
204    let mut p = 0usize;
205    let mut last_start = None;
206    while let Some(idx) = s[p..].find(marker) {
207        let start = p + idx + marker.len();
208        last_start = Some(start);
209        p = start + 1;
210    }
211    last_start.map(|start| s[start..].to_string())
212}
213
214fn resolve_gitdir_value(work_tree: &Path, gitdir_cfg: &str) -> PathBuf {
215    let p = Path::new(gitdir_cfg.trim());
216    if p.is_absolute() {
217        p.to_path_buf()
218    } else {
219        work_tree.join(p)
220    }
221}
222
223fn canonical_abs(path: &Path) -> PathBuf {
224    path.canonicalize_simplified()
225        .unwrap_or_else(|_| path.to_path_buf())
226}
227
228fn existing_gitdir_abs_paths(
229    work_tree: &Path,
230    cfg: &ConfigFile,
231    except_name: &str,
232) -> Result<HashSet<PathBuf>> {
233    let mut set = HashSet::new();
234    let suffix = ".gitdir";
235    for e in &cfg.entries {
236        if !e.key.starts_with("submodule.") || !e.key.ends_with(suffix) {
237            continue;
238        }
239        let inner = &e.key["submodule.".len()..e.key.len() - suffix.len()];
240        if inner == except_name {
241            continue;
242        }
243        if let Some(v) = e.value.as_deref() {
244            let abs = canonical_abs(&resolve_gitdir_value(work_tree, v));
245            set.insert(abs);
246        }
247    }
248    Ok(set)
249}
250
251fn gitdir_conflicts_with_existing(
252    work_tree: &Path,
253    cfg: &ConfigFile,
254    abs_gitdir: &Path,
255    submodule_name: &str,
256) -> Result<bool> {
257    let canon = canonical_abs(abs_gitdir);
258    let existing = existing_gitdir_abs_paths(work_tree, cfg, submodule_name)?;
259    Ok(existing.contains(&canon))
260}
261
262fn ignore_case_from_config(git_dir: &Path) -> bool {
263    let config_path = git_dir.join("config");
264    let Ok(content) = fs::read_to_string(&config_path) else {
265        return false;
266    };
267    let mut in_core = false;
268    for line in content.lines() {
269        let trimmed = line.trim();
270        if trimmed.starts_with('[') {
271            in_core = trimmed.eq_ignore_ascii_case("[core]");
272            continue;
273        }
274        if in_core {
275            if let Some((k, v)) = trimmed.split_once('=') {
276                if k.trim().eq_ignore_ascii_case("ignorecase") {
277                    return parse_bool(v.trim());
278                }
279            }
280        }
281    }
282    false
283}
284
285fn fold_case_git_path(s: &str) -> String {
286    s.to_ascii_lowercase()
287}
288
289fn check_casefolding_conflict(
290    proposed_abs: &Path,
291    submodule_name: &str,
292    suffixes_match: bool,
293    taken_folded: &HashSet<String>,
294) -> bool {
295    let last = last_modules_segment(proposed_abs).unwrap_or_default();
296    let folded_last = fold_case_git_path(&last);
297    let folded_name = fold_case_git_path(submodule_name);
298    if suffixes_match {
299        taken_folded.contains(&folded_last)
300    } else {
301        taken_folded.contains(&folded_name) || taken_folded.contains(&folded_last)
302    }
303}
304
305/// Validates an encoded submodule gitdir path when `submodulePathConfig` is enabled.
306pub fn validate_encoded_submodule_git_dir(
307    work_tree: &Path,
308    cfg: &ConfigFile,
309    git_dir: &Path,
310    submodule_name: &str,
311    super_git_dir: &Path,
312) -> Result<()> {
313    let last = last_modules_segment(git_dir).ok_or_else(|| {
314        Error::Worktree(WorktreeError::Submodule(
315            SubmoduleError::GitDirOutsideModules {
316                git_dir: git_dir.to_path_buf(),
317            },
318        ))
319    })?;
320    if last.contains('/') {
321        return Err(Error::Worktree(WorktreeError::Submodule(
322            SubmoduleError::GitDirSegmentHasSlash {
323                git_dir: git_dir.to_path_buf(),
324            },
325        )));
326    }
327    if is_git_directory(git_dir)
328        && gitdir_conflicts_with_existing(work_tree, cfg, git_dir, submodule_name)?
329    {
330        return Err(Error::Worktree(WorktreeError::Submodule(
331            SubmoduleError::GitDirInUse {
332                name: submodule_name.to_owned(),
333                git_dir: git_dir.to_path_buf(),
334            },
335        )));
336    }
337    if cfg!(unix) && ignore_case_from_config(super_git_dir) {
338        let mut taken: HashSet<String> = HashSet::new();
339        let suffix = ".gitdir";
340        for e in &cfg.entries {
341            if !e.key.starts_with("submodule.") || !e.key.ends_with(suffix) {
342                continue;
343            }
344            let inner = &e.key["submodule.".len()..e.key.len() - suffix.len()];
345            if inner == submodule_name {
346                continue;
347            }
348            if let Some(v) = e.value.as_deref() {
349                let abs = canonical_abs(&resolve_gitdir_value(work_tree, v));
350                if let Some(seg) = last_modules_segment(&abs) {
351                    taken.insert(fold_case_git_path(&seg));
352                }
353            }
354        }
355        let suffixes_match = last == submodule_name;
356        if check_casefolding_conflict(git_dir, submodule_name, suffixes_match, &taken) {
357            return Err(Error::Worktree(WorktreeError::Submodule(
358                SubmoduleError::GitDirCaseConflict {
359                    name: submodule_name.to_owned(),
360                    git_dir: git_dir.to_path_buf(),
361                },
362            )));
363        }
364    }
365    Ok(())
366}
367
368fn repo_git_path_append(git_dir: &Path, tail: &str) -> PathBuf {
369    let mut buf = git_dir.to_path_buf();
370    if !tail.is_empty() {
371        buf.push(tail);
372    }
373    buf
374}
375
376/// Returns the 40-character hex SHA-1 of a blob object for `data` (same as `git hash-object`).
377pub fn hash_blob_sha1_hex(data: &[u8]) -> Result<String> {
378    Ok(hash::hash_object(crate::objects::HashAlgo::Sha1, ObjectKind::Blob, data)?.to_hex())
379}
380
381/// Computes `submodule.<name>.gitdir` as a path relative to the work tree when not already set.
382pub fn compute_default_submodule_gitdir(
383    work_tree: &Path,
384    git_dir: &Path,
385    cfg: &ConfigFile,
386    submodule_name: &str,
387) -> Result<String> {
388    let key = format!("submodule.{submodule_name}.gitdir");
389    for e in &cfg.entries {
390        if e.key == key {
391            if let Some(v) = e.value.as_deref() {
392                return Ok(v.to_string());
393            }
394        }
395    }
396
397    let try_set = |rel_under_git: &str| -> Option<String> {
398        let abs = repo_git_path_append(git_dir, rel_under_git);
399        if validate_encoded_submodule_git_dir(work_tree, cfg, &abs, submodule_name, git_dir)
400            .is_err()
401        {
402            return None;
403        }
404        Some(format!(".git/{}", rel_under_git.replace('\\', "/")))
405    };
406
407    // Plain `modules/<name>` only when `name` has no directory separators: `PathBuf::push`
408    // splits on `/`, so e.g. `nested/sub` would become `modules/nested/sub` and the encoded
409    // validation rejects a multi-level tail under `modules/`.
410    let rel_plain = format!("modules/{}", submodule_name.replace('\\', "/"));
411    if !submodule_name.contains('/') && !submodule_name.contains('\\') {
412        if let Some(v) = try_set(&rel_plain) {
413            return Ok(v);
414        }
415    }
416
417    let enc = percent_encode(submodule_name, is_rfc3986_unreserved);
418    let rel_enc = format!("modules/{enc}");
419    if let Some(v) = try_set(&rel_enc) {
420        return Ok(v);
421    }
422
423    let enc_cf = percent_encode(submodule_name, is_casefolding_rfc3986_unreserved);
424    let rel_cf = format!("modules/{enc_cf}");
425    if let Some(v) = try_set(&rel_cf) {
426        return Ok(v);
427    }
428
429    for c in b'0'..=b'9' {
430        let rel = format!("modules/{}{}", enc, c as char);
431        if let Some(v) = try_set(&rel) {
432            return Ok(v);
433        }
434        let rel2 = format!("modules/{}{}", enc_cf, c as char);
435        if let Some(v) = try_set(&rel2) {
436            return Ok(v);
437        }
438    }
439
440    let hex = hash_blob_sha1_hex(submodule_name.as_bytes())?;
441    let rel_h = format!("modules/{hex}");
442    if let Some(v) = try_set(&rel_h) {
443        return Ok(v);
444    }
445
446    Err(Error::Worktree(WorktreeError::Submodule(
447        SubmoduleError::GitDirUnavailable {
448            name: submodule_name.to_owned(),
449        },
450    )))
451}
452
453/// Ensures `submodule.<name>.gitdir` exists, writing it via [`compute_default_submodule_gitdir`] if needed.
454pub fn ensure_submodule_gitdir_config(
455    work_tree: &Path,
456    git_dir: &Path,
457    cfg: &mut ConfigFile,
458    submodule_name: &str,
459) -> Result<String> {
460    let key = format!("submodule.{submodule_name}.gitdir");
461    if let Some(existing) = cfg.entries.iter().find(|e| e.key == key) {
462        if let Some(v) = existing.value.as_deref() {
463            return Ok(v.to_string());
464        }
465    }
466    let value = compute_default_submodule_gitdir(work_tree, git_dir, cfg, submodule_name)?;
467    cfg.set(&key, &value)?;
468    cfg.write()?;
469    Ok(value)
470}
471
472/// Resolves the absolute filesystem path of a submodule's git directory.
473pub fn submodule_gitdir_filesystem_path(
474    work_tree: &Path,
475    git_dir: &Path,
476    cfg: &ConfigFile,
477    submodule_name: &str,
478) -> Result<PathBuf> {
479    if submodule_path_config_enabled(git_dir) {
480        let key = format!("submodule.{submodule_name}.gitdir");
481        let value = cfg
482            .entries
483            .iter()
484            .find(|e| e.key == key)
485            .and_then(|e| e.value.clone())
486            .ok_or_else(|| {
487                Error::Worktree(WorktreeError::Submodule(
488                    SubmoduleError::GitDirNotConfigured {
489                        name: submodule_name.to_owned(),
490                    },
491                ))
492            })?;
493        Ok(resolve_gitdir_value(work_tree, &value))
494    } else {
495        Ok(git_dir.join("modules").join(submodule_name))
496    }
497}
498
499/// Migrates legacy submodule dirs under `.git/modules/`: sets `submodule.*.gitdir` and enables the extension.
500pub fn migrate_gitdir_configs(work_tree: &Path, git_dir: &Path) -> Result<()> {
501    let modules_root = git_dir.join("modules");
502    if !modules_root.is_dir() {
503        return Ok(());
504    }
505
506    let config_path = git_dir.join("config");
507    let content = fs::read_to_string(&config_path).map_err(Error::Io)?;
508    let mut cfg = ConfigFile::parse(&config_path, &content, ConfigScope::Local)?;
509
510    for entry in fs::read_dir(&modules_root).map_err(Error::Io)? {
511        let entry = entry.map_err(Error::Io)?;
512        let name = entry.file_name();
513        let name_str = name.to_string_lossy();
514        if name_str == "." || name_str == ".." {
515            continue;
516        }
517        let gd_path = modules_root.join(&name);
518        if !is_git_directory(&gd_path) {
519            continue;
520        }
521        let key = format!("submodule.{name_str}.gitdir");
522        if cfg.entries.iter().any(|e| e.key == key) {
523            continue;
524        }
525        let _ = ensure_submodule_gitdir_config(work_tree, git_dir, &mut cfg, &name_str)?;
526    }
527
528    let mut repo_version = 0u32;
529    if let Some(v) = cfg
530        .entries
531        .iter()
532        .find(|e| e.key == "core.repositoryformatversion")
533    {
534        if let Some(s) = v.value.as_deref() {
535            repo_version = s.parse().unwrap_or(0);
536        }
537    }
538    if repo_version == 0 {
539        cfg.set("core.repositoryformatversion", "1")?;
540    }
541    cfg.set("extensions.submodulePathConfig", "true")?;
542    cfg.write()?;
543    Ok(())
544}
545
546/// Returns true if `new_path` is strictly inside a gitlink path recorded in `index` (stage 0).
547pub fn path_inside_indexed_submodule(index: &Index, new_path: &str) -> bool {
548    let new_norm = new_path.replace('\\', "/");
549    for e in &index.entries {
550        if e.mode != 0o160000 || e.stage() != 0 {
551            continue;
552        }
553        let ce = String::from_utf8_lossy(&e.path).replace('\\', "/");
554        let ce_len = ce.len();
555        if new_norm.len() <= ce_len {
556            continue;
557        }
558        if new_norm.as_bytes().get(ce_len) != Some(&b'/') {
559            continue;
560        }
561        if !new_norm.starts_with(&ce) {
562            continue;
563        }
564        if new_norm.len() == ce_len + 1 {
565            continue;
566        }
567        return true;
568    }
569    false
570}
571
572/// Paths declared in `.gitmodules` (`submodule.*.path`), normalized with `/`.
573pub fn registered_submodule_paths(work_tree: &Path) -> Vec<String> {
574    let gitmodules = work_tree.join(".gitmodules");
575    let Ok(content) = fs::read_to_string(&gitmodules) else {
576        return Vec::new();
577    };
578    let (entries, _) =
579        ConfigFile::parse_gitmodules_best_effort(&gitmodules, &content, ConfigScope::Local);
580    entries
581        .into_iter()
582        .filter(|e| e.key.starts_with("submodule.") && e.key.ends_with(".path"))
583        .filter_map(|e| e.value.as_deref().map(|p| p.replace('\\', "/")))
584        .collect()
585}
586
587/// Returns true if `new_path` is under a submodule path declared in `.gitmodules`.
588pub fn path_inside_registered_submodule(work_tree: &Path, new_path: &str) -> bool {
589    let paths = registered_submodule_paths(work_tree);
590    let new_norm = new_path.replace('\\', "/");
591    for p in paths {
592        if new_norm == p || new_norm.starts_with(&format!("{p}/")) {
593            return true;
594        }
595    }
596    false
597}
598
599/// True when `new_path` is the same as or nested under a `.gitmodules` submodule **name** (the
600/// `submodule.<name>.*` section name), which may contain `/`.
601///
602/// Git rejects such paths when `submodulePathConfig` is off (`die_path_inside_submodule` on
603/// logical names). When the extension is enabled, encoded gitdirs lift this restriction.
604pub fn path_inside_registered_submodule_name(work_tree: &Path, new_path: &str) -> bool {
605    let gitmodules = work_tree.join(".gitmodules");
606    let Ok(content) = fs::read_to_string(&gitmodules) else {
607        return false;
608    };
609    let Ok(mf) = ConfigFile::parse(&gitmodules, &content, ConfigScope::Local) else {
610        return false;
611    };
612    let mut names: Vec<String> = Vec::new();
613    for e in &mf.entries {
614        if !e.key.starts_with("submodule.") {
615            continue;
616        }
617        let rest = &e.key["submodule.".len()..];
618        if let Some(last_dot) = rest.rfind('.') {
619            let name = rest[..last_dot].replace('\\', "/");
620            if !name.is_empty() {
621                names.push(name);
622            }
623        }
624    }
625    names.sort();
626    names.dedup();
627    let new_norm = new_path.replace('\\', "/");
628    for n in names {
629        if new_norm == n || new_norm.starts_with(&format!("{n}/")) {
630            return true;
631        }
632    }
633    false
634}
635
636/// Sets `core.worktree` in the submodule repo at `modules_dir`.
637///
638/// Stores a path relative to `modules_dir` (e.g. `../../../sub1`), matching C Git and
639/// `test_git_directory_exists` in the ported submodule tests.
640pub fn set_submodule_repo_worktree(modules_dir: &Path, sub_worktree: &Path) -> Result<()> {
641    let wt_rel = pathdiff_relative(modules_dir, sub_worktree);
642    let config_path = modules_dir.join("config");
643    let mut file = match ConfigFile::from_path(&config_path, ConfigScope::Local)? {
644        Some(f) => f,
645        None => ConfigFile::parse(&config_path, "", ConfigScope::Local)?,
646    };
647    file.set("core.worktree", &wt_rel)?;
648    file.write()?;
649    Ok(())
650}
651
652/// Writes `sub_worktree/.git` as a gitfile pointing at `modules_dir` (relative when possible).
653pub fn write_submodule_gitfile(sub_worktree: &Path, modules_dir: &Path) -> Result<()> {
654    let rel = pathdiff_relative(sub_worktree, modules_dir);
655    let line = format!("gitdir: {rel}\n");
656    fs::write(sub_worktree.join(".git"), line).map_err(Error::Io)?;
657    Ok(())
658}
659
660fn pathdiff_relative(from: &Path, to: &Path) -> String {
661    let from_c = from
662        .canonicalize_simplified()
663        .unwrap_or_else(|_| from.to_path_buf());
664    let to_c = to
665        .canonicalize_simplified()
666        .unwrap_or_else(|_| to.to_path_buf());
667    let from_comp: Vec<Component<'_>> = from_c.components().collect();
668    let to_comp: Vec<Component<'_>> = to_c.components().collect();
669    let mut i = 0usize;
670    while i < from_comp.len() && i < to_comp.len() && from_comp[i] == to_comp[i] {
671        i += 1;
672    }
673    let mut out = PathBuf::new();
674    for _ in i..from_comp.len() {
675        out.push("..");
676    }
677    for c in &to_comp[i..] {
678        out.push(c.as_os_str());
679    }
680    out.to_string_lossy().replace('\\', "/")
681}
682
683/// Writes the gitfile and `core.worktree` for a submodule using configured `submodule.<name>.gitdir`.
684pub fn connect_submodule_work_tree_and_git_dir(
685    work_tree: &Path,
686    super_git_dir: &Path,
687    cfg: &ConfigFile,
688    submodule_name: &str,
689    sub_worktree: &Path,
690) -> Result<()> {
691    let modules_dir =
692        submodule_gitdir_filesystem_path(work_tree, super_git_dir, cfg, submodule_name)?;
693    write_submodule_gitfile(sub_worktree, &modules_dir)?;
694    set_submodule_repo_worktree(&modules_dir, sub_worktree)?;
695    Ok(())
696}
697
698/// If `modules_dir/HEAD` is missing, sets it to `oid_hex` when that commit exists in `objects/`.
699pub fn init_submodule_head_from_gitlink(modules_dir: &Path, oid_hex: &str) -> Result<()> {
700    let head = modules_dir.join("HEAD");
701    if head.exists() {
702        return Ok(());
703    }
704    let obj_dir = modules_dir.join("objects");
705    if !obj_dir.is_dir() {
706        return Ok(());
707    }
708    let odb = Odb::new(&obj_dir);
709    let oid = ObjectId::from_hex(oid_hex)?;
710    let obj = odb.read(&oid)?;
711    if obj.kind != ObjectKind::Commit {
712        return Ok(());
713    }
714    fs::write(&head, format!("{oid_hex}\n")).map_err(Error::Io)?;
715    Ok(())
716}
717
718#[cfg(test)]
719mod submodule_modules_git_dir_tests {
720    use super::{submodule_modules_git_dir, submodule_path_config_enabled};
721    use std::path::Path;
722
723    #[test]
724    fn path_config_extension_is_read_from_config() {
725        let dir = tempfile::tempdir().unwrap();
726        let git_dir = dir.path();
727        assert!(!submodule_path_config_enabled(git_dir));
728        std::fs::write(
729            git_dir.join("config"),
730            "[extensions]\n\tsubmodulePathConfig = true\n",
731        )
732        .unwrap();
733        assert!(submodule_path_config_enabled(git_dir));
734    }
735
736    #[test]
737    fn nested_path_under_single_modules_prefix() {
738        let super_git = Path::new("/repo/.git");
739        assert_eq!(
740            submodule_modules_git_dir(super_git, "sub1/sub2"),
741            Path::new("/repo/.git/modules/sub1/sub2")
742        );
743        assert_eq!(
744            submodule_modules_git_dir(super_git, r"..\foo"),
745            Path::new("/repo/.git/modules/../foo")
746        );
747    }
748
749    #[test]
750    fn single_segment_one_modules_join() {
751        let super_git = Path::new("/repo/.git");
752        assert_eq!(
753            submodule_modules_git_dir(super_git, "sub1"),
754            Path::new("/repo/.git/modules/sub1")
755        );
756    }
757}