1use 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#[derive(Debug, Clone)]
33pub struct Environment {
34 pub cwd: PathBuf,
36 pub git_dir: Option<String>,
38 pub git_work_tree: Option<String>,
40 pub git_ceiling_directories: Option<String>,
42 pub git_index_file: Option<String>,
44 pub git_namespace: Option<String>,
46 pub git_replace_ref_base: Option<String>,
48 pub git_no_replace_objects: bool,
50 pub git_optional_locks: bool,
53 pub git_literal_pathspecs: bool,
55 pub git_glob_pathspecs: bool,
57 pub git_noglob_pathspecs: bool,
59 pub git_icase_pathspecs: bool,
61 pub git_alternate_object_directories: Option<String>,
63 pub git_object_directory: Option<String>,
72 pub git_prefix: Option<String>,
74 pub git_config_nosystem: Option<String>,
76 pub git_config_system: Option<String>,
78 pub git_config_global: Option<String>,
80 pub git_config: Option<String>,
82 pub git_config_parameters: Option<String>,
84 pub git_config_count: Option<String>,
86 pub git_config_pairs: Vec<(String, String)>,
88 pub home: Option<OsString>,
90 pub xdg_config_home: Option<String>,
92 pub userprofile: Option<OsString>,
94 pub homedrive: Option<OsString>,
96 pub homepath: Option<OsString>,
98 pub git_install_root: Option<OsString>,
100 pub git_exec_path: Option<OsString>,
102 pub pwd: Option<String>,
104 pub grit_invocation_cwd: Option<String>,
106 pub sudo_uid: Option<String>,
108 pub git_author_name: Option<String>,
110 pub git_author_email: Option<String>,
112 pub git_author_date: Option<String>,
114 pub git_committer_name: Option<String>,
116 pub git_committer_email: Option<String>,
118 pub git_committer_date: Option<String>,
120 pub tz: Option<String>,
122 pub user: Option<String>,
124 pub username: Option<String>,
126 pub program_files: Option<String>,
128 pub program_files_x86: Option<String>,
130 pub(crate) captured_vars: Option<Arc<HashMap<String, OsString>>>,
134}
135
136impl Environment {
137 #[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 #[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 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 #[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 #[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 #[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 #[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 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 #[must_use]
448 pub fn capture_process() -> Self {
449 Self::from_vars(std::env::vars_os(), process_cwd_fallback())
451 }
452
453 #[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 #[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 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 #[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 #[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 #[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 #[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 #[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#[derive(Debug, Clone, PartialEq, Eq)]
853pub struct ConfigOverride {
854 key: String,
855 value: Option<String>,
856}
857
858impl ConfigOverride {
859 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 #[must_use]
877 pub fn key(&self) -> &str {
878 &self.key
879 }
880
881 #[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 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#[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#[must_use]
921pub(crate) fn wall_clock_unix_timestamp_seconds() -> i64 {
922 OffsetDateTime::now_utc().unix_timestamp()
923}
924
925#[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
944const 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#[derive(Clone)]
1089#[non_exhaustive]
1090pub struct RepositoryOptions {
1091 pub environment: Environment,
1093 pub command_runner: Arc<dyn CommandRunner>,
1095 pub change_id_generator: Arc<dyn ChangeIdGenerator>,
1097 pub diagnostics: DiagnosticsHandle,
1099 pub network_trace: bool,
1101 pub(crate) ownership_check: Arc<dyn OwnershipCheck>,
1103 pub reference_unix_time: Option<i64>,
1105 pub thread_policy: crate::parallel::ThreadPolicy,
1107 pub work_tree: Option<std::path::PathBuf>,
1109 pub object_store: Option<Arc<dyn crate::odb::store::WritableObjectStore>>,
1112 pub odb_builder: Option<crate::odb::OdbBuilder>,
1114 pub ref_store: Option<std::sync::Arc<dyn crate::refs::store::RefStore>>,
1116 pub initial_branch: Option<String>,
1118 pub validate_repository_format: bool,
1120 pub open_for_serving: bool,
1122 pub promisor_fetcher: Option<std::sync::Arc<dyn crate::promisor_fetch::PromisorFetcher>>,
1124 pub hook_stdio: crate::hooks::HookStdio,
1126 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 #[must_use]
1174 pub fn empty() -> Self {
1175 Self::default()
1176 }
1177
1178 #[must_use]
1185 pub fn from_process() -> Self {
1186 Self::with_environment(Environment::capture_process())
1188 }
1189
1190 #[must_use]
1195 pub fn with_environment(environment: Environment) -> Self {
1196 Self {
1197 environment,
1198 ..Self::default()
1199 }
1200 }
1201
1202 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[must_use]
1372 pub fn without_format_validation(mut self) -> Self {
1373 self.validate_repository_format = false;
1374 self
1375 }
1376
1377 #[must_use]
1379 pub fn for_serving(mut self) -> Self {
1380 self.open_for_serving = true;
1381 self
1382 }
1383
1384 #[must_use]
1386 pub fn with_diagnostics(mut self, diagnostics: DiagnosticsHandle) -> Self {
1387 self.diagnostics = diagnostics;
1388 self
1389 }
1390
1391 #[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 #[must_use]
1400 pub fn reftable_write(&self) -> ReftableWriteOptions {
1401 self.reftable_write
1402 }
1403
1404 #[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 #[must_use]
1417 pub fn ownership_check(&self) -> Arc<dyn OwnershipCheck> {
1418 Arc::clone(&self.ownership_check)
1419 }
1420
1421 #[must_use]
1423 pub fn uses_default_ownership_check(&self) -> bool {
1424 is_default_ownership_check(&self.ownership_check)
1425 }
1426
1427 #[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 #[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 #[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 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}