Struct git_config::file::GitConfig[][src]

pub struct GitConfig<'event> { /* fields omitted */ }

High level git-config reader and writer.

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

impl<'event> GitConfig<'event>[src]

#[must_use]pub fn new() -> Self[src]

Constructs an empty git-config file.

pub fn value<'lookup, T: TryFrom<Cow<'event, [u8]>>>(
    &'event self,
    section_name: &'lookup str,
    subsection_name: Option<&'lookup str>,
    key: &'lookup str
) -> Result<T, GitConfigError<'lookup>>
[src]

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.

pub fn multi_value<'lookup, T: TryFrom<Cow<'event, [u8]>>>(
    &'event self,
    section_name: &'lookup str,
    subsection_name: Option<&'lookup str>,
    key: &'lookup str
) -> Result<Vec<T>, GitConfigError<'lookup>>
[src]

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>>
[src]

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>>
[src]

Returns an mutable section reference.

Errors

This function will return an error if the section and optional subsection do not exist.

pub fn new_section(
    &mut self,
    section_name: impl Into<Cow<'event, str>>,
    subsection_name: impl Into<Option<Cow<'event, str>>>
) -> MutableSection<'_, 'event>
[src]

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<'_>>
[src]

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>
[src]

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>>
[src]

Renames a section, modifying the last matching section.

Errors

Returns an error if the lookup

impl<'event> GitConfig<'event>[src]

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.

pub fn get_raw_value<'lookup>(
    &self,
    section_name: &'lookup str,
    subsection_name: Option<&'lookup str>,
    key: &'lookup str
) -> Result<Cow<'_, [u8]>, GitConfigError<'lookup>>
[src]

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>>
[src]

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.

pub fn get_raw_multi_value<'lookup>(
    &self,
    section_name: &'lookup str,
    subsection_name: Option<&'lookup str>,
    key: &'lookup str
) -> Result<Vec<Cow<'_, [u8]>>, GitConfigError<'lookup>>
[src]

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>>
[src]

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.

pub fn set_raw_value<'lookup>(
    &mut self,
    section_name: &'lookup str,
    subsection_name: Option<&'lookup str>,
    key: &'lookup str,
    new_value: Vec<u8>
) -> Result<(), GitConfigError<'lookup>>
[src]

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.

pub fn set_raw_multi_value<'lookup>(
    &mut self,
    section_name: &'lookup str,
    subsection_name: Option<&'lookup str>,
    key: &'lookup str,
    new_values: impl Iterator<Item = Cow<'event, [u8]>>
) -> Result<(), GitConfigError<'lookup>>
[src]

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

impl<'event> Clone for GitConfig<'event>[src]

impl<'event> Debug for GitConfig<'event>[src]

impl<'event> Default for GitConfig<'event>[src]

impl Display for GitConfig<'_>[src]

fn fmt(&self, f: &mut Formatter<'_>) -> Result[src]

Note that this is a best-effort attempt at printing a GitConfig. If there are non UTF-8 values in your config, this will NOT render as read.

impl<'event> Eq for GitConfig<'event>[src]

impl<'a> From<Parser<'a>> for GitConfig<'a>[src]

impl<'a> Into<Vec<u8, Global>> for GitConfig<'a>[src]

impl<'a> Into<Vec<u8, Global>> for &GitConfig<'a>[src]

impl<'event> PartialEq<GitConfig<'event>> for GitConfig<'event>[src]

impl<'event> StructuralEq for GitConfig<'event>[src]

impl<'event> StructuralPartialEq for GitConfig<'event>[src]

impl<'a> TryFrom<&'a [u8]> for GitConfig<'a>[src]

type Error = Error<'a>

The type returned in the event of a conversion error.

fn try_from(value: &'a [u8]) -> Result<Self, Self::Error>[src]

Convenience constructor. Attempts to parse the provided byte string into

impl<'a> TryFrom<&'a str> for GitConfig<'a>[src]

type Error = Error<'a>

The type returned in the event of a conversion error.

fn try_from(s: &'a str) -> Result<Self, Self::Error>[src]

Convenience constructor. Attempts to parse the provided string into a GitConfig. See parse_from_str for more information.

Auto Trait Implementations

impl<'event> RefUnwindSafe for GitConfig<'event>

impl<'event> Send for GitConfig<'event>

impl<'event> Sync for GitConfig<'event>

impl<'event> Unpin for GitConfig<'event>

impl<'event> UnwindSafe for GitConfig<'event>

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> Conv for T

impl<T> Conv for T

impl<T> FmtForward for T

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T> Pipe for T where
    T: ?Sized

impl<T> Pipe for T

impl<T> PipeAsRef for T

impl<T> PipeBorrow for T

impl<T> PipeDeref for T

impl<T> PipeRef for T

impl<T> Tap for T

impl<T> Tap for T

impl<T, U> TapAsRef<U> for T where
    U: ?Sized

impl<T, U> TapBorrow<U> for T where
    U: ?Sized

impl<T> TapDeref for T

impl<T> ToOwned for T where
    T: Clone
[src]

type Owned = T

The resulting type after obtaining ownership.

impl<T> ToString for T where
    T: Display + ?Sized
[src]

impl<T> TryConv for T

impl<T> TryConv for T

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.