Skip to main content

gix_submodule/
lib.rs

1//! Primitives for describing git submodules.
2#![deny(missing_docs)]
3#![forbid(unsafe_code)]
4
5use gix_error::ExnMessageResult;
6use std::collections::BTreeMap;
7
8use bstr::ByteSlice;
9
10/// All relevant information about a git module, typically from `.gitmodules` files.
11///
12/// Note that overrides from other configuration might be relevant, which is why this type
13/// can be used to take these into consideration when presented with other configuration
14/// from the superproject.
15#[derive(Clone)]
16pub struct File {
17    config: gix_config::File,
18}
19
20mod access;
21
22///
23pub mod config;
24
25///
26pub mod is_active_platform;
27
28/// A platform to keep the state necessary to perform repeated active checks, created by [File::is_active_platform()].
29pub struct IsActivePlatform {
30    pub(crate) search: Option<gix_pathspec::Search>,
31}
32
33/// Mutation
34impl File {
35    /// This can be used to let `config` override some values we know about submodules, namely…
36    ///
37    /// * `url`
38    /// * `fetchRecurseSubmodules`
39    /// * `ignore`
40    /// * `update`
41    /// * `branch`
42    ///
43    /// These values aren't validated yet, which will happen upon query.
44    pub fn append_submodule_overrides(&mut self, config: &gix_config::File) -> ExnMessageResult<&mut Self> {
45        let mut values = BTreeMap::<_, Vec<_>>::new();
46        for (module_name, section) in config
47            .sections_by_name("submodule")
48            .into_iter()
49            .flatten()
50            .filter_map(|s| s.header().subsection_name().map(|n| (n, s)))
51        {
52            for field in ["url", "fetchRecurseSubmodules", "ignore", "update", "branch"] {
53                if let Some(value) = section.value(field) {
54                    values.entry((module_name, field)).or_default().push(value);
55                }
56            }
57        }
58
59        let values = {
60            let mut v: Vec<_> = values.into_iter().collect();
61            v.sort_by_key(|a| a.0.0);
62            v
63        };
64
65        let mut config_to_append = gix_config::File::new(config.meta_owned());
66        let mut prev_name = None;
67        for ((module_name, field), values) in values {
68            if prev_name != Some(module_name) {
69                config_to_append
70                    .new_section("submodule", module_name)
71                    .expect("all names come from valid configuration, so remain valid");
72                prev_name = Some(module_name);
73            }
74            config_to_append
75                .section_mut("submodule", Some(module_name))
76                .expect("always set at this point")
77                .push(
78                    field,
79                    Some(
80                        values
81                            .last()
82                            .expect("at least one value or we wouldn't be here")
83                            .as_bstr(),
84                    ),
85                )?;
86        }
87
88        self.config.append(config_to_append)?;
89        Ok(self)
90    }
91}
92
93///
94pub mod init {
95    use std::path::PathBuf;
96
97    use gix_error::{ExnMessageResult, ResultExt};
98
99    use crate::File;
100
101    impl std::fmt::Debug for File {
102        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103            f.debug_struct("File")
104                .field("config_path", &self.config_path())
105                .field("config", &format_args!("r#\"{}\"#", self.config))
106                .finish()
107        }
108    }
109
110    /// A marker we use when listing names to not pick them up from overridden sections.
111    pub(crate) const META_MARKER: gix_config::Source = gix_config::Source::Api;
112
113    impl File {
114        /// Parse `bytes` as git configuration, typically from `.gitmodules`, without doing any further validation.
115        /// `path` can be provided to keep track of where the file was read from in the underlying [`config`](Self::config())
116        /// instance.
117        /// `config` is used to [apply value overrides](File::append_submodule_overrides), which can be empty if overrides
118        /// should be applied at a later time.
119        ///
120        /// Future access to the module information is lazy and configuration errors are exposed there on a per-value basis.
121        ///
122        /// ### Security Considerations
123        ///
124        /// The information itself should be used with care as it can direct the caller to fetch from remotes. It is, however,
125        /// on the caller to assure the input data can be trusted.
126        pub fn from_bytes(
127            bytes: &[u8],
128            path: impl Into<Option<PathBuf>>,
129            config: &gix_config::File,
130        ) -> ExnMessageResult<Self> {
131            let metadata = {
132                let mut meta = gix_config::file::Metadata::from(META_MARKER);
133                meta.path = path.into();
134                meta
135            };
136            let modules = gix_config::File::from_parse_events_no_includes(
137                gix_config::parse::Events::from_bytes(bytes, None)
138                    .or_raise(|| gix_error::validation("Could not parse submodule configuration"))?,
139                metadata,
140            );
141
142            let mut res = Self { config: modules };
143            res.append_submodule_overrides(config)
144                .or_raise(|| gix_error::validation("Could not apply submodule configuration overrides"))?;
145            Ok(res)
146        }
147
148        /// Turn ourselves into the underlying parsed configuration file.
149        pub fn into_config(self) -> gix_config::File {
150            self.config
151        }
152    }
153}