pub struct SnapshotMut<'repo> { /* private fields */ }
Expand description

A platform to access configuration values and modify them in memory, while making them available when this platform is dropped as form of auto-commit. Note that the values will only affect this instance of the parent repository, and not other clones that may exist.

Note that these values won’t update even if the underlying file(s) change.

Use forget() to not apply any of the changes.

Implementations

Utilities

Apply all changes made to this instance.

Note that this would also happen once this instance is dropped, but using this method may be more intuitive and won’t squelch errors in case the new configuration is partially invalid.

Create a structure the temporarily commits the changes, but rolls them back when dropped.

Don’t apply any of the changes after consuming this instance, effectively forgetting them, returning the changed configuration.

Apply configuration values of the form core.abbrev=5 or remote.origin.url = foo or core.bool-implicit-true to the repository configuration, marked with source CLI.

Methods from Deref<Target = File<'static>>

Like value(), but returning None if the string wasn’t found.

As strings perform no conversions, this will never fail.

Like string(), but the section containing the returned value must pass filter as well.

Like value(), but returning None if the path wasn’t found.

Note that this path is not vetted and should only point to resources which can’t be used to pose a security risk. Prefer using path_filter() instead.

As paths perform no conversions, this will never fail.

Like path(), but the section containing the returned value must pass filter as well.

This should be the preferred way of accessing paths as those from untrusted locations can be

As paths perform no conversions, this will never fail.

Like value(), but returning None if the boolean value wasn’t found.

Like boolean(), but the section containing the returned value must pass filter as well.

Like value(), but returning an Option if the integer wasn’t found.

Like integer(), but the section containing the returned value must pass filter as well.

Similar to values(…) but returning strings if at least one of them was found.

Similar to strings(…), but all values are in sections that passed filter.

Similar to values(…) but returning integers if at least one of them was found and if none of them overflows.

Similar to integers(…) but all integers are in sections that passed filter and that are not overflowing.

Returns the last mutable section with a given name and optional subsection_name, if it exists.

Return the mutable section identified by id, or None if it didn’t exist.

Note that id is stable across deletions and insertions.

Returns the last mutable section with a given name and optional subsection_name, if it exists, or create a new section.

Returns an mutable section with a given name and optional subsection_name, if it exists and passes filter, or create a new section.

Returns the last found mutable section with a given name and optional subsection_name, that matches filter, if it exists.

If there are sections matching section_name and subsection_name but the filter rejects all of them, Ok(None) is returned.

Adds a new section. 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 = git_config::File::default();
let section = git_config.new_section("hello", Some("world".into()))?;
let nl = section.newline().to_owned();
assert_eq!(git_config.to_string(), format!("[hello \"world\"]{nl}"));

Creating a new empty section and adding values to it:

let mut git_config = git_config::File::default();
let mut section = git_config.new_section("hello", Some("world".into()))?;
section.push(section::Key::try_from("a")?, Some("b".into()));
let nl = section.newline().to_owned();
assert_eq!(git_config.to_string(), format!("[hello \"world\"]{nl}\ta = b{nl}"));
let _section = git_config.new_section("core", None);
assert_eq!(git_config.to_string(), format!("[hello \"world\"]{nl}\ta = b{nl}[core]{nl}"));

Removes the section with name and subsection_name , returning it if there was a matching section. 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 = git_config::File::try_from(
r#"[hello "world"]
    some-value = 4
"#)?;

let section = 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 = git_config::File::try_from(
r#"[hello "world"]
    some-value = 4
[hello "world"]
    some-value = 5
"#)?;

let section = git_config.remove_section("hello", Some("world".into()));
assert_eq!(git_config.to_string(), "[hello \"world\"]\n    some-value = 4\n");

Remove the section identified by id if it exists and return it, or return None if no such section was present.

Note that section ids are unambiguous even in the face of removals and additions of sections.

Removes the section with name and subsection_name that passed filter, returning the removed section if at least one section matched the filter. 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.

Adds the provided section to the config, returning a mutable reference to it for immediate editing. Note that its meta-data will remain as is.

Renames the section with name and subsection_name, modifying the last matching section to use new_name and new_subsection_name.

Renames the section with name and subsection_name, modifying the last matching section that also passes filter to use new_name and new_subsection_name.

Note that the otherwise unused lookup::existing::Error::KeyMissing variant is used to indicate that the filter rejected all candidates, leading to no section being renamed after all.

Append another File to the end of ourselves, without losing any information.

Returns an uninterpreted value given a section, an optional subsection and key.

Consider Self::raw_values() if you want to get all values of a multivar instead.

Returns an uninterpreted value given a section, an optional subsection and key, if it passes the filter.

Consider Self::raw_values() if you want to get all values of a multivar instead.

Returns a mutable reference to an uninterpreted value given a section, an optional subsection and key.

Consider Self::raw_values_mut if you want to get mutable references to all values of a multivar instead.

Returns a mutable reference to an uninterpreted value given a section, an optional subsection and key, and if it passes filter.

Consider Self::raw_values_mut if you want to get mutable references to all values of a multivar instead.

Returns all uninterpreted values given a section, an optional subsection ain order of occurrence.

The ordering means that the last of the returned values is the one that would be the value used in the single-value case.nd 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.raw_values("core", None, "a").unwrap(),
    vec![
        Cow::<BStr>::Borrowed("b".into()),
        Cow::<BStr>::Borrowed("c".into()),
        Cow::<BStr>::Borrowed("d".into()),
    ],
);

Consider Self::raw_value if you want to get the resolved single value for a given key, if your key does not support multi-valued values.

Returns all uninterpreted values given a section, an optional subsection and key, if the value passes filter, in order of occurrence.

The ordering means that the last of the returned values is the one that would be the value used in the single-value case.

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.raw_values("core", None, "a")?,
    vec![
        Cow::<BStr>::Borrowed("b".into()),
        Cow::<BStr>::Borrowed("c".into()),
        Cow::<BStr>::Borrowed("d".into())
    ]
);

git_config.raw_values_mut("core", None, "a")?.set_all("g");

assert_eq!(
    git_config.raw_values("core", None, "a")?,
    vec![
        Cow::<BStr>::Borrowed("g".into()),
        Cow::<BStr>::Borrowed("g".into()),
        Cow::<BStr>::Borrowed("g".into())
    ],
);

Consider Self::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.

Returns mutable references to all uninterpreted values given a section, an optional subsection and key, if their sections pass filter.

Sets a value in a given section_name, optional subsection_name, and key. Note sections named section_name and subsection_name (if not None) must exist for this method to work.

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_existing_raw_value("core", None, "a", "e")?;
assert_eq!(git_config.raw_value("core", None, "a")?, Cow::<BStr>::Borrowed("e".into()));
assert_eq!(
    git_config.raw_values("core", None, "a")?,
    vec![
        Cow::<BStr>::Borrowed("b".into()),
        Cow::<BStr>::Borrowed("c".into()),
        Cow::<BStr>::Borrowed("e".into())
    ],
);

Sets a value in a given section_name, optional subsection_name, and key. Creates the section if necessary and the key as well, or overwrites the last existing value otherwise.

Examples

Given the config,

[core]
    a = b

Setting a new value to the key core.a will yield the following:

let prev = git_config.set_raw_value("core", None, "a", "e")?;
git_config.set_raw_value("core", None, "b", "f")?;
assert_eq!(prev.expect("present").as_ref(), "b");
assert_eq!(git_config.raw_value("core", None, "a")?, Cow::<BStr>::Borrowed("e".into()));
assert_eq!(git_config.raw_value("core", None, "b")?, Cow::<BStr>::Borrowed("f".into()));

Similar to set_raw_value(), but only sets existing values in sections matching filter, creating a new section otherwise.

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 raw_values_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![
    "x",
    "y",
    "z",
];
git_config.set_existing_raw_multi_value("core", None, "a", new_values.into_iter())?;
let fetched_config = git_config.raw_values("core", None, "a")?;
assert!(fetched_config.contains(&Cow::<BStr>::Borrowed("x".into())));
assert!(fetched_config.contains(&Cow::<BStr>::Borrowed("y".into())));
assert!(fetched_config.contains(&Cow::<BStr>::Borrowed("z".into())));

Setting less than the number of present values sets the first ones found:

let new_values = vec![
    "x",
    "y",
];
git_config.set_existing_raw_multi_value("core", None, "a", new_values.into_iter())?;
let fetched_config = git_config.raw_values("core", None, "a")?;
assert!(fetched_config.contains(&Cow::<BStr>::Borrowed("x".into())));
assert!(fetched_config.contains(&Cow::<BStr>::Borrowed("y".into())));

Setting more than the number of present values discards the rest:

let new_values = vec![
    "x",
    "y",
    "z",
    "discarded",
];
git_config.set_existing_raw_multi_value("core", None, "a", new_values)?;
assert!(!git_config.raw_values("core", None, "a")?.contains(&Cow::<BStr>::Borrowed("discarded".into())));

Returns an interpreted value given a section, an optional subsection and key.

It’s recommended to use one of the value types provide dby this crate as they implement the conversion, but this function is flexible and will accept any type that implements TryFrom<&BStr>.

Consider Self::values if you want to get all values of a multivar instead.

If a string is desired, use the string() method instead.

Examples
let config = r#"
    [core]
        a = 10k
        c = false
"#;
let git_config = git_config::File::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")?;

Like value(), but returning an None if the value wasn’t found at section[.subsection].key

Returns all interpreted values given a section, an optional subsection and key.

It’s recommended to use one of the value types provide dby this crate as they implement the conversion, but this function is flexible and will accept any type that implements TryFrom<&BStr>.

Consider Self::value if you want to get a single value (following last-one-wins resolution) instead.

To access plain strings, use the strings() method instead.

Examples
let config = r#"
    [core]
        a = true
        c
    [core]
        a
        a = false
"#;
let git_config = git_config::File::try_from(config).unwrap();
// You can either use the turbofish to determine the type...
let a_value = git_config.values::<Boolean>("core", None, "a")?;
assert_eq!(
    a_value,
    vec![
        Boolean(true),
        Boolean(false),
        Boolean(false),
    ]
);
// ... or explicitly declare the type to avoid the turbofish
let c_value: Vec<Boolean> = git_config.values("core", None, "c").unwrap();
assert_eq!(c_value, vec![Boolean(false)]);

Returns the last found immutable section with a given name and optional subsection_name.

Returns the last found immutable section with a given name and optional subsection_name, that matches filter.

If there are sections matching section_name and subsection_name but the filter rejects all of them, Ok(None) is returned.

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 = git_config::File::try_from(config)?;
assert_eq!(git_config.sections_by_name("core").map_or(0, |s|s.count()), 3);

Similar to sections_by_name(), but returns an identifier for this section as well to allow referring to it unambiguously even in the light of deletions.

Gets all sections that match the provided name, ignoring any subsections, and pass the filter.

Returns the number of values in the config, no matter in which section.

For example, a config with multiple empty sections will return 0. This ignores any comments.

Returns if there are no entries in the config. This will return true if there are only empty sections, with whitespace and comments not being considered void.

Return the file’s metadata to guide filtering of all values upon retrieval.

This is the metadata the file was instantiated with for use in all newly created sections.

Similar to meta(), but with shared ownership.

Return an iterator over all sections, in order of occurrence in the file itself.

Return an iterator over all sections and their ids, in order of occurrence in the file itself.

Return an iterator over all sections along with non-section events that are placed right after them, in order of occurrence in the file itself.

This allows to reproduce the look of sections perfectly when serializing them with write_to().

Return all events which are in front of the first of our sections, or None if there are none.

Return the newline characters that have been detected in this config file or the default ones for the current platform.

Note that the first found newline is the one we use in the assumption of consistency.

Traverse all include and includeIf directives found in this instance and follow them, loading the referenced files from their location and adding their content right past the value that included them.

Limitations
  • Note that this method is not idempotent and calling it multiple times will resolve includes multiple times. It’s recommended use is as part of a multi-step bootstrapping which needs fine-grained control, and unless that’s given one should prefer one of the other ways of initialization that resolve includes at the right time.
  • included values are added after the section that included them, not directly after the value. This is a deviation from how git does it, as it technically adds new value right after the include path itself, technically ‘splitting’ the section. This can only make a difference if the include section also has values which later overwrite portions of the included file, which seems unusual as these would be related to includes. We can fix this by ‘splitting’ the include section if needed so the included sections are put into the right place.

Serialize this type into a BString for convenience.

Note that to_string() can also be used, but might not be lossless.

Stream ourselves to the given out, in order to reproduce this file mostly losslessly as it was parsed.

Trait Implementations

Formats the value using the given formatter. Read more
The resulting type after dereferencing.
Dereferences the value.
Mutably dereferences the value.
Executes the destructor for this type. Read more

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

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The alignment of pointer.
The type for initializers.
Initializes a with the given initializer. Read more
Dereferences the given pointer. Read more
Mutably dereferences the given pointer. Read more
Drops the object pointed to by the given pointer. Read more
Should always be Self
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.