Finish removing git repository state and scanning logic from worktrees (#27568)

This PR completes the process of moving git repository state storage and
scanning logic from the worktree crate to `project::git_store`.

Release Notes:

- N/A

---------

Co-authored-by: Max Brunsfeld <maxbrunsfeld@gmail.com>
Co-authored-by: Conrad <conrad@zed.dev>
This commit is contained in:
Cole Miller 2025-04-01 17:41:20 -04:00 committed by GitHub
parent 8f25251faf
commit e7290df02b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
39 changed files with 3121 additions and 3529 deletions

View file

@ -872,21 +872,6 @@ impl BufferStore {
cx.background_spawn(async move { task.await.map_err(|e| anyhow!("{e}")) })
}
pub(crate) fn worktree_for_buffer(
&self,
buffer: &Entity<Buffer>,
cx: &App,
) -> Option<(Entity<Worktree>, Arc<Path>)> {
let file = buffer.read(cx).file()?;
let worktree_id = file.worktree_id(cx);
let path = file.path().clone();
let worktree = self
.worktree_store
.read(cx)
.worktree_for_id(worktree_id, cx)?;
Some((worktree, path))
}
pub fn create_buffer(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
match &self.state {
BufferStoreState::Local(this) => this.create_buffer(cx),

View file

@ -91,7 +91,7 @@ impl Manager {
for (id, repository) in project.repositories(cx) {
repositories.push(proto::RejoinRepository {
id: id.to_proto(),
scan_id: repository.read(cx).completed_scan_id as u64,
scan_id: repository.read(cx).scan_id,
});
}
for worktree in project.worktrees(cx) {

View file

@ -339,7 +339,7 @@ impl DapStore {
local_store.toolchain_store.clone(),
local_store.environment.update(cx, |env, cx| {
let worktree = worktree.read(cx);
env.get_environment(Some(worktree.id()), Some(worktree.abs_path()), cx)
env.get_environment(worktree.abs_path().into(), cx)
}),
);
let session_id = local_store.next_session_id();
@ -407,7 +407,7 @@ impl DapStore {
local_store.toolchain_store.clone(),
local_store.environment.update(cx, |env, cx| {
let worktree = worktree.read(cx);
env.get_environment(Some(worktree.id()), Some(worktree.abs_path()), cx)
env.get_environment(Some(worktree.abs_path()), cx)
}),
);
let session_id = local_store.next_session_id();

View file

@ -1,11 +1,13 @@
use futures::{FutureExt, future::Shared};
use futures::{
FutureExt,
future::{Shared, WeakShared},
};
use std::{path::Path, sync::Arc};
use util::ResultExt;
use collections::HashMap;
use gpui::{App, AppContext as _, Context, Entity, EventEmitter, Task};
use settings::Settings as _;
use worktree::WorktreeId;
use crate::{
project_settings::{DirenvSettings, ProjectSettings},
@ -13,10 +15,9 @@ use crate::{
};
pub struct ProjectEnvironment {
worktree_store: Entity<WorktreeStore>,
cli_environment: Option<HashMap<String, String>>,
environments: HashMap<WorktreeId, Shared<Task<Option<HashMap<String, String>>>>>,
environment_error_messages: HashMap<WorktreeId, EnvironmentErrorMessage>,
environments: HashMap<Arc<Path>, WeakShared<Task<Option<HashMap<String, String>>>>>,
environment_error_messages: HashMap<Arc<Path>, EnvironmentErrorMessage>,
}
pub enum ProjectEnvironmentEvent {
@ -33,14 +34,15 @@ impl ProjectEnvironment {
) -> Entity<Self> {
cx.new(|cx| {
cx.subscribe(worktree_store, |this: &mut Self, _, event, _| {
if let WorktreeStoreEvent::WorktreeRemoved(_, id) = event {
this.remove_worktree_environment(*id);
if let WorktreeStoreEvent::WorktreeRemoved(_, _) = event {
this.environments.retain(|_, weak| weak.upgrade().is_some());
this.environment_error_messages
.retain(|abs_path, _| this.environments.contains_key(abs_path));
}
})
.detach();
Self {
worktree_store: worktree_store.clone(),
cli_environment,
environments: Default::default(),
environment_error_messages: Default::default(),
@ -48,11 +50,6 @@ impl ProjectEnvironment {
})
}
pub(crate) fn remove_worktree_environment(&mut self, worktree_id: WorktreeId) {
self.environment_error_messages.remove(&worktree_id);
self.environments.remove(&worktree_id);
}
/// Returns the inherited CLI environment, if this project was opened from the Zed CLI.
pub(crate) fn get_cli_environment(&self) -> Option<HashMap<String, String>> {
if let Some(mut env) = self.cli_environment.clone() {
@ -67,28 +64,22 @@ impl ProjectEnvironment {
/// environment errors associated with this project environment.
pub(crate) fn environment_errors(
&self,
) -> impl Iterator<Item = (&WorktreeId, &EnvironmentErrorMessage)> {
) -> impl Iterator<Item = (&Arc<Path>, &EnvironmentErrorMessage)> {
self.environment_error_messages.iter()
}
pub(crate) fn remove_environment_error(
&mut self,
worktree_id: WorktreeId,
cx: &mut Context<Self>,
) {
self.environment_error_messages.remove(&worktree_id);
pub(crate) fn remove_environment_error(&mut self, abs_path: &Path, cx: &mut Context<Self>) {
self.environment_error_messages.remove(abs_path);
cx.emit(ProjectEnvironmentEvent::ErrorsUpdated);
}
/// Returns the project environment, if possible.
/// If the project was opened from the CLI, then the inherited CLI environment is returned.
/// If it wasn't opened from the CLI, and a worktree is given, then a shell is spawned in
/// the worktree's path, to get environment variables as if the user has `cd`'d into
/// the worktrees path.
/// If it wasn't opened from the CLI, and an absolute path is given, then a shell is spawned in
/// that directory, to get environment variables as if the user has `cd`'d there.
pub(crate) fn get_environment(
&mut self,
worktree_id: Option<WorktreeId>,
worktree_abs_path: Option<Arc<Path>>,
abs_path: Option<Arc<Path>>,
cx: &Context<Self>,
) -> Shared<Task<Option<HashMap<String, String>>>> {
if cfg!(any(test, feature = "test-support")) {
@ -111,74 +102,26 @@ impl ProjectEnvironment {
.shared();
}
let Some((worktree_id, worktree_abs_path)) = worktree_id.zip(worktree_abs_path) else {
let Some(abs_path) = abs_path else {
return Task::ready(None).shared();
};
if self
.worktree_store
.read(cx)
.worktree_for_id(worktree_id, cx)
.map(|w| !w.read(cx).is_local())
.unwrap_or(true)
if let Some(existing) = self
.environments
.get(&abs_path)
.and_then(|weak| weak.upgrade())
{
return Task::ready(None).shared();
}
if let Some(task) = self.environments.get(&worktree_id) {
task.clone()
existing
} else {
let task = self
.get_worktree_env(worktree_id, worktree_abs_path, cx)
.shared();
self.environments.insert(worktree_id, task.clone());
task
let env = get_directory_env(abs_path.clone(), cx).shared();
self.environments.insert(
abs_path.clone(),
env.downgrade()
.expect("environment task has not been polled yet"),
);
env
}
}
fn get_worktree_env(
&mut self,
worktree_id: WorktreeId,
worktree_abs_path: Arc<Path>,
cx: &Context<Self>,
) -> Task<Option<HashMap<String, String>>> {
let load_direnv = ProjectSettings::get_global(cx).load_direnv.clone();
cx.spawn(async move |this, cx| {
let (mut shell_env, error_message) = cx
.background_spawn({
let worktree_abs_path = worktree_abs_path.clone();
async move {
load_worktree_shell_environment(&worktree_abs_path, &load_direnv).await
}
})
.await;
if let Some(shell_env) = shell_env.as_mut() {
let path = shell_env
.get("PATH")
.map(|path| path.as_str())
.unwrap_or_default();
log::info!(
"using project environment variables shell launched in {:?}. PATH={:?}",
worktree_abs_path,
path
);
set_origin_marker(shell_env, EnvironmentOrigin::WorktreeShell);
}
if let Some(error) = error_message {
this.update(cx, |this, cx| {
this.environment_error_messages.insert(worktree_id, error);
cx.emit(ProjectEnvironmentEvent::ErrorsUpdated)
})
.log_err();
}
shell_env
})
}
}
fn set_origin_marker(env: &mut HashMap<String, String>, origin: EnvironmentOrigin) {
@ -210,25 +153,25 @@ impl EnvironmentErrorMessage {
}
}
async fn load_worktree_shell_environment(
worktree_abs_path: &Path,
async fn load_directory_shell_environment(
abs_path: &Path,
load_direnv: &DirenvSettings,
) -> (
Option<HashMap<String, String>>,
Option<EnvironmentErrorMessage>,
) {
match smol::fs::metadata(worktree_abs_path).await {
match smol::fs::metadata(abs_path).await {
Ok(meta) => {
let dir = if meta.is_dir() {
worktree_abs_path
} else if let Some(parent) = worktree_abs_path.parent() {
abs_path
} else if let Some(parent) = abs_path.parent() {
parent
} else {
return (
None,
Some(EnvironmentErrorMessage(format!(
"Failed to load shell environment in {}: not a directory",
worktree_abs_path.display()
abs_path.display()
))),
);
};
@ -239,7 +182,7 @@ async fn load_worktree_shell_environment(
None,
Some(EnvironmentErrorMessage(format!(
"Failed to load shell environment in {}: {}",
worktree_abs_path.display(),
abs_path.display(),
err
))),
),
@ -387,3 +330,43 @@ async fn load_shell_environment(
(Some(parsed_env), direnv_error)
}
fn get_directory_env(
abs_path: Arc<Path>,
cx: &Context<ProjectEnvironment>,
) -> Task<Option<HashMap<String, String>>> {
let load_direnv = ProjectSettings::get_global(cx).load_direnv.clone();
cx.spawn(async move |this, cx| {
let (mut shell_env, error_message) = cx
.background_spawn({
let abs_path = abs_path.clone();
async move { load_directory_shell_environment(&abs_path, &load_direnv).await }
})
.await;
if let Some(shell_env) = shell_env.as_mut() {
let path = shell_env
.get("PATH")
.map(|path| path.as_str())
.unwrap_or_default();
log::info!(
"using project environment variables shell launched in {:?}. PATH={:?}",
abs_path,
path
);
set_origin_marker(shell_env, EnvironmentOrigin::WorktreeShell);
}
if let Some(error) = error_message {
this.update(cx, |this, cx| {
this.environment_error_messages.insert(abs_path, error);
cx.emit(ProjectEnvironmentEvent::ErrorsUpdated)
})
.log_err();
}
shell_env
})
}

File diff suppressed because it is too large Load diff

View file

@ -3,21 +3,21 @@ use git::status::GitSummary;
use std::{ops::Deref, path::Path};
use sum_tree::Cursor;
use text::Bias;
use worktree::{
Entry, PathProgress, PathTarget, ProjectEntryId, RepositoryEntry, StatusEntry, Traversal,
};
use worktree::{Entry, PathProgress, PathTarget, Traversal};
use super::{RepositoryId, RepositorySnapshot, StatusEntry};
/// Walks the worktree entries and their associated git statuses.
pub struct GitTraversal<'a> {
traversal: Traversal<'a>,
current_entry_summary: Option<GitSummary>,
repo_snapshots: &'a HashMap<ProjectEntryId, RepositoryEntry>,
repo_location: Option<(ProjectEntryId, Cursor<'a, StatusEntry, PathProgress<'a>>)>,
repo_snapshots: &'a HashMap<RepositoryId, RepositorySnapshot>,
repo_location: Option<(RepositoryId, Cursor<'a, StatusEntry, PathProgress<'a>>)>,
}
impl<'a> GitTraversal<'a> {
pub fn new(
repo_snapshots: &'a HashMap<ProjectEntryId, RepositoryEntry>,
repo_snapshots: &'a HashMap<RepositoryId, RepositorySnapshot>,
traversal: Traversal<'a>,
) -> GitTraversal<'a> {
let mut this = GitTraversal {
@ -46,8 +46,8 @@ impl<'a> GitTraversal<'a> {
.repo_snapshots
.values()
.filter_map(|repo_snapshot| {
let relative_path = repo_snapshot.relativize_abs_path(&abs_path)?;
Some((repo_snapshot, relative_path))
let repo_path = repo_snapshot.abs_path_to_repo_path(&abs_path)?;
Some((repo_snapshot, repo_path))
})
.max_by_key(|(repo, _)| repo.work_directory_abs_path.clone())
else {
@ -61,12 +61,9 @@ impl<'a> GitTraversal<'a> {
.repo_location
.as_ref()
.map(|(prev_repo_id, _)| *prev_repo_id)
!= Some(repo.work_directory_id())
!= Some(repo.id)
{
self.repo_location = Some((
repo.work_directory_id(),
repo.statuses_by_path.cursor::<PathProgress>(&()),
));
self.repo_location = Some((repo.id, repo.statuses_by_path.cursor::<PathProgress>(&())));
}
let Some((_, statuses)) = &mut self.repo_location else {
@ -148,7 +145,7 @@ pub struct ChildEntriesGitIter<'a> {
impl<'a> ChildEntriesGitIter<'a> {
pub fn new(
repo_snapshots: &'a HashMap<ProjectEntryId, RepositoryEntry>,
repo_snapshots: &'a HashMap<RepositoryId, RepositorySnapshot>,
worktree_snapshot: &'a worktree::Snapshot,
parent_path: &'a Path,
) -> Self {
@ -771,7 +768,7 @@ mod tests {
#[track_caller]
fn check_git_statuses(
repo_snapshots: &HashMap<ProjectEntryId, RepositoryEntry>,
repo_snapshots: &HashMap<RepositoryId, RepositorySnapshot>,
worktree_snapshot: &worktree::Snapshot,
expected_statuses: &[(&Path, GitSummary)],
) {

View file

@ -8078,9 +8078,7 @@ impl LspStore {
});
if let Some(environment) = &self.as_local().map(|local| local.environment.clone()) {
environment.update(cx, |env, cx| {
env.get_environment(worktree_id, worktree_abs_path, cx)
})
environment.update(cx, |env, cx| env.get_environment(worktree_abs_path, cx))
} else {
Task::ready(None).shared()
}
@ -9864,13 +9862,10 @@ impl LocalLspAdapterDelegate {
fs: Arc<dyn Fs>,
cx: &mut App,
) -> Arc<Self> {
let (worktree_id, worktree_abs_path) = {
let worktree = worktree.read(cx);
(worktree.id(), worktree.abs_path())
};
let worktree_abs_path = worktree.read(cx).abs_path();
let load_shell_env_task = environment.update(cx, |env, cx| {
env.get_environment(Some(worktree_id), Some(worktree_abs_path), cx)
env.get_environment(Some(worktree_abs_path), cx)
});
Arc::new(Self {

View file

@ -24,7 +24,7 @@ mod direnv;
mod environment;
use buffer_diff::BufferDiff;
pub use environment::{EnvironmentErrorMessage, ProjectEnvironmentEvent};
use git_store::{GitEvent, Repository};
use git_store::{Repository, RepositoryId};
pub mod search_history;
mod yarn;
@ -300,8 +300,6 @@ pub enum Event {
RevealInProjectPanel(ProjectEntryId),
SnippetEdit(BufferId, Vec<(lsp::Range, Snippet)>),
ExpandedAllForEntry(WorktreeId, ProjectEntryId),
GitStateUpdated,
ActiveRepositoryChanged,
}
pub enum DebugAdapterClientState {
@ -924,7 +922,6 @@ impl Project {
cx,
)
});
cx.subscribe(&git_store, Self::on_git_store_event).detach();
cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
@ -1064,13 +1061,7 @@ impl Project {
});
let git_store = cx.new(|cx| {
GitStore::ssh(
&worktree_store,
buffer_store.clone(),
environment.clone(),
ssh_proto.clone(),
cx,
)
GitStore::ssh(&worktree_store, buffer_store.clone(), ssh_proto.clone(), cx)
});
cx.subscribe(&ssh, Self::on_ssh_event).detach();
@ -1655,13 +1646,13 @@ impl Project {
pub fn shell_environment_errors<'a>(
&'a self,
cx: &'a App,
) -> impl Iterator<Item = (&'a WorktreeId, &'a EnvironmentErrorMessage)> {
) -> impl Iterator<Item = (&'a Arc<Path>, &'a EnvironmentErrorMessage)> {
self.environment.read(cx).environment_errors()
}
pub fn remove_environment_error(&mut self, worktree_id: WorktreeId, cx: &mut Context<Self>) {
pub fn remove_environment_error(&mut self, abs_path: &Path, cx: &mut Context<Self>) {
self.environment.update(cx, |environment, cx| {
environment.remove_environment_error(worktree_id, cx);
environment.remove_environment_error(abs_path, cx);
});
}
@ -2760,19 +2751,6 @@ impl Project {
}
}
fn on_git_store_event(
&mut self,
_: Entity<GitStore>,
event: &GitEvent,
cx: &mut Context<Self>,
) {
match event {
GitEvent::GitStateUpdated => cx.emit(Event::GitStateUpdated),
GitEvent::ActiveRepositoryChanged => cx.emit(Event::ActiveRepositoryChanged),
GitEvent::FileSystemUpdated | GitEvent::IndexWriteError(_) => {}
}
}
fn on_ssh_event(
&mut self,
_: Entity<SshRemoteClient>,
@ -4794,7 +4772,7 @@ impl Project {
self.git_store.read(cx).active_repository()
}
pub fn repositories<'a>(&self, cx: &'a App) -> &'a HashMap<ProjectEntryId, Entity<Repository>> {
pub fn repositories<'a>(&self, cx: &'a App) -> &'a HashMap<RepositoryId, Entity<Repository>> {
self.git_store.read(cx).repositories()
}

File diff suppressed because it is too large Load diff

View file

@ -298,7 +298,7 @@ fn local_task_context_for_location(
let worktree_abs_path = worktree_abs_path.clone();
let project_env = environment
.update(cx, |environment, cx| {
environment.get_environment(worktree_id, worktree_abs_path.clone(), cx)
environment.get_environment(worktree_abs_path.clone(), cx)
})
.ok()?
.await;

View file

@ -331,11 +331,7 @@ impl LocalToolchainStore {
cx.spawn(async move |cx| {
let project_env = environment
.update(cx, |environment, cx| {
environment.get_environment(
Some(path.worktree_id),
Some(Arc::from(abs_path.as_path())),
cx,
)
environment.get_environment(Some(root.clone()), cx)
})
.ok()?
.await;