1use anyhow::Result;
2use collections::HashMap;
3use git2::{BranchType, ErrorCode};
4use parking_lot::Mutex;
5use rpc::proto;
6use serde_derive::{Deserialize, Serialize};
7use std::{
8 cmp::Ordering,
9 ffi::OsStr,
10 os::unix::prelude::OsStrExt,
11 path::{Component, Path, PathBuf},
12 sync::Arc,
13};
14use sum_tree::{MapSeekTarget, TreeMap};
15use util::ResultExt;
16
17pub use git2::Repository as LibGitRepository;
18
19#[derive(Clone, Debug, Hash, PartialEq)]
20pub struct Branch {
21 pub name: Box<str>,
22 /// Timestamp of most recent commit, normalized to Unix Epoch format.
23 pub unix_timestamp: Option<i64>,
24}
25#[async_trait::async_trait]
26pub trait GitRepository: Send {
27 fn reload_index(&self);
28
29 fn load_index_text(&self, relative_file_path: &Path) -> Option<String>;
30
31 fn branch_name(&self) -> Option<String>;
32
33 fn statuses(&self) -> Option<TreeMap<RepoPath, GitFileStatus>>;
34
35 fn status(&self, path: &RepoPath) -> Result<Option<GitFileStatus>>;
36 fn branches(&self) -> Result<Vec<Branch>> {
37 Ok(vec![])
38 }
39 fn change_branch(&self, _: &str) -> Result<()> {
40 Ok(())
41 }
42}
43
44impl std::fmt::Debug for dyn GitRepository {
45 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46 f.debug_struct("dyn GitRepository<...>").finish()
47 }
48}
49
50#[async_trait::async_trait]
51impl GitRepository for LibGitRepository {
52 fn reload_index(&self) {
53 if let Ok(mut index) = self.index() {
54 _ = index.read(false);
55 }
56 }
57
58 fn load_index_text(&self, relative_file_path: &Path) -> Option<String> {
59 fn logic(repo: &LibGitRepository, relative_file_path: &Path) -> Result<Option<String>> {
60 const STAGE_NORMAL: i32 = 0;
61 let index = repo.index()?;
62
63 // This check is required because index.get_path() unwraps internally :(
64 check_path_to_repo_path_errors(relative_file_path)?;
65
66 let oid = match index.get_path(&relative_file_path, STAGE_NORMAL) {
67 Some(entry) => entry.id,
68 None => return Ok(None),
69 };
70
71 let content = repo.find_blob(oid)?.content().to_owned();
72 Ok(Some(String::from_utf8(content)?))
73 }
74
75 match logic(&self, relative_file_path) {
76 Ok(value) => return value,
77 Err(err) => log::error!("Error loading head text: {:?}", err),
78 }
79 None
80 }
81
82 fn branch_name(&self) -> Option<String> {
83 let head = self.head().log_err()?;
84 let branch = String::from_utf8_lossy(head.shorthand_bytes());
85 Some(branch.to_string())
86 }
87
88 fn statuses(&self) -> Option<TreeMap<RepoPath, GitFileStatus>> {
89 let statuses = self.statuses(None).log_err()?;
90
91 let mut map = TreeMap::default();
92
93 for status in statuses
94 .iter()
95 .filter(|status| !status.status().contains(git2::Status::IGNORED))
96 {
97 let path = RepoPath(PathBuf::from(OsStr::from_bytes(status.path_bytes())));
98 let Some(status) = read_status(status.status()) else {
99 continue
100 };
101
102 map.insert(path, status)
103 }
104
105 Some(map)
106 }
107
108 fn status(&self, path: &RepoPath) -> Result<Option<GitFileStatus>> {
109 let status = self.status_file(path);
110 match status {
111 Ok(status) => Ok(read_status(status)),
112 Err(e) => {
113 if e.code() == ErrorCode::NotFound {
114 Ok(None)
115 } else {
116 Err(e.into())
117 }
118 }
119 }
120 }
121 fn branches(&self) -> Result<Vec<Branch>> {
122 let local_branches = self.branches(Some(BranchType::Local))?;
123 let valid_branches = local_branches
124 .filter_map(|branch| {
125 branch.ok().and_then(|(branch, _)| {
126 let name = branch.name().ok().flatten().map(Box::from)?;
127 let timestamp = branch.get().peel_to_commit().ok()?.time();
128 let unix_timestamp = timestamp.seconds();
129 let timezone_offset = timestamp.offset_minutes();
130 let utc_offset =
131 time::UtcOffset::from_whole_seconds(timezone_offset * 60).ok()?;
132 let unix_timestamp =
133 time::OffsetDateTime::from_unix_timestamp(unix_timestamp).ok()?;
134 Some(Branch {
135 name,
136 unix_timestamp: Some(unix_timestamp.to_offset(utc_offset).unix_timestamp()),
137 })
138 })
139 })
140 .collect();
141 Ok(valid_branches)
142 }
143 fn change_branch(&self, name: &str) -> Result<()> {
144 let revision = self.find_branch(name, BranchType::Local)?;
145 let revision = revision.get();
146 let as_tree = revision.peel_to_tree()?;
147 self.checkout_tree(as_tree.as_object(), None)?;
148 self.set_head(
149 revision
150 .name()
151 .ok_or_else(|| anyhow::anyhow!("Branch name could not be retrieved"))?,
152 )?;
153 Ok(())
154 }
155}
156
157fn read_status(status: git2::Status) -> Option<GitFileStatus> {
158 if status.contains(git2::Status::CONFLICTED) {
159 Some(GitFileStatus::Conflict)
160 } else if status.intersects(
161 git2::Status::WT_MODIFIED
162 | git2::Status::WT_RENAMED
163 | git2::Status::INDEX_MODIFIED
164 | git2::Status::INDEX_RENAMED,
165 ) {
166 Some(GitFileStatus::Modified)
167 } else if status.intersects(git2::Status::WT_NEW | git2::Status::INDEX_NEW) {
168 Some(GitFileStatus::Added)
169 } else {
170 None
171 }
172}
173
174#[derive(Debug, Clone, Default)]
175pub struct FakeGitRepository {
176 state: Arc<Mutex<FakeGitRepositoryState>>,
177}
178
179#[derive(Debug, Clone, Default)]
180pub struct FakeGitRepositoryState {
181 pub index_contents: HashMap<PathBuf, String>,
182 pub worktree_statuses: HashMap<RepoPath, GitFileStatus>,
183 pub branch_name: Option<String>,
184}
185
186impl FakeGitRepository {
187 pub fn open(state: Arc<Mutex<FakeGitRepositoryState>>) -> Arc<Mutex<dyn GitRepository>> {
188 Arc::new(Mutex::new(FakeGitRepository { state }))
189 }
190}
191
192#[async_trait::async_trait]
193impl GitRepository for FakeGitRepository {
194 fn reload_index(&self) {}
195
196 fn load_index_text(&self, path: &Path) -> Option<String> {
197 let state = self.state.lock();
198 state.index_contents.get(path).cloned()
199 }
200
201 fn branch_name(&self) -> Option<String> {
202 let state = self.state.lock();
203 state.branch_name.clone()
204 }
205
206 fn statuses(&self) -> Option<TreeMap<RepoPath, GitFileStatus>> {
207 let state = self.state.lock();
208 let mut map = TreeMap::default();
209 for (repo_path, status) in state.worktree_statuses.iter() {
210 map.insert(repo_path.to_owned(), status.to_owned());
211 }
212 Some(map)
213 }
214
215 fn status(&self, path: &RepoPath) -> Result<Option<GitFileStatus>> {
216 let state = self.state.lock();
217 Ok(state.worktree_statuses.get(path).cloned())
218 }
219}
220
221fn check_path_to_repo_path_errors(relative_file_path: &Path) -> Result<()> {
222 match relative_file_path.components().next() {
223 None => anyhow::bail!("repo path should not be empty"),
224 Some(Component::Prefix(_)) => anyhow::bail!(
225 "repo path `{}` should be relative, not a windows prefix",
226 relative_file_path.to_string_lossy()
227 ),
228 Some(Component::RootDir) => {
229 anyhow::bail!(
230 "repo path `{}` should be relative",
231 relative_file_path.to_string_lossy()
232 )
233 }
234 Some(Component::CurDir) => {
235 anyhow::bail!(
236 "repo path `{}` should not start with `.`",
237 relative_file_path.to_string_lossy()
238 )
239 }
240 Some(Component::ParentDir) => {
241 anyhow::bail!(
242 "repo path `{}` should not start with `..`",
243 relative_file_path.to_string_lossy()
244 )
245 }
246 _ => Ok(()),
247 }
248}
249
250#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
251pub enum GitFileStatus {
252 Added,
253 Modified,
254 Conflict,
255}
256
257impl GitFileStatus {
258 pub fn merge(
259 this: Option<GitFileStatus>,
260 other: Option<GitFileStatus>,
261 prefer_other: bool,
262 ) -> Option<GitFileStatus> {
263 if prefer_other {
264 return other;
265 } else {
266 match (this, other) {
267 (Some(GitFileStatus::Conflict), _) | (_, Some(GitFileStatus::Conflict)) => {
268 Some(GitFileStatus::Conflict)
269 }
270 (Some(GitFileStatus::Modified), _) | (_, Some(GitFileStatus::Modified)) => {
271 Some(GitFileStatus::Modified)
272 }
273 (Some(GitFileStatus::Added), _) | (_, Some(GitFileStatus::Added)) => {
274 Some(GitFileStatus::Added)
275 }
276 _ => None,
277 }
278 }
279 }
280
281 pub fn from_proto(git_status: Option<i32>) -> Option<GitFileStatus> {
282 git_status.and_then(|status| {
283 proto::GitStatus::from_i32(status).map(|status| match status {
284 proto::GitStatus::Added => GitFileStatus::Added,
285 proto::GitStatus::Modified => GitFileStatus::Modified,
286 proto::GitStatus::Conflict => GitFileStatus::Conflict,
287 })
288 })
289 }
290
291 pub fn to_proto(self) -> i32 {
292 match self {
293 GitFileStatus::Added => proto::GitStatus::Added as i32,
294 GitFileStatus::Modified => proto::GitStatus::Modified as i32,
295 GitFileStatus::Conflict => proto::GitStatus::Conflict as i32,
296 }
297 }
298}
299
300#[derive(Clone, Debug, Ord, Hash, PartialOrd, Eq, PartialEq)]
301pub struct RepoPath(pub PathBuf);
302
303impl RepoPath {
304 pub fn new(path: PathBuf) -> Self {
305 debug_assert!(path.is_relative(), "Repo paths must be relative");
306
307 RepoPath(path)
308 }
309}
310
311impl From<&Path> for RepoPath {
312 fn from(value: &Path) -> Self {
313 RepoPath::new(value.to_path_buf())
314 }
315}
316
317impl From<PathBuf> for RepoPath {
318 fn from(value: PathBuf) -> Self {
319 RepoPath::new(value)
320 }
321}
322
323impl Default for RepoPath {
324 fn default() -> Self {
325 RepoPath(PathBuf::new())
326 }
327}
328
329impl AsRef<Path> for RepoPath {
330 fn as_ref(&self) -> &Path {
331 self.0.as_ref()
332 }
333}
334
335impl std::ops::Deref for RepoPath {
336 type Target = PathBuf;
337
338 fn deref(&self) -> &Self::Target {
339 &self.0
340 }
341}
342
343#[derive(Debug)]
344pub struct RepoPathDescendants<'a>(pub &'a Path);
345
346impl<'a> MapSeekTarget<RepoPath> for RepoPathDescendants<'a> {
347 fn cmp_cursor(&self, key: &RepoPath) -> Ordering {
348 if key.starts_with(&self.0) {
349 Ordering::Greater
350 } else {
351 self.0.cmp(key)
352 }
353 }
354}