use std::{
cell::{Ref, RefCell, RefMut},
ops::ControlFlow,
path::{Path, PathBuf},
};
use gix_error::{ResultExt, bail};
pub use gix_submodule::*;
use crate::{
Repository, Result, Submodule,
bstr::{BStr, BString},
is_dir_to_mode,
open::RelatedRepositoryKind,
worktree::IndexPersistedOrInMemory,
};
pub(crate) type ModulesFileStorage = gix_parallel::OwnShared<gix_fs::SharedFileSnapshotMut<File>>;
pub type ModulesSnapshot = gix_fs::SharedFileSnapshot<File>;
pub(crate) const MODULES_FILE: &str = ".gitmodules";
mod url;
pub(crate) struct SharedState<'repo> {
repo: &'repo Repository,
pub(crate) modules: ModulesSnapshot,
is_active: RefCell<Option<IsActiveState>>,
index: RefCell<Option<IndexPersistedOrInMemory>>,
}
impl<'repo> SharedState<'repo> {
pub(crate) fn new(repo: &'repo Repository, modules: ModulesSnapshot) -> Self {
SharedState {
repo,
modules,
is_active: RefCell::new(None),
index: RefCell::new(None),
}
}
fn repo(&self) -> &'repo Repository {
self.repo
}
fn index(&self) -> Result<Ref<'_, IndexPersistedOrInMemory>> {
{
let mut state = self.index.borrow_mut();
if state.is_none() {
*state = self.repo.index_or_load_from_head()?.into();
}
}
Ok(Ref::map(self.index.borrow(), |opt| {
opt.as_ref().expect("just initialized")
}))
}
fn active_state_mut(&self) -> Result<RefMut<'_, IsActiveState>> {
let mut state = self.is_active.borrow_mut();
if state.is_none() {
let config = self.repo.trusted_submodule_config()?;
let platform = self
.modules
.is_active_platform(&config, self.repo.config.pathspec_defaults()?)?;
let index = self.index()?;
let attributes = self
.repo
.attributes_only(
&index,
gix_worktree::stack::state::attributes::Source::WorktreeThenIdMapping
.adjust_for_bare(self.repo.is_bare()),
)?
.detach();
*state = Some(IsActiveState {
config,
platform,
attributes,
});
}
Ok(RefMut::map(state, |opt| opt.as_mut().expect("populated above")))
}
}
struct IsActiveState {
config: gix_config::File,
platform: IsActivePlatform,
attributes: gix_worktree::Stack,
}
impl Submodule<'_> {
pub fn name(&self) -> &BStr {
self.name.as_ref()
}
pub fn validated_name(&self) -> Result<&BStr> {
gix_validate::submodule::name(self.name()).or_error()
}
pub fn path(&self) -> Result<BString> {
self.state.modules.path(self.name())
}
pub fn try_path(&self) -> Result<Option<BString>> {
self.state.modules.try_path(self.name())
}
pub fn url(&self) -> Result<gix_url::Url> {
self.state.modules.url(self.name())
}
pub fn update(&self) -> Result<Option<config::Update>> {
self.state.modules.update(self.name())
}
pub fn branch(&self) -> Result<Option<config::Branch>> {
self.state.modules.branch(self.name())
}
pub fn fetch_recurse(&self) -> Result<Option<config::FetchRecurse>> {
Ok(match self.state.modules.fetch_recurse(self.name())? {
Some(val) => Some(val),
None => {
let repo = self.state.repo();
let key = &crate::config::tree::Fetch::RECURSE_SUBMODULES;
key.try_into_recurse_submodules(repo.config.resolved.boolean_filter(key, repo.filter_config_section()))?
}
})
}
pub fn ignore(&self) -> Result<Option<config::Ignore>> {
self.state.modules.ignore(self.name())
}
pub fn shallow(&self) -> Result<Option<bool>> {
self.state.modules.shallow(self.name())
}
pub fn is_active(&self) -> Result<bool> {
let IsActiveState {
config,
platform,
attributes,
} = &mut *self.state.active_state_mut()?;
let is_active = platform.is_active(config, self.name.as_ref(), &mut |relative_path, case, is_dir, out| {
attributes
.set_case(case)
.at_entry(relative_path, Some(is_dir_to_mode(is_dir)), &self.state.repo().objects)
.is_ok_and(|platform| platform.matching_attributes(out))
})?;
Ok(is_active)
}
pub fn index_id(&self) -> Result<Option<gix_hash::ObjectId>> {
let path = self.path()?;
Ok(self
.state
.index()?
.entry_by_path(BStr::new(&path))
.and_then(|entry| (entry.mode == gix_index::entry::Mode::COMMIT).then_some(entry.id)))
}
pub fn head_id(&self) -> Result<Option<gix_hash::ObjectId>> {
let path = self.path()?;
Ok(self
.state
.repo()
.head_commit()?
.tree()?
.peel_to_entry_by_path(gix_path::from_bstring(path)?)?
.and_then(|entry| (entry.mode().is_commit()).then_some(entry.inner.oid)))
}
pub fn git_dir(&self) -> Result<PathBuf> {
git_dir_from_name(self.state.repo().git_dir(), self.validated_name()?)
}
pub fn work_dir(&self) -> Result<Option<PathBuf>> {
let Some(work_dir) = self.state.repo().workdir() else {
return Ok(None);
};
work_dir_from_relative_path(work_dir, self.path()?.as_ref()).map(Some)
}
pub fn git_dir_try_old_form(&self) -> Result<PathBuf> {
self.git_dir_try_old_form_inner(true)
}
fn git_dir_try_old_form_inner(&self, validate_gitdir_file_target: bool) -> Result<PathBuf> {
let git_dir = self
.git_dir()
.or_raise(|| gix_error::validation("The submodule name is invalid"))?;
let Some(worktree_gitdir) = self.worktree_gitdir()? else {
return Ok(git_dir);
};
Ok(git_dir_from_worktree_gitdir(&worktree_gitdir, validate_gitdir_file_target)?.unwrap_or(git_dir))
}
fn state_inner(&self, validate_gitdir_file_target: bool) -> Result<State> {
let maybe_old_path = self.git_dir_try_old_form_inner(validate_gitdir_file_target)?;
let worktree_git = self.worktree_gitdir()?;
let repo = self.state.repo();
let superproject_configuration = repo
.config
.resolved
.sections_by_name_and_filter("submodule", repo.filter_config_section())
.into_iter()
.flatten()
.any(|section| section.header().subsection_name() == Some(self.name.as_ref()));
Ok(State {
repository_exists: maybe_old_path.is_dir(),
is_old_form: worktree_git.as_deref().is_some_and(Path::is_dir),
worktree_checkout: worktree_git.as_deref().is_some_and(Path::exists),
superproject_configuration,
})
}
#[doc(alias = "status", alias = "git2")]
pub fn state(&self) -> Result<State> {
self.state_inner(true)
}
pub fn open(&self) -> Result<Option<Repository>> {
Ok(match self.open_inner()? {
ControlFlow::Continue(repo) => repo,
ControlFlow::Break(_) => None,
})
}
fn open_inner(&self) -> Result<ControlFlow<PathBuf, Option<Repository>>> {
open(self.state.repo(), &self.git_dir_try_old_form()?, self.path()?.as_ref())
}
fn worktree_gitdir(&self) -> Result<Option<PathBuf>> {
worktree_gitdir(self.state.repo(), self.path()?.as_ref())
}
}
fn work_dir_from_relative_path(work_dir: &Path, relative_path: &BStr) -> Result<PathBuf> {
Ok(work_dir.join(gix_path::from_bstr(relative_path)?))
}
pub(crate) fn worktree_gitdir(repo: &Repository, relative_path: &BStr) -> Result<Option<PathBuf>> {
let relative_path = gix_path::from_bstr(relative_path)?;
let Some(work_dir) = repo.workdir() else {
return Ok(None);
};
let path = gix_fs::symlink::validate_relative_path(work_dir, &relative_path)?;
Ok(Some(path.join(gix_discover::DOT_GIT_DIR)))
}
pub(crate) fn git_dir_from_worktree_gitdir(
worktree_gitdir: &Path,
validate_gitdir_file_target: bool,
) -> Result<Option<PathBuf>> {
if worktree_gitdir.is_dir() {
return Ok(Some(worktree_gitdir.to_owned()));
}
if !worktree_gitdir.is_file() {
return Ok(None);
}
if !validate_gitdir_file_target {
return Ok(gix_discover::path::from_gitdir_file(worktree_gitdir).ok());
}
let git_dir = gix_discover::path::from_gitdir_file(worktree_gitdir).or_raise(|| {
gix_error::validation(format!(
"The gitdir file at \"{}\" contains an invalid gitdir target",
worktree_gitdir.display()
))
})?;
if !git_dir.is_dir() {
bail!(gix_error::validation(format!(
"The gitdir file at \"{}\" contains an invalid gitdir target: \"{}\"",
worktree_gitdir.display(),
git_dir.display()
)));
}
Ok(Some(git_dir))
}
pub(crate) fn open(
superproject: &Repository,
git_dir: &Path,
relative_path: &BStr,
) -> Result<ControlFlow<PathBuf, Option<Repository>>> {
let work_dir = superproject
.workdir()
.map(|work_dir| work_dir_from_relative_path(work_dir, relative_path))
.transpose()?;
let worktree_gitdir = worktree_gitdir(superproject, relative_path)?;
let original_path = worktree_gitdir
.as_deref()
.filter(|path| path.is_dir() || path.is_file())
.unwrap_or(git_dir);
let kind = match gix_discover::is_git(git_dir) {
Ok(kind) => kind,
Err(_) => return Ok(ControlFlow::Continue(None)),
};
let cwd = superproject.current_dir();
let (git_dir, work_dir) = match work_dir {
Some(work_dir) => (git_dir.to_owned(), Some(work_dir)),
None => gix_discover::repository::Path::from_dot_git_dir(git_dir.to_owned(), kind, cwd)
.expect("the Git directory was validated with is_git()")
.into_repository_and_work_tree_directories(),
};
let trust = gix_discover::repository::trust(&git_dir, None, cwd, (original_path, None))?;
let mut options = superproject.options.clone_without_trust().with_trust(trust);
options.current_dir = Some(cwd.to_owned());
options.retain_inferred_worktree_when_bare = superproject.workdir().is_some();
let ControlFlow::Continue(options) = options.configure_related_open(
superproject,
RelatedRepositoryKind::Submodule,
&git_dir,
work_dir.as_deref(),
)?
else {
return Ok(ControlFlow::Break(cwd.join(git_dir)));
};
match crate::ThreadSafeRepository::open_from_paths(git_dir, work_dir, options, None) {
Ok(repo) => Ok(ControlFlow::Continue(Some(repo.into()))),
Err(err)
if err
.error()
.downcast_ref::<gix_error::Message>()
.is_some_and(|error| error.class == Some(gix_error::Class::NotFound)) =>
{
Ok(ControlFlow::Continue(None))
}
Err(err) => Err(err),
}
}
fn git_dir_from_name(git_dir: &Path, name: &BStr) -> Result<PathBuf> {
let mut git_dir = git_dir.join("modules").into_os_string();
git_dir.push(std::path::MAIN_SEPARATOR_STR);
git_dir.push(gix_path::from_bstr(name)?.as_os_str());
Ok(git_dir.into())
}
#[cfg(test)]
mod tests {
use std::path::Path;
use crate::bstr::ByteSlice;
#[test]
fn git_dir_from_name_keeps_git_compatible_names_below_modules() -> gix_testtools::TestResult {
let common_dir = Path::new("repo").join(".git");
let modules_dir = common_dir.join("modules");
for name in [
b"/etc/cron.d/x" as &[u8],
br"\Windows\Temp\x",
br"\\host\share\x",
b"//host/share/x",
br"C:\Windows\Temp\x",
b"C:/Windows/Temp/x",
b"C:x",
] {
let actual = super::git_dir_from_name(&common_dir, name.as_bstr())?;
assert!(
actual.starts_with(&modules_dir),
"Git-compatible name {name:?} must remain below {} instead of producing {}",
modules_dir.display(),
actual.display()
);
}
Ok(())
}
}
#[cfg(feature = "status")]
pub mod status {
use std::ops::ControlFlow;
use gix_submodule::config;
use super::Status;
use crate::{Result, Submodule};
impl Submodule<'_> {
#[doc(alias = "submodule_status", alias = "git2")]
pub fn status(
&self,
ignore: config::Ignore,
check_dirty: bool,
) -> Result<crate::submodule::status::types::Status> {
self.status_opts(ignore, check_dirty, &mut |s| s)
}
#[doc(alias = "submodule_status", alias = "git2")]
pub fn status_opts(
&self,
ignore: config::Ignore,
check_dirty: bool,
adjust_options: &mut dyn for<'a> FnMut(
crate::status::Platform<'a, gix_utils::progress::Discard>,
)
-> crate::status::Platform<'a, gix_utils::progress::Discard>,
) -> Result<Status> {
let mut state = self.state_inner(ignore != config::Ignore::All)?;
if ignore == config::Ignore::All {
return Ok(Status {
state,
..Default::default()
});
}
let index_id = self.index_id()?;
if !state.repository_exists {
return Ok(Status {
state,
index_id,
..Default::default()
});
}
let sm_repo = match self.open_inner()? {
ControlFlow::Break(git_dir) => return Err(crate::open::related_repository_skipped(&git_dir)),
ControlFlow::Continue(None) => {
state.repository_exists = false;
return Ok(Status {
state,
index_id,
..Default::default()
});
}
ControlFlow::Continue(Some(repo)) => repo,
};
Status {
state,
index_id,
..Default::default()
}
.with_worktree_status(&sm_repo, ignore, check_dirty, adjust_options)
}
}
impl Status {
pub(crate) fn with_worktree_status(
mut self,
repo: &crate::Repository,
ignore: config::Ignore,
check_dirty: bool,
adjust_options: &mut dyn for<'a> FnMut(
crate::status::Platform<'a, gix_utils::progress::Discard>,
)
-> crate::status::Platform<'a, gix_utils::progress::Discard>,
) -> Result<Self> {
self.checked_out_head_id = repo.head_id().ok().map(crate::Id::detach);
if ignore == config::Ignore::Dirty || check_dirty && self.is_dirty() == Some(true) {
return Ok(self);
}
if !self.state.worktree_checkout {
return Ok(self);
}
let statuses = adjust_options(repo.status(gix_utils::progress::Discard)?)
.index_worktree_options_mut(|opts| {
if ignore == config::Ignore::Untracked {
opts.dirwalk_options = None;
}
})
.into_iter(None)?;
let mut changes = Vec::new();
for change in statuses {
changes.push(change?);
if check_dirty {
break;
}
}
self.changes = Some(changes);
Ok(self)
}
pub fn is_dirty(&self) -> Option<bool> {
if !self.state.worktree_checkout || !self.state.repository_exists {
return None;
}
let is_dirty =
self.checked_out_head_id != self.index_id || self.changes.as_ref().is_some_and(|c| !c.is_empty());
Some(is_dirty)
}
}
pub(super) mod types {
use crate::submodule::State;
#[derive(Default, Clone, PartialEq, Debug)]
pub struct Status {
pub state: State,
pub index_id: Option<gix_hash::ObjectId>,
pub checked_out_head_id: Option<gix_hash::ObjectId>,
pub changes: Option<Vec<crate::status::Item>>,
}
}
}
#[cfg(feature = "status")]
pub use status::types::Status;
#[derive(Default, Copy, Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct State {
pub repository_exists: bool,
pub is_old_form: bool,
pub worktree_checkout: bool,
pub superproject_configuration: bool,
}