gix-submodule 0.36.0

A crate of the gitoxide project dealing git submodules
Documentation
//! Primitives for describing git submodules.
#![deny(missing_docs)]
#![forbid(unsafe_code)]

use bstr::ByteSlice;
use gix_error::Result;

/// All relevant information about a git module, typically from `.gitmodules` files.
///
/// Note that overrides from other configuration might be relevant, which is why this type
/// can be used to take these into consideration when presented with other configuration
/// from the superproject.
#[derive(Clone)]
pub struct File {
    config: gix_config::File,
}

mod access;

///
pub mod config;

///
pub mod is_active_platform;

/// A platform to keep the state necessary to perform repeated active checks, created by [File::is_active_platform()].
pub struct IsActivePlatform {
    pub(crate) search: Option<gix_pathspec::Search>,
}

/// Mutation
impl File {
    /// This can be used to let `config` override some values we know about submodules, namely…
    ///
    /// * `url`
    /// * `fetchRecurseSubmodules`
    /// * `ignore`
    /// * `update`
    /// * `branch`
    ///
    /// These values aren't validated yet, which will happen upon query. The caller must provide
    /// trusted configuration; each copied value retains its section's origin metadata.
    pub fn append_submodule_overrides(&mut self, config: &gix_config::File) -> Result<&mut Self> {
        let mut config_to_append = gix_config::File::new(config.meta_owned());
        for (module_name, section) in config
            .sections_by_name("submodule")
            .into_iter()
            .flatten()
            .filter_map(|s| s.header().subsection_name().map(|n| (n, s)))
        {
            let values = ["url", "fetchRecurseSubmodules", "ignore", "update", "branch"]
                .map(|field| (field, section.value(field)));
            if values.iter().all(|(_, value)| value.is_none()) {
                continue;
            }
            config_to_append.set_meta(section.meta().clone());
            let mut destination = config_to_append.new_section("submodule", module_name)?;
            for (field, value) in values {
                if let Some(value) = value {
                    destination.push(field, Some(value.as_bstr()))?;
                }
            }
        }

        self.config.append(config_to_append)?;
        Ok(self)
    }
}

///
pub mod init {
    use gix_error::{Result, validation};
    use std::path::PathBuf;

    use gix_error::ResultExt;

    use crate::File;

    impl std::fmt::Debug for File {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.debug_struct("File")
                .field("config_path", &self.config_path())
                .field("config", &format_args!("r#\"{}\"#", self.config))
                .finish()
        }
    }

    impl File {
        /// Parse `bytes` as git configuration, typically from `.gitmodules`, without doing any further validation.
        /// `path` can be provided to keep track of where the file was read from in the underlying [`config`](Self::config())
        /// instance.
        /// `config` is used to [apply value overrides](File::append_submodule_overrides), which can be empty if overrides
        /// should be applied at a later time.
        ///
        /// Future access to the module information is lazy and configuration errors are exposed there on a per-value basis.
        ///
        /// ### Security Considerations
        ///
        /// The information itself should be used with care as it can direct the caller to fetch from remotes. It is, however,
        /// on the caller to assure the input data can be trusted.
        pub fn from_bytes(bytes: &[u8], path: impl Into<Option<PathBuf>>, config: &gix_config::File) -> Result<Self> {
            let metadata = {
                let mut meta = gix_config::file::Metadata::api();
                meta.path = path.into();
                meta
            };
            let modules = gix_config::File::from_parse_events_no_includes(
                gix_config::parse::Events::from_bytes(bytes, None)
                    .or_raise(|| validation("Could not parse submodule configuration"))?,
                metadata,
            );

            let mut res = Self { config: modules };
            res.append_submodule_overrides(config)
                .or_raise(|| validation("Could not apply submodule configuration overrides"))?;
            Ok(res)
        }

        /// Turn ourselves into the underlying parsed configuration file.
        pub fn into_config(self) -> gix_config::File {
            self.config
        }
    }
}