Skip to main content

grit_lib/
init_filesystem.rs

1//! Filesystem capability detection during repository initialization.
2//!
3//! Git sets `core.filemode`, `core.symlinks`, `core.ignorecase`, and
4//! `core.precomposeunicode` in the new local config when initialization detects
5//! platform limits.
6
7use std::fs;
8use std::io;
9use std::path::Path;
10
11use thiserror::Error;
12
13use crate::config::{parse_config_parameters, ConfigFile, ConfigScope};
14use crate::environment::Environment;
15use crate::error::Result;
16use crate::unicode_normalization;
17
18/// Failure while detecting filesystem capabilities under a git directory.
19#[derive(Debug, Error)]
20#[non_exhaustive]
21pub enum FilesystemCapabilitiesError {
22    /// Underlying I/O failed while reading or probing the filesystem.
23    #[error("filesystem capability detection failed: {0}")]
24    Io(#[from] io::Error),
25}
26
27/// Result of [`FilesystemCapabilities`] detection.
28pub type FilesystemCapabilitiesResult<T> = std::result::Result<T, FilesystemCapabilitiesError>;
29
30/// When init may run the NFD→NFC precompose capability check.
31#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
32#[non_exhaustive]
33pub enum PrecomposeDetection {
34    /// Run the precompose check only when the platform would alias NFD and NFC (default).
35    #[default]
36    Platform,
37    /// Always run the precompose check (embedder/test knob, not from process env).
38    Always,
39}
40
41/// Controls when init-time filesystem capability detection may write local config.
42#[derive(Debug, Clone, Copy, Default)]
43pub struct InitFilesystemConfigOptions {
44    /// Skip all detection (Git skips on re-init).
45    pub is_reinit: bool,
46    /// How aggressively to detect `core.precomposeunicode`.
47    pub precompose_detection: PrecomposeDetection,
48}
49
50/// Platform limits Git records as `core.*` during init.
51///
52/// # Examples
53///
54/// ```
55/// use grit_lib::config::init_filesystem::FilesystemCapabilities;
56/// use std::fs;
57/// use tempfile::TempDir;
58///
59/// let td = TempDir::new().expect("tempdir");
60/// let git_dir = td.path().join(".git");
61/// fs::create_dir_all(&git_dir).expect("mkdir");
62/// fs::write(git_dir.join("config"), "[core]\n").expect("config");
63///
64/// let caps = FilesystemCapabilities::detect(&git_dir).expect("detect");
65/// let only_case = FilesystemCapabilities::detect_case_insensitive(&git_dir).expect("case");
66/// assert_eq!(only_case, caps.case_insensitive);
67/// ```
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69#[non_exhaustive]
70pub struct FilesystemCapabilities {
71    /// Whether ref and path names are compared case-insensitively (`core.ignorecase`).
72    pub case_insensitive: bool,
73    /// Whether the executable bit on files is meaningful (`core.filemode`).
74    pub trust_filemode: bool,
75    /// Whether symbolic links can be created under the git directory (`core.symlinks`).
76    pub symlinks: bool,
77    /// Whether NFD and NFC spellings alias the same path (`core.precomposeunicode`).
78    pub precomposes_unicode: bool,
79}
80
81impl FilesystemCapabilities {
82    /// Detect all init-time filesystem capabilities under `git_dir`.
83    ///
84    /// # Errors
85    ///
86    /// Returns [`FilesystemCapabilitiesError::Io`] when a probe cannot read or touch the filesystem.
87    pub fn detect(git_dir: &Path) -> FilesystemCapabilitiesResult<Self> {
88        Ok(Self {
89            case_insensitive: Self::detect_case_insensitive(git_dir)?,
90            trust_filemode: Self::detect_trust_filemode(git_dir)?,
91            symlinks: Self::detect_symlinks_supported(git_dir)?,
92            precomposes_unicode: Self::detect_precomposes_unicode(git_dir)?,
93        })
94    }
95
96    /// Whether `config` in `git_dir` is visible as `CoNfIg` (case-insensitive git dir).
97    ///
98    /// Matches Git `init_db` / `setup.c` case-insensitivity detection.
99    ///
100    /// # Errors
101    ///
102    /// Returns [`FilesystemCapabilitiesError::Io`] when the git directory cannot be read.
103    pub fn detect_case_insensitive(git_dir: &Path) -> FilesystemCapabilitiesResult<bool> {
104        let config_path = git_dir.join("config");
105        if !config_path.is_file() {
106            return Ok(false);
107        }
108        Ok(git_dir.join("CoNfIg").is_file())
109    }
110
111    /// Whether the executable bit is meaningful for `git_dir/config`.
112    ///
113    /// Matches Git `init_db` filemode trustability check in `setup.c`.
114    ///
115    /// # Errors
116    ///
117    /// Returns [`FilesystemCapabilitiesError::Io`] when permissions cannot be read or toggled.
118    pub fn detect_trust_filemode(git_dir: &Path) -> FilesystemCapabilitiesResult<bool> {
119        let config_path = git_dir.join("config");
120        if !config_path.is_file() {
121            return Ok(true);
122        }
123
124        #[cfg(unix)]
125        {
126            use std::os::unix::fs::PermissionsExt;
127            let meta = fs::metadata(&config_path)?;
128            let mode = meta.permissions().mode();
129            let toggled = mode ^ 0o100;
130            fs::set_permissions(&config_path, fs::Permissions::from_mode(toggled))?;
131            let meta2 = fs::metadata(&config_path)?;
132            let mut filemode = mode != meta2.permissions().mode();
133            fs::set_permissions(&config_path, fs::Permissions::from_mode(mode))?;
134            if filemode && mode & 0o100 != 0 {
135                filemode = false;
136            }
137            Ok(filemode)
138        }
139
140        #[cfg(not(unix))]
141        {
142            let _ = git_dir;
143            Ok(false)
144        }
145    }
146
147    /// Whether symbolic links can be created under `git_dir`.
148    ///
149    /// Uses a unique path and never deletes pre-existing files (e.g. from init templates).
150    ///
151    /// # Errors
152    ///
153    /// Returns [`FilesystemCapabilitiesError::Io`] when the probe path cannot be created.
154    pub fn detect_symlinks_supported(git_dir: &Path) -> FilesystemCapabilitiesResult<bool> {
155        for attempt in 0..128_u32 {
156            let probe_path = git_dir.join(format!(".grit-symlink-capability-{attempt:05}"));
157            if fs::symlink_metadata(&probe_path).is_ok() {
158                continue;
159            }
160
161            #[cfg(unix)]
162            {
163                use std::os::unix::fs::symlink;
164                return Ok(if symlink("testing", &probe_path).is_err() {
165                    false
166                } else {
167                    let ok = fs::symlink_metadata(&probe_path)
168                        .map(|m| m.file_type().is_symlink())
169                        .unwrap_or(false);
170                    let _ = fs::remove_file(&probe_path);
171                    ok
172                });
173            }
174
175            #[cfg(windows)]
176            {
177                use std::os::windows::fs::symlink_file;
178                return Ok(if symlink_file("testing", &probe_path).is_err() {
179                    false
180                } else {
181                    let ok = fs::symlink_metadata(&probe_path)
182                        .map(|m| m.file_type().is_symlink())
183                        .unwrap_or(false);
184                    let _ = fs::remove_file(&probe_path);
185                    ok
186                });
187            }
188
189            #[cfg(not(any(unix, windows)))]
190            {
191                let _ = git_dir;
192                return Ok(false);
193            }
194        }
195        Ok(false)
196    }
197
198    /// Whether creating a file with an NFC filename makes the NFD spelling visible (macOS / HFS+ style).
199    ///
200    /// # Errors
201    ///
202    /// Returns [`FilesystemCapabilitiesError::Io`] when the probe file cannot be written.
203    pub fn detect_precomposes_unicode(git_dir: &Path) -> FilesystemCapabilitiesResult<bool> {
204        unicode_normalization::filesystem_precomposes_unicode(git_dir).map_err(Into::into)
205    }
206}
207
208fn config_bool_from_parameters(env: &Environment, key: &str) -> Option<bool> {
209    let raw = env.git_config_parameters.as_deref()?;
210    let key_lower = key.to_ascii_lowercase();
211    let mut last: Option<bool> = None;
212    for entry in parse_config_parameters(raw) {
213        let Some((k, v)) = entry.split_once('\u{1}') else {
214            continue;
215        };
216        if !k.trim().eq_ignore_ascii_case(&key_lower) {
217            continue;
218        }
219        let v = v.trim();
220        last = Some(matches!(
221            v.to_ascii_lowercase().as_str(),
222            "true" | "yes" | "on" | "1"
223        ));
224    }
225    last
226}
227
228fn precompose_from_git_config_parameters(env: &Environment) -> Option<bool> {
229    config_bool_from_parameters(env, "core.precomposeunicode")
230}
231
232fn ignorecase_from_git_config_parameters(env: &Environment) -> Option<bool> {
233    config_bool_from_parameters(env, "core.ignorecase")
234}
235
236fn filemode_from_git_config_parameters(env: &Environment) -> Option<bool> {
237    config_bool_from_parameters(env, "core.filemode")
238}
239
240fn symlinks_from_git_config_parameters(env: &Environment) -> Option<bool> {
241    config_bool_from_parameters(env, "core.symlinks")
242}
243
244/// After a fresh `.git` layout is written, detect filesystem capabilities and set local
245/// `core.*` keys when appropriate.
246///
247/// Honors higher-priority config (system, global, `GIT_CONFIG_PARAMETERS`), values already
248/// present in the local config (including from an init template), and does not override them.
249/// When [`InitFilesystemConfigOptions::precompose_detection`] is [`PrecomposeDetection::Always`],
250/// the precompose check runs even on filesystems that would not normally normalize NFD to NFC
251/// (Linux CI).
252///
253/// # Errors
254///
255/// Returns [`Error::Io`](crate::error::Error::Io) or config parse/write failures.
256pub(crate) fn apply_init_filesystem_config(
257    git_dir: &Path,
258    opts: InitFilesystemConfigOptions,
259    environment: &Environment,
260) -> Result<()> {
261    if opts.is_reinit {
262        return Ok(());
263    }
264
265    let precompose_from_cmdline = precompose_from_git_config_parameters(environment).is_some();
266    let ignorecase_from_cmdline = ignorecase_from_git_config_parameters(environment).is_some();
267
268    let caps = FilesystemCapabilities::detect(git_dir).unwrap_or(FilesystemCapabilities {
269        case_insensitive: false,
270        trust_filemode: true,
271        symlinks: false,
272        precomposes_unicode: false,
273    });
274
275    let mut changed = false;
276    let config_path = git_dir.join("config");
277    let content = fs::read_to_string(&config_path).unwrap_or_default();
278    let mut cfg = ConfigFile::parse(&config_path, &content, ConfigScope::Local)?;
279    let precompose_locally_set = cfg.get("core.precomposeunicode").is_some();
280    let ignorecase_locally_set = cfg.get("core.ignorecase").is_some();
281
282    let filemode_value = filemode_from_git_config_parameters(environment)
283        .map(|v| if v { "true" } else { "false" })
284        .unwrap_or_else(|| if caps.trust_filemode { "true" } else { "false" });
285    cfg.set("core.filemode", filemode_value)?;
286    changed |= true;
287
288    if let Some(from_cmdline) = symlinks_from_git_config_parameters(environment) {
289        cfg.set("core.symlinks", if from_cmdline { "true" } else { "false" })?;
290        changed |= true;
291    } else if !caps.symlinks {
292        cfg.set("core.symlinks", "false")?;
293        changed |= true;
294    }
295
296    if !precompose_from_cmdline && !precompose_locally_set {
297        let precompose_ok = matches!(opts.precompose_detection, PrecomposeDetection::Always)
298            || caps.precomposes_unicode;
299        if precompose_ok {
300            cfg.set("core.precomposeunicode", "true")?;
301            changed |= true;
302        }
303    }
304
305    if !ignorecase_from_cmdline && !ignorecase_locally_set && caps.case_insensitive {
306        cfg.set("core.ignorecase", "true")?;
307        changed |= true;
308    }
309
310    if changed {
311        cfg.write()?;
312    }
313    Ok(())
314}
315
316#[cfg(test)]
317mod tests {
318    use super::*;
319    use std::fs;
320    use tempfile::TempDir;
321
322    #[test]
323    fn case_insensitive_detection_false_on_normal_fs() {
324        let td = TempDir::new().expect("tempdir");
325        let git_dir = td.path().join(".git");
326        fs::create_dir_all(&git_dir).expect("mkdir");
327        fs::write(git_dir.join("config"), "[core]\n").expect("config");
328        assert!(!FilesystemCapabilities::detect_case_insensitive(&git_dir).expect("detect"));
329    }
330
331    #[test]
332    fn apply_honors_git_config_parameters_filemode() {
333        use crate::config::environment::ConfigOverride;
334
335        let td = TempDir::new().expect("tempdir");
336        let git_dir = td.path().join(".git");
337        fs::create_dir_all(&git_dir).expect("mkdir");
338        fs::write(
339            git_dir.join("config"),
340            "[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n",
341        )
342        .expect("config");
343        let mut env = Environment::empty();
344        env.push_config_override(
345            &"core.filemode=false"
346                .parse::<ConfigOverride>()
347                .expect("override"),
348        );
349        apply_init_filesystem_config(&git_dir, InitFilesystemConfigOptions::default(), &env)
350            .expect("apply");
351        let text = fs::read_to_string(git_dir.join("config")).expect("read");
352        assert!(text.contains("filemode = false"), "{text}");
353    }
354
355    #[test]
356    fn apply_sets_filemode_from_detection() {
357        let td = TempDir::new().expect("tempdir");
358        let git_dir = td.path().join(".git");
359        fs::create_dir_all(&git_dir).expect("mkdir");
360        fs::write(
361            git_dir.join("config"),
362            "[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n",
363        )
364        .expect("config");
365        apply_init_filesystem_config(
366            &git_dir,
367            InitFilesystemConfigOptions::default(),
368            &crate::environment::Environment::empty(),
369        )
370        .expect("apply");
371        let detected = FilesystemCapabilities::detect_trust_filemode(&git_dir).expect("detect");
372        let text = fs::read_to_string(git_dir.join("config")).expect("read");
373        let expected = if detected {
374            "filemode = true"
375        } else {
376            "filemode = false"
377        };
378        assert!(text.contains(expected), "{text}");
379    }
380
381    #[test]
382    fn apply_respects_precompose_detection_always() {
383        let td = TempDir::new().expect("tempdir");
384        let git_dir = td.path().join(".git");
385        fs::create_dir_all(&git_dir).expect("mkdir");
386        fs::write(
387            git_dir.join("config"),
388            "[core]\n\trepositoryformatversion = 0\n",
389        )
390        .expect("config");
391        apply_init_filesystem_config(
392            &git_dir,
393            InitFilesystemConfigOptions {
394                precompose_detection: PrecomposeDetection::Always,
395                ..InitFilesystemConfigOptions::default()
396            },
397            &Environment::empty(),
398        )
399        .expect("apply");
400        let text = fs::read_to_string(git_dir.join("config")).expect("read");
401        assert!(text.contains("precomposeunicode = true"));
402    }
403
404    #[test]
405    fn apply_does_not_override_template_precomposeunicode_false() {
406        let tmpl = TempDir::new().expect("tempdir");
407        fs::write(
408            tmpl.path().join("config"),
409            "[core]\n\tprecomposeunicode = false\n",
410        )
411        .expect("template config");
412
413        let root = TempDir::new().expect("worktree");
414        crate::repo::init_repository(
415            root.path(),
416            false,
417            "main",
418            Some(tmpl.path()),
419            crate::RefStorageFormat::Files,
420        )
421        .expect("init");
422
423        let text = fs::read_to_string(root.path().join(".git/config")).expect("read");
424        assert!(
425            text.contains("precomposeunicode = false"),
426            "template local value must be preserved:\n{text}"
427        );
428    }
429
430    #[test]
431    fn symlink_detection_does_not_delete_template_file() {
432        let td = TempDir::new().expect("tempdir");
433        let git_dir = td.path().join(".git");
434        fs::create_dir_all(&git_dir).expect("mkdir");
435        fs::write(git_dir.join("config"), "[core]\n").expect("config");
436        let sentinel = git_dir.join(".grit-symlink-capability-00000");
437        fs::write(&sentinel, "keep me").expect("sentinel");
438        let _ = FilesystemCapabilities::detect_symlinks_supported(&git_dir);
439        assert!(
440            sentinel.is_file(),
441            "detection must not remove an existing template file"
442        );
443        assert_eq!(fs::read_to_string(&sentinel).expect("read"), "keep me");
444    }
445}