Skip to main content

grit_lib/
environment.rs

1//! Explicit discovery and configuration environment for embedding callers.
2//!
3//! [`Environment`] holds the variables Git reads during repository discovery and config
4//! cascade loading. Library code must not read the process environment for these values;
5//! embedders (including the `grit` CLI) construct an [`Environment`] and pass it into
6//! [`crate::repo::Repository::discover`](crate::repo::Repository::discover) and
7//! [`crate::repo::Repository::open`](crate::repo::Repository::open), and
8//! [`ConfigSet::load`](crate::config::ConfigSet::load).
9
10use crate::git_path::CanonicalizeExt;
11use std::collections::HashMap;
12use std::ffi::OsString;
13use std::path::{Path, PathBuf};
14use std::str::FromStr;
15use std::sync::Arc;
16
17use time::{OffsetDateTime, UtcOffset};
18
19use crate::change_id::{ChangeIdGenerator, OsChangeIdGenerator};
20use crate::command_runner::{system_command_runner, CommandRunner};
21use crate::config::parse_git_config_maybe_bool;
22use crate::diagnostics::{DiagnosticsHandle, NullDiagnostics};
23use crate::git_date::tm::{local_tzoffset_with_tz, TzHhmm};
24use crate::ident_resolve::IdentityEnv;
25use crate::ownership_check::{default_ownership_check, is_default_ownership_check, OwnershipCheck};
26use crate::reftable::ReftableWriteOptions;
27
28/// Discovery and config variables that affect repository open/discover and `ConfigSet` loading.
29///
30/// Cloning shares the captured variable map. Public fields remain independent, so callers
31/// can adjust discovery/config overrides on a clone without changing the original snapshot.
32#[derive(Debug, Clone)]
33pub struct Environment {
34    /// Process working directory used for relative path resolution during discovery.
35    pub cwd: PathBuf,
36    /// Override for `GIT_DIR` when set (see Git environment variable of the same name).
37    pub git_dir: Option<String>,
38    /// Override for `GIT_WORK_TREE` when set (see Git environment variable of the same name).
39    pub git_work_tree: Option<String>,
40    /// Override for `GIT_CEILING_DIRECTORIES` when set (see Git environment variable of the same name).
41    pub git_ceiling_directories: Option<String>,
42    /// Override for `GIT_INDEX_FILE` when set (see Git environment variable of the same name).
43    pub git_index_file: Option<String>,
44    /// Override for `GIT_NAMESPACE` when set (see Git environment variable of the same name).
45    pub git_namespace: Option<String>,
46    /// Override for `GIT_REPLACE_REF_BASE` when set (see Git environment variable of the same name).
47    pub git_replace_ref_base: Option<String>,
48    /// When true, replacement objects from `GIT_REPLACE_OBJECT` are ignored.
49    pub git_no_replace_objects: bool,
50    /// When false, opportunistic index updates that take optional locks are skipped (Git
51    /// `GIT_OPTIONAL_LOCKS=0` / `--no-optional-locks`). Defaults to true when unset.
52    pub git_optional_locks: bool,
53    /// `GIT_LITERAL_PATHSPECS` — argv pathspecs treat `*` and `?` as literal.
54    pub git_literal_pathspecs: bool,
55    /// `GIT_GLOB_PATHSPECS` — argv pathspecs are globs.
56    pub git_glob_pathspecs: bool,
57    /// `GIT_NOGLOB_PATHSPECS` — disable glob interpretation in argv pathspecs.
58    pub git_noglob_pathspecs: bool,
59    /// `GIT_ICASE_PATHSPECS` — case-fold argv pathspec patterns.
60    pub git_icase_pathspecs: bool,
61    /// Override for `GIT_ALTERNATE_OBJECT_DIRECTORIES` when set (see Git environment variable of the same name).
62    pub git_alternate_object_directories: Option<String>,
63    /// Override for `GIT_OBJECT_DIRECTORY` when set (see Git environment variable of the same name).
64    ///
65    /// When set, a [`Repository`](crate::repo::Repository) opened with this environment reads
66    /// and writes objects in this directory instead of `<git-dir>/objects` (a relative path
67    /// resolves against [`Self::cwd`]). The directory must exist, or opening fails with
68    /// [`RepositoryError::NotARepository`](crate::repo::RepositoryError::NotARepository); an empty value fails
69    /// the same way, as in Git. `<git-dir>/objects` is not consulted unless it is listed in
70    /// [`Self::git_alternate_object_directories`] or in this directory's `info/alternates`.
71    pub git_object_directory: Option<String>,
72    /// When set, overrides the repository-relative cwd prefix derived from `cwd`.
73    pub git_prefix: Option<String>,
74    /// Override for `GIT_CONFIG_NOSYSTEM` when set (see Git environment variable of the same name).
75    pub git_config_nosystem: Option<String>,
76    /// Override for `GIT_CONFIG_SYSTEM` when set (see Git environment variable of the same name).
77    pub git_config_system: Option<String>,
78    /// Override for `GIT_CONFIG_GLOBAL` when set (see Git environment variable of the same name).
79    pub git_config_global: Option<String>,
80    /// Override for `GIT_CONFIG` when set (see Git environment variable of the same name).
81    pub git_config: Option<String>,
82    /// Override for `GIT_CONFIG_PARAMETERS` when set (see Git environment variable of the same name).
83    pub git_config_parameters: Option<String>,
84    /// Override for `GIT_CONFIG_COUNT` when set (see Git environment variable of the same name).
85    pub git_config_count: Option<String>,
86    /// Pairs from `GIT_CONFIG_KEY_n` / `GIT_CONFIG_VALUE_n` when `GIT_CONFIG_COUNT` is set.
87    pub git_config_pairs: Vec<(String, String)>,
88    /// Override for `HOME` when set (see Git environment variable of the same name).
89    pub home: Option<OsString>,
90    /// Override for `XDG_CONFIG_HOME` when set (see Git environment variable of the same name).
91    pub xdg_config_home: Option<String>,
92    /// Override for `USERPROFILE` when set (see Git environment variable of the same name).
93    pub userprofile: Option<OsString>,
94    /// Override for `HOMEDRIVE` when set (see Git environment variable of the same name).
95    pub homedrive: Option<OsString>,
96    /// Override for `HOMEPATH` when set (see Git environment variable of the same name).
97    pub homepath: Option<OsString>,
98    /// Override for `GIT_INSTALL_ROOT` when set (see Git environment variable of the same name).
99    pub git_install_root: Option<OsString>,
100    /// Override for `GIT_EXEC_PATH` when set (see Git environment variable of the same name).
101    pub git_exec_path: Option<OsString>,
102    /// `$PWD` when set (symlink-preserving absolute path for include matching).
103    pub pwd: Option<String>,
104    /// Original working directory of the `grit` invocation (for messages).
105    pub grit_invocation_cwd: Option<String>,
106    /// Override for `SUDO_UID` when set (see Git environment variable of the same name).
107    pub sudo_uid: Option<String>,
108    /// Override for `GIT_AUTHOR_NAME` when set (see Git environment variable of the same name).
109    pub git_author_name: Option<String>,
110    /// Override for `GIT_AUTHOR_EMAIL` when set (see Git environment variable of the same name).
111    pub git_author_email: Option<String>,
112    /// Override for `GIT_AUTHOR_DATE` when set (see Git environment variable of the same name).
113    pub git_author_date: Option<String>,
114    /// Override for `GIT_COMMITTER_NAME` when set (see Git environment variable of the same name).
115    pub git_committer_name: Option<String>,
116    /// Override for `GIT_COMMITTER_EMAIL` when set (see Git environment variable of the same name).
117    pub git_committer_email: Option<String>,
118    /// Override for `GIT_COMMITTER_DATE` when set (see Git environment variable of the same name).
119    pub git_committer_date: Option<String>,
120    /// Timezone for local date formatting (`TZ`).
121    pub tz: Option<String>,
122    /// Override for `USER` when set (see Git environment variable of the same name).
123    pub user: Option<String>,
124    /// Override for `USERNAME` when set (see Git environment variable of the same name).
125    pub username: Option<String>,
126    /// Windows `%ProgramFiles%` (for Git for Windows system config discovery).
127    pub program_files: Option<String>,
128    /// Windows `%ProgramFiles(x86)%`.
129    pub program_files_x86: Option<String>,
130    /// Full variable snapshot from [`Self::from_vars`] / [`Self::capture_process`].
131    /// Shared across clones; typed overrides stay local to each environment.
132    /// An empty snapshot needs no allocation for this map.
133    pub(crate) captured_vars: Option<Arc<HashMap<String, OsString>>>,
134}
135
136impl Environment {
137    /// No variables at all; [`Self::cwd`] is `"."` (canonicalized by callers when needed).
138    ///
139    /// Config loaded with this environment has no home directory, so `~/.gitconfig` and
140    /// `$XDG_CONFIG_HOME/git/config` are not read, and on Windows the Git for Windows system
141    /// gitconfig is not found. On Unix `/etc/gitconfig` still loads unless
142    /// [`Self::git_config_nosystem`] is set. Use it for hermetic work (tests, repositories the
143    /// caller created); use [`Self::capture_process`] to match `git` on a user's machine.
144    #[must_use]
145    pub fn empty() -> Self {
146        Self {
147            cwd: PathBuf::from("."),
148            git_dir: None,
149            git_work_tree: None,
150            git_ceiling_directories: None,
151            git_index_file: None,
152            git_namespace: None,
153            git_replace_ref_base: None,
154            git_no_replace_objects: false,
155            git_optional_locks: true,
156            git_literal_pathspecs: false,
157            git_glob_pathspecs: false,
158            git_noglob_pathspecs: false,
159            git_icase_pathspecs: false,
160            git_alternate_object_directories: None,
161            git_object_directory: None,
162            git_prefix: None,
163            git_config_nosystem: None,
164            git_config_system: None,
165            git_config_global: None,
166            git_config: None,
167            git_config_parameters: None,
168            git_config_count: None,
169            git_config_pairs: Vec::new(),
170            home: None,
171            xdg_config_home: None,
172            userprofile: None,
173            homedrive: None,
174            homepath: None,
175            git_install_root: None,
176            git_exec_path: None,
177            pwd: None,
178            grit_invocation_cwd: None,
179            sudo_uid: None,
180            git_author_name: None,
181            git_author_email: None,
182            git_author_date: None,
183            git_committer_name: None,
184            git_committer_email: None,
185            git_committer_date: None,
186            tz: None,
187            user: None,
188            username: None,
189            program_files: None,
190            program_files_x86: None,
191            captured_vars: None,
192        }
193    }
194
195    /// Whether this snapshot matches [`Self::empty`], the default
196    /// [`crate::transfer::FetchOptions::environment`] value.
197    ///
198    /// SSH transport uses the repository [`Environment`] when fetch options still
199    /// carry this sentinel so `FetchOptions::default()` does not mask `GIT_SSH_*`
200    /// stored on the repository handle.
201    #[must_use]
202    pub fn is_fetch_options_default(&self) -> bool {
203        let e = Self::empty();
204        self.cwd == e.cwd
205            && self.git_dir == e.git_dir
206            && self.git_work_tree == e.git_work_tree
207            && self.git_ceiling_directories == e.git_ceiling_directories
208            && self.git_index_file == e.git_index_file
209            && self.git_namespace == e.git_namespace
210            && self.git_replace_ref_base == e.git_replace_ref_base
211            && self.git_no_replace_objects == e.git_no_replace_objects
212            && self.git_optional_locks == e.git_optional_locks
213            && self.git_literal_pathspecs == e.git_literal_pathspecs
214            && self.git_glob_pathspecs == e.git_glob_pathspecs
215            && self.git_noglob_pathspecs == e.git_noglob_pathspecs
216            && self.git_icase_pathspecs == e.git_icase_pathspecs
217            && self.git_alternate_object_directories == e.git_alternate_object_directories
218            && self.git_object_directory == e.git_object_directory
219            && self.git_prefix == e.git_prefix
220            && self.git_config_nosystem == e.git_config_nosystem
221            && self.git_config_system == e.git_config_system
222            && self.git_config_global == e.git_config_global
223            && self.git_config == e.git_config
224            && self.git_config_parameters == e.git_config_parameters
225            && self.git_config_count == e.git_config_count
226            && self.git_config_pairs == e.git_config_pairs
227            && self.home == e.home
228            && self.xdg_config_home == e.xdg_config_home
229            && self.userprofile == e.userprofile
230            && self.homedrive == e.homedrive
231            && self.homepath == e.homepath
232            && self.git_install_root == e.git_install_root
233            && self.git_exec_path == e.git_exec_path
234            && self.pwd == e.pwd
235            && self.grit_invocation_cwd == e.grit_invocation_cwd
236            && self.sudo_uid == e.sudo_uid
237            && self.git_author_name == e.git_author_name
238            && self.git_author_email == e.git_author_email
239            && self.git_author_date == e.git_author_date
240            && self.git_committer_name == e.git_committer_name
241            && self.git_committer_email == e.git_committer_email
242            && self.git_committer_date == e.git_committer_date
243            && self.tz == e.tz
244            && self.user == e.user
245            && self.username == e.username
246            && self.program_files == e.program_files
247            && self.program_files_x86 == e.program_files_x86
248            && self.captured_vars == e.captured_vars
249    }
250
251    /// Parse known discovery/config variables from `vars` without reading the process environment.
252    ///
253    /// Unknown keys from `vars` are retained for later lookup via [`Self::var`] / [`Self::var_os`].
254    /// `GIT_CONFIG_COUNT` expands into [`Self::git_config_pairs`].
255    pub fn from_vars(vars: impl IntoIterator<Item = (OsString, OsString)>, cwd: PathBuf) -> Self {
256        let map: HashMap<String, OsString> = vars
257            .into_iter()
258            .map(|(k, v)| (k.to_string_lossy().into_owned(), v))
259            .collect();
260        let get = |key: &str| -> Option<String> {
261            map.get(key).and_then(|v| v.to_str().map(str::to_owned))
262        };
263        let get_os = |key: &str| -> Option<OsString> { map.get(key).cloned() };
264
265        let mut git_config_pairs = Vec::new();
266        if let Some(count_str) = get("GIT_CONFIG_COUNT") {
267            if let Ok(count) = count_str.parse::<usize>() {
268                for i in 0..count {
269                    let key_var = format!("GIT_CONFIG_KEY_{i}");
270                    let value_var = format!("GIT_CONFIG_VALUE_{i}");
271                    if let (Some(k), Some(v)) = (get(&key_var), get(&value_var)) {
272                        git_config_pairs.push((k, v));
273                    }
274                }
275            }
276        }
277
278        Self {
279            cwd,
280            git_dir: get("GIT_DIR"),
281            git_work_tree: get("GIT_WORK_TREE"),
282            git_ceiling_directories: get("GIT_CEILING_DIRECTORIES"),
283            git_index_file: get("GIT_INDEX_FILE"),
284            git_namespace: get("GIT_NAMESPACE"),
285            git_replace_ref_base: get("GIT_REPLACE_REF_BASE"),
286            git_no_replace_objects: map.contains_key("GIT_NO_REPLACE_OBJECTS"),
287            git_optional_locks: git_optional_locks_from_env(get("GIT_OPTIONAL_LOCKS").as_deref()),
288            git_literal_pathspecs: map.contains_key("GIT_LITERAL_PATHSPECS"),
289            git_glob_pathspecs: map.contains_key("GIT_GLOB_PATHSPECS"),
290            git_noglob_pathspecs: map.contains_key("GIT_NOGLOB_PATHSPECS"),
291            git_icase_pathspecs: map.contains_key("GIT_ICASE_PATHSPECS"),
292            git_alternate_object_directories: get("GIT_ALTERNATE_OBJECT_DIRECTORIES"),
293            git_object_directory: get("GIT_OBJECT_DIRECTORY"),
294            git_prefix: get("GIT_PREFIX"),
295            git_config_nosystem: get("GIT_CONFIG_NOSYSTEM"),
296            git_config_system: get("GIT_CONFIG_SYSTEM"),
297            git_config_global: get("GIT_CONFIG_GLOBAL"),
298            git_config: get("GIT_CONFIG"),
299            git_config_parameters: get("GIT_CONFIG_PARAMETERS"),
300            git_config_count: get("GIT_CONFIG_COUNT"),
301            git_config_pairs,
302            home: get_os("HOME"),
303            xdg_config_home: get("XDG_CONFIG_HOME"),
304            userprofile: get_os("USERPROFILE"),
305            homedrive: get_os("HOMEDRIVE"),
306            homepath: get_os("HOMEPATH"),
307            git_install_root: get_os("GIT_INSTALL_ROOT"),
308            git_exec_path: get_os("GIT_EXEC_PATH"),
309            pwd: get("PWD"),
310            grit_invocation_cwd: get("GRIT_INVOCATION_CWD"),
311            sudo_uid: get("SUDO_UID"),
312            git_author_name: get("GIT_AUTHOR_NAME"),
313            git_author_email: get("GIT_AUTHOR_EMAIL"),
314            git_author_date: get("GIT_AUTHOR_DATE"),
315            git_committer_name: get("GIT_COMMITTER_NAME"),
316            git_committer_email: get("GIT_COMMITTER_EMAIL"),
317            git_committer_date: get("GIT_COMMITTER_DATE"),
318            tz: get("TZ"),
319            user: get("USER"),
320            username: get("USERNAME"),
321            program_files: get("ProgramFiles"),
322            program_files_x86: get("ProgramFiles(x86)"),
323            captured_vars: (!map.is_empty()).then(|| Arc::new(map)),
324        }
325    }
326
327    /// Parsed epoch from `GIT_AUTHOR_DATE` / `GIT_COMMITTER_DATE` when set.
328    #[must_use]
329    pub fn git_now_date_override(&self) -> Option<i64> {
330        let raw = self
331            .git_committer_date
332            .as_deref()
333            .or(self.git_author_date.as_deref())?;
334        raw.split_whitespace()
335            .next()
336            .and_then(|p| p.parse::<i64>().ok())
337    }
338
339    /// Use `path` as the repository directory, like setting `GIT_DIR`.
340    ///
341    /// A relative `path` is resolved against [`Self::cwd`] now, so the stored value stays
342    /// correct when it is exported to subprocesses that run in another directory.
343    ///
344    /// # Parameters
345    ///
346    /// - `path`: the `.git` directory (or gitfile) to open instead of discovering one.
347    ///
348    /// # Returns
349    ///
350    /// This environment with [`Self::git_dir`] set.
351    #[must_use]
352    pub fn with_git_dir(mut self, path: impl AsRef<Path>) -> Self {
353        self.git_dir = Some(self.absolute_from_cwd(path.as_ref()));
354        self
355    }
356
357    /// Use `path` as the work tree root, like setting `GIT_WORK_TREE`.
358    ///
359    /// A relative `path` is resolved against [`Self::cwd`] now, as in [`Self::with_git_dir`].
360    ///
361    /// # Parameters
362    ///
363    /// - `path`: the directory to treat as the top of the work tree.
364    ///
365    /// # Returns
366    ///
367    /// This environment with [`Self::git_work_tree`] set.
368    #[must_use]
369    pub fn with_work_tree(mut self, path: impl AsRef<Path>) -> Self {
370        self.git_work_tree = Some(self.absolute_from_cwd(path.as_ref()));
371        self
372    }
373
374    /// Set or override one subprocess variable without resnapshotting the process.
375    ///
376    /// The value is stored in the shared captured map (cloned on first use) and
377    /// exported through [`Self::subprocess_environment`] like any other untyped
378    /// variable. Typed fields on this environment still win over the same key.
379    ///
380    /// # Parameters
381    ///
382    /// - `key`: variable name (for example `REMOTE_USER`).
383    /// - `value`: UTF-8 value to export to hook and filter subprocesses.
384    ///
385    /// # Returns
386    ///
387    /// This environment with `key` set to `value`.
388    #[must_use]
389    pub fn with_var(mut self, key: impl Into<String>, value: impl Into<OsString>) -> Self {
390        let key = key.into();
391        let value = value.into();
392        let mut map = self
393            .captured_vars
394            .as_ref()
395            .map(|vars| (**vars).clone())
396            .unwrap_or_default();
397        map.insert(key, value);
398        self.captured_vars = Some(Arc::new(map));
399        self
400    }
401
402    /// Append a command-line configuration override (`git -c key=value`).
403    ///
404    /// The override is added to [`Self::git_config_parameters`] in the quoted
405    /// `'key'='value'` form (`'key'=` for a bare key) that Git itself writes to
406    /// `GIT_CONFIG_PARAMETERS` for `git -c`, so it is read by
407    /// [`ConfigSet::load`](crate::config::ConfigSet::load) with command-line scope and is
408    /// inherited by subprocesses through [`Self::subprocess_environment`]. Later overrides win
409    /// over earlier ones, over `GIT_CONFIG_COUNT` pairs, and over every config file.
410    ///
411    /// # Parameters
412    ///
413    /// - `config_override`: the validated key and optional value to add.
414    pub fn push_config_override(&mut self, config_override: &ConfigOverride) {
415        use crate::transport::sq_quote_shell_arg;
416
417        let mut entry = sq_quote_shell_arg(&config_override.key);
418        entry.push('=');
419        if let Some(value) = &config_override.value {
420            entry.push_str(&sq_quote_shell_arg(value));
421        }
422        match &mut self.git_config_parameters {
423            Some(existing) if !existing.trim().is_empty() => {
424                existing.push(' ');
425                existing.push_str(&entry);
426            }
427            slot => *slot = Some(entry),
428        }
429    }
430
431    fn absolute_from_cwd(&self, path: &Path) -> String {
432        if path.is_absolute() {
433            path.to_string_lossy().into_owned()
434        } else {
435            self.cwd.join(path).to_string_lossy().into_owned()
436        }
437    }
438
439    /// Snapshot the calling process's variables and working directory.
440    ///
441    /// This is the environment `git` and the `grit` CLI run with: `HOME` (global config,
442    /// `core.excludesFile`), `GIT_CONFIG_*`, Windows `ProgramFiles` (the Git for Windows system
443    /// gitconfig), identity variables and the rest. Embedders working on a user's repositories
444    /// call it once at their process boundary, usually through
445    /// [`RepositoryOptions::from_process`]. Library code never calls it; it takes an
446    /// [`Environment`] argument instead.
447    #[must_use]
448    pub fn capture_process() -> Self {
449        // hygiene: CLI boundary — snapshot process environment into [`Environment`].
450        Self::from_vars(std::env::vars_os(), process_cwd_fallback())
451    }
452
453    /// Fingerprint of config-related fields for cascade cache keys (mirrors prior env-var scan).
454    #[must_use]
455    pub fn config_fingerprint(&self) -> Option<Vec<(String, Option<String>)>> {
456        const VARS: [&str; 8] = [
457            "GIT_CONFIG_NOSYSTEM",
458            "GIT_CONFIG_SYSTEM",
459            "GIT_CONFIG_GLOBAL",
460            "XDG_CONFIG_HOME",
461            "HOME",
462            "GIT_CONFIG",
463            "GIT_CONFIG_PARAMETERS",
464            "GIT_CONFIG_COUNT",
465        ];
466        let mut fp: Vec<(String, Option<String>)> = VARS
467            .iter()
468            .map(|name| {
469                let val = match *name {
470                    "GIT_CONFIG_NOSYSTEM" => self.git_config_nosystem.clone(),
471                    "GIT_CONFIG_SYSTEM" => self.git_config_system.clone(),
472                    "GIT_CONFIG_GLOBAL" => self.git_config_global.clone(),
473                    "XDG_CONFIG_HOME" => self.xdg_config_home.clone(),
474                    "HOME" => self
475                        .home
476                        .as_ref()
477                        .and_then(|h| h.to_str().map(str::to_owned)),
478                    "GIT_CONFIG" => self.git_config.clone(),
479                    "GIT_CONFIG_PARAMETERS" => self.git_config_parameters.clone(),
480                    "GIT_CONFIG_COUNT" => self.git_config_count.clone(),
481                    _ => None,
482                };
483                ((*name).to_owned(), val)
484            })
485            .collect();
486        if let Some(count_str) = &self.git_config_count {
487            const MAX_TRACKED: usize = 256;
488            match count_str.parse::<usize>() {
489                Ok(n) if n <= MAX_TRACKED => {
490                    for i in 0..n {
491                        fp.push((
492                            format!("GIT_CONFIG_KEY_{i}"),
493                            self.git_config_pairs.get(i).map(|p| p.0.clone()),
494                        ));
495                        fp.push((
496                            format!("GIT_CONFIG_VALUE_{i}"),
497                            self.git_config_pairs.get(i).map(|p| p.1.clone()),
498                        ));
499                    }
500                }
501                Ok(_) => return None,
502                Err(_) => {}
503            }
504        }
505        fp.push((
506            "GRIT_ENV_CWD".to_owned(),
507            self.cwd.to_str().map(str::to_owned),
508        ));
509        fp.push(("GRIT_ENV_PWD".to_owned(), self.pwd.clone()));
510        Some(fp)
511    }
512
513    /// Return a string env var from this environment, if present and UTF-8.
514    #[must_use]
515    pub fn var(&self, key: &str) -> Option<String> {
516        match key {
517            "GIT_DIR" => self.git_dir.clone(),
518            "GIT_WORK_TREE" => self.git_work_tree.clone(),
519            "GIT_CEILING_DIRECTORIES" => self.git_ceiling_directories.clone(),
520            "GIT_INDEX_FILE" => self.git_index_file.clone(),
521            "GIT_NAMESPACE" => self.git_namespace.clone(),
522            "GIT_REPLACE_REF_BASE" => self.git_replace_ref_base.clone(),
523            "GIT_OPTIONAL_LOCKS" => Some(if self.git_optional_locks {
524                "1".to_owned()
525            } else {
526                "0".to_owned()
527            }),
528            "GIT_ALTERNATE_OBJECT_DIRECTORIES" => self.git_alternate_object_directories.clone(),
529            "GIT_OBJECT_DIRECTORY" => self.git_object_directory.clone(),
530            "GIT_CONFIG_NOSYSTEM" => self.git_config_nosystem.clone(),
531            "GIT_CONFIG_SYSTEM" => self.git_config_system.clone(),
532            "GIT_CONFIG_GLOBAL" => self.git_config_global.clone(),
533            "GIT_CONFIG" => self.git_config.clone(),
534            "GIT_CONFIG_PARAMETERS" => self.git_config_parameters.clone(),
535            "GIT_CONFIG_COUNT" => self.git_config_count.clone(),
536            "GIT_PREFIX" => self.git_prefix.clone(),
537            "GIT_AUTHOR_NAME" => self.git_author_name.clone(),
538            "GIT_AUTHOR_EMAIL" => self.git_author_email.clone(),
539            "GIT_AUTHOR_DATE" => self.git_author_date.clone(),
540            "GIT_COMMITTER_NAME" => self.git_committer_name.clone(),
541            "GIT_COMMITTER_EMAIL" => self.git_committer_email.clone(),
542            "GIT_COMMITTER_DATE" => self.git_committer_date.clone(),
543            "TZ" => self.tz.clone(),
544            "USER" => self.user.clone(),
545            "USERNAME" => self.username.clone(),
546            "XDG_CONFIG_HOME" => self.xdg_config_home.clone(),
547            "HOME" => self
548                .home
549                .as_ref()
550                .and_then(|h| h.to_str().map(str::to_owned)),
551            "USERPROFILE" => self
552                .userprofile
553                .as_ref()
554                .and_then(|h| h.to_str().map(str::to_owned)),
555            "HOMEDRIVE" => self
556                .homedrive
557                .as_ref()
558                .and_then(|h| h.to_str().map(str::to_owned)),
559            "HOMEPATH" => self
560                .homepath
561                .as_ref()
562                .and_then(|h| h.to_str().map(str::to_owned)),
563            key if key.starts_with("GIT_CONFIG_KEY_") => {
564                let idx: usize = key["GIT_CONFIG_KEY_".len()..].parse().ok()?;
565                self.git_config_pairs.get(idx).map(|p| p.0.clone())
566            }
567            key if key.starts_with("GIT_CONFIG_VALUE_") => {
568                let idx: usize = key["GIT_CONFIG_VALUE_".len()..].parse().ok()?;
569                self.git_config_pairs.get(idx).map(|p| p.1.clone())
570            }
571            _ => self
572                .captured_vars
573                .as_ref()
574                .and_then(|vars| vars.get(key))
575                .and_then(|v| v.to_str().map(str::to_owned)),
576        }
577    }
578
579    #[must_use]
580    /// Var os.
581    pub fn var_os(&self, key: &str) -> Option<OsString> {
582        if key == "HOME" {
583            return self.home.clone();
584        }
585        if key == "GIT_NO_REPLACE_OBJECTS" && self.git_no_replace_objects {
586            return Some(OsString::new());
587        }
588        if key == "GIT_OPTIONAL_LOCKS" {
589            return Some(OsString::from(if self.git_optional_locks {
590                "1"
591            } else {
592                "0"
593            }));
594        }
595        if key == "GIT_INSTALL_ROOT" {
596            return self.git_install_root.clone();
597        }
598        if key == "GIT_EXEC_PATH" {
599            return self.git_exec_path.clone();
600        }
601        if let Some(v) = self.var(key) {
602            return Some(OsString::from(v));
603        }
604        self.captured_vars.as_ref()?.get(key).cloned()
605    }
606
607    /// This environment as seen by a repository served over a local transport (a
608    /// `file://` URL or a path), the way Git's local transport passes the client's
609    /// environment to the `upload-pack` it runs.
610    ///
611    /// Global and system config discovery (`HOME`, `XDG_CONFIG_HOME`,
612    /// `GIT_CONFIG_GLOBAL`, `GIT_CONFIG_SYSTEM`, `GIT_CONFIG_NOSYSTEM`, …) is kept, so the
613    /// served repository sees settings such as `uploadpack.allowFilter` from
614    /// `~/.gitconfig`. Variables that describe the client's own repository are dropped:
615    /// `GIT_DIR`, `GIT_WORK_TREE`, `GIT_COMMON_DIR`, `GIT_INDEX_FILE`,
616    /// `GIT_OBJECT_DIRECTORY`, `GIT_ALTERNATE_OBJECT_DIRECTORIES`, `GIT_PREFIX`,
617    /// replace-object and graft/shallow overrides, and the `-c` / `GIT_CONFIG_*`
618    /// command-line config (`GIT_CONFIG`, `GIT_CONFIG_PARAMETERS`, `GIT_CONFIG_COUNT`).
619    #[must_use]
620    pub(crate) fn for_local_transport(&self) -> Self {
621        const CLIENT_REPO_VARS: &[&str] = &[
622            "GIT_DIR",
623            "GIT_WORK_TREE",
624            "GIT_IMPLICIT_WORK_TREE",
625            "GIT_COMMON_DIR",
626            "GIT_INDEX_FILE",
627            "GIT_OBJECT_DIRECTORY",
628            "GIT_ALTERNATE_OBJECT_DIRECTORIES",
629            "GIT_GRAFT_FILE",
630            "GIT_SHALLOW_FILE",
631            "GIT_NO_REPLACE_OBJECTS",
632            "GIT_REPLACE_REF_BASE",
633            "GIT_PREFIX",
634            "GIT_CONFIG",
635            "GIT_CONFIG_PARAMETERS",
636            "GIT_CONFIG_COUNT",
637        ];
638        let is_client_repo_var = |key: &str| {
639            CLIENT_REPO_VARS.contains(&key)
640                || key.starts_with("GIT_CONFIG_KEY_")
641                || key.starts_with("GIT_CONFIG_VALUE_")
642        };
643        let mut env = self.clone();
644        env.git_dir = None;
645        env.git_work_tree = None;
646        env.git_index_file = None;
647        env.git_object_directory = None;
648        env.git_alternate_object_directories = None;
649        env.git_prefix = None;
650        env.git_no_replace_objects = false;
651        env.git_replace_ref_base = None;
652        env.git_config = None;
653        env.git_config_parameters = None;
654        env.git_config_count = None;
655        env.git_config_pairs = Vec::new();
656        env.captured_vars = self.captured_vars.as_ref().and_then(|vars| {
657            let kept: HashMap<String, OsString> = vars
658                .iter()
659                .filter(|(k, _)| !is_client_repo_var(k))
660                .map(|(k, v)| (k.clone(), v.clone()))
661                .collect();
662            (!kept.is_empty()).then(|| Arc::new(kept))
663        });
664        env
665    }
666
667    /// Resolve `cwd` for discovery: canonicalize when possible without `env::current_dir`.
668    #[must_use]
669    pub fn discovery_cwd(&self) -> PathBuf {
670        self.cwd
671            .canonicalize_simplified()
672            .unwrap_or_else(|_| self.cwd.clone())
673    }
674
675    /// Variables exported to hook/filter subprocesses (no process inheritance).
676    ///
677    /// Typed fields are authoritative for the variables they model (clearing
678    /// [`Self::git_dir`] removes `GIT_DIR` even when the original snapshot had it). Every other
679    /// variable captured by [`Self::from_vars`] (`PATH`, `SystemRoot`, `LANG`, …) is passed
680    /// through unchanged, as Git does for hooks, so child processes can find their tools.
681    #[must_use]
682    pub fn subprocess_environment(&self) -> Vec<(OsString, OsString)> {
683        let mut passthrough: Vec<(&String, &OsString)> = self
684            .captured_vars
685            .iter()
686            .flat_map(|vars| vars.iter())
687            .filter(|(k, _)| !is_typed_environment_var(k))
688            .collect();
689        passthrough.sort_unstable_by(|a, b| a.0.cmp(b.0));
690        let mut set: Vec<(OsString, OsString)> = passthrough
691            .into_iter()
692            .map(|(k, v)| (OsString::from(k), v.clone()))
693            .collect();
694        subprocess_push_str(&mut set, "GIT_DIR", self.git_dir.as_deref());
695        subprocess_push_str(&mut set, "GIT_WORK_TREE", self.git_work_tree.as_deref());
696        subprocess_push_str(
697            &mut set,
698            "GIT_CEILING_DIRECTORIES",
699            self.git_ceiling_directories.as_deref(),
700        );
701        subprocess_push_str(&mut set, "GIT_INDEX_FILE", self.git_index_file.as_deref());
702        subprocess_push_str(&mut set, "GIT_NAMESPACE", self.git_namespace.as_deref());
703        subprocess_push_str(
704            &mut set,
705            "GIT_REPLACE_REF_BASE",
706            self.git_replace_ref_base.as_deref(),
707        );
708        subprocess_push_str(
709            &mut set,
710            "GIT_ALTERNATE_OBJECT_DIRECTORIES",
711            self.git_alternate_object_directories.as_deref(),
712        );
713        subprocess_push_str(
714            &mut set,
715            "GIT_OBJECT_DIRECTORY",
716            self.git_object_directory.as_deref(),
717        );
718        subprocess_push_str(&mut set, "GIT_PREFIX", self.git_prefix.as_deref());
719        subprocess_push_str(
720            &mut set,
721            "GIT_CONFIG_NOSYSTEM",
722            self.git_config_nosystem.as_deref(),
723        );
724        subprocess_push_str(
725            &mut set,
726            "GIT_CONFIG_SYSTEM",
727            self.git_config_system.as_deref(),
728        );
729        subprocess_push_str(
730            &mut set,
731            "GIT_CONFIG_GLOBAL",
732            self.git_config_global.as_deref(),
733        );
734        subprocess_push_str(&mut set, "GIT_CONFIG", self.git_config.as_deref());
735        subprocess_push_str(
736            &mut set,
737            "GIT_CONFIG_PARAMETERS",
738            self.git_config_parameters.as_deref(),
739        );
740        subprocess_push_str(
741            &mut set,
742            "GIT_CONFIG_COUNT",
743            self.git_config_count.as_deref(),
744        );
745        for (i, (k, v)) in self.git_config_pairs.iter().enumerate() {
746            set.push((
747                OsString::from(format!("GIT_CONFIG_KEY_{i}")),
748                OsString::from(k),
749            ));
750            set.push((
751                OsString::from(format!("GIT_CONFIG_VALUE_{i}")),
752                OsString::from(v),
753            ));
754        }
755        subprocess_push_os(&mut set, "HOME", self.home.as_ref());
756        subprocess_push_str(&mut set, "XDG_CONFIG_HOME", self.xdg_config_home.as_deref());
757        subprocess_push_os(&mut set, "USERPROFILE", self.userprofile.as_ref());
758        subprocess_push_os(&mut set, "HOMEDRIVE", self.homedrive.as_ref());
759        subprocess_push_os(&mut set, "HOMEPATH", self.homepath.as_ref());
760        subprocess_push_os(&mut set, "GIT_INSTALL_ROOT", self.git_install_root.as_ref());
761        subprocess_push_os(&mut set, "GIT_EXEC_PATH", self.git_exec_path.as_ref());
762        subprocess_push_str(&mut set, "PWD", self.pwd.as_deref());
763        subprocess_push_str(
764            &mut set,
765            "GRIT_INVOCATION_CWD",
766            self.grit_invocation_cwd.as_deref(),
767        );
768        subprocess_push_str(&mut set, "SUDO_UID", self.sudo_uid.as_deref());
769        subprocess_push_str(&mut set, "GIT_AUTHOR_NAME", self.git_author_name.as_deref());
770        subprocess_push_str(
771            &mut set,
772            "GIT_AUTHOR_EMAIL",
773            self.git_author_email.as_deref(),
774        );
775        subprocess_push_str(&mut set, "GIT_AUTHOR_DATE", self.git_author_date.as_deref());
776        subprocess_push_str(
777            &mut set,
778            "GIT_COMMITTER_NAME",
779            self.git_committer_name.as_deref(),
780        );
781        subprocess_push_str(
782            &mut set,
783            "GIT_COMMITTER_EMAIL",
784            self.git_committer_email.as_deref(),
785        );
786        subprocess_push_str(
787            &mut set,
788            "GIT_COMMITTER_DATE",
789            self.git_committer_date.as_deref(),
790        );
791        subprocess_push_str(&mut set, "TZ", self.tz.as_deref());
792        subprocess_push_str(&mut set, "USER", self.user.as_deref());
793        subprocess_push_str(&mut set, "USERNAME", self.username.as_deref());
794        subprocess_push_str(&mut set, "ProgramFiles", self.program_files.as_deref());
795        subprocess_push_str(
796            &mut set,
797            "ProgramFiles(x86)",
798            self.program_files_x86.as_deref(),
799        );
800        if self.git_no_replace_objects {
801            set.push((OsString::from("GIT_NO_REPLACE_OBJECTS"), OsString::new()));
802        }
803        if !self.git_optional_locks {
804            set.push((OsString::from("GIT_OPTIONAL_LOCKS"), OsString::from("0")));
805        }
806        set
807    }
808
809    /// User home directory using the same resolution as Git config loading.
810    #[must_use]
811    pub fn home_dir(&self) -> Option<PathBuf> {
812        if let Some(home) = self.home.as_ref().filter(|h| !h.is_empty()) {
813            return Some(PathBuf::from(home));
814        }
815        #[cfg(windows)]
816        {
817            if let (Some(drive), Some(path)) = (
818                self.homedrive.as_ref().filter(|d| !d.is_empty()),
819                self.homepath.as_ref().filter(|p| !p.is_empty()),
820            ) {
821                let mut combined = drive.clone();
822                combined.push(path);
823                return Some(PathBuf::from(combined));
824            }
825            if let Some(profile) = self.userprofile.as_ref().filter(|p| !p.is_empty()) {
826                return Some(PathBuf::from(profile));
827            }
828        }
829        None
830    }
831
832    /// Default path for `$XDG_CONFIG_HOME/git/{name}` or `$HOME/.config/git/{name}`.
833    ///
834    /// Used for Git's implicit global excludes (`ignore`) and attributes (`attributes`) files
835    /// when `core.excludesfile` / `core.attributesfile` are unset.
836    #[must_use]
837    pub fn default_xdg_config_git_file(&self, name: &str) -> Option<PathBuf> {
838        if let Some(xdg) = self.xdg_config_home.as_deref().filter(|s| !s.is_empty()) {
839            return Some(PathBuf::from(xdg).join("git").join(name));
840        }
841        self.home_dir()
842            .map(|home| home.join(".config").join("git").join(name))
843    }
844}
845
846/// One command-line configuration override, the `key[=value]` argument of `git -c`.
847///
848/// Parse one with [`str::parse`] (or [`ConfigOverride::new`]) and apply it with
849/// [`Environment::push_config_override`]. The key is validated like any config key
850/// (`section[.subsection].name`); a bare `key` with no `=` sets the boolean value `true`,
851/// and `key=` sets the empty string.
852#[derive(Debug, Clone, PartialEq, Eq)]
853pub struct ConfigOverride {
854    key: String,
855    value: Option<String>,
856}
857
858impl ConfigOverride {
859    /// Build an override from a key and optional value.
860    ///
861    /// # Parameters
862    ///
863    /// - `key`: config key such as `user.name` or `remote.origin.url`.
864    /// - `value`: the value to set, or `None` for a boolean `true` (bare key).
865    ///
866    /// # Errors
867    ///
868    /// Returns [`crate::error::Error::Config`] when `key` is not a valid config key.
869    pub fn new(key: impl Into<String>, value: Option<String>) -> crate::error::Result<Self> {
870        let key = key.into();
871        crate::config::canonical_key(&key)?;
872        Ok(Self { key, value })
873    }
874
875    /// The config key, as given.
876    #[must_use]
877    pub fn key(&self) -> &str {
878        &self.key
879    }
880
881    /// The value, or `None` when the key was given without `=` (boolean `true`).
882    #[must_use]
883    pub fn value(&self) -> Option<&str> {
884        self.value.as_deref()
885    }
886}
887
888impl FromStr for ConfigOverride {
889    type Err = crate::error::Error;
890
891    /// Parse `key=value` (value may be empty or contain `=`) or a bare `key`.
892    fn from_str(spec: &str) -> Result<Self, Self::Err> {
893        match spec.split_once('=') {
894            Some((key, value)) => Self::new(key, Some(value.to_owned())),
895            None => Self::new(spec, None),
896        }
897    }
898}
899
900impl IdentityEnv for Environment {
901    fn var(&self, key: &str) -> Option<String> {
902        Environment::var(self, key)
903    }
904
905    fn var_os(&self, key: &str) -> Option<OsString> {
906        Environment::var_os(self, key)
907    }
908}
909
910/// Nanoseconds since the Unix epoch from the process wall clock.
911///
912/// Callers pass this into [`crate::fsmonitor::FsmonitorRefreshOptions`] so fsmonitor hook
913/// protocol v1 tokens are sampled before the hook subprocess runs.
914#[must_use]
915pub(crate) fn wall_clock_unix_timestamp_nanos() -> u64 {
916    u64::try_from(OffsetDateTime::now_utc().unix_timestamp_nanos()).unwrap_or(u64::MAX)
917}
918
919/// Whole seconds since the Unix epoch from the process wall clock.
920#[must_use]
921pub(crate) fn wall_clock_unix_timestamp_seconds() -> i64 {
922    OffsetDateTime::now_utc().unix_timestamp()
923}
924
925/// Map a Unix timestamp through an optional `TZ`-style string (or the process default offset).
926#[must_use]
927pub fn offset_from_epoch_and_tz(epoch: i64, tz: Option<&str>) -> OffsetDateTime {
928    let tz_hhmm = local_tzoffset_with_tz(epoch as u64, tz);
929    let offset = utc_offset_from_tz_hhmm(tz_hhmm).unwrap_or(UtcOffset::UTC);
930    OffsetDateTime::from_unix_timestamp(epoch)
931        .unwrap_or(OffsetDateTime::UNIX_EPOCH)
932        .to_offset(offset)
933}
934
935fn utc_offset_from_tz_hhmm(tz: TzHhmm) -> Option<UtcOffset> {
936    let sign: i32 = if tz < 0 { -1 } else { 1 };
937    let abs = tz.unsigned_abs();
938    let hours = (abs / 100) as i32;
939    let minutes = (abs % 100) as i32;
940    let seconds = sign * (hours * 3600 + minutes * 60);
941    UtcOffset::from_whole_seconds(seconds).ok()
942}
943
944/// Variables [`Environment::from_vars`] parses into typed fields; keep in sync with it.
945const TYPED_ENVIRONMENT_VARS: &[&str] = &[
946    "GIT_DIR",
947    "GIT_WORK_TREE",
948    "GIT_CEILING_DIRECTORIES",
949    "GIT_INDEX_FILE",
950    "GIT_NAMESPACE",
951    "GIT_REPLACE_REF_BASE",
952    "GIT_NO_REPLACE_OBJECTS",
953    "GIT_OPTIONAL_LOCKS",
954    "GIT_ALTERNATE_OBJECT_DIRECTORIES",
955    "GIT_OBJECT_DIRECTORY",
956    "GIT_PREFIX",
957    "GIT_CONFIG_NOSYSTEM",
958    "GIT_CONFIG_SYSTEM",
959    "GIT_CONFIG_GLOBAL",
960    "GIT_CONFIG",
961    "GIT_CONFIG_PARAMETERS",
962    "GIT_CONFIG_COUNT",
963    "HOME",
964    "XDG_CONFIG_HOME",
965    "USERPROFILE",
966    "HOMEDRIVE",
967    "HOMEPATH",
968    "GIT_INSTALL_ROOT",
969    "GIT_EXEC_PATH",
970    "PWD",
971    "GRIT_INVOCATION_CWD",
972    "SUDO_UID",
973    "GIT_AUTHOR_NAME",
974    "GIT_AUTHOR_EMAIL",
975    "GIT_AUTHOR_DATE",
976    "GIT_COMMITTER_NAME",
977    "GIT_COMMITTER_EMAIL",
978    "GIT_COMMITTER_DATE",
979    "TZ",
980    "USER",
981    "USERNAME",
982    "ProgramFiles",
983    "ProgramFiles(x86)",
984];
985
986fn is_typed_environment_var(key: &str) -> bool {
987    TYPED_ENVIRONMENT_VARS.contains(&key)
988        || key.starts_with("GIT_CONFIG_KEY_")
989        || key.starts_with("GIT_CONFIG_VALUE_")
990}
991
992fn git_optional_locks_from_env(raw: Option<&str>) -> bool {
993    match raw {
994        None => true,
995        Some(value) => parse_git_config_maybe_bool(value).unwrap_or(true),
996    }
997}
998
999fn subprocess_push_str(out: &mut Vec<(OsString, OsString)>, key: &str, val: Option<&str>) {
1000    if let Some(v) = val {
1001        out.push((OsString::from(key), OsString::from(v)));
1002    }
1003}
1004
1005fn subprocess_push_os(out: &mut Vec<(OsString, OsString)>, key: &str, val: Option<&OsString>) {
1006    if let Some(v) = val {
1007        out.push((OsString::from(key), v.clone()));
1008    }
1009}
1010
1011/// Options passed to [`crate::repo::Repository::open`], [`crate::repo::Repository::discover`],
1012/// and related entry points.
1013///
1014/// # Opening a normal repository
1015///
1016/// ```
1017/// use grit_lib::config::environment::RepositoryOptions;
1018/// use grit_lib::repo::{InitOptions, Repository};
1019///
1020/// # fn main() -> grit_lib::error::Result<()> {
1021/// let dir = tempfile::tempdir()?;
1022/// let (repo, _) = Repository::init(dir.path(), &InitOptions::default())?;
1023/// let again = Repository::open(
1024///     repo.git_dir(),
1025///     &RepositoryOptions::empty().with_work_tree(dir.path()),
1026/// )?;
1027/// assert_eq!(again.git_dir(), repo.git_dir());
1028/// # Ok(())
1029/// # }
1030/// ```
1031///
1032/// # Discovering from a working directory
1033///
1034/// ```
1035/// use grit_lib::config::environment::RepositoryOptions;
1036/// use grit_lib::repo::{InitOptions, Repository};
1037///
1038/// # fn main() -> grit_lib::error::Result<()> {
1039/// let dir = tempfile::tempdir()?;
1040/// Repository::init(dir.path(), &InitOptions::default())?;
1041/// let repo = Repository::discover(Some(dir.path()), &RepositoryOptions::empty())?;
1042/// assert!(repo.work_tree().is_some());
1043/// # Ok(())
1044/// # }
1045/// ```
1046///
1047/// # Bare repository
1048///
1049/// Open the bare git directory; leave [`Self::work_tree`] unset.
1050///
1051/// # Linked worktree
1052///
1053/// Open the worktree's admin directory (under `worktrees/`) and set [`Self::work_tree`] to the
1054/// linked checkout path, or call [`Repository::discover`](crate::repo::Repository::discover) from
1055/// the linked checkout with environment overrides cleared (no `GIT_DIR` / `GIT_WORK_TREE`).
1056///
1057/// # Injected ref store and custom object store
1058///
1059/// With both stores injected the git directory may be missing: nothing is read from its
1060/// layout, though config and the index are still looked up there.
1061///
1062/// ```
1063/// use std::sync::Arc;
1064///
1065/// use grit_lib::config::environment::RepositoryOptions;
1066/// use grit_lib::objects::odb::store::MemoryStore;
1067/// use grit_lib::objects::{HashAlgo, ObjectKind};
1068/// use grit_lib::refs::store::MemoryRefStore;
1069/// use grit_lib::repo::Repository;
1070///
1071/// # fn main() -> grit_lib::error::Result<()> {
1072/// let dir = tempfile::tempdir()?;
1073/// let git_dir = dir.path().join("in-memory.git");
1074/// let store = Arc::new(MemoryStore::new(HashAlgo::Sha1));
1075/// let repo = Repository::open(
1076///     &git_dir,
1077///     &RepositoryOptions::empty()
1078///         .with_object_store(store.clone())
1079///         .with_ref_store(Arc::new(MemoryRefStore::new()))
1080///         .with_initial_branch("main"),
1081/// )?;
1082/// let oid = repo.odb().write(ObjectKind::Blob, b"hello")?;
1083/// assert!(grit_lib::objects::odb::store::ObjectStore::contains(store.as_ref(), &oid)?);
1084/// assert!(!git_dir.exists());
1085/// # Ok(())
1086/// # }
1087/// ```
1088#[derive(Clone)]
1089#[non_exhaustive]
1090pub struct RepositoryOptions {
1091    /// Discovery and configuration environment.
1092    pub environment: Environment,
1093    /// Subprocess runner for hooks, filters, and helpers.
1094    pub command_runner: Arc<dyn CommandRunner>,
1095    /// Random bytes for new change ids (`grit.changeIds`).
1096    pub change_id_generator: Arc<dyn ChangeIdGenerator>,
1097    /// Where non-fatal warnings and trace events are delivered.
1098    pub diagnostics: DiagnosticsHandle,
1099    /// When true, network operations may emit [`crate::diagnostics::Trace::Network`] events.
1100    pub network_trace: bool,
1101    /// Injectable ownership checks for discovery (`safe.directory`).
1102    pub(crate) ownership_check: Arc<dyn OwnershipCheck>,
1103    /// Wall-clock reference for rev-parse date selectors; embedders set explicitly.
1104    pub reference_unix_time: Option<i64>,
1105    /// Parallel worker overrides (`--threads` in the CLI).
1106    pub thread_policy: crate::parallel::ThreadPolicy,
1107    /// Work tree path for [`crate::repo::Repository::open`] (non-bare repos).
1108    pub work_tree: Option<std::path::PathBuf>,
1109    /// Primary object store to use instead of the files layout under `objects/`
1110    /// (see [`Self::with_object_store`]).
1111    pub object_store: Option<Arc<dyn crate::odb::store::WritableObjectStore>>,
1112    /// Read layers, attached commit-graph and alternates policy (see [`crate::odb::OdbBuilder`]).
1113    pub odb_builder: Option<crate::odb::OdbBuilder>,
1114    /// Ref backend to use instead of opening one from the git directory.
1115    pub ref_store: Option<std::sync::Arc<dyn crate::refs::store::RefStore>>,
1116    /// When the ref store has no `HEAD` after open, seed an unborn branch at `refs/heads/<name>`.
1117    pub initial_branch: Option<String>,
1118    /// When false, skip [`crate::repo::validate_repo_format`] during open.
1119    pub validate_repository_format: bool,
1120    /// When true, [`crate::repo::Repository::open`] resolves `path` like wire-protocol serving.
1121    pub open_for_serving: bool,
1122    /// Optional on-demand fetcher for partial-clone promisor objects.
1123    pub promisor_fetcher: Option<std::sync::Arc<dyn crate::promisor_fetch::PromisorFetcher>>,
1124    /// Where hook subprocesses write their output (captured by default).
1125    pub hook_stdio: crate::hooks::HookStdio,
1126    /// Overrides for reftable stack writes on repositories opened with these options.
1127    pub reftable_write: ReftableWriteOptions,
1128}
1129
1130impl std::fmt::Debug for RepositoryOptions {
1131    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1132        f.debug_struct("RepositoryOptions")
1133            .field("environment", &self.environment)
1134            .field("command_runner", &"<CommandRunner>")
1135            .field("network_trace", &self.network_trace)
1136            .finish_non_exhaustive()
1137    }
1138}
1139
1140impl Default for RepositoryOptions {
1141    fn default() -> Self {
1142        Self {
1143            environment: Environment::empty(),
1144            command_runner: system_command_runner(),
1145            change_id_generator: Arc::new(OsChangeIdGenerator),
1146            diagnostics: Arc::new(NullDiagnostics),
1147            network_trace: false,
1148            ownership_check: default_ownership_check(),
1149            reference_unix_time: None,
1150            thread_policy: crate::parallel::ThreadPolicy::default(),
1151            work_tree: None,
1152            object_store: None,
1153            odb_builder: None,
1154            ref_store: None,
1155            initial_branch: None,
1156            validate_repository_format: true,
1157            open_for_serving: false,
1158            promisor_fetcher: None,
1159            hook_stdio: crate::hooks::HookStdio::default(),
1160            reftable_write: ReftableWriteOptions::default(),
1161        }
1162    }
1163}
1164
1165impl RepositoryOptions {
1166    /// Options with [`Environment::empty`]: no home directory, no global config and, on
1167    /// Windows, no system config.
1168    ///
1169    /// Operations then ignore settings such as `core.autocrlf`, `user.name`, `safe.directory`
1170    /// and `core.excludesFile` from the user's system and global config, so results can differ
1171    /// from `git` on the same repository. Meant for tests and repositories the caller created;
1172    /// use [`Self::from_process`] for a user's repositories.
1173    #[must_use]
1174    pub fn empty() -> Self {
1175        Self::default()
1176    }
1177
1178    /// Options with [`Environment::capture_process`]: the embedder equivalent of running `git`
1179    /// or `grit` in this process.
1180    ///
1181    /// System and global config apply (`core.autocrlf`, identity, `safe.directory`,
1182    /// `core.excludesFile`, credential helpers), found through `HOME`, `GIT_CONFIG_*` and, on
1183    /// Windows, `ProgramFiles`. Call it at the program boundary, not from library code.
1184    #[must_use]
1185    pub fn from_process() -> Self {
1186        // hygiene: embedder boundary — the documented way to snapshot the process environment.
1187        Self::with_environment(Environment::capture_process())
1188    }
1189
1190    /// Options around an explicit [`Environment`] snapshot.
1191    ///
1192    /// This is an associated constructor, not a builder method: write
1193    /// `RepositoryOptions::with_environment(env).with_command_runner(runner)`.
1194    #[must_use]
1195    pub fn with_environment(environment: Environment) -> Self {
1196        Self {
1197            environment,
1198            ..Self::default()
1199        }
1200    }
1201
1202    /// Override the injectable subprocess runner used for hooks and filters.
1203    #[must_use]
1204    pub fn with_command_runner(mut self, runner: Arc<dyn CommandRunner>) -> Self {
1205        self.command_runner = runner;
1206        self
1207    }
1208
1209    /// Override the generator used for random change ids on new commits.
1210    #[must_use]
1211    pub fn with_change_id_generator(mut self, generator: Arc<dyn ChangeIdGenerator>) -> Self {
1212        self.change_id_generator = generator;
1213        self
1214    }
1215
1216    /// Attach an explicit work tree for [`crate::repo::Repository::open`].
1217    #[must_use]
1218    pub fn with_work_tree(mut self, work_tree: impl Into<std::path::PathBuf>) -> Self {
1219        self.work_tree = Some(work_tree.into());
1220        self
1221    }
1222
1223    /// Use `store` as the repository's primary object store instead of the files layout
1224    /// under `objects/`.
1225    ///
1226    /// Writes and primary reads go through this backend, including commits, staging
1227    /// ([`crate::porcelain::add::stage`]), merges, stash, notes, and bundle creation.
1228    /// [`Maintenance::fsck`](crate::maintenance::Maintenance::fsck) validates the objects this store
1229    /// lists. Received packs are written into it object by object:
1230    /// [`ingest_received_pack`](crate::index_pack::ingest_received_pack) and
1231    /// [`Bundle::unbundle`](crate::bundle::Bundle::unbundle) resolve every delta and call
1232    /// [`WritableObjectStore::write`](crate::odb::store::WritableObjectStore::write) instead
1233    /// of installing a pack under `objects/pack/`. Fetch, push, pull, bundles and
1234    /// [`clone_into`](crate::clone::clone_into) read and write objects through it.
1235    ///
1236    /// [`Repository::open`](crate::repo::Repository::open) still resolves the `objects/`
1237    /// directory (honoring `GIT_OBJECT_DIRECTORY`), but never reads or writes objects there,
1238    /// and the directory need not exist. Alternates are off unless
1239    /// [`OdbBuilder::alternates`](crate::odb::OdbBuilder::alternates) turns them on. Partial
1240    /// clone filters and filesystem maintenance ([`crate::odb::Odb::write_commit_graph`],
1241    /// repack, multi-pack-index) refuse with
1242    /// [`RepositoryError::UnsupportedObjectStore`](crate::repo::RepositoryError::UnsupportedObjectStore).
1243    /// Garbage collection and pruning ([`crate::odb::Odb::gc`], [`crate::maintenance::gc`],
1244    /// [`crate::maintenance::prune_loose_objects`]) work when the store can delete objects
1245    /// ([`WritableObjectStore::as_prunable`](crate::odb::store::WritableObjectStore::as_prunable))
1246    /// and refuse with [`FilesOnlyOperation::Prune`](crate::repo::error::FilesOnlyOperation::Prune)
1247    /// otherwise.
1248    ///
1249    /// The store's [`ObjectStore::hash_algo`](crate::odb::store::ObjectStore::hash_algo) must
1250    /// match the repository's object format, or [`Repository::open`](crate::repo::Repository::open)
1251    /// fails with [`RepositoryError::ObjectFormatMismatch`](crate::repo::RepositoryError::ObjectFormatMismatch).
1252    ///
1253    /// # Without a git directory
1254    ///
1255    /// A bare repository opened with this store, a [`Self::with_ref_store`] backend and its
1256    /// config in the [`Environment`] (through [`Environment::push_config_override`], with
1257    /// [`Environment::git_config_nosystem`] set to keep `/etc/gitconfig` out) needs nothing on
1258    /// disk. The git directory may be a path that does not exist, and grit-lib does not create
1259    /// it. `<git_dir>/config` is still read when it exists.
1260    ///
1261    /// | Area | Without a git directory |
1262    /// | ---- | ----------------------- |
1263    /// | Objects, trees and commits ([`Repository::objects`](crate::repo::Repository::objects)) | Work through the store. |
1264    /// | Refs, reflogs, `HEAD` and ref transactions ([`Repository::references`](crate::repo::Repository::references)) | Work through the ref store. |
1265    /// | Config ([`Repository::config`](crate::repo::Repository::config)) | Comes from the [`Environment`]. |
1266    /// | Rev-parse, revwalk and log | Work. |
1267    /// | Tree diff, [`write_merge_tree`](crate::porcelain::merge::write_merge_tree) and blame at a commit | Work. |
1268    /// | Notes, and bundles written to any [`std::io::Write`] ([`RepositoryBundles::write_to`](crate::repo_handles::RepositoryBundles::write_to)) | Work. |
1269    /// | History edits ([`History::reword`](crate::revwalk::history::History::reword), [`History::apply`](crate::revwalk::history::History::apply)) | Work. |
1270    /// | Fetch from a path or URL | Works. The pack is spooled in the system temp directory and removed after ingest, and `FETCH_HEAD` is not written. |
1271    /// | Hooks | A missing hooks directory means no hooks. |
1272    /// | The index, staging and worktree commits | Out of scope: the index, `COMMIT_EDITMSG` and merge, revert and rebase state live in the git directory, which staging creates. |
1273    /// | Work-tree operations (checkout, switch, status, reset, stash) | Out of scope: they need a work tree and an index. |
1274    /// | Linked worktrees | Out of scope: their admin directories live under `worktrees/`. |
1275    /// | rerere and sparse-checkout | Out of scope: their state is kept in files in the git directory. |
1276    /// | Hooks that expect `GIT_DIR` on disk | Out of scope: objects and refs held by the stores are invisible to other programs, such as the system `git`. |
1277    /// | gc and prune | Work when the store can delete objects ([`WritableObjectStore::as_prunable`](crate::odb::store::WritableObjectStore::as_prunable)), as described above. |
1278    /// | Repack, commit-graph and multi-pack-index files | Refused with [`RepositoryError::UnsupportedObjectStore`](crate::repo::RepositoryError::UnsupportedObjectStore). |
1279    ///
1280    /// # Examples
1281    ///
1282    /// ```
1283    /// use std::sync::Arc;
1284    ///
1285    /// use grit_lib::config::environment::RepositoryOptions;
1286    /// use grit_lib::objects::odb::store::{MemoryStore, ObjectStore};
1287    /// use grit_lib::objects::{HashAlgo, ObjectKind};
1288    /// use grit_lib::repo::{InitOptions, Repository};
1289    ///
1290    /// # fn main() -> grit_lib::error::Result<()> {
1291    /// let dir = tempfile::tempdir()?;
1292    /// Repository::init(dir.path(), &InitOptions::default())?;
1293    /// let store = Arc::new(MemoryStore::new(HashAlgo::Sha1));
1294    /// let repo = Repository::open(
1295    ///     &dir.path().join(".git"),
1296    ///     &RepositoryOptions::empty()
1297    ///         .with_object_store(store.clone())
1298    ///         .with_work_tree(dir.path()),
1299    /// )?;
1300    /// let oid = repo.odb().write(ObjectKind::Blob, b"hello")?;
1301    /// assert!(store.contains(&oid)?);
1302    /// # Ok(())
1303    /// # }
1304    /// ```
1305    ///
1306    /// A bare repository with no git directory, its config held in the [`Environment`]:
1307    ///
1308    /// ```
1309    /// use std::sync::Arc;
1310    ///
1311    /// use grit_lib::config::environment::{ConfigOverride, Environment, RepositoryOptions};
1312    /// use grit_lib::objects::odb::store::MemoryStore;
1313    /// use grit_lib::objects::HashAlgo;
1314    /// use grit_lib::refs::store::MemoryRefStore;
1315    /// use grit_lib::repo::Repository;
1316    ///
1317    /// # fn main() -> grit_lib::error::Result<()> {
1318    /// let mut env = Environment::empty();
1319    /// env.git_config_nosystem = Some("1".to_owned());
1320    /// env.push_config_override(&ConfigOverride::new("user.name", Some("Ada".to_owned()))?);
1321    /// let dir = tempfile::tempdir()?;
1322    /// let git_dir = dir.path().join("never-created.git");
1323    /// let repo = Repository::open(
1324    ///     &git_dir,
1325    ///     &RepositoryOptions::with_environment(env)
1326    ///         .with_object_store(Arc::new(MemoryStore::new(HashAlgo::Sha1)))
1327    ///         .with_ref_store(Arc::new(MemoryRefStore::new()))
1328    ///         .with_initial_branch("main"),
1329    /// )?;
1330    /// assert!(repo.is_bare());
1331    /// assert_eq!(repo.config().snapshot()?.get("user.name")?.as_deref(), Some("Ada"));
1332    /// assert!(!git_dir.exists());
1333    /// # Ok(())
1334    /// # }
1335    /// ```
1336    #[must_use]
1337    pub fn with_object_store(
1338        mut self,
1339        store: Arc<dyn crate::odb::store::WritableObjectStore>,
1340    ) -> Self {
1341        self.object_store = Some(store);
1342        self
1343    }
1344
1345    /// Layer read-only stores, a commit-graph, or an alternates override over the primary
1346    /// object store (see [`crate::odb::OdbBuilder`]).
1347    #[must_use]
1348    pub fn with_odb_builder(mut self, builder: crate::odb::OdbBuilder) -> Self {
1349        self.odb_builder = Some(builder);
1350        self
1351    }
1352
1353    /// Use `store` as the ref backend instead of opening one from the git directory.
1354    #[must_use]
1355    pub fn with_ref_store(
1356        mut self,
1357        store: std::sync::Arc<dyn crate::refs::store::RefStore>,
1358    ) -> Self {
1359        self.ref_store = Some(store);
1360        self
1361    }
1362
1363    /// Seed `HEAD` at `refs/heads/<branch>` when the ref store has no `HEAD` after open.
1364    #[must_use]
1365    pub fn with_initial_branch(mut self, branch: impl Into<String>) -> Self {
1366        self.initial_branch = Some(branch.into());
1367        self
1368    }
1369
1370    /// Skip repository format validation when opening (discovery follow-up paths).
1371    #[must_use]
1372    pub fn without_format_validation(mut self) -> Self {
1373        self.validate_repository_format = false;
1374        self
1375    }
1376
1377    /// Resolve `path` for smart-HTTP / upload-pack serving instead of a bare git directory.
1378    #[must_use]
1379    pub fn for_serving(mut self) -> Self {
1380        self.open_for_serving = true;
1381        self
1382    }
1383
1384    /// Override the diagnostic sink for warnings and trace events.
1385    #[must_use]
1386    pub fn with_diagnostics(mut self, diagnostics: DiagnosticsHandle) -> Self {
1387        self.diagnostics = diagnostics;
1388        self
1389    }
1390
1391    /// Override reftable write behavior (for example disable auto-compaction in tests).
1392    #[must_use]
1393    pub fn with_reftable_write(mut self, reftable_write: ReftableWriteOptions) -> Self {
1394        self.reftable_write = reftable_write;
1395        self
1396    }
1397
1398    /// Reftable write overrides installed on these options.
1399    #[must_use]
1400    pub fn reftable_write(&self) -> ReftableWriteOptions {
1401        self.reftable_write
1402    }
1403
1404    /// Replace the ownership check used during discovery and clone safety checks.
1405    ///
1406    /// The default [`crate::ownership_check::SystemOwnershipCheck`] compares the effective Unix
1407    /// uid against repository paths. Custom implementations can treat repositories as always
1408    /// foreign so `safe.directory` always applies (sandboxes and tests).
1409    #[must_use]
1410    pub fn with_ownership_check(mut self, check: Arc<dyn OwnershipCheck>) -> Self {
1411        self.ownership_check = check;
1412        self
1413    }
1414
1415    /// Ownership check installed on these options.
1416    #[must_use]
1417    pub fn ownership_check(&self) -> Arc<dyn OwnershipCheck> {
1418        Arc::clone(&self.ownership_check)
1419    }
1420
1421    /// Whether these options still use the shared default [`SystemOwnershipCheck`](crate::ownership_check::SystemOwnershipCheck).
1422    #[must_use]
1423    pub fn uses_default_ownership_check(&self) -> bool {
1424        is_default_ownership_check(&self.ownership_check)
1425    }
1426
1427    /// Choose whether hooks run by repositories opened with these options have their output
1428    /// captured ([`HookStdio::Capture`](crate::command_runner::hooks::HookStdio::Capture), the default) or
1429    /// write straight to this process's stderr.
1430    #[must_use]
1431    pub fn with_hook_stdio(mut self, hook_stdio: crate::hooks::HookStdio) -> Self {
1432        self.hook_stdio = hook_stdio;
1433        self
1434    }
1435
1436    /// Enable or disable network trace events.
1437    #[must_use]
1438    pub fn with_network_trace(mut self, network_trace: bool) -> Self {
1439        self.network_trace = network_trace;
1440        self
1441    }
1442
1443    /// Install a promisor on-demand object fetcher for repositories opened with these options.
1444    #[must_use]
1445    pub fn with_promisor_fetcher(
1446        mut self,
1447        fetcher: Option<std::sync::Arc<dyn crate::promisor_fetch::PromisorFetcher>>,
1448    ) -> Self {
1449        self.promisor_fetcher = fetcher;
1450        self
1451    }
1452}
1453
1454fn process_cwd_fallback() -> PathBuf {
1455    // hygiene: used only from [`Environment::capture_process`].
1456    std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
1457}
1458
1459#[cfg(test)]
1460mod tests {
1461    use super::*;
1462
1463    #[test]
1464    fn cloned_environment_keeps_overrides_independent() {
1465        let original = Environment::from_vars(
1466            [
1467                (OsString::from("GIT_DIR"), OsString::from("original.git")),
1468                (OsString::from("HOME"), OsString::from("/original/home")),
1469                (OsString::from("BUILD_SETTING"), OsString::from("captured")),
1470            ],
1471            PathBuf::from("/workspace"),
1472        );
1473        let sibling = original.clone();
1474        let mut changed = original.clone();
1475        drop(original);
1476        changed.git_dir = None;
1477        changed.home = Some(OsString::from("/changed/home"));
1478        changed.push_config_override(&"user.name=Changed".parse().expect("override"));
1479
1480        assert_eq!(sibling.var("GIT_DIR").as_deref(), Some("original.git"));
1481        assert_eq!(
1482            sibling.home.as_deref(),
1483            Some(std::ffi::OsStr::new("/original/home"))
1484        );
1485        assert!(sibling.git_config_parameters.is_none());
1486        let exported = changed.subprocess_environment();
1487        assert!(!exported.iter().any(|(key, _)| key == "GIT_DIR"));
1488        assert!(exported.contains(&(OsString::from("HOME"), OsString::from("/changed/home"))));
1489        assert!(exported.contains(&(OsString::from("BUILD_SETTING"), OsString::from("captured"))));
1490    }
1491
1492    #[cfg(unix)]
1493    #[test]
1494    fn cloned_environment_preserves_non_unicode_passthrough() {
1495        use std::os::unix::ffi::OsStringExt;
1496
1497        let value = OsString::from_vec(vec![b'a', 0xff, b'z']);
1498        let original = Environment::from_vars(
1499            [(OsString::from("BUILD_SETTING"), value.clone())],
1500            PathBuf::from("."),
1501        );
1502        let cloned = original.clone();
1503        drop(original);
1504        assert_eq!(cloned.var("BUILD_SETTING"), None);
1505        assert_eq!(cloned.var_os("BUILD_SETTING"), Some(value.clone()));
1506        assert_eq!(
1507            cloned.subprocess_environment(),
1508            vec![(OsString::from("BUILD_SETTING"), value)]
1509        );
1510    }
1511
1512    #[test]
1513    fn git_optional_locks_parses_like_git() {
1514        assert!(Environment::from_vars([], PathBuf::from(".")).git_optional_locks);
1515        for disabled in ["0", "false", "no", "off", "FALSE"] {
1516            let env = Environment::from_vars(
1517                [(
1518                    OsString::from("GIT_OPTIONAL_LOCKS"),
1519                    OsString::from(disabled),
1520                )],
1521                PathBuf::from("."),
1522            );
1523            assert!(!env.git_optional_locks, "expected disabled for {disabled}");
1524        }
1525        let enabled = Environment::from_vars(
1526            [(OsString::from("GIT_OPTIONAL_LOCKS"), OsString::from("1"))],
1527            PathBuf::from("."),
1528        );
1529        assert!(enabled.git_optional_locks);
1530    }
1531
1532    #[test]
1533    fn is_fetch_options_default_matches_empty() {
1534        assert!(Environment::empty().is_fetch_options_default());
1535        assert!(Environment::from_vars([], PathBuf::from("."))
1536            .clone()
1537            .is_fetch_options_default());
1538        let mut env = Environment::from_vars(
1539            [(
1540                OsString::from("GIT_SSH_COMMAND"),
1541                OsString::from("/bin/wrap"),
1542            )],
1543            PathBuf::from("."),
1544        );
1545        assert!(!env.is_fetch_options_default());
1546        env.captured_vars = None;
1547        assert!(env.is_fetch_options_default());
1548    }
1549
1550    #[test]
1551    fn local_transport_keeps_config_discovery_and_drops_the_client_repository() {
1552        let vars = [
1553            ("HOME", "/home/u"),
1554            ("XDG_CONFIG_HOME", "/home/u/.config"),
1555            ("GIT_CONFIG_NOSYSTEM", "1"),
1556            ("GIT_CONFIG_GLOBAL", "/home/u/alt.gitconfig"),
1557            ("GIT_DIR", "/client/.git"),
1558            ("GIT_WORK_TREE", "/client"),
1559            ("GIT_COMMON_DIR", "/client/.git"),
1560            ("GIT_OBJECT_DIRECTORY", "/client/.git/objects"),
1561            ("GIT_ALTERNATE_OBJECT_DIRECTORIES", "/elsewhere"),
1562            ("GIT_INDEX_FILE", "/client/.git/index"),
1563            ("GIT_CONFIG_PARAMETERS", "'core.bare'='true'"),
1564            ("GIT_CONFIG_COUNT", "1"),
1565            ("GIT_CONFIG_KEY_0", "uploadpack.allowfilter"),
1566            ("GIT_CONFIG_VALUE_0", "false"),
1567            ("PATH", "/usr/bin"),
1568        ]
1569        .map(|(k, v)| (OsString::from(k), OsString::from(v)));
1570        let env = Environment::from_vars(vars, PathBuf::from("/client")).for_local_transport();
1571        assert_eq!(env.var("HOME").as_deref(), Some("/home/u"));
1572        assert_eq!(
1573            env.var("XDG_CONFIG_HOME").as_deref(),
1574            Some("/home/u/.config")
1575        );
1576        assert_eq!(env.var("GIT_CONFIG_NOSYSTEM").as_deref(), Some("1"));
1577        assert_eq!(
1578            env.var("GIT_CONFIG_GLOBAL").as_deref(),
1579            Some("/home/u/alt.gitconfig")
1580        );
1581        assert_eq!(env.var("PATH").as_deref(), Some("/usr/bin"));
1582        for key in [
1583            "GIT_DIR",
1584            "GIT_WORK_TREE",
1585            "GIT_COMMON_DIR",
1586            "GIT_OBJECT_DIRECTORY",
1587            "GIT_ALTERNATE_OBJECT_DIRECTORIES",
1588            "GIT_INDEX_FILE",
1589            "GIT_CONFIG_PARAMETERS",
1590            "GIT_CONFIG_COUNT",
1591            "GIT_CONFIG_KEY_0",
1592            "GIT_CONFIG_VALUE_0",
1593        ] {
1594            assert_eq!(env.var_os(key), None, "{key}");
1595        }
1596        assert!(env.git_config_pairs.is_empty());
1597    }
1598
1599    #[test]
1600    fn var_reads_typed_object_directory_fields() {
1601        let vars = [
1602            ("GIT_OBJECT_DIRECTORY", "/captured/objects"),
1603            ("GIT_ALTERNATE_OBJECT_DIRECTORIES", "/captured/alt"),
1604        ]
1605        .into_iter()
1606        .map(|(k, v)| (OsString::from(k), OsString::from(v)));
1607        let mut env = Environment::from_vars(vars, PathBuf::from("/tmp"));
1608        assert_eq!(
1609            env.var("GIT_OBJECT_DIRECTORY").as_deref(),
1610            Some("/captured/objects")
1611        );
1612        env.git_object_directory = Some("/typed/objects".to_owned());
1613        env.git_alternate_object_directories = None;
1614        assert_eq!(
1615            env.var("GIT_OBJECT_DIRECTORY").as_deref(),
1616            Some("/typed/objects")
1617        );
1618        assert_eq!(env.var("GIT_ALTERNATE_OBJECT_DIRECTORIES"), None);
1619    }
1620
1621    #[test]
1622    fn subprocess_environment_passes_through_untyped_vars() {
1623        let vars = [
1624            ("PATH", "/opt/tools/bin:/usr/bin"),
1625            ("SystemRoot", r"C:\Windows"),
1626            ("GIT_AUTHOR_NAME", "Ada"),
1627            ("GIT_DIR", "/stale/.git"),
1628            ("GIT_CONFIG_COUNT", "1"),
1629            ("GIT_CONFIG_KEY_0", "user.name"),
1630            ("GIT_CONFIG_VALUE_0", "Ada"),
1631        ]
1632        .into_iter()
1633        .map(|(k, v)| (OsString::from(k), OsString::from(v)));
1634        let mut env = Environment::from_vars(vars, PathBuf::from("/tmp"));
1635        env.git_dir = None;
1636        env.git_config_pairs[0].1 = "Grace".to_owned();
1637
1638        let set = env.subprocess_environment();
1639        let get = |key: &str| -> Vec<&OsString> {
1640            set.iter()
1641                .filter(|(k, _)| k == key)
1642                .map(|(_, v)| v)
1643                .collect()
1644        };
1645        assert_eq!(get("PATH"), vec!["/opt/tools/bin:/usr/bin"]);
1646        assert_eq!(get("SystemRoot"), vec![r"C:\Windows"]);
1647        assert_eq!(get("GIT_AUTHOR_NAME"), vec!["Ada"]);
1648        assert!(get("GIT_DIR").is_empty(), "cleared typed field must win");
1649        assert_eq!(get("GIT_CONFIG_VALUE_0"), vec!["Grace"]);
1650    }
1651
1652    #[test]
1653    fn subprocess_environment_of_empty_snapshot_is_empty() {
1654        assert!(Environment::empty().subprocess_environment().is_empty());
1655    }
1656
1657    #[test]
1658    fn with_var_overlays_without_resnapshotting_process() {
1659        let env = Environment::empty()
1660            .with_var("REMOTE_USER", "alice@example.com")
1661            .with_var("GRIT_USER", "alice@example.com");
1662        let set = env.subprocess_environment();
1663        let get = |key: &str| {
1664            set.iter()
1665                .find(|(k, _)| k == key)
1666                .map(|(_, v)| v.to_string_lossy().into_owned())
1667        };
1668        assert_eq!(get("REMOTE_USER").as_deref(), Some("alice@example.com"));
1669        assert_eq!(get("GRIT_USER").as_deref(), Some("alice@example.com"));
1670    }
1671
1672    #[test]
1673    fn from_vars_parses_config_count_pairs() {
1674        let vars = [
1675            ("GIT_CONFIG_COUNT", "1"),
1676            ("GIT_CONFIG_KEY_0", "user.name"),
1677            ("GIT_CONFIG_VALUE_0", "Ada"),
1678        ]
1679        .into_iter()
1680        .map(|(k, v)| (OsString::from(k), OsString::from(v)));
1681        let env = Environment::from_vars(vars, PathBuf::from("/tmp"));
1682        assert_eq!(env.git_config_count.as_deref(), Some("1"));
1683        assert_eq!(
1684            env.git_config_pairs,
1685            vec![("user.name".to_owned(), "Ada".to_owned())]
1686        );
1687    }
1688
1689    #[test]
1690    fn config_fingerprint_tracks_global_override() {
1691        let mut env = Environment::empty();
1692        env.git_config_global = Some("/tmp/global.cfg".to_owned());
1693        let fp = env.config_fingerprint().expect("fingerprint");
1694        assert!(fp
1695            .iter()
1696            .any(|(k, v)| k == "GIT_CONFIG_GLOBAL" && v.as_deref() == Some("/tmp/global.cfg")));
1697    }
1698
1699    #[test]
1700    fn default_xdg_config_git_file_prefers_xdg() {
1701        let mut env = Environment::empty();
1702        env.home = Some(OsString::from("/home/u"));
1703        env.xdg_config_home = Some("/xdg".to_owned());
1704        assert_eq!(
1705            env.default_xdg_config_git_file("ignore"),
1706            Some(PathBuf::from("/xdg/git/ignore"))
1707        );
1708    }
1709
1710    fn isolated_env(dir: &Path) -> Environment {
1711        let mut env = Environment::empty();
1712        env.cwd = dir.to_path_buf();
1713        env.home = Some(dir.as_os_str().to_owned());
1714        env.git_config_nosystem = Some("1".to_owned());
1715        env.git_config_global = Some(dir.join("no-global").to_string_lossy().into_owned());
1716        env
1717    }
1718
1719    fn override_of(spec: &str) -> ConfigOverride {
1720        spec.parse().expect("valid override")
1721    }
1722
1723    #[test]
1724    fn config_override_parses_key_value_bare_and_empty() {
1725        let o = override_of("user.name=Ada Lovelace");
1726        assert_eq!((o.key(), o.value()), ("user.name", Some("Ada Lovelace")));
1727        let o = override_of("http.extraHeader=Authorization: a=b");
1728        assert_eq!(o.value(), Some("Authorization: a=b"));
1729        let o = override_of("core.bare");
1730        assert_eq!((o.key(), o.value()), ("core.bare", None));
1731        let o = override_of("user.email=");
1732        assert_eq!(o.value(), Some(""));
1733        let o = override_of("remote.My Origin.url=x");
1734        assert_eq!(o.key(), "remote.My Origin.url");
1735    }
1736
1737    #[test]
1738    fn config_override_rejects_invalid_keys() {
1739        for spec in [
1740            "nosection",
1741            "=value",
1742            "user.=x",
1743            ".name=x",
1744            "us er.name=x",
1745            "",
1746        ] {
1747            assert!(
1748                spec.parse::<ConfigOverride>().is_err(),
1749                "{spec:?} should be rejected"
1750            );
1751        }
1752        assert!(ConfigOverride::new("a\nb.c", None).is_err());
1753    }
1754
1755    #[test]
1756    fn push_config_override_round_trips_through_parameter_parser() {
1757        let mut env = Environment::empty();
1758        let tricky = "it's a \"quote\" = !bang  spaced";
1759        env.push_config_override(
1760            &ConfigOverride::new("user.name", Some(tricky.to_owned())).unwrap(),
1761        );
1762        env.push_config_override(&override_of("core.bare"));
1763        env.push_config_override(&override_of("user.email="));
1764        let raw = env.git_config_parameters.clone().expect("parameters set");
1765        assert_eq!(
1766            crate::config::parse_config_parameters(&raw),
1767            vec![
1768                format!("user.name\u{1}{tricky}"),
1769                "core.bare\u{1}".to_owned(),
1770                "user.email\u{1}".to_owned(),
1771            ]
1772        );
1773    }
1774
1775    #[test]
1776    fn push_config_override_appends_to_inherited_parameters() {
1777        let mut env = Environment::empty();
1778        env.git_config_parameters = Some("'core.editor'='vi'".to_owned());
1779        env.push_config_override(&override_of("user.name=CI"));
1780        assert_eq!(
1781            env.git_config_parameters.as_deref(),
1782            Some("'core.editor'='vi' 'user.name'='CI'")
1783        );
1784        let mut blank = Environment::empty();
1785        blank.git_config_parameters = Some("  ".to_owned());
1786        blank.push_config_override(&override_of("user.name=CI"));
1787        assert_eq!(
1788            blank.git_config_parameters.as_deref(),
1789            Some("'user.name'='CI'")
1790        );
1791    }
1792
1793    #[test]
1794    fn later_config_override_wins_over_earlier_env_pairs_and_files() {
1795        let dir = tempfile::tempdir().unwrap();
1796        let git_dir = dir.path().join(".git");
1797        std::fs::create_dir_all(&git_dir).unwrap();
1798        std::fs::write(
1799            git_dir.join("config"),
1800            "[user]\n\tname = FromRepo\n\temail = repo@x.y\n[core]\n\tbare = false\n",
1801        )
1802        .unwrap();
1803        let mut env = isolated_env(dir.path());
1804        env.git_config_count = Some("1".to_owned());
1805        env.git_config_pairs = vec![("user.name".to_owned(), "FromCount".to_owned())];
1806        env.push_config_override(&override_of("user.name=First"));
1807        env.push_config_override(&override_of("user.name=Second"));
1808        env.push_config_override(&override_of("core.bare"));
1809
1810        let config = crate::config::ConfigSet::load(
1811            &env,
1812            Some(&git_dir),
1813            &crate::config::LoadConfigOptions::standard(&env, Some(&git_dir)),
1814        )
1815        .unwrap();
1816        assert_eq!(config.value("user.name").as_deref(), Some("Second"));
1817        assert_eq!(config.value("user.email").as_deref(), Some("repo@x.y"));
1818        assert_eq!(config.get_bool("core.bare").unwrap(), Some(true));
1819    }
1820
1821    #[test]
1822    fn config_override_is_exported_to_subprocesses() {
1823        let mut env = Environment::empty();
1824        env.push_config_override(&override_of("user.name=CI"));
1825        assert!(env.subprocess_environment().contains(&(
1826            OsString::from("GIT_CONFIG_PARAMETERS"),
1827            OsString::from("'user.name'='CI'")
1828        )));
1829    }
1830
1831    #[test]
1832    fn with_git_dir_and_work_tree_resolve_relative_paths_against_cwd() {
1833        let mut env = Environment::empty();
1834        env.cwd = PathBuf::from("/base/dir");
1835        let env = env.with_git_dir("repo/.git").with_work_tree("wt");
1836        assert_eq!(
1837            env.git_dir.as_deref().map(PathBuf::from),
1838            Some(PathBuf::from("/base/dir/repo/.git"))
1839        );
1840        assert_eq!(
1841            env.git_work_tree.as_deref().map(PathBuf::from),
1842            Some(PathBuf::from("/base/dir/wt"))
1843        );
1844        let abs = std::env::temp_dir().join("abs.git");
1845        let env = env.with_git_dir(&abs);
1846        assert_eq!(env.git_dir.as_deref().map(PathBuf::from), Some(abs));
1847    }
1848
1849    #[test]
1850    fn with_git_dir_opens_that_repository_from_elsewhere() {
1851        let dir = tempfile::tempdir().unwrap();
1852        let repo_dir = dir.path().join("r");
1853        crate::repo::init_repository(
1854            &repo_dir,
1855            false,
1856            "main",
1857            None,
1858            crate::ref_storage::RefStorageFormat::Files,
1859        )
1860        .unwrap();
1861        let elsewhere = dir.path().join("elsewhere");
1862        std::fs::create_dir_all(&elsewhere).unwrap();
1863        let mut env = isolated_env(&elsewhere);
1864        env.cwd = elsewhere.clone();
1865        let env = env.with_git_dir("../r/.git").with_work_tree("../r");
1866        let repo =
1867            crate::repo::Repository::discover(None, &RepositoryOptions::with_environment(env))
1868                .unwrap();
1869        assert_eq!(
1870            repo.git_dir().canonicalize_simplified().unwrap(),
1871            repo_dir.join(".git").canonicalize_simplified().unwrap()
1872        );
1873        assert_eq!(
1874            repo.work_tree()
1875                .map(|p| p.canonicalize_simplified().unwrap()),
1876            Some(repo_dir.canonicalize_simplified().unwrap())
1877        );
1878    }
1879
1880    #[test]
1881    fn default_xdg_config_git_file_falls_back_to_home_config() {
1882        let mut env = Environment::empty();
1883        env.home = Some(OsString::from("/home/u"));
1884        assert_eq!(
1885            env.default_xdg_config_git_file("ignore"),
1886            Some(PathBuf::from("/home/u/.config/git/ignore"))
1887        );
1888    }
1889
1890    #[test]
1891    fn empty_options_have_no_home_or_system_config_roots() {
1892        let env = RepositoryOptions::empty().environment;
1893        assert!(env.home.is_none());
1894        assert!(env.userprofile.is_none());
1895        assert!(env.homedrive.is_none() && env.homepath.is_none());
1896        assert!(env.xdg_config_home.is_none());
1897        assert!(env.program_files.is_none() && env.program_files_x86.is_none());
1898        assert!(env.git_install_root.is_none());
1899        assert!(env.git_config_system.is_none() && env.git_config_global.is_none());
1900        assert!(env.captured_vars.is_none());
1901    }
1902
1903    #[test]
1904    fn from_process_snapshots_the_process_environment() {
1905        let options = RepositoryOptions::from_process();
1906        let process = Environment::capture_process();
1907        assert_eq!(options.environment.home, process.home);
1908        assert_eq!(options.environment.program_files, process.program_files);
1909        assert_eq!(options.environment.cwd, process.cwd);
1910        assert_eq!(options.environment.home, std::env::var_os("HOME"));
1911        assert!(options.environment.captured_vars.is_some());
1912    }
1913}