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_by("submodule", Some(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    /// This is the raw configured URL, including any overrides. Relative URLs like `./module` or `../module`
136    /// remain unchanged and are parsed as local file paths. Relative URLs from `.gitmodules` must be
137    /// resolved against the superproject's remote before cloning or fetching; overrides are treated as initialized.
138    /// Parse failures include the URL bytes as `input` [metadata](gix_error::Error::metadata()).
139    pub fn url(&self, name: &BStr) -> Result<gix_url::Url> {
140        let url = self.config.string_by("submodule", Some(name), "url").ok_or_raise(|| {
141            message!("The submodule '{name}' was missing its 'url' field or it was empty").validation()
142        })?;
143
144        if url.is_empty() {
145            bail!("The submodule '{name}' was missing its 'url' field or it was empty".validation());
146        }
147        gix_url::Url::from_bytes(url.as_ref())
148            .or_raise(|| validation(format!("The url of submodule '{name}' could not be parsed")).with_input(url))
149    }
150
151    /// Retrieve the `update` field of the submodule named `name`, if present.
152    /// Invalid value or command bytes are stored as `input` in [`gix_error::Message::values`].
153    /// After [wrapping](gix_error::Error::from_error()), inspect them with [metadata](gix_error::Error::metadata()).
154    pub fn update(&self, name: &BStr) -> Result<Option<Update>> {
155        let mut value_is_from_modules_file = None;
156        let our_meta = self.config.meta();
157        let value: Update = match self.config.string_filter_by("submodule", Some(name), "update", |meta| {
158            value_is_from_modules_file = Some(std::ptr::eq(meta, our_meta));
159            true
160        }) {
161            Some(v) => v.as_bstr().try_into().map_err(|()| {
162                message!("The 'update' field of submodule '{name}' was invalid")
163                    .with_input(v)
164                    .validation_error()
165            })?,
166            None => return Ok(None),
167        };
168
169        if let Update::Command(cmd) = &value
170            && value_is_from_modules_file.unwrap_or_default()
171        {
172            bail!(
173                "The 'update' field of submodule '{name}' tried to set a command to be shared"
174                    .validation()
175                    .with_input(cmd.to_owned())
176            );
177        }
178        Ok(Some(value))
179    }
180
181    /// Retrieve the `branch` field of the submodule named `name`, or `None` if unset.
182    ///
183    /// Note that `Default` is implemented for [`Branch`].
184    /// Parse failures include the branch bytes as `input` [metadata](gix_error::Error::metadata()).
185    pub fn branch(&self, name: &BStr) -> Result<Option<Branch>> {
186        let branch = match self.config.string_by("submodule", Some(name), "branch") {
187            Some(v) => v,
188            None => return Ok(None),
189        };
190
191        Branch::try_from(branch.as_ref()).map(Some).or_raise(|| {
192            message!("The 'branch' field of submodule '{name}' couldn't be turned into a valid fetch refspec")
193                .validation()
194                .with_input(branch)
195        })
196    }
197
198    /// Retrieve the `fetchRecurseSubmodules` field of the submodule named `name`, or `None` if unset.
199    ///
200    /// Note that if it's unset, it should be retrieved from `fetch.recurseSubmodules` in the configuration.
201    /// Invalid value bytes are stored as `input` in [`gix_error::Message::values`].
202    /// After [wrapping](gix_error::Error::from_error()), inspect them with [metadata](gix_error::Error::metadata()).
203    pub fn fetch_recurse(&self, name: &BStr) -> Result<Option<FetchRecurse>> {
204        FetchRecurse::new(
205            self.config
206                .boolean_by("submodule", Some(name), "fetchRecurseSubmodules"),
207        )
208        .map_err(|value| {
209            message!("The 'fetchRecurseSubmodules' field of submodule '{name}' was invalid")
210                .with_input(value)
211                .validation_error()
212        })
213    }
214
215    /// Retrieve the `ignore` field of the submodule named `name`, or `None` if unset.
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 ignore(&self, name: &BStr) -> Result<Option<Ignore>> {
219        self.config
220            .string_by("submodule", Some(name), "ignore")
221            .map(|value| {
222                Ignore::try_from(value.as_ref()).map_err(|()| {
223                    message!("The 'ignore' field of submodule '{name}' was invalid")
224                        .with_input(value)
225                        .validation_error()
226                })
227            })
228            .transpose()
229    }
230
231    /// Retrieve the `shallow` field of the submodule named `name`, or `None` if unset.
232    ///
233    /// If `true`, the submodule will be checked out with `depth = 1`. If unset, `false` is assumed.
234    pub fn shallow(&self, name: &BStr) -> Result<Option<bool>> {
235        self.config.boolean_by("submodule", Some(name), "shallow")
236    }
237}