repository.rs

  1use anyhow::Result;
  2use git2::Repository as LibGitRepository;
  3use parking_lot::Mutex;
  4use std::{path::Path, sync::Arc};
  5use util::ResultExt;
  6
  7#[async_trait::async_trait]
  8pub trait GitRepository: Send + Sync + std::fmt::Debug {
  9    fn manages(&self, path: &Path) -> bool;
 10
 11    fn in_dot_git(&self, path: &Path) -> bool;
 12
 13    fn content_path(&self) -> &Path;
 14
 15    fn git_dir_path(&self) -> &Path;
 16
 17    fn scan_id(&self) -> usize;
 18
 19    fn set_scan_id(&mut self, scan_id: usize);
 20
 21    fn reopen_git_repo(&mut self) -> bool;
 22
 23    fn git_repo(&self) -> Arc<Mutex<LibGitRepository>>;
 24
 25    fn boxed_clone(&self) -> Box<dyn GitRepository>;
 26
 27    async fn load_head_text(&self, relative_file_path: &Path) -> Option<String>;
 28}
 29
 30#[derive(Clone)]
 31pub struct RealGitRepository {
 32    // Path to folder containing the .git file or directory
 33    content_path: Arc<Path>,
 34    // Path to the actual .git folder.
 35    // Note: if .git is a file, this points to the folder indicated by the .git file
 36    git_dir_path: Arc<Path>,
 37    scan_id: usize,
 38    libgit_repository: Arc<Mutex<LibGitRepository>>,
 39}
 40
 41impl RealGitRepository {
 42    pub fn open(dotgit_path: &Path) -> Option<Box<dyn GitRepository>> {
 43        LibGitRepository::open(&dotgit_path)
 44            .log_err()
 45            .and_then::<Box<dyn GitRepository>, _>(|libgit_repository| {
 46                Some(Box::new(Self {
 47                    content_path: libgit_repository.workdir()?.into(),
 48                    git_dir_path: dotgit_path.canonicalize().log_err()?.into(),
 49                    scan_id: 0,
 50                    libgit_repository: Arc::new(parking_lot::Mutex::new(libgit_repository)),
 51                }))
 52            })
 53    }
 54}
 55
 56#[async_trait::async_trait]
 57impl GitRepository for RealGitRepository {
 58    fn manages(&self, path: &Path) -> bool {
 59        path.canonicalize()
 60            .map(|path| path.starts_with(&self.content_path))
 61            .unwrap_or(false)
 62    }
 63
 64    fn in_dot_git(&self, path: &Path) -> bool {
 65        path.canonicalize()
 66            .map(|path| path.starts_with(&self.git_dir_path))
 67            .unwrap_or(false)
 68    }
 69
 70    fn content_path(&self) -> &Path {
 71        self.content_path.as_ref()
 72    }
 73
 74    fn git_dir_path(&self) -> &Path {
 75        self.git_dir_path.as_ref()
 76    }
 77
 78    fn scan_id(&self) -> usize {
 79        self.scan_id
 80    }
 81
 82    async fn load_head_text(&self, relative_file_path: &Path) -> Option<String> {
 83        fn logic(repo: &LibGitRepository, relative_file_path: &Path) -> Result<Option<String>> {
 84            const STAGE_NORMAL: i32 = 0;
 85            let index = repo.index()?;
 86            let oid = match index.get_path(relative_file_path, STAGE_NORMAL) {
 87                Some(entry) => entry.id,
 88                None => return Ok(None),
 89            };
 90
 91            let content = repo.find_blob(oid)?.content().to_owned();
 92            let head_text = String::from_utf8(content)?;
 93            Ok(Some(head_text))
 94        }
 95
 96        match logic(&self.libgit_repository.as_ref().lock(), relative_file_path) {
 97            Ok(value) => return value,
 98            Err(err) => log::error!("Error loading head text: {:?}", err),
 99        }
100        None
101    }
102
103    fn reopen_git_repo(&mut self) -> bool {
104        match LibGitRepository::open(&self.git_dir_path) {
105            Ok(repo) => {
106                self.libgit_repository = Arc::new(Mutex::new(repo));
107                true
108            }
109
110            Err(_) => false,
111        }
112    }
113
114    fn git_repo(&self) -> Arc<Mutex<LibGitRepository>> {
115        self.libgit_repository.clone()
116    }
117
118    fn set_scan_id(&mut self, scan_id: usize) {
119        self.scan_id = scan_id;
120    }
121
122    fn boxed_clone(&self) -> Box<dyn GitRepository> {
123        Box::new(self.clone())
124    }
125}
126
127impl std::fmt::Debug for RealGitRepository {
128    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
129        f.debug_struct("GitRepository")
130            .field("content_path", &self.content_path)
131            .field("git_dir_path", &self.git_dir_path)
132            .field("scan_id", &self.scan_id)
133            .field("libgit_repository", &"LibGitRepository")
134            .finish()
135    }
136}
137
138#[derive(Debug, Clone)]
139pub struct FakeGitRepository {
140    content_path: Arc<Path>,
141    git_dir_path: Arc<Path>,
142    scan_id: usize,
143}
144
145impl FakeGitRepository {
146    pub fn open(dotgit_path: &Path, scan_id: usize) -> Box<dyn GitRepository> {
147        Box::new(FakeGitRepository {
148            content_path: dotgit_path.parent().unwrap().into(),
149            git_dir_path: dotgit_path.into(),
150            scan_id,
151        })
152    }
153}
154
155#[async_trait::async_trait]
156impl GitRepository for FakeGitRepository {
157    fn manages(&self, path: &Path) -> bool {
158        path.starts_with(self.content_path())
159    }
160
161    fn in_dot_git(&self, path: &Path) -> bool {
162        path.starts_with(self.git_dir_path())
163    }
164
165    fn content_path(&self) -> &Path {
166        &self.content_path
167    }
168
169    fn git_dir_path(&self) -> &Path {
170        &self.git_dir_path
171    }
172
173    fn scan_id(&self) -> usize {
174        self.scan_id
175    }
176
177    async fn load_head_text(&self, _: &Path) -> Option<String> {
178        unimplemented!()
179    }
180
181    fn reopen_git_repo(&mut self) -> bool {
182        unimplemented!()
183    }
184
185    fn git_repo(&self) -> Arc<Mutex<LibGitRepository>> {
186        unimplemented!()
187    }
188
189    fn set_scan_id(&mut self, scan_id: usize) {
190        self.scan_id = scan_id;
191    }
192
193    fn boxed_clone(&self) -> Box<dyn GitRepository> {
194        Box::new(self.clone())
195    }
196}