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
11impl File {
16 pub fn config(&self) -> &gix_config::File {
21 &self.config
22 }
23
24 pub fn config_path(&self) -> Option<&Path> {
26 self.config.sections().filter_map(|s| s.meta().path.as_deref()).next()
27 }
28
29 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 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 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 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
104impl File {
106 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 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 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 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 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 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 pub fn shallow(&self, name: &BStr) -> ExnMessageResult<Option<bool>> {
251 self.config.boolean(&format!("submodule.{name}.shallow"))
252 }
253}