1use 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#[non_exhaustive]
15#[derive(Debug, Clone, Default)]
16pub struct ConfigWriteOptions {
17 dry_run: bool,
18 value_type: Option<ConfigValueType>,
19 replace_all: bool,
21 replace_value_pattern: Option<String>,
23 unset_value_pattern: Option<String>,
24}
25
26impl ConfigWriteOptions {
27 #[must_use]
29 pub fn new() -> Self {
30 Self::default()
31 }
32
33 #[must_use]
35 pub fn dry_run(mut self, dry_run: bool) -> Self {
36 self.dry_run = dry_run;
37 self
38 }
39
40 #[must_use]
42 pub fn value_type(mut self, ty: ConfigValueType) -> Self {
43 self.value_type = Some(ty);
44 self
45 }
46
47 #[must_use]
51 pub fn replace_all(mut self, replace_all: bool) -> Self {
52 self.replace_all = replace_all;
53 self
54 }
55
56 #[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 #[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 #[must_use]
72 pub fn is_dry_run(&self) -> bool {
73 self.dry_run
74 }
75}
76
77#[derive(Debug, Clone)]
79pub struct ConfigEditor {
80 path: PathBuf,
81 file_scope: ConfigScope,
82 env: Environment,
83}
84
85impl ConfigEditor {
86 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 #[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 #[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 #[must_use]
124 pub fn path(&self) -> &Path {
125 &self.path
126 }
127
128 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 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 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 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 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 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 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 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 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 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 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 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 #[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}