gix-config-value 0.20.0

A crate of the gitoxide project providing git-config value parsing
Documentation
use std::{borrow::Cow, ffi::OsString, fmt::Display};

use bstr::{BStr, BString};
use gix_error::{ErrorExt, Message, ResultExt, validation};

use crate::{Boolean, Integer};

fn bool_err(input: impl Into<BString>) -> Message {
    validation("Booleans need to be 'no', 'off', 'false', '' or 'yes', 'on', 'true' or any number")
        .with("input", gix_error::MetadataValue::Bytes(input.into()))
}

impl TryFrom<OsString> for Boolean {
    type Error = gix_error::Exn<gix_error::Message>;

    fn try_from(value: OsString) -> Result<Self, Self::Error> {
        let value = gix_path::os_str_into_bstr(&value)
            .or_raise(|| validation("Illformed UTF-8").with("input", value.as_encoded_bytes()))?;
        Self::try_from(value)
    }
}

/// # Deviation
///
/// Numeric values use [`Integer`]'s bases and `k`/`m`/`g` suffixes, with the full
/// `i64::MIN..=i64::MAX` range after applying the suffix. Zero is false; nonzero is true.
///
/// # Warning
///
/// The direct usage of `try_from("string")` is discouraged as it will produce the wrong result for values
/// obtained from `core.bool-implicit-true`, which have no separator and are implicitly true.
/// This method chooses to work correctly for `core.bool-empty=`, which is an empty string and resolves
/// to being `false`.
///
/// Instead of this, obtain booleans with `config.boolean(…)`, which handles the case were no separator is
/// present correctly.
impl TryFrom<&BStr> for Boolean {
    type Error = gix_error::Exn<gix_error::Message>;

    fn try_from(value: &BStr) -> Result<Self, Self::Error> {
        if parse_true(value) {
            Ok(Boolean(true))
        } else if parse_false(value) {
            Ok(Boolean(false))
        } else if let Some(integer) = Integer::try_from(value).ok().and_then(|integer| integer.to_decimal()) {
            Ok(Boolean(integer != 0))
        } else {
            Err(bool_err(value).raise())
        }
    }
}

impl TryFrom<&str> for Boolean {
    type Error = gix_error::Exn<gix_error::Message>;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::try_from(BStr::new(value))
    }
}

impl Boolean {
    /// Return true if the boolean is a true value.
    ///
    /// Note that the inner value is accessible directly as well.
    pub fn is_true(self) -> bool {
        self.0
    }
}

impl TryFrom<Cow<'_, BStr>> for Boolean {
    type Error = gix_error::Exn<gix_error::Message>;
    fn try_from(c: Cow<'_, BStr>) -> Result<Self, Self::Error> {
        Self::try_from(c.as_ref())
    }
}

impl TryFrom<BString> for Boolean {
    type Error = gix_error::Exn<gix_error::Message>;
    fn try_from(value: BString) -> Result<Self, Self::Error> {
        Self::try_from(BStr::new(&value))
    }
}

impl Display for Boolean {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl From<Boolean> for bool {
    fn from(b: Boolean) -> Self {
        b.0
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Boolean {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_bool(self.0)
    }
}

fn parse_true(value: &BStr) -> bool {
    value.eq_ignore_ascii_case(b"yes") || value.eq_ignore_ascii_case(b"on") || value.eq_ignore_ascii_case(b"true")
}

fn parse_false(value: &BStr) -> bool {
    value.eq_ignore_ascii_case(b"no")
        || value.eq_ignore_ascii_case(b"off")
        || value.eq_ignore_ascii_case(b"false")
        || value.is_empty()
}