727 lines · 24.4 KB · Rust
RawDownload
#![allow(clippy::result_large_err)]use std::{    error::Error,    fmt::{Debug, Formatter},}; use gix_config::KeyRef; use crate::{    bstr::{BStr, ByteSlice},    config,    config::tree::{Key, Link, Note, Section, SubSectionRequirement},}; /// Implements a value without any constraints, i.e. a any value.#[derive(Copy, Clone)]pub struct Any<T: Validate = validate::All> {    /// The key of the value in the git configuration.    pub name: &'static str,    /// The parent section of the key.    pub section: &'static dyn Section,    /// The subsection requirement to use.    pub subsection_requirement: Option<SubSectionRequirement>,    /// A link to other resources that might be eligible as value.    pub link: Option<Link>,    /// A note about this key.    pub note: Option<Note>,    /// The way validation and transformation should happen.    validate: T,} /// Initimpl Any<validate::All> {    /// Create a new instance from `name` and `section`    pub const fn new(name: &'static str, section: &'static dyn Section) -> Self {        Any::new_with_validate(name, section, validate::All)    }} /// Init other validate implementationsimpl<T: Validate> Any<T> {    /// Create a new instance from `name` and `section`    pub const fn new_with_validate(name: &'static str, section: &'static dyn Section, validate: T) -> Self {        Any {            name,            section,            subsection_requirement: Some(SubSectionRequirement::Never),            link: None,            note: None,            validate,        }    }} /// Builderimpl<T: Validate> Any<T> {    /// Set the subsection requirement to non-default values.    pub const fn with_subsection_requirement(mut self, requirement: Option<SubSectionRequirement>) -> Self {        self.subsection_requirement = requirement;        self    }     /// Associate an environment variable with this key.    ///    /// This is mainly useful for enriching error messages.    pub const fn with_environment_override(mut self, var: &'static str) -> Self {        self.link = Some(Link::EnvironmentOverride(var));        self    }     /// Set a link to another key which serves as fallback to provide a value if this key is not set.    pub const fn with_fallback(mut self, key: &'static dyn Key) -> Self {        self.link = Some(Link::FallbackKey(key));        self    }     /// Attach an informative message to this key.    pub const fn with_note(mut self, message: &'static str) -> Self {        self.note = Some(Note::Informative(message));        self    }     /// Inform about a deviation in how this key is interpreted.    pub const fn with_deviation(mut self, message: &'static str) -> Self {        self.note = Some(Note::Deviation(message));        self    }} /// Conversionimpl<T: Validate> Any<T> {    /// Try to convert `value` into a refspec suitable for the `op` operation.    pub fn try_into_refspec(        &'static self,        value: impl gix_utils::AsBStr,        op: gix_refspec::parse::Operation,    ) -> Result<gix_refspec::RefSpec, config::refspec::Error> {        let value = value.as_bstr();        gix_refspec::parse(value.as_bstr(), op)            .map(|spec| spec.to_owned())            .map_err(|err| config::refspec::Error::from_value(self, value.into()).with_source(err))    }     /// Try to interpret `value` as UTF-8 encoded string.    pub fn try_into_string(        &'static self,        value: impl gix_utils::AsBStr,    ) -> Result<std::string::String, config::string::Error> {        use crate::bstr::ByteVec;        Vec::from(value.as_bstr().to_owned()).into_string().map_err(|err| {            let utf8_err = err.utf8_error().clone();            config::string::Error::from_value(self, err.into_vec().into()).with_source(utf8_err)        })    }} impl<T: Validate> Debug for Any<T> {    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {        self.logical_name().fmt(f)    }} impl<T: Validate> std::fmt::Display for Any<T> {    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {        f.write_str(&self.logical_name())    }} impl<T: Validate> Key for Any<T> {    fn name(&self) -> &str {        self.name    }     fn validate(&self, value: &BStr) -> Result<(), config::tree::key::validate::Error> {        Ok(self.validate.validate(value)?)    }     fn section(&self) -> &dyn Section {        self.section    }     fn subsection_requirement(&self) -> Option<&SubSectionRequirement> {        self.subsection_requirement.as_ref()    }     fn link(&self) -> Option<&Link> {        self.link.as_ref()    }     fn note(&self) -> Option<&Note> {        self.note.as_ref()    }} impl<T: Validate + Copy + Clone> gix_config::AsKey for Any<T> {    fn as_key(&self) -> gix_config::KeyRef<'_> {        self.try_as_key().expect("infallible")    }     fn try_as_key(&self) -> Option<KeyRef<'_>> {        let section_name = self.section.parent().map_or_else(|| self.section.name(), Section::name);        let subsection_name = if self.section.parent().is_some() {            Some(self.section.name().into())        } else {            None        };        let value_name = self.name;        gix_config::KeyRef {            section_name,            subsection_name,            value_name,        }        .into()    }} /// A key which represents a date.pub type Time = Any<validate::Time>; /// The `core.(filesRefLockTimeout|packedRefsTimeout)` keys, or any other lock timeout for that matter.pub type LockTimeout = Any<validate::LockTimeout>; /// The `core.compression`, `core.looseCompression` and `pack.compression` keys to validate compression values.pub type Compression = Any<validate::Compression>; /// Keys specifying durations in milliseconds.pub type DurationInMilliseconds = Any<validate::DurationInMilliseconds>; /// A key which represents any unsigned integer.pub type UnsignedInteger = Any<validate::UnsignedInteger>; /// A key that represents a remote name, either as url or symbolic name.pub type RemoteName = Any<validate::RemoteName>; /// A key that represents a boolean value.pub type Boolean = Any<validate::Boolean>; /// A key that represents an executable program, shell script or shell commands.////// Once obtained with [trusted_program()](crate::config::Snapshot::trusted_program())/// one can run it with [command::prepare()](gix_command::prepare), possibly after/// [obtaining](crate::Repository::command_context) and [setting](gix_command::Prepare::with_context)/// a git [command context](gix_command::Context) (depending on the commands needs).pub type Program = Any<validate::Program>; /// A key that represents an executable program as identified by name or path.////// Once obtained with [trusted_program()](crate::config::Snapshot::trusted_program())/// one can run it with [command::prepare()](gix_command::prepare), possibly after/// [obtaining](crate::Repository::command_context) and [setting](gix_command::Prepare::with_context)/// a git [command context](gix_command::Context) (depending on the commands needs).pub type Executable = Any<validate::Executable>; /// A key that represents a path (to a resource).pub type Path = Any<validate::Path>; /// A key that represents a URL.pub type Url = Any<validate::Url>; /// A key that represents a UTF-8 string.pub type String = Any<validate::String>; /// A key that represents a `RefSpec` for pushing.pub type PushRefSpec = Any<validate::PushRefSpec>; /// A key that represents a `RefSpec` for fetching.pub type FetchRefSpec = Any<validate::FetchRefSpec>; mod duration {    use std::time::Duration;     use crate::{        config,        config::tree::{Section, keys::DurationInMilliseconds},    };     impl DurationInMilliseconds {        /// Create a new instance.        pub const fn new_duration(name: &'static str, section: &'static dyn Section) -> Self {            Self::new_with_validate(name, section, super::validate::DurationInMilliseconds)        }         /// Return a valid duration as parsed from an integer that is interpreted as milliseconds.        pub fn try_into_duration(            &'static self,            value: Result<Option<i64>, gix_config::value::Error>,        ) -> Result<Option<std::time::Duration>, config::duration::Error> {            let Some(value) = value.map_err(|err| config::duration::Error::from(self).with_source(err))? else {                return Ok(None);            };            Ok(Some(match value {                val if val < 0 => Duration::from_secs(u64::MAX),                val => Duration::from_millis(val.try_into().expect("i64 to u64 always works if positive")),            }))        }    }} mod lock_timeout {    use std::time::Duration;     use gix_lock::acquire::Fail;     use crate::{        config,        config::tree::{Section, keys::LockTimeout},    };     impl LockTimeout {        /// Create a new instance.        pub const fn new_lock_timeout(name: &'static str, section: &'static dyn Section) -> Self {            Self::new_with_validate(name, section, super::validate::LockTimeout)        }         /// Return information on how long to wait for locked files.        pub fn try_into_lock_timeout(            &'static self,            value: Result<Option<i64>, gix_config::value::Error>,        ) -> Result<Option<gix_lock::acquire::Fail>, config::lock_timeout::Error> {            let Some(value) = value.map_err(|err| config::lock_timeout::Error::from(self).with_source(err))? else {                return Ok(None);            };            Ok(Some(match value {                val if val < 0 => Fail::AfterDurationWithBackoff(Duration::from_secs(u64::MAX)),                0 => Fail::Immediately,                val => Fail::AfterDurationWithBackoff(Duration::from_millis(                    val.try_into().expect("i64 to u64 always works if positive"),                )),            }))        }    }} mod compression {    use crate::{        config,        config::tree::{Section, keys::Compression},    };     impl Compression {        /// Create a new instance.        pub const fn new_compression(name: &'static str, section: &'static dyn Section) -> Self {            Self::new_with_validate(name, section, super::validate::Compression)        }         /// Convert `value` into a zlib compression level, where `-1` is mapped to the        /// zlib default, just like `git` does.        pub fn try_into_compression(            &'static self,            value: Result<Option<i64>, gix_config::value::Error>,        ) -> Result<Option<gix_zlib::Compression>, config::key::GenericError> {            let Some(value) = value.map_err(|err| config::key::GenericError::from(self).with_source(err))? else {                return Ok(None);            };            match value {                -1 => Ok(Some(gix_zlib::Compression::DEFAULT)),                level => i32::try_from(level)                    .ok()                    .and_then(gix_zlib::Compression::new)                    .map(Some)                    .ok_or_else(|| config::key::GenericError::from(self)),            }        }    }} mod refspecs {    use crate::config::tree::{        Section,        keys::{FetchRefSpec, PushRefSpec, validate},    };     impl PushRefSpec {        /// Create a new instance.        pub const fn new_push_refspec(name: &'static str, section: &'static dyn Section) -> Self {            Self::new_with_validate(name, section, validate::PushRefSpec)        }    }     impl FetchRefSpec {        /// Create a new instance.        pub const fn new_fetch_refspec(name: &'static str, section: &'static dyn Section) -> Self {            Self::new_with_validate(name, section, validate::FetchRefSpec)        }    }} mod url {    use crate::{        bstr::ByteSlice,        config,        config::tree::{            Section,            keys::{Url, validate},        },    };     impl Url {        /// Create a new instance.        pub const fn new_url(name: &'static str, section: &'static dyn Section) -> Self {            Self::new_with_validate(name, section, validate::Url)        }         /// Try to parse `value` as URL.        pub fn try_into_url(&'static self, value: impl gix_utils::AsBStr) -> Result<gix_url::Url, config::url::Error> {            let value = value.as_bstr();            gix_url::parse(value.as_bstr())                .map_err(|err| config::url::Error::from_value(self, value.into()).with_source(err))        }    }} impl String {    /// Create a new instance.    pub const fn new_string(name: &'static str, section: &'static dyn Section) -> Self {        Self::new_with_validate(name, section, validate::String)    }} impl Program {    /// Create a new instance.    pub const fn new_program(name: &'static str, section: &'static dyn Section) -> Self {        Self::new_with_validate(name, section, validate::Program)    }} impl Executable {    /// Create a new instance.    pub const fn new_executable(name: &'static str, section: &'static dyn Section) -> Self {        Self::new_with_validate(name, section, validate::Executable)    }} impl Path {    /// Create a new instance.    pub const fn new_path(name: &'static str, section: &'static dyn Section) -> Self {        Self::new_with_validate(name, section, validate::Path)    }} mod workers {    use crate::config::tree::{Section, keys::UnsignedInteger};     impl UnsignedInteger {        /// Create a new instance.        pub const fn new_unsigned_integer(name: &'static str, section: &'static dyn Section) -> Self {            Self::new_with_validate(name, section, super::validate::UnsignedInteger)        }         /// Convert `value` into a `usize` or wrap it into a specialized error.        pub fn try_into_usize(            &'static self,            value: Result<Option<i64>, gix_config::value::Error>,        ) -> Result<Option<usize>, crate::config::unsigned_integer::Error> {            let value = value.map_err(|err| crate::config::unsigned_integer::Error::from(self).with_source(err))?;            value                .map(|value| {                    value                        .try_into()                        .map_err(|_| crate::config::unsigned_integer::Error::from(self))                })                .transpose()        }         /// Convert `value` into a `u64` or wrap it into a specialized error.        pub fn try_into_u64(            &'static self,            value: Result<Option<i64>, gix_config::value::Error>,        ) -> Result<Option<u64>, crate::config::unsigned_integer::Error> {            let value = value.map_err(|err| crate::config::unsigned_integer::Error::from(self).with_source(err))?;            value                .map(|value| {                    value                        .try_into()                        .map_err(|_| crate::config::unsigned_integer::Error::from(self))                })                .transpose()        }         /// Convert `value` into a `u32` or wrap it into a specialized error.        pub fn try_into_u32(            &'static self,            value: Result<Option<i64>, gix_config::value::Error>,        ) -> Result<Option<u32>, crate::config::unsigned_integer::Error> {            let value = value.map_err(|err| crate::config::unsigned_integer::Error::from(self).with_source(err))?;            value                .map(|value| {                    value                        .try_into()                        .map_err(|_| crate::config::unsigned_integer::Error::from(self))                })                .transpose()        }    }} mod time {    use crate::{        bstr::ByteSlice,        config::tree::{            Section,            keys::{Time, validate},        },    };    use gix_error::Exn;     impl Time {        /// Create a new instance.        pub const fn new_time(name: &'static str, section: &'static dyn Section) -> Self {            Self::new_with_validate(name, section, validate::Time)        }         /// Convert the `value` into a date if possible, with `now` as reference time for relative dates.        pub fn try_into_time(            &self,            value: impl gix_utils::AsBStr,            now: Option<std::time::SystemTime>,        ) -> Result<gix_date::Time, Exn<gix_date::Error>> {            let value = value.as_bstr();            gix_date::parse(                value                    .as_bstr()                    .to_str()                    .map_err(|_| gix_date::Error::new_with_input("UTF8 conversion failed", value))?,                now,            )        }    }} mod boolean {    use crate::{        config,        config::tree::{            Section,            keys::{Boolean, validate},        },    };     impl Boolean {

Lines 1–500 of 727.

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t