Skip to main content

gix_submodule/
access.rs

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