Skip to main content

gix_submodule/
access.rs

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