Skip to main content

grit_lib/config/
write.rs

1//! Scoped config file writes for [`Config`](super::handle::Config) and [`ConfigEditor`].
2use std::fs;
3use std::io::{self, ErrorKind};
4use std::path::{Path, PathBuf};
5
6use super::{
7    canonicalize_config_write_value, global_config_write_path, resolve_config_override_path,
8    system_config_path, ConfigFile, ConfigScope, ConfigValueType, ConfigWritePreview,
9};
10use crate::environment::Environment;
11use crate::error::{ConfigError, Error, Result};
12
13/// Options for a config file write (dry-run, typed canonicalization, unset patterns).
14#[non_exhaustive]
15#[derive(Debug, Clone, Default)]
16pub struct ConfigWriteOptions {
17    dry_run: bool,
18    value_type: Option<ConfigValueType>,
19    /// When true, [`ConfigEditor::set`] and [`Config::set`] call [`ConfigFile::replace_all`].
20    replace_all: bool,
21    /// Values to replace must match this pattern when using replace-all (Git value pattern).
22    replace_value_pattern: Option<String>,
23    unset_value_pattern: Option<String>,
24}
25
26impl ConfigWriteOptions {
27    /// Default options: persist changes and accept values as given.
28    #[must_use]
29    pub fn new() -> Self {
30        Self::default()
31    }
32
33    /// When `true`, return a [`ConfigWritePreview`] instead of writing disk.
34    #[must_use]
35    pub fn dry_run(mut self, dry_run: bool) -> Self {
36        self.dry_run = dry_run;
37        self
38    }
39
40    /// Canonicalize `value` with Git `--type` rules before writing.
41    #[must_use]
42    pub fn value_type(mut self, ty: ConfigValueType) -> Self {
43        self.value_type = Some(ty);
44        self
45    }
46
47    /// Replace every occurrence of `key` with `value` (Git `replace-all` semantics).
48    ///
49    /// When `false` (the default), a single-valued `set` overwrites one slot; see [`ConfigFile::set`].
50    #[must_use]
51    pub fn replace_all(mut self, replace_all: bool) -> Self {
52        self.replace_all = replace_all;
53        self
54    }
55
56    /// When using [`Self::replace_all`], only replace values matching this Git config value pattern.
57    #[must_use]
58    pub fn replace_value_pattern(mut self, pattern: impl Into<String>) -> Self {
59        self.replace_value_pattern = Some(pattern.into());
60        self
61    }
62
63    /// When unsetting, remove only values matching this pattern (`unset-all` / `--value`).
64    #[must_use]
65    pub fn unset_value_pattern(mut self, pattern: impl Into<String>) -> Self {
66        self.unset_value_pattern = Some(pattern.into());
67        self
68    }
69
70    /// Whether this write should only preview the change.
71    #[must_use]
72    pub fn is_dry_run(&self) -> bool {
73        self.dry_run
74    }
75}
76
77/// Edit a config file outside an open [`Repository`](crate::repo::Repository) (global, system, or `-f` path).
78#[derive(Debug, Clone)]
79pub struct ConfigEditor {
80    path: PathBuf,
81    file_scope: ConfigScope,
82    env: Environment,
83}
84
85impl ConfigEditor {
86    /// Open the per-user global config file for writes (respects `GIT_CONFIG_GLOBAL` / XDG).
87    ///
88    /// # Errors
89    ///
90    /// Returns [`ConfigError::NoGlobalConfigPath`] when no global path can be resolved.
91    pub fn global(env: &Environment) -> Result<Self> {
92        Ok(Self {
93            path: global_config_write_path(env)?,
94            file_scope: ConfigScope::Global,
95            env: env.clone(),
96        })
97    }
98
99    /// Open the system config file for writes.
100    #[must_use]
101    pub fn system(env: &Environment) -> Self {
102        Self {
103            path: system_config_path(env),
104            file_scope: ConfigScope::System,
105            env: env.clone(),
106        }
107    }
108
109    /// Open an explicit config file (for example `grit config -f path`).
110    ///
111    /// `file_scope` is the scope stored in parsed entries (typically [`ConfigScope::Local`]).
112    #[must_use]
113    pub fn open(env: &Environment, path: PathBuf, file_scope: ConfigScope) -> Self {
114        let path = resolve_config_override_path(env, path.to_string_lossy().as_ref());
115        Self {
116            path,
117            file_scope,
118            env: env.clone(),
119        }
120    }
121
122    /// Path that would be read or written.
123    #[must_use]
124    pub fn path(&self) -> &Path {
125        &self.path
126    }
127
128    /// Set `key` to `value`, replacing an existing single-valued key.
129    pub fn set(
130        &self,
131        key: &str,
132        value: &str,
133        options: &ConfigWriteOptions,
134    ) -> Result<Option<ConfigWritePreview>> {
135        let value = canonicalize_value(key, value, options, &self.env)?;
136        write_file(&self.path, self.file_scope, None, options, |cfg| {
137            if options.replace_all {
138                cfg.replace_all(key, &value, options.replace_value_pattern.as_deref())?;
139                return Ok(format!(
140                    "replace-all {key}={value}{}",
141                    options
142                        .replace_value_pattern
143                        .as_ref()
144                        .map(|p| format!(" (pattern {p})"))
145                        .unwrap_or_default()
146                ));
147            }
148            cfg.set(key, &value)?;
149            Ok(format!("set {key}={value}"))
150        })
151    }
152
153    /// Append `value` for a multi-valued `key`.
154    pub fn add_value(
155        &self,
156        key: &str,
157        value: &str,
158        options: &ConfigWriteOptions,
159    ) -> Result<Option<ConfigWritePreview>> {
160        let value = canonicalize_value(key, value, options, &self.env)?;
161        write_file(&self.path, self.file_scope, None, options, |cfg| {
162            cfg.add_value(key, &value)?;
163            Ok(format!("add {key}={value}"))
164        })
165    }
166
167    /// Remove the last value for `key`.
168    pub fn unset(
169        &self,
170        key: &str,
171        options: &ConfigWriteOptions,
172    ) -> Result<Option<ConfigWritePreview>> {
173        write_file(&self.path, self.file_scope, None, options, |cfg| {
174            if !self.path.exists() {
175                return Err(Error::Config(ConfigError::KeyNotSet {
176                    key: key.to_owned(),
177                }));
178            }
179            let removed = cfg.unset_last(key)?;
180            if removed == 0 {
181                return Err(Error::Config(ConfigError::KeyNotSet {
182                    key: key.to_owned(),
183                }));
184            }
185            Ok(format!("unset {key}"))
186        })
187    }
188
189    /// Remove every value for `key`, optionally filtered by [`ConfigWriteOptions::unset_value_pattern`].
190    pub fn unset_all(
191        &self,
192        key: &str,
193        options: &ConfigWriteOptions,
194    ) -> Result<(usize, Option<ConfigWritePreview>)> {
195        let pattern = options.unset_value_pattern.as_deref();
196        let mut removed_count = 0usize;
197        let preview = write_file(&self.path, self.file_scope, None, options, |cfg| {
198            let removed = cfg.unset_matching(key, pattern, false)?;
199            if removed == 0 {
200                return Err(Error::Config(ConfigError::KeyNotSet {
201                    key: key.to_owned(),
202                }));
203            }
204            removed_count = removed;
205            Ok(format!("unset-all {key} ({removed} values)"))
206        })?;
207        Ok((removed_count, preview))
208    }
209
210    /// Rename a section in the file.
211    pub fn rename_section(
212        &self,
213        old_name: &str,
214        new_name: &str,
215        options: &ConfigWriteOptions,
216    ) -> Result<Option<ConfigWritePreview>> {
217        write_file(&self.path, self.file_scope, None, options, |cfg| {
218            if !cfg.rename_section(old_name, new_name)? {
219                return Err(Error::Config(ConfigError::SectionNotFound {
220                    section: old_name.to_owned(),
221                }));
222            }
223            Ok(format!("rename-section {old_name} -> {new_name}"))
224        })
225    }
226
227    /// Remove an entire section from the file.
228    pub fn remove_section(
229        &self,
230        section: &str,
231        options: &ConfigWriteOptions,
232    ) -> Result<Option<ConfigWritePreview>> {
233        write_file(&self.path, self.file_scope, None, options, |cfg| {
234            if !cfg.remove_section(section)? {
235                return Err(Error::Config(ConfigError::SectionNotFound {
236                    section: section.to_owned(),
237                }));
238            }
239            Ok(format!("remove-section {section}"))
240        })
241    }
242}
243
244impl<'repo> super::Config<'repo> {
245    /// Set `key` to `value` in the config file for `scope`.
246    pub fn set(
247        &self,
248        scope: ConfigScope,
249        key: &str,
250        value: &str,
251        options: &ConfigWriteOptions,
252    ) -> Result<Option<ConfigWritePreview>> {
253        let env = self.repository().environment();
254        let value = canonicalize_value(key, value, options, env)?;
255        let git_dir = self.repository().git_dir();
256        let path = write_path_for_scope(scope, env, git_dir)?;
257        let preview = write_file(&path, scope.file_scope(), Some(git_dir), options, |cfg| {
258            if options.replace_all {
259                cfg.replace_all(key, &value, options.replace_value_pattern.as_deref())?;
260                return Ok(format!(
261                    "replace-all {key}={value}{}",
262                    options
263                        .replace_value_pattern
264                        .as_ref()
265                        .map(|p| format!(" (pattern {p})"))
266                        .unwrap_or_default()
267                ));
268            }
269            cfg.set(key, &value)?;
270            Ok(format!("set {key}={value}"))
271        })?;
272        if preview.is_none() {
273            self.repository().reload_config()?;
274        }
275        Ok(preview)
276    }
277
278    /// Append `value` for a multi-valued `key` in the config file for `scope`.
279    pub fn add_value(
280        &self,
281        scope: ConfigScope,
282        key: &str,
283        value: &str,
284        options: &ConfigWriteOptions,
285    ) -> Result<Option<ConfigWritePreview>> {
286        let env = self.repository().environment();
287        let value = canonicalize_value(key, value, options, env)?;
288        let git_dir = self.repository().git_dir();
289        let path = write_path_for_scope(scope, env, git_dir)?;
290        let preview = write_file(&path, scope.file_scope(), Some(git_dir), options, |cfg| {
291            cfg.add_value(key, &value)?;
292            Ok(format!("add {key}={value}"))
293        })?;
294        if preview.is_none() {
295            self.repository().reload_config()?;
296        }
297        Ok(preview)
298    }
299
300    /// Remove the last value for `key` in the config file for `scope`.
301    pub fn unset(
302        &self,
303        scope: ConfigScope,
304        key: &str,
305        options: &ConfigWriteOptions,
306    ) -> Result<Option<ConfigWritePreview>> {
307        let env = self.repository().environment();
308        let git_dir = self.repository().git_dir();
309        let path = write_path_for_scope(scope, env, git_dir)?;
310        let preview = write_file(&path, scope.file_scope(), Some(git_dir), options, |cfg| {
311            if !path.exists() {
312                return Err(Error::Config(ConfigError::KeyNotSet {
313                    key: key.to_owned(),
314                }));
315            }
316            let removed = cfg.unset_last(key)?;
317            if removed == 0 {
318                return Err(Error::Config(ConfigError::KeyNotSet {
319                    key: key.to_owned(),
320                }));
321            }
322            Ok(format!("unset {key}"))
323        })?;
324        if preview.is_none() {
325            self.repository().reload_config()?;
326        }
327        Ok(preview)
328    }
329
330    /// Remove every value for `key` in the config file for `scope`.
331    pub fn unset_all(
332        &self,
333        scope: ConfigScope,
334        key: &str,
335        options: &ConfigWriteOptions,
336    ) -> Result<(usize, Option<ConfigWritePreview>)> {
337        let env = self.repository().environment();
338        let git_dir = self.repository().git_dir();
339        let path = write_path_for_scope(scope, env, git_dir)?;
340        let pattern = options.unset_value_pattern.as_deref();
341        let mut removed_count = 0usize;
342        let preview = write_file(&path, scope.file_scope(), Some(git_dir), options, |cfg| {
343            let removed = cfg.unset_matching(key, pattern, false)?;
344            if removed == 0 {
345                return Err(Error::Config(ConfigError::KeyNotSet {
346                    key: key.to_owned(),
347                }));
348            }
349            removed_count = removed;
350            Ok(format!("unset-all {key} ({removed} values)"))
351        })?;
352        if preview.is_none() {
353            self.repository().reload_config()?;
354        }
355        Ok((removed_count, preview))
356    }
357
358    /// Rename a section in the config file for `scope`.
359    pub fn rename_section(
360        &self,
361        scope: ConfigScope,
362        old_name: &str,
363        new_name: &str,
364        options: &ConfigWriteOptions,
365    ) -> Result<Option<ConfigWritePreview>> {
366        let env = self.repository().environment();
367        let git_dir = self.repository().git_dir();
368        let path = write_path_for_scope(scope, env, git_dir)?;
369        let preview = write_file(&path, scope.file_scope(), Some(git_dir), options, |cfg| {
370            if !cfg.rename_section(old_name, new_name)? {
371                return Err(Error::Config(ConfigError::SectionNotFound {
372                    section: old_name.to_owned(),
373                }));
374            }
375            Ok(format!("rename-section {old_name} -> {new_name}"))
376        })?;
377        if preview.is_none() {
378            self.repository().reload_config()?;
379        }
380        Ok(preview)
381    }
382
383    /// Remove an entire section from the config file for `scope`.
384    pub fn remove_section(
385        &self,
386        scope: ConfigScope,
387        section: &str,
388        options: &ConfigWriteOptions,
389    ) -> Result<Option<ConfigWritePreview>> {
390        let env = self.repository().environment();
391        let git_dir = self.repository().git_dir();
392        let path = write_path_for_scope(scope, env, git_dir)?;
393        let preview = write_file(&path, scope.file_scope(), Some(git_dir), options, |cfg| {
394            if !cfg.remove_section(section)? {
395                return Err(Error::Config(ConfigError::SectionNotFound {
396                    section: section.to_owned(),
397                }));
398            }
399            Ok(format!("remove-section {section}"))
400        })?;
401        if preview.is_none() {
402            self.repository().reload_config()?;
403        }
404        Ok(preview)
405    }
406}
407
408impl ConfigScope {
409    /// Scope tag stored in [`ConfigFile`] entries for this write target.
410    #[must_use]
411    pub(crate) fn file_scope(self) -> ConfigScope {
412        match self {
413            Self::System | Self::Global | Self::Local | Self::Worktree => self,
414            Self::Command => ConfigScope::Local,
415        }
416    }
417}
418
419fn canonicalize_value(
420    key: &str,
421    value: &str,
422    options: &ConfigWriteOptions,
423    env: &Environment,
424) -> Result<String> {
425    match options.value_type {
426        Some(ty) => canonicalize_config_write_value(key, ty, value, env),
427        None => Ok(value.to_owned()),
428    }
429}
430
431fn write_path_for_scope(scope: ConfigScope, env: &Environment, git_dir: &Path) -> Result<PathBuf> {
432    match scope {
433        ConfigScope::Global => global_config_write_path(env),
434        ConfigScope::Local => Ok(crate::repo::local_config_write_path(git_dir)),
435        ConfigScope::System => Ok(system_config_path(env)),
436        ConfigScope::Worktree => {
437            ensure_worktree_write_allowed(git_dir)?;
438            Ok(git_dir.join("config.worktree"))
439        }
440        ConfigScope::Command => Err(Error::Config(ConfigError::UnknownValue {
441            key: "config scope".to_owned(),
442            value: "command".to_owned(),
443        })),
444    }
445}
446
447fn ensure_worktree_write_allowed(git_dir: &Path) -> Result<()> {
448    let common = crate::repo::common_git_dir_for_config(git_dir);
449    if !crate::repo::worktree_config_enabled(&common) {
450        return Err(Error::Config(ConfigError::WorktreeConfigNotEnabled));
451    }
452    Ok(())
453}
454
455fn open_config_file(path: &Path, scope: ConfigScope) -> Result<ConfigFile> {
456    let content = match fs::read(path) {
457        Ok(bytes) => match std::str::from_utf8(&bytes) {
458            Ok(text) => text.to_owned(),
459            Err(_) => {
460                return Err(Error::Io(io::Error::new(
461                    ErrorKind::InvalidData,
462                    format!("config file {} is not valid UTF-8", path.display()),
463                )));
464            }
465        },
466        Err(err) if err.kind() == ErrorKind::NotFound => String::new(),
467        Err(err) => return Err(Error::Io(err)),
468    };
469    ConfigFile::parse(path, &content, scope)
470}
471
472fn write_file(
473    path: &Path,
474    file_scope: ConfigScope,
475    git_dir: Option<&Path>,
476    options: &ConfigWriteOptions,
477    mut apply: impl FnMut(&mut ConfigFile) -> Result<String>,
478) -> Result<Option<ConfigWritePreview>> {
479    if file_scope == ConfigScope::Worktree {
480        let gd = git_dir.ok_or_else(|| Error::Config(ConfigError::RepositoryRequired))?;
481        ensure_worktree_write_allowed(gd)?;
482    }
483    let mut cfg = open_config_file(path, file_scope)?;
484    let summary = apply(&mut cfg)?;
485    if options.dry_run {
486        return Ok(Some(ConfigWritePreview {
487            path: path.to_path_buf(),
488            summary,
489        }));
490    }
491    cfg.write()?;
492    Ok(None)
493}