1use std::io;
4use std::path::{Path, PathBuf};
5
6use crate::error::{Error, Result};
7use crate::objects::odb::Odb;
8use crate::repo::RepositoryError;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12#[non_exhaustive]
13pub enum GitDirPathOperation {
14 WriteObject,
16 UpdateRef,
18 AppendReflog,
20 WriteIndex,
22 GcPack,
24 CreateDir,
26}
27
28impl GitDirPathOperation {
29 fn phrase(self) -> &'static str {
30 match self {
31 Self::WriteObject => "add an object to the object database",
32 Self::UpdateRef => "update the ref store",
33 Self::AppendReflog => "append to the reflog",
34 Self::WriteIndex => "write the index",
35 Self::GcPack => "run repository maintenance",
36 Self::CreateDir => "create a directory in the repository",
37 }
38 }
39}
40
41fn layout_uses_dot_git_prefix(git_dir: &Path) -> bool {
43 git_dir.file_name().is_some_and(|n| n == ".git")
44}
45
46fn normalize_repo_relative_suffix(rel: &str) -> String {
48 rel.trim_start_matches(['/', '\\']).replace('\\', "/")
49}
50
51fn format_layout_path(layout_git_dir: &Path, rel: &str) -> String {
53 if rel.is_empty() {
54 if layout_uses_dot_git_prefix(layout_git_dir) {
55 return ".git".to_owned();
56 }
57 return layout_git_dir
58 .file_name()
59 .map(|s| s.to_string_lossy().into_owned())
60 .unwrap_or_else(|| ".".into());
61 }
62 if layout_uses_dot_git_prefix(layout_git_dir) {
63 format!(".git/{rel}")
64 } else {
65 rel.to_owned()
66 }
67}
68
69#[must_use]
71pub fn display_ref_store_path(common_dir: &Path, checkout_git_dir: &Path, path: &Path) -> String {
72 let layout = if layout_uses_dot_git_prefix(common_dir) {
73 common_dir
74 } else {
75 checkout_git_dir
76 };
77 let rel = if let Ok(r) = path.strip_prefix(common_dir) {
78 normalize_repo_relative_suffix(&r.to_string_lossy())
79 } else if let Ok(tail) = path.strip_prefix(checkout_git_dir) {
80 let middle = checkout_git_dir
81 .strip_prefix(common_dir)
82 .map(|p| normalize_repo_relative_suffix(&p.to_string_lossy()))
83 .unwrap_or_default();
84 let tail = normalize_repo_relative_suffix(&tail.to_string_lossy());
85 if middle.is_empty() {
86 tail
87 } else {
88 format!("{middle}/{tail}")
89 }
90 } else {
91 return path.display().to_string();
92 };
93 format_layout_path(layout, &rel)
94}
95
96#[must_use]
98pub fn display_git_dir_path(git_dir: &Path, path: &Path) -> String {
99 if let Ok(rel) = path.strip_prefix(git_dir) {
100 let trimmed = normalize_repo_relative_suffix(&rel.to_string_lossy());
101 return format_layout_path(git_dir, &trimmed);
102 }
103 if layout_uses_dot_git_prefix(git_dir) {
104 if let Some(worktree) = git_dir.parent() {
105 if let Ok(rel) = path.strip_prefix(worktree) {
106 return normalize_repo_relative_suffix(&rel.to_string_lossy());
107 }
108 }
109 }
110 path.display().to_string()
111}
112
113#[must_use]
115pub fn git_dir_for_pack_io(odb: &Odb, pack_area_path: &Path) -> PathBuf {
116 if let Some(git_dir) = odb.config_git_dir() {
117 return git_dir.to_path_buf();
118 }
119 pack_area_path
120 .parent()
121 .and_then(|objects| objects.parent())
122 .map(Path::to_path_buf)
123 .unwrap_or_else(|| pack_area_path.to_path_buf())
124}
125
126#[must_use]
128pub fn git_dir_from_objects_dir(objects_dir: &Path) -> PathBuf {
129 objects_dir
130 .parent()
131 .map(Path::to_path_buf)
132 .unwrap_or_else(|| objects_dir.to_path_buf())
133}
134
135#[must_use]
137pub fn git_dir_from_pack_dir(pack_dir: &Path) -> PathBuf {
138 pack_dir
139 .parent()
140 .and_then(|objects| objects.parent())
141 .map(Path::to_path_buf)
142 .unwrap_or_else(|| pack_dir.to_path_buf())
143}
144
145#[must_use]
147pub fn is_git_dir_transient_contention(operation: GitDirPathOperation, source: &io::Error) -> bool {
148 if crate::worktree::io_error::is_file_in_use(source) {
149 return true;
150 }
151 matches!(
152 operation,
153 GitDirPathOperation::WriteIndex | GitDirPathOperation::UpdateRef
154 ) && crate::atomic_replace::is_replace_contention(source)
155}
156
157#[must_use]
159pub fn format_git_dir_io_message(
160 path: &str,
161 operation: GitDirPathOperation,
162 source: &io::Error,
163) -> String {
164 if is_git_dir_transient_contention(operation, source) {
165 format!(
166 "cannot {} ({path}): file is in use by another process (close it and retry)",
167 operation.phrase()
168 )
169 } else if source.kind() == io::ErrorKind::PermissionDenied {
170 format!(
171 "insufficient permission to {} ({path}): {source}",
172 operation.phrase()
173 )
174 } else {
175 format!("cannot {} ({path}): {source}", operation.phrase())
176 }
177}
178
179#[must_use]
181pub fn map_git_dir_io(
182 git_dir: &Path,
183 path: &Path,
184 operation: GitDirPathOperation,
185 source: io::Error,
186) -> Error {
187 RepositoryError::git_dir_path_io(display_git_dir_path(git_dir, path), operation, source).into()
188}
189
190#[must_use]
192pub fn map_ref_store_path_io(
193 common_dir: &Path,
194 checkout_git_dir: &Path,
195 path: &Path,
196 operation: GitDirPathOperation,
197 source: io::Error,
198) -> Error {
199 RepositoryError::git_dir_path_io(
200 display_ref_store_path(common_dir, checkout_git_dir, path),
201 operation,
202 source,
203 )
204 .into()
205}
206
207pub fn io_with_git_path<T>(
209 git_dir: &Path,
210 path: &Path,
211 operation: GitDirPathOperation,
212 result: io::Result<T>,
213) -> Result<T> {
214 result.map_err(|source| map_git_dir_io(git_dir, path, operation, source))
215}
216
217#[must_use]
219pub fn map_index_write_error(git_dir: &Path, index_path: &Path, err: Error) -> Error {
220 let display_path = if let Some(common) = crate::refs::common_dir(git_dir) {
221 display_ref_store_path(&common, git_dir, index_path)
222 } else {
223 display_git_dir_path(git_dir, index_path)
224 };
225 match err {
226 Error::Io(source) => {
227 RepositoryError::git_dir_path_io(display_path, GitDirPathOperation::WriteIndex, source)
228 .into()
229 }
230 other => other,
231 }
232}
233
234pub fn io_with_ref_store_path<T>(
236 common_dir: &Path,
237 checkout_git_dir: &Path,
238 path: &Path,
239 operation: GitDirPathOperation,
240 result: io::Result<T>,
241) -> Result<T> {
242 result.map_err(|source| {
243 map_ref_store_path_io(common_dir, checkout_git_dir, path, operation, source)
244 })
245}
246
247#[must_use]
249pub fn map_objects_dir_io(
250 objects_dir: &Path,
251 path: &Path,
252 operation: GitDirPathOperation,
253 source: io::Error,
254) -> Error {
255 let git_dir = git_dir_from_objects_dir(objects_dir);
256 map_git_dir_io(&git_dir, path, operation, source)
257}
258
259#[cfg(test)]
260mod tests {
261 use super::*;
262 use std::path::PathBuf;
263
264 #[test]
265 fn display_path_under_dot_git() {
266 let git = PathBuf::from("/tmp/pe/.git");
267 let path = git.join("objects/ab/cdef");
268 assert_eq!(display_git_dir_path(&git, &path), ".git/objects/ab/cdef");
269 }
270
271 #[test]
272 fn strip_prefix_suffix_normalizes_windows_separators() {
273 let git = PathBuf::from("/tmp/pe/.git");
274 let rel = normalize_repo_relative_suffix(r"\objects\ab\cdef");
275 assert_eq!(rel, "objects/ab/cdef");
276 assert_eq!(format_layout_path(&git, &rel), ".git/objects/ab/cdef");
277 }
278
279 #[cfg(windows)]
280 #[test]
281 fn display_path_under_dot_git_on_windows() {
282 let git = PathBuf::from(r"C:\Users\pe\repo\.git");
283 let path = PathBuf::from(r"C:\Users\pe\repo\.git\objects\ab\cdef");
284 let display = display_git_dir_path(&git, &path);
285 assert_eq!(display, ".git/objects/ab/cdef");
286 assert!(
287 !display.contains('\\'),
288 "git-dir display paths must use forward slashes: {display}"
289 );
290 }
291
292 #[test]
293 fn display_path_under_bare_repo() {
294 let git = PathBuf::from("/tmp/foo.git");
295 let path = git.join("objects/pack/tmp_repack_1");
296 assert_eq!(
297 display_git_dir_path(&git, &path),
298 "objects/pack/tmp_repack_1"
299 );
300 }
301
302 #[test]
303 fn storage_path_uses_dot_git_for_worktree_layout() {
304 let git = PathBuf::from("/tmp/wt/.git");
305 let common = PathBuf::from("/shared/commondir");
306 let path = common.join("refs/heads/main");
307 assert_eq!(
308 display_ref_store_path(&common, &git, &path),
309 ".git/refs/heads/main"
310 );
311 }
312
313 #[test]
314 fn ref_store_path_for_linked_worktree_head_lock() {
315 let common = PathBuf::from("/tmp/main/.git");
316 let admin = common.join("worktrees/linked");
317 let lock = admin.join("HEAD.lock");
318 assert_eq!(
319 display_ref_store_path(&common, &admin, &lock),
320 ".git/worktrees/linked/HEAD.lock"
321 );
322 }
323
324 #[test]
325 fn ref_store_path_for_bare_pack_staging() {
326 let bare = PathBuf::from("/tmp/repo.git");
327 let path = bare.join("objects/pack/tmp_repack_1");
328 assert_eq!(
329 display_ref_store_path(&bare, &bare, &path),
330 "objects/pack/tmp_repack_1"
331 );
332 }
333
334 #[test]
335 fn permission_message_names_git_path() {
336 let err = io::Error::from_raw_os_error(libc::EACCES as i32);
337 let msg = format_git_dir_io_message(".git/objects", GitDirPathOperation::WriteObject, &err);
338 assert!(msg.contains(".git/objects"));
339 assert!(msg.contains("insufficient permission"));
340 }
341
342 #[test]
343 fn sharing_violation_maps_to_in_use_message() {
344 let err = io::Error::from_raw_os_error(libc::EBUSY as i32);
345 let msg = format_git_dir_io_message(".git/index", GitDirPathOperation::WriteIndex, &err);
346 assert!(msg.contains("in use by another process"));
347 assert!(!msg.contains("insufficient permission"));
348 }
349
350 #[cfg(windows)]
351 #[test]
352 fn access_denied_maps_to_in_use_for_index_write_only() {
353 let err = io::Error::from_raw_os_error(5);
354 let index = format_git_dir_io_message(".git/index", GitDirPathOperation::WriteIndex, &err);
355 assert!(index.contains("in use by another process"));
356 let object =
357 format_git_dir_io_message(".git/objects", GitDirPathOperation::WriteObject, &err);
358 assert!(object.contains("insufficient permission"));
359 }
360}