Skip to main content

grit_lib/config/
location.rs

1//! Config file locations (`--local`, `--global`, `-f`) and scoped load/write helpers.
2
3use std::path::{Path, PathBuf};
4
5use crate::environment::Environment;
6use crate::error::{ConfigError, Error, Result};
7
8use super::{
9    global_config_paths_pub, resolve_config_override_path, system_config_path, ConfigFile,
10    ConfigScope, ConfigSet, IncludeContext, IncludeOptions,
11};
12
13/// Which config file(s) to read or write.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub enum ConfigLocation {
16    /// Repository `.git/config` (or `commondir/config` for linked worktrees).
17    Local,
18    /// Per-user global config (XDG + `~/.gitconfig`, or `GIT_CONFIG_GLOBAL`).
19    Global,
20    /// System-wide `/etc/gitconfig` (or platform equivalent).
21    System,
22    /// Per-worktree `config.worktree` (when enabled).
23    Worktree,
24    /// A single file from `-f` / `--file`.
25    File(PathBuf),
26}
27
28impl ConfigLocation {
29    /// Scope stored in parsed entries from this location's on-disk file.
30    #[must_use]
31    pub fn file_scope(&self) -> ConfigScope {
32        match self {
33            Self::Local => ConfigScope::Local,
34            Self::File(_) => ConfigScope::Local,
35            Self::Global => ConfigScope::Global,
36            Self::System => ConfigScope::System,
37            Self::Worktree => ConfigScope::Worktree,
38        }
39    }
40
41    /// Path to create or update when writing a value at this location.
42    ///
43    /// Global writes follow Git's writer preference: an existing `~/.gitconfig`, then an
44    /// existing XDG `git/config`, otherwise the conventional `~/.gitconfig`.
45    ///
46    /// # Errors
47    ///
48    /// Returns [`Error::Config`] when the location needs a repository but none was given.
49    pub fn write_path(&self, env: &Environment, git_dir: Option<&Path>) -> Result<PathBuf> {
50        match self {
51            Self::Global => global_config_write_path(env),
52            Self::Local => {
53                let gd = git_dir.ok_or_else(|| Error::Config(ConfigError::RepositoryRequired))?;
54                Ok(crate::repo::local_config_write_path(gd))
55            }
56            Self::File(path) => {
57                let s = path.to_string_lossy();
58                Ok(resolve_config_override_path(env, s.as_ref()))
59            }
60            Self::System => Ok(system_config_path(env)),
61            Self::Worktree => {
62                let gd = git_dir.ok_or_else(|| Error::Config(ConfigError::RepositoryRequired))?;
63                Ok(gd.join("config.worktree"))
64            }
65        }
66    }
67
68    /// Load configuration from this location only (no full cascade).
69    ///
70    /// `[include]` / `[includeIf]` directives are expanded. Command-line overrides are not
71    /// included except for the full-repository [`ConfigSet::load`] path used by the CLI default
72    /// read mode.
73    pub fn load_single(&self, env: &Environment, git_dir: Option<&Path>) -> Result<ConfigSet> {
74        let mut set = ConfigSet::new();
75        let includes = IncludeOptions::default().with_context(IncludeContext {
76            git_dir: git_dir.map(Path::to_path_buf),
77            command_line_relative_include_is_error: false,
78            cwd: env.cwd.clone(),
79            pwd: env.pwd.clone(),
80            env: std::sync::Arc::new(env.clone()),
81        });
82
83        match self {
84            Self::Global => {
85                for path in global_config_paths_pub(env) {
86                    if let Some(f) = ConfigFile::from_path(&path, ConfigScope::Global)? {
87                        set.merge_file(&f, &includes)?;
88                    }
89                }
90            }
91            Self::Local => {
92                let gd = git_dir.ok_or_else(|| Error::Config(ConfigError::RepositoryRequired))?;
93                let local_path = crate::repo::local_config_write_path(gd);
94                if let Some(f) = ConfigFile::from_path(&local_path, ConfigScope::Local)? {
95                    set.merge_file(&f, &includes)?;
96                }
97            }
98            Self::System => {
99                let system_path = system_config_path(env);
100                if let Some(f) = ConfigFile::from_path(&system_path, ConfigScope::System)? {
101                    set.merge_file(&f, &includes)?;
102                }
103            }
104            Self::Worktree => {
105                let gd = git_dir.ok_or_else(|| Error::Config(ConfigError::RepositoryRequired))?;
106                let common = crate::repo::common_git_dir_for_config(gd);
107                if !crate::repo::worktree_config_enabled(&common) {
108                    return Ok(set);
109                }
110                let wt_path = gd.join("config.worktree");
111                if let Some(f) = ConfigFile::from_path(&wt_path, ConfigScope::Worktree)? {
112                    set.merge_file(&f, &includes)?;
113                }
114            }
115            Self::File(path) => {
116                let s = path.to_string_lossy();
117                let path = resolve_config_override_path(env, s.as_ref());
118                if let Some(f) = ConfigFile::from_path(&path, ConfigScope::Command)? {
119                    set.merge_file(&f, &includes)?;
120                }
121            }
122        }
123
124        Ok(set)
125    }
126}
127
128/// Global config file path for writes, matching Git's preference for an existing file.
129///
130/// When `GIT_CONFIG_GLOBAL` is set, that path is always used. Otherwise prefer an existing
131/// `~/.gitconfig`, then an existing XDG `git/config`, then create `~/.gitconfig`.
132pub fn global_config_write_path(env: &Environment) -> Result<PathBuf> {
133    let paths = global_config_paths_pub(env);
134    let Some(dotgitconfig) = paths.last() else {
135        return Err(Error::Config(ConfigError::NoGlobalConfigPath));
136    };
137    if paths.len() == 1 || dotgitconfig.exists() {
138        return Ok(dotgitconfig.clone());
139    }
140    let existing_xdg = paths.first().filter(|xdg| xdg.exists());
141    Ok(existing_xdg.unwrap_or(dotgitconfig).clone())
142}
143
144/// Human-readable summary of a config write that `--dry-run` would perform.
145#[derive(Debug, Clone, PartialEq, Eq)]
146pub struct ConfigWritePreview {
147    /// Config file that would be updated.
148    pub path: PathBuf,
149    /// Short description of the change.
150    pub summary: String,
151}