Skip to main content

KeyFile

Struct KeyFile 

Source
pub struct KeyFile { /* private fields */ }
Expand description

A parsed key file, such as the repository config file.

A key file is an ordered list of groups. Each group is an ordered list of entries, and each entry is a key and its raw value text.

§Syntax

parse reads a subset of the GLib key file format:

  • A [group] line starts a group. The group name is the text from [ to the first ]. Only white space can follow the ].
  • A key=value line is an entry of the current group. The key is the text before the first =.
  • A line that starts with # is a comment line. Only # starts a comment. A # in a value is part of the value.
  • A blank line has no text or only white space.
  • A line ends with LF or with CRLF. The parser removes one carriage return at the end of a line.

The parser uses ASCII space and tab as white space:

  • It ignores this white space around a blank line, a comment line, and a group header.
  • It removes this white space around a key and at the start of a value.
  • It keeps the white space at the end of a value.
  • It keeps a non-breaking space (U+00A0) and all other non-ASCII white space everywhere.

The parser keeps the group order, the key order, and the raw value text. It drops comment lines and blank lines. A repeated group header merges into the group of the first header. A repeated key keeps its first position and takes the last value.

§Writes

get_value returns the raw value text. The typed getters unescape the value on read, and get_string_list also splits it into items.

The Display output parses to an equal KeyFile. A rewritten file keeps the groups and the keys that the caller did not change, in their order and with their value text. It does not keep the comment lines and the blank lines of the input. The ostree command rewrites a config file in the same way.

§Examples

use ostrya_core::KeyFile;

let mut config = KeyFile::parse("[core]\nrepo_version=1\nmode=archive-z2\n")?;
assert_eq!(config.get_value("core", "mode"), Some("archive-z2"));
assert_eq!(config.get_integer("core", "repo_version")?, Some(1));

config.set_string("core", "fsync", "false")?;
assert_eq!(
    config.to_string(),
    "[core]\nrepo_version=1\nmode=archive-z2\nfsync=false\n",
);

Implementations§

Source§

impl KeyFile

Source

pub fn parse(input: &str) -> Result<KeyFile, Error>

Parses a key file from text.

The rules are in KeyFile syntax.

§Errors

Error::KeyFile with one of these reasons, after a “line N:” prefix:

  • “group header is not closed with ‘]’” if a line starts with [ and has no ].
  • “group header has trailing text after ‘]’” if text other than white space follows the first ].
  • “empty group name” if the group name is empty.
  • “group name ‘NAME’ contains ‘[’ or ‘]’” if the group name contains a [.
  • “expected a key=value pair” if a line is not blank, not a comment, not a group header, and has no =.
  • “empty key” if the text before the = is empty or only white space.
  • “key ‘KEY’ precedes any group” if an entry comes before the first group header.
Source

pub fn has_group(&self, group: &str) -> bool

Returns true if the key file has the group group.

Source

pub fn group_name(&self, group: &str) -> Option<&str>

Returns the name of the group group as the key file holds it, or None if the key file has no such group.

The name is equal to group. It borrows from the key file, so it lives as long as the key file and not as long as group.

Source

pub fn groups(&self) -> impl Iterator<Item = &str>

Returns an iterator over the group names in file order.

Source

pub fn keys(&self, group: &str) -> impl Iterator<Item = &str>

Returns an iterator over the keys of one group in file order.

If the group is absent, the iterator is empty.

Source

pub fn get_value(&self, group: &str, key: &str) -> Option<&str>

Returns the raw value text of a key.

The text keeps its escape sequences. If the group or the key is absent, the method returns None.

Source

pub fn get_string( &self, group: &str, key: &str, ) -> Result<Option<String>, Error>

Returns the unescaped string value of a key.

The method replaces each escape sequence with its character:

  • \s with a space
  • \t with a tab
  • \n with a newline
  • \r with a carriage return
  • \\ with a backslash
  • \; with a ;

If the group or the key is absent, the method returns Ok(None).

§Errors
  • Error::KeyFile with the reason “invalid escape ‘\X’” if a backslash comes before a character X that is not in the list.
  • Error::KeyFile with the reason “value ends with a lone backslash” if the value ends with a backslash that starts no escape sequence.
Source

pub fn get_bool(&self, group: &str, key: &str) -> Result<Option<bool>, Error>

Returns the boolean value of a key.

The value text true or 1 gives true, and false or 0 gives false. The match is exact. If the group or the key is absent, the method returns Ok(None).

§Errors

Error::KeyFile with the reason “value ‘VALUE’ for GROUP.KEY is not a boolean” if the value text is not one of the four values.

Source

pub fn get_integer(&self, group: &str, key: &str) -> Result<Option<i64>, Error>

Returns the signed integer value of a key.

The value text is a decimal i64 with an optional - sign. If the group or the key is absent, the method returns Ok(None).

§Errors

Error::KeyFile with the reason “value ‘VALUE’ for GROUP.KEY is not an integer” if the value text is not a decimal i64. White space in the text and a leading + sign cause this error.

Source

pub fn get_string_list( &self, group: &str, key: &str, ) -> Result<Option<Vec<String>>, Error>

Returns the list value of a key as unescaped strings.

A ; separates two items, and \; is a ; in an item. The text after the last ; is an item only if it is not empty, so a trailing ; adds no empty item. The method unescapes each item as get_string does. If the group or the key is absent, the method returns Ok(None).

§Errors
  • Error::KeyFile with the reason “invalid escape ‘\X’” if a backslash comes before a character X that get_string does not accept.
  • Error::KeyFile with the reason “value ends with a lone backslash” if the value ends with a backslash that starts no escape sequence.
Source

pub fn set_value( &mut self, group: &str, key: &str, value: &str, ) -> Result<(), Error>

Sets the raw value text of a key.

If the group is absent, the method adds it at the end of the file. If the key is present, the new value replaces the old value at the same position. If the key is absent, the method adds it at the end of the group.

The method does not escape the value. set_string escapes it.

The method checks the group name, the key, and the value, so that the Display output parses to an equal KeyFile. If a check fails, the key file does not change.

§Errors

Error::KeyFile if one of these conditions is true:

  • The group name is empty.
  • The group name contains [, ], a newline, or a carriage return.
  • The key is empty.
  • The key starts or ends with a space or a tab.
  • The key contains =, a newline, or a carriage return.
  • The key starts with # or [.
  • The value contains a newline or a carriage return.
  • The value starts with a space or a tab.
Source

pub fn set_string( &mut self, group: &str, key: &str, value: &str, ) -> Result<(), Error>

Sets the string value of a key and escapes the value.

The method escapes the value as the ostree command does when it writes a value:

  • A backslash becomes \\, a newline \n, and a carriage return \r, at each position in the value.
  • In the run of white space at the start of the value, each space becomes \s and each tab \t.
  • A space or a tab after that run, and a ;, stay as they are.

The escaped value parses again to the same text, and get_string returns the original value. The method places the group and the key as set_value does. set_value stores a value that is already escaped.

§Errors

Error::KeyFile if the group name or the key fails a check of set_value. The escaped value always passes the checks.

Source

pub fn set_string_list( &mut self, group: &str, key: &str, items: &[impl AsRef<str>], ) -> Result<(), Error>

Sets the list value of a key and escapes each item.

get_string_list returns the same list. The method escapes each item as set_string escapes a value, so each space and tab at the start of an item becomes \s or \t. A ; in an item becomes \;.

A ; follows each item, also the last item. An empty list gives an empty value. Because the last item always has a separator, an empty item reads back: ["a", ""] gives a;;, and [""] gives ;.

§Errors

Error::KeyFile if the group name or the key fails a check of set_value. The escaped value always passes the checks.

Source

pub fn remove_key(&mut self, group: &str, key: &str) -> bool

Removes one key and returns true if the key was present.

The group stays, also when it loses its last key. The ostree command keeps the header of an empty group in the same way. Display writes the header with no entries.

Source

pub fn remove_group(&mut self, group: &str) -> bool

Removes a group and its keys, and returns true if the group was present.

The other groups keep their order.

Trait Implementations§

Source§

impl Clone for KeyFile

Source§

fn clone(&self) -> KeyFile

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for KeyFile

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Default for KeyFile

Source§

fn default() -> KeyFile

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

impl Display for KeyFile

Writes the groups and the keys in file order, in the GLib key file layout.

Each group starts with a [name] line, and each entry is a key=value line. A blank line separates two groups. to_string gives the text of the whole file.

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Eq for KeyFile

Source§

impl PartialEq for KeyFile

Source§

fn eq(&self, other: &KeyFile) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more

Auto Trait Implementations§

§

impl Forget for KeyFile

§

impl Freeze for KeyFile

§

impl Move for KeyFile

§

impl RefUnwindSafe for KeyFile

§

impl Send for KeyFile
where RawVecInner: Send, RawTable<(String, usize)>: Send,

§

impl Sync for KeyFile
where RawVecInner: Sync, RawTable<(String, usize)>: Sync,

§

impl Unpin for KeyFile
where *const u8 is !null: Unpin,

§

impl UnsafeUnpin for KeyFile

§

impl UnwindSafe for KeyFile
where RawVecInner: UnwindSafe, HashMap<String, usize>: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> Conv for T

Source§

fn conv<T>(self) -> T
where Self: Into<T>,

Converts self into T using Into<T>. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> FmtForward for T

Source§

fn fmt_binary(self) -> FmtBinary<Self>
where Self: Binary,

Causes self to use its Binary implementation when Debug-formatted.
Source§

fn fmt_display(self) -> FmtDisplay<Self>
where Self: Display,

Causes self to use its Display implementation when Debug-formatted.
Source§

fn fmt_lower_exp(self) -> FmtLowerExp<Self>
where Self: LowerExp,

Causes self to use its LowerExp implementation when Debug-formatted.
Source§

fn fmt_lower_hex(self) -> FmtLowerHex<Self>
where Self: LowerHex,

Causes self to use its LowerHex implementation when Debug-formatted.
Source§

fn fmt_octal(self) -> FmtOctal<Self>
where Self: Octal,

Causes self to use its Octal implementation when Debug-formatted.
Source§

fn fmt_pointer(self) -> FmtPointer<Self>
where Self: Pointer,

Causes self to use its Pointer implementation when Debug-formatted.
Source§

fn fmt_upper_exp(self) -> FmtUpperExp<Self>
where Self: UpperExp,

Causes self to use its UpperExp implementation when Debug-formatted.
Source§

fn fmt_upper_hex(self) -> FmtUpperHex<Self>
where Self: UpperHex,

Causes self to use its UpperHex implementation when Debug-formatted.
Source§

fn fmt_list(self) -> FmtList<Self>
where &'a Self: for<'a> IntoIterator,

Formats each item in a sequence. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

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

Source§

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

Source§

fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R
where Self: Sized,

Pipes by value. This is generally the method you want to use. Read more
Source§

fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> R
where R: 'a,

Borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> R
where R: 'a,

Mutably borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
where Self: Borrow<B>, B: 'a + ?Sized, R: 'a,

Borrows self, then passes self.borrow() into the pipe function. Read more
Source§

fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
where Self: BorrowMut<B>, B: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
Source§

fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
where Self: AsRef<U>, U: 'a + ?Sized, R: 'a,

Borrows self, then passes self.as_ref() into the pipe function.
Source§

fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
where Self: AsMut<U>, U: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.as_mut() into the pipe function.
Source§

fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
where Self: Deref<Target = T>, T: 'a + ?Sized, R: 'a,

Borrows self, then passes self.deref() into the pipe function.
Source§

fn pipe_deref_mut<'a, T, R>( &'a mut self, func: impl FnOnce(&'a mut T) -> R, ) -> R
where Self: DerefMut<Target = T> + Deref, T: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.deref_mut() into the pipe function.
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> Tap for T

Source§

fn tap(self, func: impl FnOnce(&Self)) -> Self

Immutable access to a value. Read more
Source§

fn tap_mut(self, func: impl FnOnce(&mut Self)) -> Self

Mutable access to a value. Read more
Source§

fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Immutable access to the Borrow<B> of a value. Read more
Source§

fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Mutable access to the BorrowMut<B> of a value. Read more
Source§

fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Immutable access to the AsRef<R> view of a value. Read more
Source§

fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Mutable access to the AsMut<R> view of a value. Read more
Source§

fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Immutable access to the Deref::Target of a value. Read more
Source§

fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Mutable access to the Deref::Target of a value. Read more
Source§

fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self

Calls .tap() only in debug builds, and is erased in release builds.
Source§

fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self

Calls .tap_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Calls .tap_borrow() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Calls .tap_borrow_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Calls .tap_ref() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Calls .tap_ref_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Calls .tap_deref() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

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

fn clone_into(&self, target: &mut T)

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

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T> TryConv for T

Source§

fn try_conv<T>(self) -> Result<T, Self::Error>
where Self: TryInto<T>,

Attempts to convert self into T using TryInto<T>. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

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

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more