2022-09-28 00:06:18 +00:00
|
|
|
use anyhow::Result;
|
2022-09-30 19:50:55 +00:00
|
|
|
use collections::HashMap;
|
2022-09-22 23:55:24 +00:00
|
|
|
use parking_lot::Mutex;
|
2022-10-01 00:33:34 +00:00
|
|
|
use std::{
|
|
|
|
path::{Path, PathBuf},
|
|
|
|
sync::Arc,
|
|
|
|
};
|
|
|
|
|
|
|
|
pub use git2::Repository as LibGitRepository;
|
2022-09-22 23:55:24 +00:00
|
|
|
|
2022-09-28 18:42:22 +00:00
|
|
|
#[async_trait::async_trait]
|
2022-09-30 22:25:25 +00:00
|
|
|
pub trait GitRepository: Send {
|
|
|
|
fn load_head_text(&self, relative_file_path: &Path) -> Option<String>;
|
2022-09-28 18:42:22 +00:00
|
|
|
}
|
2022-09-22 23:55:24 +00:00
|
|
|
|
2022-09-28 18:42:22 +00:00
|
|
|
#[async_trait::async_trait]
|
2022-09-30 22:25:25 +00:00
|
|
|
impl GitRepository for LibGitRepository {
|
|
|
|
fn load_head_text(&self, relative_file_path: &Path) -> Option<String> {
|
2022-09-28 15:43:33 +00:00
|
|
|
fn logic(repo: &LibGitRepository, relative_file_path: &Path) -> Result<Option<String>> {
|
2022-09-29 17:10:39 +00:00
|
|
|
const STAGE_NORMAL: i32 = 0;
|
|
|
|
let index = repo.index()?;
|
|
|
|
let oid = match index.get_path(relative_file_path, STAGE_NORMAL) {
|
|
|
|
Some(entry) => entry.id,
|
2022-09-28 00:06:18 +00:00
|
|
|
None => return Ok(None),
|
|
|
|
};
|
|
|
|
|
2022-09-29 17:10:39 +00:00
|
|
|
let content = repo.find_blob(oid)?.content().to_owned();
|
|
|
|
let head_text = String::from_utf8(content)?;
|
2022-09-28 00:06:18 +00:00
|
|
|
Ok(Some(head_text))
|
|
|
|
}
|
|
|
|
|
2022-09-30 22:25:25 +00:00
|
|
|
match logic(&self, relative_file_path) {
|
2022-09-28 00:06:18 +00:00
|
|
|
Ok(value) => return value,
|
|
|
|
Err(err) => log::error!("Error loading head text: {:?}", err),
|
|
|
|
}
|
|
|
|
None
|
|
|
|
}
|
2022-09-22 23:55:24 +00:00
|
|
|
}
|
2022-09-28 18:42:22 +00:00
|
|
|
|
2022-10-01 00:33:34 +00:00
|
|
|
#[derive(Debug, Clone, Default)]
|
2022-09-28 18:42:22 +00:00
|
|
|
pub struct FakeGitRepository {
|
2022-09-30 19:50:55 +00:00
|
|
|
state: Arc<Mutex<FakeGitRepositoryState>>,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug, Clone, Default)]
|
|
|
|
pub struct FakeGitRepositoryState {
|
|
|
|
pub index_contents: HashMap<PathBuf, String>,
|
2022-09-28 18:42:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl FakeGitRepository {
|
2022-10-01 00:33:34 +00:00
|
|
|
pub fn open(state: Arc<Mutex<FakeGitRepositoryState>>) -> Arc<Mutex<dyn GitRepository>> {
|
|
|
|
Arc::new(Mutex::new(FakeGitRepository { state }))
|
2022-09-28 18:42:22 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[async_trait::async_trait]
|
|
|
|
impl GitRepository for FakeGitRepository {
|
2022-10-01 00:33:34 +00:00
|
|
|
fn load_head_text(&self, path: &Path) -> Option<String> {
|
2022-09-30 19:50:55 +00:00
|
|
|
let state = self.state.lock();
|
|
|
|
state.index_contents.get(path).cloned()
|
2022-09-28 18:42:22 +00:00
|
|
|
}
|
|
|
|
}
|