Struct git_config::file::GitConfig [−][src]
pub struct GitConfig<'event> { /* fields omitted */ }
Expand description
High level git-config
reader and writer.
This is the full-featured implementation that can deserialize, serialize,
and edit git-config
files without loss of whitespace or comments. As a
result, it’s lot more complex than it’s read-only variant,
ResolvedGitConfig
that exposes a HashMap
-like interface. Users that
only need to read git-config
files should use that instead.
Internally, this uses various acceleration data structures to improve performance of the typical usage behavior of many lookups and relatively fewer insertions.
Multivar behavior
git
is flexible enough to allow users to set a key multiple times in
any number of identically named sections. When this is the case, the key
is known as a “multivar”. In this case, get_raw_value
follows the
“last one wins” approach that git-config
internally uses for multivar
resolution.
Concretely, the following config has a multivar, a
, with the values
of b
, c
, and d
, while e
is a single variable with the value
f g h
.
[core]
a = b
a = c
[core]
a = d
e = f g h
Calling methods that fetch or set only one value (such as get_raw_value
)
key a
with the above config will fetch d
or replace d
, since the last
valid config key/value pair is a = d
:
assert_eq!(git_config.get_raw_value("core", None, "a"), Ok(Cow::Borrowed("d".as_bytes())));
Consider the multi
variants of the methods instead, if you want to work
with all values instead.
Implementations
Constructs a git-config
file from the provided path.
Errors
Returns an error if there was an IO error or if the file wasn’t a valid git-config file.
Constructs a git-config
file from the provided paths in the order provided.
This is neither zero-copy nor zero-alloc.
Errors
Returns an error if there was an IO error or if a file wasn’t a valid git-config file.
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.
Errors
Returns an error if GIT_CONFIG_COUNT
set and is not a number, or if
there was an invalid key value pair.
Returns an interpreted value given a section, an optional subsection and key.
It’s recommended to use one of the values in the values
module as
the conversion is already implemented, but this function is flexible and
will accept any type that implements TryFrom<&[u8]>
.
Consider Self::multi_value
if you want to get all values of a
multivar instead.
Examples
let config = r#"
[core]
a = 10k
c
"#;
let git_config = GitConfig::try_from(config)?;
// You can either use the turbofish to determine the type...
let a_value = git_config.value::<Integer>("core", None, "a")?;
// ... or explicitly declare the type to avoid the turbofish
let c_value: Boolean = git_config.value("core", None, "c")?;
Errors
This function will return an error if the key is not in the requested section and subsection, if the section and subsection do not exist, or if there was an issue converting the type into the requested variant.
Returns all interpreted values given a section, an optional subsection and key.
It’s recommended to use one of the values in the values
module as
the conversion is already implemented, but this function is flexible and
will accept any type that implements TryFrom<&[u8]>
.
Consider Self::value
if you want to get a single value
(following last-one-wins resolution) instead.
Examples
let config = r#"
[core]
a = true
c = g
[core]
a
a = false
"#;
let git_config = GitConfig::try_from(config).unwrap();
// You can either use the turbofish to determine the type...
let a_value = git_config.multi_value::<Boolean>("core", None, "a")?;
assert_eq!(
a_value,
vec![
Boolean::True(TrueVariant::Explicit(Cow::Borrowed("true"))),
Boolean::True(TrueVariant::Implicit),
Boolean::False(Cow::Borrowed("false")),
]
);
// ... or explicitly declare the type to avoid the turbofish
let c_value: Vec<Value> = git_config.multi_value("core", None, "c")?;
assert_eq!(c_value, vec![Value::Other(Cow::Borrowed(b"g"))]);
Errors
This function will return an error if the key is not in the requested section and subsection, if the section and subsection do not exist, or if there was an issue converting the type into the requested variant.
pub fn section<'lookup>(
&mut self,
section_name: &'lookup str,
subsection_name: Option<&'lookup str>
) -> Result<&SectionBody<'event>, GitConfigError<'lookup>>
pub fn section<'lookup>(
&mut self,
section_name: &'lookup str,
subsection_name: Option<&'lookup str>
) -> Result<&SectionBody<'event>, GitConfigError<'lookup>>
Returns an immutable section reference.
Errors
This function will return an error if the section and optional subsection do not exist.
pub fn section_mut<'lookup>(
&mut self,
section_name: &'lookup str,
subsection_name: Option<&'lookup str>
) -> Result<MutableSection<'_, 'event>, GitConfigError<'lookup>>
pub fn section_mut<'lookup>(
&mut self,
section_name: &'lookup str,
subsection_name: Option<&'lookup str>
) -> Result<MutableSection<'_, 'event>, GitConfigError<'lookup>>
Returns an mutable section reference.
Errors
This function will return an error if the section and optional subsection do not exist.
pub fn sections_by_name<'lookup>(
&self,
section_name: &'lookup str
) -> Vec<&SectionBody<'event>>
pub fn sections_by_name<'lookup>(
&self,
section_name: &'lookup str
) -> Vec<&SectionBody<'event>>
Gets all sections that match the provided name, ignoring any subsections.
Examples
Provided the following config:
[core]
a = b
[core ""]
c = d
[core "apple"]
e = f
Calling this method will yield all sections:
let config = r#"
[core]
a = b
[core ""]
c = d
[core "apple"]
e = f
"#;
let git_config = GitConfig::try_from(config).unwrap();
assert_eq!(git_config.sections_by_name("core").len(), 3);
pub fn new_section(
&mut self,
section_name: impl Into<Cow<'event, str>>,
subsection_name: impl Into<Option<Cow<'event, str>>>
) -> MutableSection<'_, 'event>
pub fn new_section(
&mut self,
section_name: impl Into<Cow<'event, str>>,
subsection_name: impl Into<Option<Cow<'event, str>>>
) -> MutableSection<'_, 'event>
Adds a new section to config. If a subsection name was provided, then the generated header will use the modern subsection syntax. Returns a reference to the new section for immediate editing.
Examples
Creating a new empty section:
let mut git_config = GitConfig::new();
let _section = git_config.new_section("hello", Some("world".into()));
assert_eq!(git_config.to_string(), "[hello \"world\"]\n");
Creating a new empty section and adding values to it:
let mut git_config = GitConfig::new();
let mut section = git_config.new_section("hello", Some("world".into()));
section.push("a".into(), "b".as_bytes().into());
assert_eq!(git_config.to_string(), "[hello \"world\"]\n a=b\n");
let _section = git_config.new_section("core", None);
assert_eq!(git_config.to_string(), "[hello \"world\"]\n a=b\n[core]\n");
pub fn remove_section<'lookup>(
&mut self,
section_name: &'lookup str,
subsection_name: impl Into<Option<&'lookup str>>
) -> Option<SectionBody<'_>>
pub fn remove_section<'lookup>(
&mut self,
section_name: &'lookup str,
subsection_name: impl Into<Option<&'lookup str>>
) -> Option<SectionBody<'_>>
Removes the section, returning the events it had, if any. If multiple sections have the same name, then the last one is returned. Note that later sections with the same name have precedent over earlier ones.
Examples
Creating and removing a section:
let mut git_config = GitConfig::try_from(
r#"[hello "world"]
some-value = 4
"#).unwrap();
let events = git_config.remove_section("hello", Some("world".into()));
assert_eq!(git_config.to_string(), "");
Precedence example for removing sections with the same name:
let mut git_config = GitConfig::try_from(
r#"[hello "world"]
some-value = 4
[hello "world"]
some-value = 5
"#).unwrap();
let events = git_config.remove_section("hello", Some("world".into()));
assert_eq!(git_config.to_string(), "[hello \"world\"]\n some-value = 4\n");
pub fn push_section(
&mut self,
section_name: impl Into<Cow<'event, str>>,
subsection_name: impl Into<Option<Cow<'event, str>>>,
section: SectionBody<'event>
) -> MutableSection<'_, 'event>
pub fn push_section(
&mut self,
section_name: impl Into<Cow<'event, str>>,
subsection_name: impl Into<Option<Cow<'event, str>>>,
section: SectionBody<'event>
) -> MutableSection<'_, 'event>
Adds the provided section to the config, returning a mutable reference to it.
pub fn rename_section<'lookup>(
&mut self,
section_name: &'lookup str,
subsection_name: impl Into<Option<&'lookup str>>,
new_section_name: impl Into<SectionHeaderName<'event>>,
new_subsection_name: impl Into<Option<Cow<'event, str>>>
) -> Result<(), GitConfigError<'lookup>>
pub fn rename_section<'lookup>(
&mut self,
section_name: &'lookup str,
subsection_name: impl Into<Option<&'lookup str>>,
new_section_name: impl Into<SectionHeaderName<'event>>,
new_subsection_name: impl Into<Option<Cow<'event, str>>>
) -> Result<(), GitConfigError<'lookup>>
Renames a section, modifying the last matching section.
Errors
Returns an error if the lookup doesn’t exist
Returns the number of entries in the config. This ignores any comments. For example, a config with multiple empty sections will return 0.
Raw value API
These functions are the raw value API. Instead of returning Rust structures, these functions return bytes which may or may not be owned.
Returns an uninterpreted value given a section, an optional subsection and key.
Consider Self::get_raw_multi_value
if you want to get all values of
a multivar instead.
Errors
This function will return an error if the key is not in the requested section and subsection, or if the section and subsection do not exist.
pub fn get_raw_value_mut<'lookup>(
&mut self,
section_name: &'lookup str,
subsection_name: Option<&'lookup str>,
key: &'lookup str
) -> Result<MutableValue<'_, 'lookup, 'event>, GitConfigError<'lookup>>
pub fn get_raw_value_mut<'lookup>(
&mut self,
section_name: &'lookup str,
subsection_name: Option<&'lookup str>,
key: &'lookup str
) -> Result<MutableValue<'_, 'lookup, 'event>, GitConfigError<'lookup>>
Returns a mutable reference to an uninterpreted value given a section, an optional subsection and key.
Consider Self::get_raw_multi_value_mut
if you want to get mutable
references to all values of a multivar instead.
Errors
This function will return an error if the key is not in the requested section and subsection, or if the section and subsection do not exist.
Returns all uninterpreted values given a section, an optional subsection and key.
Examples
If you have the following config:
[core]
a = b
[core]
a = c
a = d
Attempting to get all values of a
yields the following:
assert_eq!(
git_config.get_raw_multi_value("core", None, "a"),
Ok(vec![
Cow::<[u8]>::Borrowed(b"b"),
Cow::<[u8]>::Borrowed(b"c"),
Cow::<[u8]>::Borrowed(b"d"),
]),
);
Consider Self::get_raw_value
if you want to get the resolved single
value for a given key, if your key does not support multi-valued values.
Errors
This function will return an error if the key is not in any requested section and subsection, or if no instance of the section and subsections exist.
pub fn get_raw_multi_value_mut<'lookup>(
&mut self,
section_name: &'lookup str,
subsection_name: Option<&'lookup str>,
key: &'lookup str
) -> Result<MutableMultiValue<'_, 'lookup, 'event>, GitConfigError<'lookup>>
pub fn get_raw_multi_value_mut<'lookup>(
&mut self,
section_name: &'lookup str,
subsection_name: Option<&'lookup str>,
key: &'lookup str
) -> Result<MutableMultiValue<'_, 'lookup, 'event>, GitConfigError<'lookup>>
Returns mutable references to all uninterpreted values given a section, an optional subsection and key.
Examples
If you have the following config:
[core]
a = b
[core]
a = c
a = d
Attempting to get all values of a
yields the following:
assert_eq!(
git_config.get_raw_multi_value("core", None, "a")?,
vec![
Cow::Borrowed(b"b"),
Cow::Borrowed(b"c"),
Cow::Borrowed(b"d")
]
);
git_config.get_raw_multi_value_mut("core", None, "a")?.set_str_all("g");
assert_eq!(
git_config.get_raw_multi_value("core", None, "a")?,
vec![
Cow::Borrowed(b"g"),
Cow::Borrowed(b"g"),
Cow::Borrowed(b"g")
],
);
Consider Self::get_raw_value
if you want to get the resolved single
value for a given key, if your key does not support multi-valued values.
Note that this operation is relatively expensive, requiring a full traversal of the config.
Errors
This function will return an error if the key is not in any requested section and subsection, or if no instance of the section and subsections exist.
Sets a value in a given section, optional subsection, and key value.
Examples
Given the config,
[core]
a = b
[core]
a = c
a = d
Setting a new value to the key core.a
will yield the following:
git_config.set_raw_value("core", None, "a", vec![b'e'])?;
assert_eq!(git_config.get_raw_value("core", None, "a")?, Cow::Borrowed(b"e"));
Errors
This errors if any lookup input (section, subsection, and key value) fails.
Sets a multivar in a given section, optional subsection, and key value.
This internally zips together the new values and the existing values. As a result, if more new values are provided than the current amount of multivars, then the latter values are not applied. If there are less new values than old ones then the remaining old values are unmodified.
Note: Mutation order is not guaranteed and is non-deterministic.
If you need finer control over which values of the multivar are set,
consider using get_raw_multi_value_mut
, which will let you iterate
and check over the values instead. This is best used as a convenience
function for setting multivars whose values should be treated as an
unordered set.
Examples
Let us use the follow config for all examples:
[core]
a = b
[core]
a = c
a = d
Setting an equal number of values:
let new_values: Vec<Cow<'_, [u8]>> = vec![
Cow::Borrowed(b"x"),
Cow::Borrowed(b"y"),
Cow::Borrowed(b"z"),
];
git_config.set_raw_multi_value("core", None, "a", new_values.into_iter())?;
let fetched_config = git_config.get_raw_multi_value("core", None, "a")?;
assert!(fetched_config.contains(&Cow::Borrowed(b"x")));
assert!(fetched_config.contains(&Cow::Borrowed(b"y")));
assert!(fetched_config.contains(&Cow::Borrowed(b"z")));
Setting less than the number of present values sets the first ones found:
let new_values: Vec<Cow<'_, [u8]>> = vec![
Cow::Borrowed(b"x"),
Cow::Borrowed(b"y"),
];
git_config.set_raw_multi_value("core", None, "a", new_values.into_iter())?;
let fetched_config = git_config.get_raw_multi_value("core", None, "a")?;
assert!(fetched_config.contains(&Cow::Borrowed(b"x")));
assert!(fetched_config.contains(&Cow::Borrowed(b"y")));
Setting more than the number of present values discards the rest:
let new_values: Vec<Cow<'_, [u8]>> = vec![
Cow::Borrowed(b"x"),
Cow::Borrowed(b"y"),
Cow::Borrowed(b"z"),
Cow::Borrowed(b"discarded"),
];
git_config.set_raw_multi_value("core", None, "a", new_values.into_iter())?;
assert!(!git_config.get_raw_multi_value("core", None, "a")?.contains(&Cow::Borrowed(b"discarded")));
Errors
This errors if any lookup input (section, subsection, and key value) fails.
Trait Implementations
Auto Trait Implementations
impl<'event> RefUnwindSafe for GitConfig<'event>
impl<'event> UnwindSafe for GitConfig<'event>
Blanket Implementations
Mutably borrows from an owned value. Read more