Skip to main content

gix_submodule/
access.rs

1use std::{collections::HashSet, path::Path};
2
3use bstr::{BStr, BString, ByteSlice};
4use gix_error::{ErrorExt, ExnMessageResult, ResultExt};
5
6use crate::{
7    File, IsActivePlatform,
8    config::{Branch, FetchRecurse, Ignore, Update},
9};
10
11/// High-Level Access
12///
13/// Note that all methods perform validation of the requested value and report issues right away.
14/// If a bypass is needed, use [`config()`](File::config()) for direct access.
15impl File {
16    /// Return the underlying configuration file.
17    ///
18    /// Note that it might have been merged with values from another configuration file and may
19    /// thus not be accurately reflecting that state of a `.gitmodules` file anymore.
20    pub fn config(&self) -> &gix_config::File {
21        &self.config
22    }
23
24    /// Return the path at which the `.gitmodules` file lives, if it is known.
25    pub fn config_path(&self) -> Option<&Path> {
26        self.config.sections().filter_map(|s| s.meta().path.as_deref()).next()
27    }
28
29    /// Return the unvalidated names of the submodules for which configuration is present.
30    ///
31    /// Note that these exact names have to be used for querying submodule values.
32    pub fn names(&self) -> impl Iterator<Item = &BStr> {
33        let mut seen = HashSet::<&BStr>::default();
34        self.config
35            .sections_by_name("submodule")
36            .into_iter()
37            .flatten()
38            .filter_map(move |s| {
39                s.header()
40                    .subsection_name()
41                    .filter(|_| s.meta().source == crate::init::META_MARKER)
42                    .filter(|name| seen.insert(*name))
43            })
44    }
45
46    /// Similar to [Self::is_active_platform()], but automatically applies it to each name to learn if a submodule is active or not.
47    pub fn names_and_active_state<'a>(
48        &'a self,
49        config: &'a gix_config::File,
50        defaults: gix_pathspec::Defaults,
51        attributes: &'a mut (
52                    dyn FnMut(
53            &BStr,
54            gix_pathspec::attributes::glob::pattern::Case,
55            bool,
56            &mut gix_pathspec::attributes::search::Outcome,
57        ) -> bool
58                        + 'a
59                ),
60    ) -> ExnMessageResult<impl Iterator<Item = (&'a BStr, ExnMessageResult<bool>)> + 'a> {
61        let mut platform = self.is_active_platform(config, defaults)?;
62        let iter = self
63            .names()
64            .map(move |name| (name, platform.is_active(config, name, attributes)));
65        Ok(iter)
66    }
67
68    /// Return a platform which allows to check if a submodule name is active or inactive.
69    /// Use `defaults` for parsing the pathspecs used to later match on names via `submodule.active` configuration retrieved from `config`.
70    ///
71    /// All `submodule.active` pathspecs are considered to be top-level specs and match the name of submodules, which are active
72    /// on inclusive match.
73    /// The full algorithm is described as [hierarchy of rules](https://git-scm.com/docs/gitsubmodules#_active_submodules).
74    pub fn is_active_platform(
75        &self,
76        config: &gix_config::File,
77        defaults: gix_pathspec::Defaults,
78    ) -> ExnMessageResult<IsActivePlatform> {
79        let search = config
80            .strings("submodule.active")
81            .map(|patterns| -> ExnMessageResult<_> {
82                let patterns = patterns
83                    .into_iter()
84                    .map(|pattern| gix_pathspec::parse(&pattern, defaults))
85                    .collect::<std::result::Result<Vec<_>, _>>()?;
86                gix_pathspec::Search::from_specs(patterns, None, std::path::Path::new(""))
87            })
88            .transpose()?;
89        Ok(IsActivePlatform { search })
90    }
91
92    /// Given the `relative_path` (as seen from the root of the worktree) of a submodule with possibly platform-specific
93    /// component separators, find the submodule's name associated with this path, or `None` if none was found.
94    ///
95    /// Note that this does a linear search and compares `relative_path` in a normalized form to the same form of the path
96    /// associated with the submodule.
97    pub fn name_by_path(&self, relative_path: &BStr) -> Option<&BStr> {
98        self.names()
99            .filter_map(|n| self.path(n).ok().map(|p| (n, p)))
100            .find_map(|(n, p)| (p == relative_path).then_some(n))
101    }
102}
103
104/// Per-Submodule Access
105impl File {
106    /// Return the path relative to the root directory of the working tree at which the submodule is expected to be checked out.
107    /// It's an error if the path doesn't exist as it's the only way to associate a path in the index with additional submodule
108    /// information, like the URL to fetch from.
109    /// Invalid path bytes are stored as `input` in [`gix_error::Message::values`].
110    /// After [wrapping](gix_error::Error::from_error()), inspect them with [metadata](gix_error::Error::metadata()).
111    ///
112    /// ### Deviation
113    ///
114    /// Git currently allows absolute paths to be used when adding submodules, but fails later as it can't find the submodule by
115    /// relative path anymore. Let's play it safe here.
116    pub fn path(&self, name: &BStr) -> ExnMessageResult<BString> {
117        let path_bstr = self.config.string(&format!("submodule.{name}.path")).ok_or_else(|| {
118            gix_error::validation(format!(
119                "The submodule '{name}' was missing its 'path' field or it was empty"
120            ))
121        })?;
122        if path_bstr.is_empty() {
123            return Err(gix_error::validation(format!(
124                "The submodule '{name}' was missing its 'path' field or it was empty"
125            ))
126            .into());
127        }
128        let path = gix_path::from_bstr(path_bstr.as_bstr());
129        if path.is_absolute() {
130            return Err(
131                gix_error::validation(format!("The path of submodule '{name}' needs to be relative"))
132                    .with("input", path_bstr)
133                    .into(),
134            );
135        }
136        if gix_path::normalize(path, "".as_ref()).is_none() {
137            return Err(
138                gix_error::validation("The path would lead outside of the repository worktree")
139                    .with("input", path_bstr)
140                    .into(),
141            );
142        }
143        Ok(path_bstr)
144    }
145
146    /// Retrieve the `url` field of the submodule named `name`. It's an error if it doesn't exist or is empty.
147    /// Parse failures include the URL bytes as `input` [metadata](gix_error::Exn::metadata()).
148    pub fn url(&self, name: &BStr) -> ExnMessageResult<gix_url::Url> {
149        let url = self.config.string(&format!("submodule.{name}.url")).ok_or_else(|| {
150            gix_error::validation(format!(
151                "The submodule '{name}' was missing its 'url' field or it was empty"
152            ))
153            .raise()
154        })?;
155
156        if url.is_empty() {
157            return Err(gix_error::validation(format!(
158                "The submodule '{name}' was missing its 'url' field or it was empty"
159            ))
160            .raise());
161        }
162        gix_url::Url::from_bytes(url.as_ref()).or_raise(|| {
163            gix_error::validation(format!("The url of submodule '{name}' could not be parsed")).with("input", url)
164        })
165    }
166
167    /// Retrieve the `update` field of the submodule named `name`, if present.
168    /// Invalid value or command bytes are stored as `input` in [`gix_error::Message::values`].
169    /// After [wrapping](gix_error::Error::from_error()), inspect them with [metadata](gix_error::Error::metadata()).
170    pub fn update(&self, name: &BStr) -> ExnMessageResult<Option<Update>> {
171        let mut value_is_from_modules_file = None;
172        let our_meta = self.config.meta();
173        let value: Update = match self.config.string_filter(&format!("submodule.{name}.update"), |meta| {
174            value_is_from_modules_file = Some(std::ptr::eq(meta, our_meta));
175            true
176        }) {
177            Some(v) => v.as_bstr().try_into().map_err(|()| {
178                gix_error::validation(format!("The 'update' field of submodule '{name}' was invalid")).with("input", v)
179            })?,
180            None => return Ok(None),
181        };
182
183        if let Update::Command(cmd) = &value
184            && value_is_from_modules_file.unwrap_or_default()
185        {
186            return Err(gix_error::validation(format!(
187                "The 'update' field of submodule '{name}' tried to set a command to be shared"
188            ))
189            .with("input", cmd.to_owned())
190            .into());
191        }
192        Ok(Some(value))
193    }
194
195    /// Retrieve the `branch` field of the submodule named `name`, or `None` if unset.
196    ///
197    /// Note that `Default` is implemented for [`Branch`].
198    /// Parse failures include the branch bytes as `input` [metadata](gix_error::Exn::metadata()).
199    pub fn branch(&self, name: &BStr) -> ExnMessageResult<Option<Branch>> {
200        let branch = match self.config.string(&format!("submodule.{name}.branch")) {
201            Some(v) => v,
202            None => return Ok(None),
203        };
204
205        Branch::try_from(branch.as_ref()).map(Some).or_raise(|| {
206            gix_error::validation(format!(
207                "The 'branch' field of submodule '{name}' couldn't be turned into a valid fetch refspec"
208            ))
209            .with("input", branch)
210        })
211    }
212
213    /// Retrieve the `fetchRecurseSubmodules` field of the submodule named `name`, or `None` if unset.
214    ///
215    /// Note that if it's unset, it should be retrieved from `fetch.recurseSubmodules` in the configuration.
216    /// Invalid value bytes are stored as `input` in [`gix_error::Message::values`].
217    /// After [wrapping](gix_error::Error::from_error()), inspect them with [metadata](gix_error::Error::metadata()).
218    pub fn fetch_recurse(&self, name: &BStr) -> ExnMessageResult<Option<FetchRecurse>> {
219        Ok(
220            FetchRecurse::new(self.config.boolean(&format!("submodule.{name}.fetchRecurseSubmodules"))).map_err(
221                |value| {
222                    gix_error::validation(format!(
223                        "The 'fetchRecurseSubmodules' field of submodule '{name}' was invalid"
224                    ))
225                    .with("input", value)
226                },
227            )?,
228        )
229    }
230
231    /// Retrieve the `ignore` field of the submodule named `name`, or `None` if unset.
232    /// Invalid value bytes are stored as `input` in [`gix_error::Message::values`].
233    /// After [wrapping](gix_error::Error::from_error()), inspect them with [metadata](gix_error::Error::metadata()).
234    pub fn ignore(&self, name: &BStr) -> ExnMessageResult<Option<Ignore>> {
235        Ok(self
236            .config
237            .string(&format!("submodule.{name}.ignore"))
238            .map(|value| {
239                Ignore::try_from(value.as_ref()).map_err(|()| {
240                    gix_error::validation(format!("The 'ignore' field of submodule '{name}' was invalid"))
241                        .with("input", value)
242                })
243            })
244            .transpose()?)
245    }
246
247    /// Retrieve the `shallow` field of the submodule named `name`, or `None` if unset.
248    ///
249    /// If `true`, the submodule will be checked out with `depth = 1`. If unset, `false` is assumed.
250    pub fn shallow(&self, name: &BStr) -> ExnMessageResult<Option<bool>> {
251        self.config.boolean(&format!("submodule.{name}.shallow"))
252    }
253}