Skip to content

Add GitConfig::from_env_paths with git-like sequence resolution #240

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 19, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 47 additions & 1 deletion git-config/src/file/git_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::{
collections::{HashMap, VecDeque},
convert::TryFrom,
fmt::Display,
path::Path,
path::{Path, PathBuf},
};

use crate::{
Expand Down Expand Up @@ -162,6 +162,49 @@ impl<'event> GitConfig<'event> {
Ok(config)
}

/// Constructs a `git-config` from the default cascading sequence.
/// This is neither zero-alloc nor zero-copy.
///
/// See https://git-scm.com/docs/git-config#FILES for details.
pub fn from_env_paths() -> Result<Self, ParserOrIoError<'static>> {
use std::env;

let mut paths = vec![];

if let Err(_) = env::var("GIT_CONFIG_NO_SYSTEM") {
if let Ok(git_config_system) = env::var("GIT_CONFIG_SYSTEM") {
paths.push(PathBuf::from(git_config_system))
} else {
// In git the fallback is set to a build time macro which defaults to /etc/gitconfig
paths.push(PathBuf::from("/etc/gitconfig"));
}
}

if let Ok(git_config_global) = env::var("GIT_CONFIG_GLOBAL") {
paths.push(PathBuf::from(git_config_global));
} else {
// Divergence from git-config(1)
// These two are supposed to share the same scope and override
// rather than append according to git-config(1) documentation.
if let Ok(xdg_config_home) = env::var("XDG_CONFIG_HOME") {
paths.push(PathBuf::from(xdg_config_home).join("git/config"));
} else if let Ok(home) = env::var("HOME") {
paths.push(PathBuf::from(home).join(".config/git/config"));
}

if let Ok(home) = env::var("HOME") {
paths.push(PathBuf::from(home).join(".gitconfig"));
}
}

if let Ok(git_dir) = env::var("GIT_DIR") {
paths.push(PathBuf::from(git_dir).join("config"));
}

let paths = paths.iter().map(PathBuf::as_path).collect::<Vec<&Path>>();
Self::from_paths(&paths)
}

/// Generates a config from the environment variables. This is neither
/// zero-copy nor zero-alloc. See [`git-config`'s documentation] on
/// environment variable for more information.
Expand Down Expand Up @@ -1622,6 +1665,9 @@ mod from_paths {
}
}

#[cfg(test)]
pub mod from_env_paths {}

#[cfg(test)]
mod from_env {
use std::env;
Expand Down