use super::super::roots::{subdirs, Roots, GIT_OBJECTS_INFO_DIR};
use super::{bind, bind_over, read_only, shut_empty};
use base::paths::{
WorktreeGit, GIT_WORKTREES_DIR, GIT_WORKTREE_CONTROL_FILES, REPOSITORY_CONFIG_DIR,
};
use std::path::{Path, PathBuf};
pub(super) fn guard_linked(args: &mut Vec<String>, roots: &Roots, linked: &WorktreeGit) {
open_branch_ref(args, roots, linked);
let objects_info = linked.dir.join(GIT_OBJECTS_INFO_DIR);
if roots.opens(&objects_info) {
read_only(args, &objects_info);
}
}
pub(super) fn guard_entries(
args: &mut Vec<String>,
roots: &Roots,
repo: &Path,
open: bool,
make: bool,
) {
let admin = repo.join(GIT_WORKTREES_DIR);
let held = open && !roots.only_additional && hold_worktree_parent(args, &admin, make);
for worktree in subdirs(&admin) {
if held {
bind(args, "--bind", &worktree);
}
let linked_entry = roots
.worktree_git
.as_ref()
.is_some_and(|linked| linked.admin == worktree && roots.opens(&worktree));
for f in GIT_WORKTREE_CONTROL_FILES {
let file = worktree.join(f);
if linked_entry && file.symlink_metadata().is_err() {
bind_over(args, Path::new("/dev/null"), &file);
} else {
bind(args, "--ro-bind-try", &file);
}
}
}
}
pub(super) fn guard_links(args: &mut Vec<String>, roots: &Roots, made: &mut Vec<PathBuf>) {
for links in roots.paths.worktree_dirs_in(&roots.cwd) {
let guarded = roots.opens(&links) && !roots.only_additional;
if guarded && links.symlink_metadata().is_err() {
shut_empty(args, &links, made);
continue;
}
let held = guarded && hold_worktree_parent(args, &links, false);
for worktree in subdirs(&links) {
if held {
bind(args, "--bind", &worktree);
}
bind(args, "--ro-bind-try", &worktree.join(REPOSITORY_CONFIG_DIR));
}
}
}
fn open_branch_ref(args: &mut Vec<String>, roots: &Roots, linked: &WorktreeGit) {
let own = [linked.branch_ref(), linked.branch_ref_lock()];
let Some(dir) = own[0].parent().filter(|dir| dir.is_dir()) else {
return;
};
if !roots.opens(&own[0]) {
return;
}
bind(args, "--bind", dir);
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten().filter(|e| !own.contains(&e.path())) {
bind(args, "--ro-bind", &entry.path());
}
}
fn hold_worktree_parent(args: &mut Vec<String>, dir: &Path, make: bool) -> bool {
if make && dir.symlink_metadata().is_err() && std::fs::create_dir(dir).is_err() {
return false;
}
if !dir.symlink_metadata().is_ok_and(|m| m.is_dir()) {
return false;
}
bind(args, "--ro-bind", dir);
true
}