#![allow(clippy::result_large_err)]
use std::path::{Path, PathBuf};
use crate::{
Repository, ThreadSafeRepository,
bstr::{BStr, BString, ByteSlice},
worktree::Proxy,
};
#[expect(missing_docs)]
pub mod into_repo {
use std::path::PathBuf;
#[derive(Debug, thiserror::Error)]
#[expect(missing_docs)]
pub enum Error {
#[error(transparent)]
Open(#[from] crate::open::Error),
#[error("Worktree at '{}' is inaccessible", .base.display())]
MissingWorktree { base: PathBuf },
#[error(transparent)]
MissingGitDirFile(#[from] std::io::Error),
}
}
impl<'repo> Proxy<'repo> {
pub(crate) fn new(parent: &'repo Repository, git_dir: impl Into<PathBuf>) -> Self {
Proxy {
parent,
git_dir: git_dir.into(),
}
}
pub(crate) fn new_if_gitdir_file_exists(parent: &'repo Repository, git_dir: impl Into<PathBuf>) -> Option<Self> {
let git_dir = git_dir.into();
if git_dir.join("gitdir").is_file() {
Some(Proxy::new(parent, git_dir))
} else {
None
}
}
}
impl Proxy<'_> {
pub fn base(&self) -> std::io::Result<PathBuf> {
let git_dir = self.git_dir.join("gitdir");
let base_dot_git = gix_discover::path::from_plain_file_relative_to_file(&git_dir).ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("Required file '{}' does not exist", git_dir.display()),
)
})??;
Ok(gix_discover::path::without_dot_git_dir(base_dot_git))
}
pub fn git_dir(&self) -> &Path {
&self.git_dir
}
pub fn id(&self) -> &BStr {
gix_path::os_str_into_bstr(self.git_dir.file_name().expect("worktrees/ parent dir"))
.expect("no illformed UTF-8")
}
pub fn is_locked(&self) -> bool {
self.git_dir.join("locked").is_file()
}
pub fn lock_reason(&self) -> Option<BString> {
std::fs::read(self.git_dir.join("locked"))
.ok()
.map(|contents| contents.trim().into())
}
pub fn into_repo_with_possibly_inaccessible_worktree(self) -> Result<Repository, crate::open::Error> {
let base = self.base().ok();
let options = self.parent.options.clone().without_repository_environment_overrides();
let repo = ThreadSafeRepository::open_from_paths(self.git_dir, base, options)?;
Ok(repo.into())
}
pub fn into_repo(self) -> Result<Repository, into_repo::Error> {
let base = self.base()?;
if !base.is_dir() {
return Err(into_repo::Error::MissingWorktree { base });
}
let options = self.parent.options.clone().without_repository_environment_overrides();
let repo = ThreadSafeRepository::open_from_paths(self.git_dir, base.into(), options)?;
Ok(repo.into())
}
}