2022-09-22 23:55:24 +00:00
|
|
|
use git2::Repository;
|
|
|
|
use parking_lot::Mutex;
|
|
|
|
use std::{path::Path, sync::Arc};
|
|
|
|
use util::ResultExt;
|
|
|
|
|
|
|
|
#[derive(Clone)]
|
2022-09-26 20:57:31 +00:00
|
|
|
pub struct GitRepository {
|
2022-09-22 23:55:24 +00:00
|
|
|
// 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>,
|
2022-09-27 18:37:33 +00:00
|
|
|
scan_id: usize,
|
2022-09-22 23:55:24 +00:00
|
|
|
libgit_repository: Arc<Mutex<git2::Repository>>,
|
|
|
|
}
|
|
|
|
|
2022-09-26 20:57:31 +00:00
|
|
|
impl GitRepository {
|
|
|
|
pub fn open(dotgit_path: &Path) -> Option<GitRepository> {
|
|
|
|
Repository::open(&dotgit_path)
|
2022-09-22 23:55:24 +00:00
|
|
|
.log_err()
|
2022-09-26 20:57:31 +00:00
|
|
|
.and_then(|libgit_repository| {
|
|
|
|
Some(Self {
|
|
|
|
content_path: libgit_repository.workdir()?.into(),
|
|
|
|
git_dir_path: dotgit_path.canonicalize().log_err()?.into(),
|
2022-09-27 18:37:33 +00:00
|
|
|
scan_id: 0,
|
2022-09-22 23:55:24 +00:00
|
|
|
libgit_repository: Arc::new(parking_lot::Mutex::new(libgit_repository)),
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-09-27 18:37:33 +00:00
|
|
|
pub fn manages(&self, path: &Path) -> bool {
|
2022-09-26 20:57:31 +00:00
|
|
|
path.canonicalize()
|
|
|
|
.map(|path| path.starts_with(&self.content_path))
|
|
|
|
.unwrap_or(false)
|
2022-09-22 23:55:24 +00:00
|
|
|
}
|
|
|
|
|
2022-09-27 18:37:33 +00:00
|
|
|
pub fn in_dot_git(&self, path: &Path) -> bool {
|
2022-09-26 20:57:31 +00:00
|
|
|
path.canonicalize()
|
|
|
|
.map(|path| path.starts_with(&self.git_dir_path))
|
|
|
|
.unwrap_or(false)
|
2022-09-22 23:55:24 +00:00
|
|
|
}
|
|
|
|
|
2022-09-26 20:57:31 +00:00
|
|
|
pub fn content_path(&self) -> &Path {
|
2022-09-22 23:55:24 +00:00
|
|
|
self.content_path.as_ref()
|
|
|
|
}
|
|
|
|
|
2022-09-26 20:57:31 +00:00
|
|
|
pub fn git_dir_path(&self) -> &Path {
|
2022-09-22 23:55:24 +00:00
|
|
|
self.git_dir_path.as_ref()
|
|
|
|
}
|
|
|
|
|
2022-09-27 18:37:33 +00:00
|
|
|
pub fn scan_id(&self) -> usize {
|
|
|
|
self.scan_id
|
2022-09-22 23:55:24 +00:00
|
|
|
}
|
|
|
|
|
2022-09-27 18:37:33 +00:00
|
|
|
pub(super) fn set_scan_id(&mut self, scan_id: usize) {
|
|
|
|
self.scan_id = scan_id;
|
2022-09-22 23:55:24 +00:00
|
|
|
}
|
2022-09-26 14:59:51 +00:00
|
|
|
|
2022-09-27 18:07:53 +00:00
|
|
|
pub fn with_repo<F: FnOnce(&mut git2::Repository)>(&mut self, f: F) {
|
2022-09-26 14:59:51 +00:00
|
|
|
let mut git2 = self.libgit_repository.lock();
|
|
|
|
f(&mut git2)
|
|
|
|
}
|
2022-09-22 23:55:24 +00:00
|
|
|
}
|