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