Move git related things into specialized git crate

Co-Authored-By: Mikayla Maki <mikayla@zed.dev>
This commit is contained in:
Julia
2022-09-29 13:16:02 -04:00
co-authored by Mikayla Maki
parent bf3b3da6ed
commit d5fd531743
17 changed files with 151 additions and 100 deletions
-4
View File
@@ -1,11 +1,9 @@
use anyhow::{anyhow, Result};
use fsevent::EventStream;
use futures::{future::BoxFuture, Stream, StreamExt};
use language::git::libgit::{Repository, RepositoryOpenFlags};
use language::LineEnding;
use smol::io::{AsyncReadExt, AsyncWriteExt};
use std::{
ffi::OsStr,
io,
os::unix::fs::MetadataExt,
path::{Component, Path, PathBuf},
@@ -22,8 +20,6 @@ use futures::lock::Mutex;
#[cfg(any(test, feature = "test-support"))]
use std::sync::{Arc, Weak};
use crate::git_repository::GitRepository;
#[async_trait::async_trait]
pub trait Fs: Send + Sync {
async fn create_dir(&self, path: &Path) -> Result<()>;
-99
View File
@@ -1,99 +0,0 @@
use anyhow::Result;
use git2::{Repository as LibGitRepository, RepositoryOpenFlags as LibGitRepositoryOpenFlags};
use parking_lot::Mutex;
use std::{ffi::OsStr, path::Path, sync::Arc};
use util::ResultExt;
#[derive(Clone)]
pub struct GitRepository {
// Path to folder containing the .git file or directory
content_path: Arc<Path>,
// Path to the actual .git folder.
// Note: if .git is a file, this points to the folder indicated by the .git file
git_dir_path: Arc<Path>,
scan_id: usize,
libgit_repository: Arc<Mutex<LibGitRepository>>,
}
impl GitRepository {
pub fn open(dotgit_path: &Path) -> Option<GitRepository> {
LibGitRepository::open(&dotgit_path)
.log_err()
.and_then(|libgit_repository| {
Some(Self {
content_path: libgit_repository.workdir()?.into(),
git_dir_path: dotgit_path.canonicalize().log_err()?.into(),
scan_id: 0,
libgit_repository: Arc::new(parking_lot::Mutex::new(libgit_repository)),
})
})
}
pub fn manages(&self, path: &Path) -> bool {
path.canonicalize()
.map(|path| path.starts_with(&self.content_path))
.unwrap_or(false)
}
pub fn in_dot_git(&self, path: &Path) -> bool {
path.canonicalize()
.map(|path| path.starts_with(&self.git_dir_path))
.unwrap_or(false)
}
pub fn content_path(&self) -> &Path {
self.content_path.as_ref()
}
pub fn git_dir_path(&self) -> &Path {
self.git_dir_path.as_ref()
}
pub fn scan_id(&self) -> usize {
self.scan_id
}
pub(super) fn set_scan_id(&mut self, scan_id: usize) {
self.scan_id = scan_id;
}
pub fn with_repo<F: FnOnce(&mut git2::Repository)>(&mut self, f: F) {
let mut git2 = self.libgit_repository.lock();
f(&mut git2)
}
pub async fn load_head_text(&self, file_path: &Path) -> Option<String> {
fn logic(repo: &LibGitRepository, file_path: &Path) -> Result<Option<String>> {
let object = repo
.head()?
.peel_to_tree()?
.get_path(file_path)?
.to_object(&repo)?;
let content = match object.as_blob() {
Some(blob) => blob.content().to_owned(),
None => return Ok(None),
};
let head_text = String::from_utf8(content.to_owned())?;
Ok(Some(head_text))
}
match logic(&self.libgit_repository.lock(), file_path) {
Ok(value) => return value,
Err(err) => log::error!("Error loading head text: {:?}", err),
}
None
}
}
impl std::fmt::Debug for GitRepository {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("GitRepository")
.field("content_path", &self.content_path)
.field("git_dir_path", &self.git_dir_path)
.field("scan_id", &self.scan_id)
.field("libgit_repository", &"LibGitRepository")
.finish()
}
}
+28 -17
View File
@@ -1,5 +1,4 @@
pub mod fs;
mod git_repository;
mod ignore;
mod lsp_command;
pub mod search;
@@ -13,7 +12,7 @@ use client::{proto, Client, PeerId, TypedEnvelope, User, UserStore};
use clock::ReplicaId;
use collections::{hash_map, BTreeMap, HashMap, HashSet};
use futures::{future::Shared, AsyncWriteExt, Future, FutureExt, StreamExt, TryFutureExt};
use git_repository::GitRepository;
use git::repository::GitRepository;
use gpui::{
AnyModelHandle, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle,
MutableAppContext, Task, UpgradeModelHandle, WeakModelHandle,
@@ -4538,6 +4537,7 @@ impl Project {
cx.subscribe(worktree, |this, worktree, event, cx| match event {
worktree::Event::UpdatedEntries => this.update_local_worktree_buffers(worktree, cx),
worktree::Event::UpdatedGitRepositories(updated_repos) => {
println!("{updated_repos:#?}");
this.update_local_worktree_buffers_git_repos(updated_repos, cx)
}
})
@@ -4649,24 +4649,35 @@ impl Project {
fn update_local_worktree_buffers_git_repos(
&mut self,
updated_repos: &[GitRepository],
repos: &[GitRepository],
cx: &mut ModelContext<Self>,
) {
for (buffer_id, buffer) in &self.opened_buffers {
if let Some(buffer) = buffer.upgrade(cx) {
buffer.update(cx, |buffer, cx| {
let updated = updated_repos.iter().any(|repo| {
buffer
.file()
.and_then(|file| file.as_local())
.map(|file| repo.manages(&file.abs_path(cx)))
.unwrap_or(false)
});
//TODO: Produce protos
if updated {
buffer.update_git(cx);
}
});
for (_, buffer) in &self.opened_buffers {
if let Some(buffer) = buffer.upgrade(cx) {
let file = match buffer.read(cx).file().and_then(|file| file.as_local()) {
Some(file) => file,
None => return,
};
let path = file.path().clone();
let abs_path = file.abs_path(cx);
println!("got file");
let repo = match repos.iter().find(|repo| repo.manages(&abs_path)) {
Some(repo) => repo.clone(),
None => return,
};
println!("got repo");
cx.spawn(|_, mut cx| async move {
let head_text = repo.load_head_text(&path).await;
buffer.update(&mut cx, |buffer, cx| {
println!("got calling update");
buffer.update_head_text(head_text, cx);
});
})
.detach();
}
}
}
+31 -23
View File
@@ -1,10 +1,9 @@
use crate::{copy_recursive, git_repository::GitRepository, ProjectEntryId, RemoveOptions};
use super::{
fs::{self, Fs},
ignore::IgnoreStack,
DiagnosticSummary,
};
use crate::{copy_recursive, ProjectEntryId, RemoveOptions};
use ::ignore::gitignore::{Gitignore, GitignoreBuilder};
use anyhow::{anyhow, Context, Result};
use client::{proto, Client};
@@ -18,6 +17,8 @@ use futures::{
Stream, StreamExt,
};
use fuzzy::CharBag;
use git::repository::GitRepository;
use git::{DOT_GIT, GITIGNORE};
use gpui::{
executor, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, MutableAppContext,
Task,
@@ -48,7 +49,7 @@ use std::{
time::{Duration, SystemTime},
};
use sum_tree::{Bias, Edit, SeekTarget, SumTree, TreeMap, TreeSet};
use util::{ResultExt, TryFutureExt, DOT_GIT, GITIGNORE};
use util::{ResultExt, TryFutureExt};
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
pub struct WorktreeId(usize);
@@ -523,7 +524,10 @@ impl LocalWorktree {
match self.scan_state() {
ScanState::Idle => {
let new_snapshot = self.background_snapshot.lock().clone();
let updated_repos = self.list_updated_repos(&new_snapshot);
let updated_repos = Self::list_updated_repos(
&self.snapshot.git_repositories,
&new_snapshot.git_repositories,
);
self.snapshot = new_snapshot;
if let Some(share) = self.share.as_mut() {
@@ -541,7 +545,10 @@ impl LocalWorktree {
let is_fake_fs = self.fs.is_fake();
let new_snapshot = self.background_snapshot.lock().clone();
let updated_repos = self.list_updated_repos(&new_snapshot);
let updated_repos = Self::list_updated_repos(
&self.snapshot.git_repositories,
&new_snapshot.git_repositories,
);
self.snapshot = new_snapshot;
self.poll_task = Some(cx.spawn_weak(|this, mut cx| async move {
@@ -573,16 +580,20 @@ impl LocalWorktree {
cx.notify();
}
fn list_updated_repos(&self, new_snapshot: &LocalSnapshot) -> Vec<GitRepository> {
let old_snapshot = &self.snapshot;
fn list_updated_repos(
old_repos: &[GitRepository],
new_repos: &[GitRepository],
) -> Vec<GitRepository> {
println!("old repos: {:#?}", old_repos);
println!("new repos: {:#?}", new_repos);
fn diff<'a>(
a: &'a LocalSnapshot,
b: &'a LocalSnapshot,
a: &'a [GitRepository],
b: &'a [GitRepository],
updated: &mut HashMap<&'a Path, GitRepository>,
) {
for a_repo in &a.git_repositories {
let matched = b.git_repositories.iter().find(|b_repo| {
for a_repo in a {
let matched = b.iter().find(|b_repo| {
a_repo.git_dir_path() == b_repo.git_dir_path()
&& a_repo.scan_id() == b_repo.scan_id()
});
@@ -595,10 +606,10 @@ impl LocalWorktree {
let mut updated = HashMap::<&Path, GitRepository>::default();
diff(old_snapshot, new_snapshot, &mut updated);
diff(new_snapshot, old_snapshot, &mut updated);
diff(old_repos, new_repos, &mut updated);
diff(new_repos, old_repos, &mut updated);
updated.into_values().collect()
dbg!(updated.into_values().collect())
}
pub fn scan_complete(&self) -> impl Future<Output = ()> {
@@ -653,7 +664,7 @@ impl LocalWorktree {
settings::GitFilesIncluded::All | settings::GitFilesIncluded::OnlyTracked
) {
let results = if let Some(repo) = snapshot.repo_for(&abs_path) {
repo.load_head_text(&abs_path).await
repo.load_head_text(&path).await
} else {
None
};
@@ -1362,6 +1373,7 @@ impl LocalSnapshot {
}
pub(crate) fn in_dot_git(&mut self, path: &Path) -> Option<&mut GitRepository> {
println!("chechking {path:?}");
self.git_repositories
.iter_mut()
.rev() //git_repository is ordered lexicographically
@@ -1510,7 +1522,6 @@ impl LocalSnapshot {
parent_path: Arc<Path>,
entries: impl IntoIterator<Item = Entry>,
ignore: Option<Arc<Gitignore>>,
fs: &dyn Fs,
) {
let mut parent_entry = if let Some(parent_entry) =
self.entries_by_path.get(&PathKey(parent_path.clone()), &())
@@ -2391,12 +2402,9 @@ impl BackgroundScanner {
new_entries.push(child_entry);
}
self.snapshot.lock().populate_dir(
job.path.clone(),
new_entries,
new_ignore,
self.fs.as_ref(),
);
self.snapshot
.lock()
.populate_dir(job.path.clone(), new_entries, new_ignore);
for new_job in new_jobs {
job.scan_queue.send(new_job).await.unwrap();
}
@@ -2595,7 +2603,7 @@ impl BackgroundScanner {
.git_repositories
.iter()
.cloned()
.filter(|repo| git2::Repository::open(repo.git_dir_path()).is_ok())
.filter(|repo| git::libgit::Repository::open(repo.git_dir_path()).is_ok())
.collect();
snapshot.git_repositories = new_repos;