girt 0.17.0

An incremental, idiomatic Rust implementation of Git
Documentation
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
//! Which working-tree names a checkout may write, and which of them one volume treats as the same
//! file.
//!
//! Git refuses tree entries that a filesystem could resolve to the repository's own `.git`
//! directory. `.git` in any ASCII case is always refused. `core.protectNTFS` adds the spellings
//! NTFS resolves to `.git`, and `core.protectHFS` adds those HFS+ resolves to it. These rules
//! were observed from the git CLI; see `docs/compatibility.md`.
//!
//! Name equivalence is a property of the volume, not the platform. [`NamePolicy`] says whether the
//! working tree's volume folds case and Unicode normalization, from Git's config with a read-only
//! probe and a macOS fallback that can only add folding. Planned paths that share a [`NamePolicy`]
//! key are resolved the way Git resolves them; see [`NamePolicy::resolve`].

use std::collections::BTreeMap;
use std::collections::btree_map::Entry;

use unicode_normalization::UnicodeNormalization as _;

use crate::Repository;
use crate::checkout::Collision;

/// Which metadata-name rules apply, read from `core.protectNTFS` and `core.protectHFS`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Protection {
    ntfs: bool,
    hfs: bool,
}

impl Protection {
    /// Reads both options, using Git's defaults when unset: NTFS protection everywhere, HFS+
    /// protection on macOS.
    ///
    /// Returns the name of the first option whose value is not a boolean.
    pub(crate) fn from_config(repo: &Repository) -> Result<Self, &'static str> {
        let config = repo.config();
        let ntfs = config
            .boolean("core", None, "protectntfs")
            .map_err(|_| "core.protectNTFS")?;
        let hfs = config
            .boolean("core", None, "protecthfs")
            .map_err(|_| "core.protectHFS")?;
        Ok(Self {
            ntfs: ntfs.unwrap_or(true),
            hfs: hfs.unwrap_or(cfg!(target_os = "macos")),
        })
    }

    /// Whether any component of `path` is a name these rules refuse.
    pub(crate) fn refuses(self, path: &[u8]) -> bool {
        path.split(|byte| *byte == b'/')
            .any(|component| self.refuses_component(component))
    }

    fn refuses_component(self, component: &[u8]) -> bool {
        if component.eq_ignore_ascii_case(b".git") {
            return true;
        }
        if self.ntfs {
            // NTFS ignores trailing dots and spaces, and `name:stream` names a stream of `name`.
            let base = component
                .split(|byte| *byte == b':')
                .next()
                .unwrap_or(component);
            let end = base
                .iter()
                .rposition(|byte| !matches!(byte, b'.' | b' '))
                .map_or(0, |last| last + 1);
            let base = &base[..end];
            if base.eq_ignore_ascii_case(b".git") || base.eq_ignore_ascii_case(b"git~1") {
                return true;
            }
        }
        self.hfs && without_hfs_ignorables(component).eq_ignore_ascii_case(b".git")
    }
}

/// Which names the working tree's volume treats as one file.
///
/// Case folds when `core.ignoreCase` is true or the working tree's root resolves `.GIT` to `.git`.
/// Normalization folds on macOS, whose APFS and HFS+ volumes fold it even when case-sensitive; Git
/// reads `core.precomposeUnicode` only there. Config can only add folding to what the volume
/// shows, so missing or stale config never lets two names that collide on disk both be written.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct NamePolicy {
    case: bool,
    normalization: bool,
}

/// Paths as one volume stores them, with the sets of planned paths it merges.
pub(crate) struct Resolved<V> {
    /// Leaves by the path they occupy on the volume.
    pub(crate) disk: BTreeMap<Vec<u8>, V>,
    /// The planned path each leaf on the volume was written from, where the two differ.
    pub(crate) sources: BTreeMap<Vec<u8>, Vec<u8>>,
    /// Sets of planned paths that share a name on the volume.
    pub(crate) collisions: Vec<Collision>,
}

impl NamePolicy {
    /// Byte-exact names, as on Linux volumes.
    #[cfg(test)]
    pub(crate) const EXACT: Self = Self {
        case: false,
        normalization: false,
    };

    /// Reads the policy for `repo`'s working tree.
    ///
    /// Returns the name of the first option whose value is not a boolean.
    pub(crate) fn from_config(repo: &Repository) -> Result<Self, &'static str> {
        let config = repo.config();
        let case = config
            .boolean("core", None, "ignorecase")
            .map_err(|_| "core.ignoreCase")?;
        Ok(Self {
            case: case == Some(true) || probe_case_folding(repo),
            // Git applies core.precomposeUnicode only on macOS, whose volumes fold normalization
            // whatever the setting; elsewhere a volume stores both spellings.
            normalization: cfg!(target_os = "macos"),
        })
    }

    /// The name `component` shares with every name this volume treats as the same file.
    pub(crate) fn key(self, component: &[u8]) -> Vec<u8> {
        if !self.case && !self.normalization {
            return component.to_vec();
        }
        let Ok(text) = std::str::from_utf8(component) else {
            // Normalizing volumes reject invalid UTF-8; folding ASCII still finds case aliases.
            return if self.case {
                component.to_ascii_lowercase()
            } else {
                component.to_vec()
            };
        };
        let mut key: String = if self.normalization {
            text.nfd().filter(|c| !is_hfs_ignorable(*c)).collect()
        } else {
            text.to_owned()
        };
        if self.case {
            // Folding through upper case merges characters whose lower cases differ, such as the
            // Kelvin sign and `k`; decomposing again keeps the key canonical.
            key = key
                .chars()
                .flat_map(char::to_uppercase)
                .flat_map(char::to_lowercase)
                .collect();
            if self.normalization {
                key = key.nfd().collect();
            }
        }
        key.into_bytes()
    }

    /// Where each of `leaves` lands on this volume, resolving shared names as Git does.
    ///
    /// Paths are taken in index order. Directories sharing a name take the first spelling, so
    /// later spellings' children land inside it. Leaves sharing a name keep the last, with its
    /// own name and value; the earlier ones are shadowed. Every merge is reported. A leaf sharing
    /// a name with a directory has no single result and is refused, returning that leaf's path.
    pub(crate) fn resolve<V: Copy>(
        self,
        leaves: &BTreeMap<Vec<u8>, V>,
    ) -> Result<Resolved<V>, Vec<u8>> {
        // Both maps are keyed by (parent path on disk, name key). A directory keeps the planned
        // prefix that named it; a leaf keeps the planned path whose value it holds.
        let mut directories: BTreeMap<(Vec<u8>, Vec<u8>), Name<()>> = BTreeMap::new();
        let mut files: BTreeMap<(Vec<u8>, Vec<u8>), Name<V>> = BTreeMap::new();
        let mut collisions = Vec::new();
        for (path, value) in leaves {
            let mut disk = Vec::new();
            let mut end = 0;
            let mut components = path.split(|byte| *byte == b'/').peekable();
            while let Some(component) = components.next() {
                end += component.len();
                let planned = &path[..end];
                let slot = (disk.clone(), self.key(component));
                let on_disk = join(&disk, component);
                if components.peek().is_none() {
                    if directories.contains_key(&slot) {
                        return Err(path.clone());
                    }
                    match files.entry(slot) {
                        Entry::Vacant(vacant) => {
                            vacant.insert(Name::new(planned, on_disk, *value));
                        }
                        // The last spelling wins, with its own name and value.
                        Entry::Occupied(mut occupied) => {
                            let name = occupied.get_mut();
                            let shadowed = std::mem::replace(&mut name.planned, path.clone());
                            name.disk = on_disk;
                            name.value = *value;
                            name.shadow(shadowed, &mut collisions);
                        }
                    }
                    break;
                }
                if files.contains_key(&slot) {
                    return Err(planned.to_vec());
                }
                // The first spelling names the directory; later ones land inside it.
                let name = directories
                    .entry(slot)
                    .or_insert_with(|| Name::new(planned, on_disk, ()));
                if name.planned != planned {
                    name.shadow(planned.to_vec(), &mut collisions);
                }
                disk.clone_from(&name.disk);
                end += 1;
            }
        }
        let mut disk = BTreeMap::new();
        let mut sources = BTreeMap::new();
        for name in files.into_values() {
            if name.planned != name.disk {
                sources.insert(name.disk.clone(), name.planned);
            }
            disk.insert(name.disk, name.value);
        }
        collisions.sort_by(|a: &Collision, b| a.written.cmp(&b.written));
        Ok(Resolved {
            disk,
            sources,
            collisions,
        })
    }
}

/// One name on the volume during [`NamePolicy::resolve`].
struct Name<V> {
    /// The planned path written under this name.
    planned: Vec<u8>,
    disk: Vec<u8>,
    value: V,
    /// Position of this name's entry in the collision list, once another spelling arrives.
    collision: Option<usize>,
}

impl<V> Name<V> {
    fn new(planned: &[u8], disk: Vec<u8>, value: V) -> Self {
        Self {
            planned: planned.to_vec(),
            disk,
            value,
            collision: None,
        }
    }

    /// Records `shadowed` as another planned spelling of this name, now written as `planned`.
    fn shadow(&mut self, shadowed: Vec<u8>, collisions: &mut Vec<Collision>) {
        let index = *self.collision.get_or_insert_with(|| {
            collisions.push(Collision::default());
            collisions.len() - 1
        });
        let collision = &mut collisions[index];
        collision.written.clone_from(&self.planned);
        if !collision.shadowed.contains(&shadowed) {
            collision.shadowed.push(shadowed);
        }
    }
}

/// Whether the working tree's root directory resolves `.GIT` to its `.git` entry. Read-only. When
/// the root has no `.git` entry, or a lookup fails other than by absence, folding is assumed.
///
/// A volume mounted below the root is outside checkout's contract; the `lstat` of each wanted
/// name still refuses an alias that already exists there.
fn probe_case_folding(repo: &Repository) -> bool {
    use std::os::unix::fs::MetadataExt as _;
    let Some(root) = repo.worktree() else {
        return true;
    };
    match (
        std::fs::symlink_metadata(root.join(".git")),
        std::fs::symlink_metadata(root.join(".GIT")),
    ) {
        (Ok(_), Err(error)) if error.kind() == std::io::ErrorKind::NotFound => false,
        (Ok(actual), Ok(alias)) => actual.dev() == alias.dev() && actual.ino() == alias.ino(),
        _ => true,
    }
}

fn join(parent: &[u8], name: &[u8]) -> Vec<u8> {
    let mut path = parent.to_vec();
    if !path.is_empty() {
        path.push(b'/');
    }
    path.extend_from_slice(name);
    path
}

fn is_hfs_ignorable(c: char) -> bool {
    matches!(
        c,
        '\u{200c}'..='\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{206a}'..='\u{206f}' | '\u{feff}'
    )
}

/// `name` without the code points HFS+ ignores when comparing names.
fn without_hfs_ignorables(name: &[u8]) -> Vec<u8> {
    let Ok(text) = std::str::from_utf8(name) else {
        return name.to_vec();
    };
    text.chars()
        .filter(|c| !is_hfs_ignorable(*c))
        .collect::<String>()
        .into_bytes()
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use rstest::rstest;

    use super::{NamePolicy, Protection};
    use crate::checkout::Collision;

    const FOLDING: NamePolicy = NamePolicy {
        case: true,
        normalization: true,
    };
    const NORMALIZING: NamePolicy = NamePolicy {
        case: false,
        normalization: true,
    };

    #[rstest]
    #[case::ascii_case(FOLDING, "README", "readme", true)]
    #[case::composed(FOLDING, "caf\u{e9}", "cafe\u{301}", true)]
    #[case::unicode_case(FOLDING, "\u{c9}t\u{e9}", "\u{e9}t\u{e9}", true)]
    #[case::kelvin(FOLDING, "\u{212a}", "k", true)]
    #[case::ignorable(FOLDING, ".g\u{200c}it", ".git", true)]
    #[case::distinct(FOLDING, "a", "b", false)]
    #[case::case_sensitive_apfs(NORMALIZING, "README", "readme", false)]
    #[case::case_sensitive_apfs_composed(NORMALIZING, "caf\u{e9}", "cafe\u{301}", true)]
    #[case::exact_case(NamePolicy::EXACT, "README", "readme", false)]
    #[case::exact_composed(NamePolicy::EXACT, "caf\u{e9}", "cafe\u{301}", false)]
    fn keys_merge_what_the_volume_merges(
        #[case] policy: NamePolicy,
        #[case] a: &str,
        #[case] b: &str,
        #[case] same: bool,
    ) {
        assert_eq!(policy.key(a.as_bytes()) == policy.key(b.as_bytes()), same);
    }

    #[test]
    fn invalid_utf8_folds_ascii_only_when_case_folds() {
        assert_eq!(FOLDING.key(b"A\xff"), FOLDING.key(b"a\xff"));
        assert_ne!(NORMALIZING.key(b"A\xff"), NORMALIZING.key(b"a\xff"));
    }

    fn leaves(paths: &[(&str, u8)]) -> BTreeMap<Vec<u8>, u8> {
        paths
            .iter()
            .map(|(path, value)| (path.as_bytes().to_vec(), *value))
            .collect()
    }

    fn disk(entries: &[(&str, u8)]) -> BTreeMap<Vec<u8>, u8> {
        leaves(entries)
    }

    // Matches what Git 2.56.0 wrote on a case-insensitive APFS volume for the same tree.
    #[test]
    fn resolves_collisions_as_git_does() {
        let resolved = FOLDING
            .resolve(&leaves(&[
                ("Dir/f", 1),
                ("X.h", 2),
                ("caf\u{e9}", 3),
                ("cafe\u{301}", 4),
                ("dir/f", 5),
                ("dir/g", 6),
                ("x.h", 7),
            ]))
            .unwrap();
        assert_eq!(
            resolved.disk,
            disk(&[("Dir/f", 5), ("Dir/g", 6), ("caf\u{e9}", 3), ("x.h", 7)])
        );
        let collision = |written: &str, shadowed: &[&str]| Collision {
            written: written.as_bytes().to_vec(),
            shadowed: shadowed
                .iter()
                .map(|path| path.as_bytes().to_vec())
                .collect(),
        };
        assert_eq!(
            resolved.collisions,
            [
                collision("Dir", &["dir"]),
                collision("caf\u{e9}", &["cafe\u{301}"]),
                collision("dir/f", &["Dir/f"]),
                collision("x.h", &["X.h"]),
            ]
        );
    }

    #[test]
    fn exact_policy_keeps_every_path() {
        let planned = leaves(&[
            ("X.h", 1),
            ("x.h", 2),
            ("xt_CONNMARK.h", 3),
            ("xt_connmark.h", 4),
        ]);
        let resolved = NamePolicy::EXACT.resolve(&planned).unwrap();
        assert_eq!(resolved.disk, planned);
        assert!(resolved.collisions.is_empty());
    }

    #[rstest]
    #[case::file_first(&[("A", 1), ("a/b", 2)], "a")]
    #[case::directory_first(&[("A/b", 1), ("a", 2)], "a")]
    fn refuses_a_file_and_directory_sharing_a_name(#[case] paths: &[(&str, u8)], #[case] at: &str) {
        assert_eq!(
            FOLDING.resolve(&leaves(paths)).err().unwrap(),
            at.as_bytes()
        );
    }

    const ALL: Protection = Protection {
        ntfs: true,
        hfs: true,
    };
    const NONE: Protection = Protection {
        ntfs: false,
        hfs: false,
    };

    #[rstest]
    #[case::exact(".git", true, true, true)]
    #[case::ascii_case("a/.GIT/b", true, true, true)]
    #[case::short_name("git~1", true, false, true)]
    #[case::short_name_case("GIT~1", true, false, true)]
    #[case::trailing_space(".git ", true, false, true)]
    #[case::trailing_dots(".git..", true, false, true)]
    #[case::stream(".git::$INDEX_ALLOCATION", true, false, true)]
    #[case::hfs_ignorable(".g\u{200c}it", true, true, false)]
    #[case::bom("\u{feff}.git", true, true, false)]
    #[case::colon("c:d", false, false, false)]
    #[case::backslash("a\\b", false, false, false)]
    #[case::device("aux", false, false, false)]
    #[case::gitignore(".gitignore", false, false, false)]
    #[case::git_dot_x(".git.x", false, false, false)]
    fn matches_git_metadata_rules(
        #[case] path: &str,
        #[case] all: bool,
        #[case] hfs_only: bool,
        #[case] ntfs_only: bool,
    ) {
        let path = path.as_bytes();
        assert_eq!(ALL.refuses(path), all);
        assert_eq!(
            Protection {
                ntfs: false,
                hfs: true
            }
            .refuses(path),
            hfs_only
        );
        assert_eq!(
            Protection {
                ntfs: true,
                hfs: false
            }
            .refuses(path),
            ntfs_only
        );
        // Only `.git` in some ASCII case is refused under every rule set.
        assert_eq!(NONE.refuses(path), all && hfs_only && ntfs_only);
    }
}