1use std::{
2 borrow::Cow,
3 io::{self, Read},
4 path::{Path, PathBuf},
5};
6
7pub use error::Error;
8
9use crate::{
10 BStr, BString, FullNameRef, PartialName, PartialNameRef, Reference, file,
11 name::is_pseudo_ref,
12 store_impl::{file::loose, packed},
13};
14
15impl file::Store {
26 pub fn try_find<'a, Name, E>(&self, partial: Name) -> Result<Option<Reference>, Error>
38 where
39 Name: TryInto<&'a PartialNameRef, Error = E>,
40 Error: From<E>,
41 {
42 let packed = self.assure_packed_refs_uptodate()?;
43 self.find_one_with_verified_input(partial.try_into()?, packed.as_ref().map(|b| &***b))
44 }
45
46 pub fn try_find_loose<'a, Name, E>(&self, partial: Name) -> Result<Option<loose::Reference>, Error>
52 where
53 Name: TryInto<&'a PartialNameRef, Error = E>,
54 Error: From<E>,
55 {
56 self.find_one_with_verified_input(partial.try_into()?, None)
57 .map(|r| r.map(Into::into))
58 }
59
60 pub fn try_find_packed<'a, Name, E>(
62 &self,
63 partial: Name,
64 packed: Option<&packed::Buffer>,
65 ) -> Result<Option<Reference>, Error>
66 where
67 Name: TryInto<&'a PartialNameRef, Error = E>,
68 Error: From<E>,
69 {
70 self.find_one_with_verified_input(partial.try_into()?, packed)
71 }
72
73 pub(crate) fn find_one_with_verified_input(
74 &self,
75 partial_name: &PartialNameRef,
76 packed: Option<&packed::Buffer>,
77 ) -> Result<Option<Reference>, Error> {
78 fn decompose_if(mut r: Reference, input_changed_to_precomposed: bool) -> Reference {
79 if input_changed_to_precomposed {
80 use gix_object::bstr::ByteSlice;
81 let decomposed = r
82 .name
83 .0
84 .to_str()
85 .ok()
86 .map(|name| gix_utils::str::decompose(name.into()));
87 if let Some(Cow::Owned(decomposed)) = decomposed {
88 r.name.0 = decomposed.into();
89 }
90 }
91 r
92 }
93 let mut buf = BString::default();
94 let mut precomposed_partial_name_storage = packed.filter(|_| self.precompose_unicode).and_then(|_| {
95 use gix_object::bstr::ByteSlice;
96 let precomposed = partial_name.0.to_str().ok()?;
97 let precomposed = gix_utils::str::precompose(precomposed.into());
98 match precomposed {
99 Cow::Owned(precomposed) => Some(PartialName(precomposed.into())),
100 Cow::Borrowed(_) => None,
101 }
102 });
103 let precomposed_partial_name = precomposed_partial_name_storage
104 .as_ref()
105 .map(std::convert::AsRef::as_ref);
106 for consider_pseudo_ref in [true, false] {
107 if !consider_pseudo_ref && !is_pseudo_ref(partial_name.as_bstr()) {
108 break;
109 }
110 'try_directories: for inbetween in &["", "tags", "heads", "remotes"] {
111 match self.find_inner(
112 inbetween,
113 partial_name,
114 precomposed_partial_name,
115 packed,
116 &mut buf,
117 consider_pseudo_ref,
118 ) {
119 Ok(Some(r)) => return Ok(Some(decompose_if(r, precomposed_partial_name.is_some()))),
120 Ok(None) => {
121 if consider_pseudo_ref && is_pseudo_ref(partial_name.as_bstr()) {
122 break 'try_directories;
123 }
124 continue;
125 }
126 Err(err) => return Err(err),
127 }
128 }
129 }
130 if partial_name.as_bstr() != "HEAD" {
131 if let Some(mut precomposed) = precomposed_partial_name_storage {
132 precomposed = precomposed.join("HEAD".into()).expect("HEAD is valid name");
133 precomposed_partial_name_storage = Some(precomposed);
134 }
135 self.find_inner(
136 "remotes",
137 partial_name
138 .to_owned()
139 .join("HEAD".into())
140 .expect("HEAD is valid name")
141 .as_ref(),
142 precomposed_partial_name_storage
143 .as_ref()
144 .map(std::convert::AsRef::as_ref),
145 None,
146 &mut buf,
147 true, )
149 .map(|res| res.map(|r| decompose_if(r, precomposed_partial_name_storage.is_some())))
150 } else {
151 Ok(None)
152 }
153 }
154
155 fn find_inner(
156 &self,
157 inbetween: &str,
158 partial_name: &PartialNameRef,
159 precomposed_partial_name: Option<&PartialNameRef>,
160 packed: Option<&packed::Buffer>,
161 path_buf: &mut BString,
162 consider_pseudo_ref: bool,
163 ) -> Result<Option<Reference>, Error> {
164 let full_name = precomposed_partial_name
165 .unwrap_or(partial_name)
166 .construct_full_name_ref(inbetween, path_buf, consider_pseudo_ref);
167 let content_buf = self.ref_contents(full_name).map_err(|err| Error::ReadFileContents {
168 source: err,
169 path: self.reference_path(full_name),
170 })?;
171
172 match content_buf {
173 None => {
174 if let Some(packed) = packed {
175 if let Some(full_name) = packed::find::transform_full_name_for_lookup(full_name) {
176 let full_name_backing;
177 let full_name = match &self.namespace {
178 Some(namespace) => {
179 full_name_backing = namespace.to_owned().into_namespaced_name(full_name);
180 full_name_backing.as_ref()
181 }
182 None => full_name,
183 };
184 if let Some(packed_ref) = packed.try_find_full_name(full_name)? {
185 let mut res: Reference = packed_ref.into();
186 if let Some(namespace) = &self.namespace {
187 res.strip_namespace(namespace);
188 }
189 return Ok(Some(res));
190 }
191 }
192 }
193 Ok(None)
194 }
195 Some(content) => Ok(Some(
196 loose::Reference::try_from_path(full_name.to_owned(), &content, self.object_hash)
197 .map(Into::into)
198 .map(|mut r: Reference| {
199 if let Some(namespace) = &self.namespace {
200 r.strip_namespace(namespace);
201 }
202 r
203 })
204 .map_err(|err| Error::ReferenceCreation {
205 source: err,
206 relative_path: full_name.to_path().to_owned(),
207 })?,
208 )),
209 }
210 }
211}
212
213impl file::Store {
214 pub(crate) fn to_base_dir_and_relative_name<'a>(
215 &self,
216 name: &'a FullNameRef,
217 is_reflog: bool,
218 ) -> (Cow<'_, Path>, &'a FullNameRef) {
219 let commondir = self.common_dir_resolved();
220 let linked_git_dir =
221 |worktree_name: &BStr| commondir.join("worktrees").join(gix_path::from_bstr(worktree_name));
222 name.category_and_short_name()
223 .map(|(c, sn)| {
224 use crate::Category::*;
225 let sn = FullNameRef::new_unchecked(sn);
226 match c {
227 LinkedPseudoRef { name: worktree_name } => {
228 if is_reflog {
229 (linked_git_dir(worktree_name).into(), sn)
230 } else {
231 (commondir.into(), name)
232 }
233 }
234 Tag | LocalBranch | RemoteBranch | Note => (commondir.into(), name),
235 MainRef | MainPseudoRef => (commondir.into(), sn),
236 LinkedRef { name: worktree_name } => {
237 if sn.category().is_some_and(|cat| cat.is_worktree_private()) {
238 if is_reflog {
239 (linked_git_dir(worktree_name).into(), sn)
240 } else {
241 (commondir.into(), name)
242 }
243 } else {
244 (commondir.into(), sn)
245 }
246 }
247 PseudoRef | Bisect | Rewritten | WorktreePrivate => (self.git_dir.as_path().into(), name),
248 }
249 })
250 .unwrap_or((commondir.into(), name))
251 }
252
253 pub(crate) fn reference_path_with_base<'b>(&self, name: &'b FullNameRef) -> (Cow<'_, Path>, Cow<'b, Path>) {
255 let (base, name) = self.to_base_dir_and_relative_name(name, false);
256 (
257 base,
258 match &self.namespace {
259 None => gix_path::to_native_path_on_windows(name.as_bstr()),
260 Some(namespace) => {
261 gix_path::to_native_path_on_windows(namespace.to_owned().into_namespaced_name(name).into_inner())
262 }
263 },
264 )
265 }
266
267 pub(crate) fn reference_path(&self, name: &FullNameRef) -> PathBuf {
269 let (base, relative_path) = self.reference_path_with_base(name);
270 base.join(relative_path)
271 }
272
273 pub(crate) fn ref_contents(&self, name: &FullNameRef) -> io::Result<Option<Vec<u8>>> {
275 let (base, relative_path) = self.reference_path_with_base(name);
276 if self.prohibit_windows_device_names
277 && relative_path
278 .components()
279 .filter_map(|c| gix_path::try_os_str_into_bstr(c.as_os_str().into()).ok())
280 .any(|c| gix_validate::path::component_is_windows_device(c.as_ref()))
281 {
282 return Err(std::io::Error::other(format!(
283 "Illegal use of reserved Windows device name in \"{}\"",
284 name.as_bstr()
285 )));
286 }
287
288 let ref_path = base.join(relative_path);
289 match std::fs::File::open(&ref_path) {
290 Ok(mut file) => {
291 let mut buf = Vec::with_capacity(128);
292 if let Err(err) = file.read_to_end(&mut buf) {
293 return if ref_path.is_dir() { Ok(None) } else { Err(err) };
294 }
295 Ok(buf.into())
296 }
297 Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
298 #[cfg(windows)]
299 Err(err) if err.kind() == std::io::ErrorKind::PermissionDenied => Ok(None),
300 Err(err) => Err(err),
301 }
302 }
303}
304
305pub mod existing {
307 pub use error::Error;
308
309 use crate::{
310 PartialNameRef, Reference,
311 file::{self},
312 store_impl::{
313 file::{find, loose},
314 packed,
315 },
316 };
317
318 impl file::Store {
319 pub fn find<'a, Name, E>(&self, partial: Name) -> Result<Reference, Error>
321 where
322 Name: TryInto<&'a PartialNameRef, Error = E>,
323 crate::name::Error: From<E>,
324 {
325 let packed = self.assure_packed_refs_uptodate().map_err(find::Error::PackedOpen)?;
326 self.find_existing_inner(partial, packed.as_ref().map(|b| &***b))
327 }
328
329 pub fn find_packed<'a, Name, E>(
331 &self,
332 partial: Name,
333 packed: Option<&packed::Buffer>,
334 ) -> Result<Reference, Error>
335 where
336 Name: TryInto<&'a PartialNameRef, Error = E>,
337 crate::name::Error: From<E>,
338 {
339 self.find_existing_inner(partial, packed)
340 }
341
342 pub fn find_loose<'a, Name, E>(&self, partial: Name) -> Result<loose::Reference, Error>
344 where
345 Name: TryInto<&'a PartialNameRef, Error = E>,
346 crate::name::Error: From<E>,
347 {
348 self.find_existing_inner(partial, None).map(Into::into)
349 }
350
351 pub(crate) fn find_existing_inner<'a, Name, E>(
353 &self,
354 partial: Name,
355 packed: Option<&packed::Buffer>,
356 ) -> Result<Reference, Error>
357 where
358 Name: TryInto<&'a PartialNameRef, Error = E>,
359 crate::name::Error: From<E>,
360 {
361 let path = partial
362 .try_into()
363 .map_err(|err| Error::Find(find::Error::RefnameValidation(err.into())))?;
364 match self.find_one_with_verified_input(path, packed) {
365 Ok(Some(r)) => Ok(r),
366 Ok(None) => Err(Error::NotFound {
367 name: path.to_partial_path().to_owned(),
368 }),
369 Err(err) => Err(err.into()),
370 }
371 }
372 }
373
374 mod error {
375 use std::path::PathBuf;
376
377 use crate::store_impl::file::find;
378
379 #[derive(Debug, thiserror::Error)]
381 #[allow(missing_docs)]
382 pub enum Error {
383 #[error("An error occurred while trying to find a reference")]
384 Find(#[from] find::Error),
385 #[error("The ref partially named {name:?} could not be found")]
386 NotFound { name: PathBuf },
387 }
388 }
389}
390
391mod error {
392 use std::{convert::Infallible, io, path::PathBuf};
393
394 use crate::{file, store_impl::packed};
395
396 #[derive(Debug, thiserror::Error)]
398 #[allow(missing_docs)]
399 pub enum Error {
400 #[error("The ref name or path is not a valid ref name")]
401 RefnameValidation(#[from] crate::name::Error),
402 #[error("The ref file {path:?} could not be read in full")]
403 ReadFileContents { source: io::Error, path: PathBuf },
404 #[error("The reference at \"{relative_path}\" could not be instantiated")]
405 ReferenceCreation {
406 source: file::loose::reference::decode::Error,
407 relative_path: PathBuf,
408 },
409 #[error("A packed ref lookup failed")]
410 PackedRef(#[from] packed::find::Error),
411 #[error("Could not open the packed refs buffer when trying to find references.")]
412 PackedOpen(#[from] packed::buffer::open::Error),
413 }
414
415 impl From<Infallible> for Error {
416 fn from(_: Infallible) -> Self {
417 unreachable!("this impl is needed to allow passing a known valid partial path as parameter")
418 }
419 }
420}