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 an empty git-config file.

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.

Returns an immutable section reference.

Errors

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

Returns an mutable section reference.

Errors

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

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);

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");

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");

Adds the provided section to the config, returning a mutable reference to it.

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.

Returns if there are no entries in the config. This will return true if there are only empty sections or comments.

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.

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.

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

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

Returns the “default value” for a type. Read more

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.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

Convenience constructor. Attempts to parse the provided byte string into

The type returned in the event of a conversion error.

Convenience constructor. Attempts to parse the provided byte string into

The type returned in the event of a conversion error.

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

The type returned in the event of a conversion error.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Performs the conversion.

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

recently added

Uses borrowed data to replace owned data, usually by cloning. Read more

Converts the given value to a String. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.