1use anyhow::Result;
2use collections::HashMap;
3use git2::Status;
4use parking_lot::Mutex;
5use std::{
6 ffi::OsStr,
7 os::unix::prelude::OsStrExt,
8 path::{Component, Path, PathBuf},
9 sync::Arc,
10};
11use util::ResultExt;
12
13pub use git2::Repository as LibGitRepository;
14
15#[async_trait::async_trait]
16pub trait GitRepository: Send {
17 fn reload_index(&self);
18
19 fn load_index_text(&self, relative_file_path: &Path) -> Option<String>;
20
21 fn branch_name(&self) -> Option<String>;
22
23 fn statuses(&self) -> Option<HashMap<RepoPath, GitStatus>>;
24
25 fn file_status(&self, path: &RepoPath) -> Option<GitStatus>;
26}
27
28impl std::fmt::Debug for dyn GitRepository {
29 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30 f.debug_struct("dyn GitRepository<...>").finish()
31 }
32}
33
34#[async_trait::async_trait]
35impl GitRepository for LibGitRepository {
36 fn reload_index(&self) {
37 if let Ok(mut index) = self.index() {
38 _ = index.read(false);
39 }
40 }
41
42 fn load_index_text(&self, relative_file_path: &Path) -> Option<String> {
43 fn logic(repo: &LibGitRepository, relative_file_path: &Path) -> Result<Option<String>> {
44 const STAGE_NORMAL: i32 = 0;
45 let index = repo.index()?;
46
47 // This check is required because index.get_path() unwraps internally :(
48 check_path_to_repo_path_errors(relative_file_path)?;
49
50 let oid = match index.get_path(&relative_file_path, STAGE_NORMAL) {
51 Some(entry) => entry.id,
52 None => return Ok(None),
53 };
54
55 let content = repo.find_blob(oid)?.content().to_owned();
56 Ok(Some(String::from_utf8(content)?))
57 }
58
59 match logic(&self, relative_file_path) {
60 Ok(value) => return value,
61 Err(err) => log::error!("Error loading head text: {:?}", err),
62 }
63 None
64 }
65
66 fn branch_name(&self) -> Option<String> {
67 let head = self.head().log_err()?;
68 let branch = String::from_utf8_lossy(head.shorthand_bytes());
69 Some(branch.to_string())
70 }
71
72 fn statuses(&self) -> Option<HashMap<RepoPath, GitStatus>> {
73 let statuses = self.statuses(None).log_err()?;
74
75 let mut result = HashMap::default();
76
77 for status in statuses
78 .iter()
79 .filter(|status| !status.status().contains(git2::Status::IGNORED))
80 {
81 let path = RepoPath(PathBuf::from(OsStr::from_bytes(status.path_bytes())));
82
83 result.insert(path, status.status().into());
84 }
85
86 Some(result)
87 }
88
89 fn file_status(&self, path: &RepoPath) -> Option<GitStatus> {
90 let status = self.status_file(path).log_err()?;
91
92 Some(status.into())
93 }
94}
95
96#[derive(Debug, Clone, Default)]
97pub struct FakeGitRepository {
98 state: Arc<Mutex<FakeGitRepositoryState>>,
99}
100
101#[derive(Debug, Clone, Default)]
102pub struct FakeGitRepositoryState {
103 pub index_contents: HashMap<PathBuf, String>,
104 pub git_statuses: HashMap<RepoPath, GitStatus>,
105 pub branch_name: Option<String>,
106}
107
108impl FakeGitRepository {
109 pub fn open(state: Arc<Mutex<FakeGitRepositoryState>>) -> Arc<Mutex<dyn GitRepository>> {
110 Arc::new(Mutex::new(FakeGitRepository { state }))
111 }
112}
113
114#[async_trait::async_trait]
115impl GitRepository for FakeGitRepository {
116 fn reload_index(&self) {}
117
118 fn load_index_text(&self, path: &Path) -> Option<String> {
119 let state = self.state.lock();
120 state.index_contents.get(path).cloned()
121 }
122
123 fn branch_name(&self) -> Option<String> {
124 let state = self.state.lock();
125 state.branch_name.clone()
126 }
127
128 fn statuses(&self) -> Option<HashMap<RepoPath, GitStatus>> {
129 let state = self.state.lock();
130 let mut map = HashMap::default();
131 for (repo_path, status) in state.git_statuses.iter() {
132 map.insert(repo_path.to_owned(), status.to_owned());
133 }
134 Some(map)
135 }
136
137 fn file_status(&self, path: &RepoPath) -> Option<GitStatus> {
138 let state = self.state.lock();
139 state.git_statuses.get(path).cloned()
140 }
141}
142
143fn check_path_to_repo_path_errors(relative_file_path: &Path) -> Result<()> {
144 match relative_file_path.components().next() {
145 None => anyhow::bail!("repo path should not be empty"),
146 Some(Component::Prefix(_)) => anyhow::bail!(
147 "repo path `{}` should be relative, not a windows prefix",
148 relative_file_path.to_string_lossy()
149 ),
150 Some(Component::RootDir) => {
151 anyhow::bail!(
152 "repo path `{}` should be relative",
153 relative_file_path.to_string_lossy()
154 )
155 }
156 Some(Component::CurDir) => {
157 anyhow::bail!(
158 "repo path `{}` should not start with `.`",
159 relative_file_path.to_string_lossy()
160 )
161 }
162 Some(Component::ParentDir) => {
163 anyhow::bail!(
164 "repo path `{}` should not start with `..`",
165 relative_file_path.to_string_lossy()
166 )
167 }
168 _ => Ok(()),
169 }
170}
171
172#[derive(Debug, Clone, Default, PartialEq, Eq)]
173pub enum GitStatus {
174 Added,
175 Modified,
176 Conflict,
177 #[default]
178 Untracked,
179}
180
181impl From<Status> for GitStatus {
182 fn from(value: Status) -> Self {
183 if value.contains(git2::Status::CONFLICTED) {
184 GitStatus::Conflict
185 } else if value.intersects(
186 git2::Status::INDEX_MODIFIED
187 | git2::Status::WT_MODIFIED
188 | git2::Status::INDEX_RENAMED
189 | git2::Status::WT_RENAMED,
190 ) {
191 GitStatus::Modified
192 } else if value.intersects(git2::Status::INDEX_NEW | git2::Status::WT_NEW) {
193 GitStatus::Added
194 } else {
195 GitStatus::Untracked
196 }
197 }
198}
199
200#[derive(Clone, Debug, Ord, Hash, PartialOrd, Eq, PartialEq)]
201pub struct RepoPath(PathBuf);
202
203impl RepoPath {
204 fn new(path: PathBuf) -> Self {
205 debug_assert!(path.is_relative(), "Repo paths must be relative");
206
207 RepoPath(path)
208 }
209}
210
211impl From<&Path> for RepoPath {
212 fn from(value: &Path) -> Self {
213 RepoPath::new(value.to_path_buf())
214 }
215}
216
217impl From<PathBuf> for RepoPath {
218 fn from(value: PathBuf) -> Self {
219 RepoPath::new(value)
220 }
221}
222
223impl Default for RepoPath {
224 fn default() -> Self {
225 RepoPath(PathBuf::new())
226 }
227}
228
229impl AsRef<Path> for RepoPath {
230 fn as_ref(&self) -> &Path {
231 self.0.as_ref()
232 }
233}
234
235impl std::ops::Deref for RepoPath {
236 type Target = PathBuf;
237
238 fn deref(&self) -> &Self::Target {
239 &self.0
240 }
241}