JavaScript is disabled, refresh for a better experience. ambee/giterated

ambee/giterated

Git repository hosting, collaboration, and discovery for the Fediverse.

Utilize for GitBackend and trim end slashes in folder

Emilia - ⁨1⁩ year ago

parent: tbd commit: ⁨4b440ef

⁨giterated-daemon/src/backend/git.rs⁩ - ⁨40049⁩ bytes
Raw
1 use anyhow::Error;
2 use async_trait::async_trait;
3
4 use git2::BranchType;
5 use giterated_models::instance::{Instance, RepositoryCreateRequest};
6
7 use giterated_models::repository::{
8 AccessList, Commit, DefaultBranch, Description, IssueLabel, Repository, RepositoryBranch,
9 RepositoryBranchFilter, RepositoryBranchesRequest, RepositoryChunkLine,
10 RepositoryCommitBeforeRequest, RepositoryCommitFromIdRequest, RepositoryDiff,
11 RepositoryDiffFile, RepositoryDiffFileChunk, RepositoryDiffFileInfo, RepositoryDiffFileStatus,
12 RepositoryDiffPatchRequest, RepositoryDiffRequest, RepositoryFile, RepositoryFileFromIdRequest,
13 RepositoryFileFromPathRequest, RepositoryFileInspectRequest, RepositoryIssue,
14 RepositoryIssueLabelsRequest, RepositoryIssuesCountRequest, RepositoryIssuesRequest,
15 RepositoryLastCommitOfFileRequest, RepositoryObjectType, RepositoryStatistics,
16 RepositoryStatisticsRequest, RepositoryTreeEntry, RepositoryVisibility, Visibility,
17 };
18
19 use giterated_models::user::User;
20
21 use giterated_stack::{AuthenticatedUser, GiteratedStack};
22
23 use sqlx::PgPool;
24 use std::ops::Deref;
25 use std::{
26 path::{Path, PathBuf},
27 sync::Arc,
28 };
29 use thiserror::Error;
30 use tokio::sync::OnceCell;
31
32 use super::{IssuesBackend, RepositoryBackend};
33
34 // TODO: Handle this
35 //region database structures
36
37 /// Repository in the database
38 #[derive(Debug, sqlx::FromRow)]
39 pub struct GitRepository {
40 #[sqlx(try_from = "String")]
41 pub owner_user: User,
42 pub name: String,
43 pub description: Option<String>,
44 pub visibility: RepositoryVisibility,
45 pub default_branch: String,
46 }
47
48 impl GitRepository {
49 // Separate function because "Private" will be expanded later
50 /// Checks if the user is allowed to view this repository
51 pub async fn can_user_view_repository(
52 &self,
53 our_instance: &Instance,
54 user: &Option<AuthenticatedUser>,
55 stack: &GiteratedStack,
56 ) -> bool {
57 if matches!(self.visibility, RepositoryVisibility::Public) {
58 return true;
59 }
60
61 // User must exist for any further checks to pass
62 let user = match user {
63 Some(user) => user,
64 None => return false,
65 };
66
67 if *user.deref() == self.owner_user {
68 // owner can always view
69 return true;
70 }
71
72 if matches!(self.visibility, RepositoryVisibility::Private) {
73 // Check if the user can view\
74 let access_list = stack
75 .new_get_setting::<_, AccessList>(&Repository {
76 owner: self.owner_user.clone(),
77 name: self.name.clone(),
78 instance: our_instance.clone(),
79 })
80 .await
81 .unwrap();
82
83 access_list
84 .0
85 .iter()
86 .any(|access_list_user| access_list_user == user.deref())
87 } else {
88 false
89 }
90 }
91
92 // This is in it's own function because I assume I'll have to add logic to this later
93 pub fn open_git2_repository(
94 &self,
95 repository_directory: &str,
96 ) -> Result<git2::Repository, GitBackendError> {
97 match git2::Repository::open(format!(
98 "{}/{}/{}/{}",
99 repository_directory, self.owner_user.instance, self.owner_user.username, self.name
100 )) {
101 Ok(repository) => Ok(repository),
102 Err(err) => {
103 let err = GitBackendError::FailedOpeningFromDisk(err);
104 error!("Couldn't open a repository, this is bad! {:?}", err);
105
106 Err(err)
107 }
108 }
109 }
110 }
111
112 //endregion
113
114 #[derive(Error, Debug)]
115 pub enum GitBackendError {
116 #[error("Failed creating repository")]
117 FailedCreatingRepository(git2::Error),
118 #[error("Failed inserting into the database")]
119 FailedInsertingIntoDatabase(sqlx::Error),
120 #[error("Failed finding repository {owner_user:?}/{name:?}")]
121 RepositoryNotFound { owner_user: String, name: String },
122 #[error("Repository {owner_user:?}/{name:?} already exists")]
123 RepositoryAlreadyExists { owner_user: String, name: String },
124 #[error("Repository couldn't be deleted from the disk")]
125 CouldNotDeleteFromDisk(std::io::Error),
126 #[error("Failed deleting repository from database")]
127 FailedDeletingFromDatabase(sqlx::Error),
128 #[error("Failed opening repository on disk")]
129 FailedOpeningFromDisk(git2::Error),
130 #[error("Couldn't find ref with name `{0}`")]
131 RefNotFound(String),
132 #[error("Couldn't find repository head")]
133 HeadNotFound,
134 #[error("Couldn't find path in repository `{0}`")]
135 PathNotFound(String),
136 #[error("Couldn't find commit for path `{0}`")]
137 LastCommitNotFound(String),
138 #[error("Object ID `{0}` is invalid")]
139 InvalidObjectId(String),
140 #[error("Blob with ID `{0}` not found")]
141 BlobNotFound(String),
142 #[error("Tree with ID `{0}` not found")]
143 TreeNotFound(String),
144 #[error("Commit with ID `{0}` not found")]
145 CommitNotFound(String),
146 #[error("Parent for commit with ID `{0}` not found")]
147 CommitParentNotFound(String),
148 #[error("Failed diffing tree with ID `{0}` to tree with ID `{1}`")]
149 FailedDiffing(String, String),
150 }
151
152 pub struct GitBackend {
153 pg_pool: PgPool,
154 repository_folder: String,
155 instance: Instance,
156 stack: Arc<OnceCell<GiteratedStack>>,
157 }
158
159 impl GitBackend {
160 pub fn new(
161 pg_pool: &PgPool,
162 repository_folder: &str,
163 instance: impl ToOwned<Owned = Instance>,
164 stack: Arc<OnceCell<GiteratedStack>>,
165 ) -> Self {
166 let instance = instance.to_owned();
167
168 Self {
169 pg_pool: pg_pool.clone(),
170 // We make sure there's no end slash
171 repository_folder: repository_folder.trim_end_matches(&['/', '\\']).to_string(),
172 instance,
173 stack,
174 }
175 }
176
177 pub async fn find_by_owner_user_name(
178 &self,
179 user: &User,
180 repository_name: &str,
181 ) -> Result<GitRepository, GitBackendError> {
182 if let Ok(repository) = sqlx::query_as!(GitRepository,
183 r#"SELECT owner_user, name, description, visibility as "visibility: _", default_branch FROM repositories WHERE owner_user = $1 AND name = $2"#,
184 user.to_string(), repository_name)
185 .fetch_one(&self.pg_pool.clone())
186 .await {
187 Ok(repository)
188 } else {
189 Err(GitBackendError::RepositoryNotFound {
190 owner_user: user.to_string(),
191 name: repository_name.to_string(),
192 })
193 }
194 }
195
196 pub async fn delete_by_owner_user_name(
197 &self,
198 user: &User,
199 repository_name: &str,
200 ) -> Result<u64, GitBackendError> {
201 if let Err(err) = std::fs::remove_dir_all(PathBuf::from(format!(
202 "{}/{}/{}/{}",
203 self.repository_folder, user.instance, user.username, repository_name
204 ))) {
205 let err = GitBackendError::CouldNotDeleteFromDisk(err);
206 error!(
207 "Couldn't delete repository from disk, this is bad! {:?}",
208 err
209 );
210
211 return Err(err);
212 }
213
214 // Delete the repository from the database
215 self.delete_from_database(user, repository_name).await
216 }
217
218 /// Deletes the repository from the database
219 pub async fn delete_from_database(
220 &self,
221 user: &User,
222 repository_name: &str,
223 ) -> Result<u64, GitBackendError> {
224 match sqlx::query!(
225 "DELETE FROM repositories WHERE owner_user = $1 AND name = $2",
226 user.to_string(),
227 repository_name
228 )
229 .execute(&self.pg_pool.clone())
230 .await
231 {
232 Ok(deleted) => Ok(deleted.rows_affected()),
233 Err(err) => Err(GitBackendError::FailedDeletingFromDatabase(err)),
234 }
235 }
236
237 pub async fn open_repository_and_check_permissions(
238 &self,
239 owner: &User,
240 name: &str,
241 requester: &Option<AuthenticatedUser>,
242 ) -> Result<git2::Repository, GitBackendError> {
243 let repository = match self
244 .find_by_owner_user_name(
245 // &request.owner.instance.url,
246 owner, name,
247 )
248 .await
249 {
250 Ok(repository) => repository,
251 Err(err) => return Err(err),
252 };
253
254 if let Some(requester) = requester {
255 if !repository
256 .can_user_view_repository(
257 &self.instance,
258 &Some(requester.clone()),
259 self.stack.get().unwrap(),
260 )
261 .await
262 {
263 return Err(GitBackendError::RepositoryNotFound {
264 owner_user: repository.owner_user.to_string(),
265 name: repository.name.clone(),
266 });
267 }
268 } else if matches!(repository.visibility, RepositoryVisibility::Private) {
269 // Unauthenticated users can never view private repositories
270
271 return Err(GitBackendError::RepositoryNotFound {
272 owner_user: repository.owner_user.to_string(),
273 name: repository.name.clone(),
274 });
275 }
276
277 match repository.open_git2_repository(&self.repository_folder) {
278 Ok(git) => Ok(git),
279 Err(err) => Err(err),
280 }
281 }
282
283 // TODO: Find where this fits
284 // TODO: Cache this and general repository tree and invalidate select files on push
285 // TODO: Find better and faster technique for this
286 pub fn get_last_commit_of_file(
287 path: &str,
288 git: &git2::Repository,
289 start_commit: &git2::Commit,
290 ) -> anyhow::Result<Commit> {
291 trace!("Getting last commit for file: {}", path);
292
293 let mut revwalk = git.revwalk()?;
294 revwalk.set_sorting(git2::Sort::TIME)?;
295 revwalk.push(start_commit.id())?;
296
297 for oid in revwalk {
298 let oid = oid?;
299 let commit = git.find_commit(oid)?;
300
301 // Merge commits have 2 or more parents
302 // Commits with 0 parents are handled different because we can't diff against them
303 if commit.parent_count() == 0 {
304 return Ok(commit.into());
305 } else if commit.parent_count() == 1 {
306 let tree = commit.tree()?;
307 let last_tree = commit.parent(0)?.tree()?;
308
309 // Get the diff between the current tree and the last one
310 let diff = git.diff_tree_to_tree(Some(&last_tree), Some(&tree), None)?;
311
312 for dd in diff.deltas() {
313 // Get the path of the current file we're diffing against
314 let current_path = dd.new_file().path().unwrap();
315
316 // Path or directory
317 if current_path.eq(Path::new(&path)) || current_path.starts_with(path) {
318 return Ok(commit.into());
319 }
320 }
321 }
322 }
323
324 Err(GitBackendError::LastCommitNotFound(path.to_string()))?
325 }
326
327 /// Gets the total amount of commits using revwalk
328 pub fn get_total_commit_count(
329 git: &git2::Repository,
330 start_commit: &git2::Commit,
331 ) -> anyhow::Result<usize> {
332 // TODO: There must be a better way
333 let mut revwalk = git.revwalk()?;
334 revwalk.set_sorting(git2::Sort::TIME)?;
335 revwalk.push(start_commit.id())?;
336
337 Ok(revwalk.count())
338 }
339
340 /// Attempts to get the oid in this order:
341 /// 1. Full refname (refname_to_id)
342 /// 2. Short branch name (find_branch)
343 /// 3. Other (revparse_single)
344 pub fn get_oid_from_reference(
345 git: &git2::Repository,
346 rev: Option<&str>,
347 ) -> anyhow::Result<git2::Oid> {
348 // If the rev is None try and get the repository head
349 let Some(rev) = rev else {
350 if let Ok(head) = git.head() {
351 // TODO: Fix for symbolic references
352 // TODO: unsafe unwrap?
353 return Ok(head.target().unwrap());
354 } else {
355 // Nothing in database, render empty tree.
356 return Err(GitBackendError::HeadNotFound.into());
357 }
358 };
359
360 // TODO: This is far from ideal or speedy and would love for a better way to check this in the same order, but I can't find proper methods to do any of this.
361
362 // Try getting it as a refname (refs/heads/name)
363 if let Ok(oid) = git.refname_to_id(rev) {
364 Ok(oid)
365 // Try finding it as a short branch name
366 } else if let Ok(branch) = git.find_branch(rev, BranchType::Local) {
367 // SHOULD be safe to unwrap
368 Ok(branch.get().target().unwrap())
369 // As last resort, try revparsing (will catch short oid and tags)
370 } else if let Ok(object) = git.revparse_single(rev) {
371 Ok(object.id())
372 } else {
373 Err(Box::new(GitBackendError::RefNotFound(rev.to_string())).into())
374 }
375 }
376
377 /// Gets the last commit in a rev
378 pub fn get_last_commit_in_rev(git: &git2::Repository, rev: &str) -> anyhow::Result<Commit> {
379 let oid = Self::get_oid_from_reference(git, Some(rev))?;
380
381 // Walk through the repository commit graph starting at our rev
382 let mut revwalk = git.revwalk()?;
383 revwalk.set_sorting(git2::Sort::TIME)?;
384 revwalk.push(oid)?;
385
386 if let Some(Ok(commit_oid)) = revwalk.next() {
387 if let Ok(commit) = git
388 .find_commit(commit_oid)
389 .map_err(|_| GitBackendError::CommitNotFound(commit_oid.to_string()))
390 {
391 return Ok(Commit::from(commit));
392 }
393 }
394
395 Err(GitBackendError::RefNotFound(oid.to_string()).into())
396 }
397 }
398
399 #[async_trait]
400 impl RepositoryBackend for GitBackend {
401 async fn exists(
402 &mut self,
403 requester: &Option<AuthenticatedUser>,
404 repository: &Repository,
405 ) -> Result<bool, Error> {
406 if let Ok(repository) = self
407 .find_by_owner_user_name(&repository.owner.clone(), &repository.name)
408 .await
409 {
410 Ok(repository
411 .can_user_view_repository(&self.instance, requester, self.stack.get().unwrap())
412 .await)
413 } else {
414 Ok(false)
415 }
416 }
417
418 async fn create_repository(
419 &mut self,
420 _user: &AuthenticatedUser,
421 request: &RepositoryCreateRequest,
422 ) -> Result<Repository, GitBackendError> {
423 // Check if repository already exists in the database
424 if let Ok(repository) = self
425 .find_by_owner_user_name(&request.owner, &request.name)
426 .await
427 {
428 let err = GitBackendError::RepositoryAlreadyExists {
429 owner_user: repository.owner_user.to_string(),
430 name: repository.name,
431 };
432 error!("{:?}", err);
433
434 return Err(err);
435 }
436
437 // Insert the repository into the database
438 let _ = match sqlx::query_as!(GitRepository,
439 r#"INSERT INTO repositories VALUES ($1, $2, $3, $4, $5) RETURNING owner_user, name, description, visibility as "visibility: _", default_branch"#,
440 request.owner.to_string(), request.name, request.description, request.visibility as _, "master")
441 .fetch_one(&self.pg_pool.clone())
442 .await {
443 Ok(repository) => repository,
444 Err(err) => {
445 let err = GitBackendError::FailedInsertingIntoDatabase(err);
446 error!("Failed inserting into the database! {:?}", err);
447
448 return Err(err);
449 }
450 };
451
452 // Create bare (server side) repository on disk
453 match git2::Repository::init_bare(PathBuf::from(format!(
454 "{}/{}/{}/{}",
455 self.repository_folder, request.owner.instance, request.owner.username, request.name
456 ))) {
457 Ok(_) => {
458 debug!(
459 "Created new repository with the name {}/{}/{}",
460 request.owner.instance, request.owner.username, request.name
461 );
462
463 let stack = self.stack.get().unwrap();
464
465 let repository = Repository {
466 owner: request.owner.clone(),
467 name: request.name.clone(),
468 instance: request.instance.as_ref().unwrap_or(&self.instance).clone(),
469 };
470
471 stack
472 .write_setting(
473 &repository,
474 Description(request.description.clone().unwrap_or_default()),
475 )
476 .await
477 .unwrap();
478
479 stack
480 .write_setting(&repository, Visibility(request.visibility.clone()))
481 .await
482 .unwrap();
483
484 stack
485 .write_setting(&repository, DefaultBranch(request.default_branch.clone()))
486 .await
487 .unwrap();
488
489 Ok(repository)
490 }
491 Err(err) => {
492 let err = GitBackendError::FailedCreatingRepository(err);
493 error!("Failed creating repository on disk {:?}", err);
494
495 // Delete repository from database
496 self.delete_from_database(&request.owner, request.name.as_str())
497 .await?;
498
499 // ???
500 Err(err)
501 }
502 }
503 }
504
505 async fn repository_file_inspect(
506 &mut self,
507 requester: &Option<AuthenticatedUser>,
508 repository: &Repository,
509 request: &RepositoryFileInspectRequest,
510 ) -> Result<Vec<RepositoryTreeEntry>, Error> {
511 let git = self
512 .open_repository_and_check_permissions(&repository.owner, &repository.name, requester)
513 .await?;
514
515 // Try and find the tree_id/branch
516 let tree_id = Self::get_oid_from_reference(&git, request.rev.as_deref())?;
517
518 // Get the commit from the oid
519 let commit = match git.find_commit(tree_id) {
520 Ok(commit) => commit,
521 // If the commit isn't found, it's generally safe to assume the tree is empty.
522 Err(_) => return Ok(vec![]),
523 };
524
525 // this is stupid
526 let rev = request.rev.clone().unwrap_or_else(|| "master".to_string());
527 let mut current_path = rev.clone();
528
529 // Get the commit tree
530 let git_tree = if let Some(path) = &request.path {
531 // Add it to our full path string
532 current_path.push_str(format!("/{}", path).as_str());
533 // Get the specified path, return an error if it wasn't found.
534 let entry = match commit
535 .tree()
536 .unwrap()
537 .get_path(&PathBuf::from(path))
538 .map_err(|_| GitBackendError::PathNotFound(path.to_string()))
539 {
540 Ok(entry) => entry,
541 Err(err) => return Err(Box::new(err).into()),
542 };
543 // Turn the entry into a git tree
544 entry.to_object(&git).unwrap().as_tree().unwrap().clone()
545 } else {
546 commit.tree().unwrap()
547 };
548
549 // Iterate over the git tree and collect it into our own tree types
550 let mut tree = git_tree
551 .iter()
552 .map(|entry| {
553 let object_type = match entry.kind().unwrap() {
554 git2::ObjectType::Tree => RepositoryObjectType::Tree,
555 git2::ObjectType::Blob => RepositoryObjectType::Blob,
556 _ => unreachable!(),
557 };
558 let mut tree_entry = RepositoryTreeEntry::new(
559 entry.id().to_string().as_str(),
560 entry.name().unwrap(),
561 object_type,
562 entry.filemode(),
563 );
564
565 if request.extra_metadata {
566 // Get the file size if It's a blob
567 let object = entry.to_object(&git).unwrap();
568 if let Some(blob) = object.as_blob() {
569 tree_entry.size = Some(blob.size());
570 }
571
572 // Get the path to the folder the file is in by removing the rev from current_path
573 let mut path = current_path.replace(&rev, "");
574 if path.starts_with('/') {
575 path.remove(0);
576 }
577
578 // Format it as the path + file name
579 let full_path = if path.is_empty() {
580 entry.name().unwrap().to_string()
581 } else {
582 format!("{}/{}", path, entry.name().unwrap())
583 };
584
585 // Get the last commit made to the entry
586 if let Ok(last_commit) =
587 GitBackend::get_last_commit_of_file(&full_path, &git, &commit)
588 {
589 tree_entry.last_commit = Some(last_commit);
590 }
591 }
592
593 tree_entry
594 })
595 .collect::<Vec<RepositoryTreeEntry>>();
596
597 // Sort the tree alphabetically and with tree first
598 tree.sort_unstable_by_key(|entry| entry.name.to_lowercase());
599 tree.sort_unstable_by_key(|entry| {
600 std::cmp::Reverse(format!("{:?}", entry.object_type).to_lowercase())
601 });
602
603 Ok(tree)
604 }
605
606 async fn repository_file_from_id(
607 &mut self,
608 requester: &Option<AuthenticatedUser>,
609 repository: &Repository,
610 request: &RepositoryFileFromIdRequest,
611 ) -> Result<RepositoryFile, Error> {
612 let git = self
613 .open_repository_and_check_permissions(&repository.owner, &repository.name, requester)
614 .await?;
615
616 // Parse the passed object id
617 let oid = match git2::Oid::from_str(request.0.as_str()) {
618 Ok(oid) => oid,
619 Err(_) => {
620 return Err(Box::new(GitBackendError::InvalidObjectId(request.0.clone())).into())
621 }
622 };
623
624 // Find the file and turn it into our own struct
625 let file = match git.find_blob(oid) {
626 Ok(blob) => RepositoryFile {
627 id: blob.id().to_string(),
628 content: blob.content().to_vec(),
629 binary: blob.is_binary(),
630 size: blob.size(),
631 },
632 Err(_) => return Err(Box::new(GitBackendError::BlobNotFound(oid.to_string())).into()),
633 };
634
635 Ok(file)
636 }
637
638 async fn repository_file_from_path(
639 &mut self,
640 requester: &Option<AuthenticatedUser>,
641 repository: &Repository,
642 request: &RepositoryFileFromPathRequest,
643 ) -> Result<(RepositoryFile, String), Error> {
644 let git = self
645 .open_repository_and_check_permissions(&repository.owner, &repository.name, requester)
646 .await?;
647
648 let tree_id = Self::get_oid_from_reference(&git, request.rev.as_deref())?;
649
650 // unwrap might be dangerous?
651 // Get the commit from the oid
652 let commit = git.find_commit(tree_id).unwrap();
653
654 // this is stupid
655 let mut current_path = request.rev.clone().unwrap_or_else(|| "master".to_string());
656
657 // Add it to our full path string
658 current_path.push_str(format!("/{}", request.path).as_str());
659 // Get the specified path, return an error if it wasn't found.
660 let entry = match commit
661 .tree()
662 .unwrap()
663 .get_path(&PathBuf::from(request.path.clone()))
664 .map_err(|_| GitBackendError::PathNotFound(request.path.to_string()))
665 {
666 Ok(entry) => entry,
667 Err(err) => return Err(Box::new(err).into()),
668 };
669
670 // Find the file and turn it into our own struct
671 let file = match git.find_blob(entry.id()) {
672 Ok(blob) => RepositoryFile {
673 id: blob.id().to_string(),
674 content: blob.content().to_vec(),
675 binary: blob.is_binary(),
676 size: blob.size(),
677 },
678 Err(_) => {
679 return Err(Box::new(GitBackendError::BlobNotFound(entry.id().to_string())).into())
680 }
681 };
682
683 Ok((file, commit.id().to_string()))
684 }
685
686 async fn repository_commit_from_id(
687 &mut self,
688 requester: &Option<AuthenticatedUser>,
689 repository: &Repository,
690 request: &RepositoryCommitFromIdRequest,
691 ) -> Result<Commit, Error> {
692 let git = self
693 .open_repository_and_check_permissions(&repository.owner, &repository.name, requester)
694 .await?;
695
696 // Parse the passed object ids
697 let oid = git2::Oid::from_str(request.0.as_str())
698 .map_err(|_| GitBackendError::InvalidObjectId(request.0.clone()))?;
699
700 // Get the commit from the oid
701 let commit = git
702 .find_commit(oid)
703 .map_err(|_| GitBackendError::CommitNotFound(oid.to_string()))?;
704
705 Ok(Commit::from(commit))
706 }
707
708 async fn repository_last_commit_of_file(
709 &mut self,
710 requester: &Option<AuthenticatedUser>,
711 repository: &Repository,
712 request: &RepositoryLastCommitOfFileRequest,
713 ) -> Result<Commit, Error> {
714 let git = self
715 .open_repository_and_check_permissions(&repository.owner, &repository.name, requester)
716 .await?;
717
718 // Parse the passed object ids
719 let oid = git2::Oid::from_str(&request.start_commit)
720 .map_err(|_| GitBackendError::InvalidObjectId(request.start_commit.clone()))?;
721
722 // Get the commit from the oid
723 let commit = git
724 .find_commit(oid)
725 .map_err(|_| GitBackendError::CommitNotFound(oid.to_string()))?;
726
727 // Find the last commit of the file
728 let commit = GitBackend::get_last_commit_of_file(request.path.as_str(), &git, &commit)?;
729
730 Ok(commit)
731 }
732
733 async fn repository_get_statistics(
734 &mut self,
735 requester: &Option<AuthenticatedUser>,
736 repository: &Repository,
737 request: &RepositoryStatisticsRequest,
738 ) -> Result<RepositoryStatistics, Error> {
739 let git = self
740 .open_repository_and_check_permissions(&repository.owner, &repository.name, requester)
741 .await?;
742
743 let tree_id = Self::get_oid_from_reference(&git, request.rev.as_deref())?;
744
745 // Count the amount of branches and tags
746 let mut branches = 0;
747 let mut tags = 0;
748 if let Ok(references) = git.references() {
749 for reference in references.flatten() {
750 if reference.is_branch() {
751 branches += 1;
752 } else if reference.is_tag() {
753 tags += 1;
754 }
755 }
756 }
757
758 // Attempt to get the commit from the oid
759 let commits = if let Ok(commit) = git.find_commit(tree_id) {
760 // Get the total commit count if we found the tree oid commit
761 GitBackend::get_total_commit_count(&git, &commit)?
762 } else {
763 0
764 };
765
766 Ok(RepositoryStatistics {
767 commits,
768 branches,
769 tags,
770 })
771 }
772
773 async fn repository_get_branches(
774 &mut self,
775 requester: &Option<AuthenticatedUser>,
776 repository: &Repository,
777 request: &RepositoryBranchesRequest,
778 ) -> Result<Vec<RepositoryBranch>, Error> {
779 let git = self
780 .open_repository_and_check_permissions(&repository.owner, &repository.name, requester)
781 .await?;
782
783 // Could be done better with the RepositoryBranchFilter::None check done beforehand.
784 let mut filtered_branches = git
785 .branches(None)?
786 .filter_map(|branch| {
787 let branch = branch.ok()?.0;
788
789 let Some(name) = branch.name().ok().flatten() else {
790 return None;
791 };
792
793 // TODO: Non UTF-8?
794 let Some(commit) =
795 GitBackend::get_last_commit_in_rev(&git, branch.get().name().unwrap()).ok()
796 else {
797 return None;
798 };
799
800 // TODO: Implement stale with configurable age
801 let stale = false;
802
803 // Filter based on if the branch is stale or not
804 if request.filter != RepositoryBranchFilter::None {
805 #[allow(clippy::if_same_then_else)]
806 if stale && request.filter == RepositoryBranchFilter::Active {
807 return None;
808 } else if !stale && request.filter == RepositoryBranchFilter::Stale {
809 return None;
810 }
811 }
812
813 Some((name.to_string(), branch, stale, commit))
814 })
815 .collect::<Vec<_>>();
816
817 // Sort the branches by commit date
818 filtered_branches.sort_by(|(_, _, _, c1), (_, _, _, c2)| c2.time.cmp(&c1.time));
819 // Go to the requested position
820 let mut filtered_branches = filtered_branches.iter().skip(request.range.0);
821
822 let head = git.head()?;
823 let mut branches = vec![];
824
825 // Iterate through the filtered branches using the passed range
826 for _ in request.range.0..request.range.1 {
827 let Some((name, branch, stale, commit)) = filtered_branches.next() else {
828 break;
829 };
830
831 // Get how many commits are ahead of and behind of the head
832 let ahead_behind_head = if head.target().is_some() && branch.get().target().is_some() {
833 git.graph_ahead_behind(branch.get().target().unwrap(), head.target().unwrap())
834 .ok()
835 } else {
836 None
837 };
838
839 branches.push(RepositoryBranch {
840 name: name.to_string(),
841 stale: *stale,
842 last_commit: Some(commit.clone()),
843 ahead_behind_head,
844 })
845 }
846
847 Ok(branches)
848 }
849
850 async fn repository_diff(
851 &mut self,
852 requester: &Option<AuthenticatedUser>,
853 repository: &Repository,
854 request: &RepositoryDiffRequest,
855 ) -> Result<RepositoryDiff, Error> {
856 let git = self
857 .open_repository_and_check_permissions(&repository.owner, &repository.name, requester)
858 .await?;
859
860 // Parse the passed object ids
861 let oid_old = git2::Oid::from_str(request.old_id.as_str())
862 .map_err(|_| GitBackendError::InvalidObjectId(request.old_id.clone()))?;
863 let oid_new = git2::Oid::from_str(request.new_id.as_str())
864 .map_err(|_| GitBackendError::InvalidObjectId(request.new_id.clone()))?;
865
866 // Get the ids associates commits
867 let commit_old = git
868 .find_commit(oid_old)
869 .map_err(|_| GitBackendError::CommitNotFound(oid_old.to_string()))?;
870 let commit_new = git
871 .find_commit(oid_new)
872 .map_err(|_| GitBackendError::CommitNotFound(oid_new.to_string()))?;
873
874 // Get the commit trees
875 let tree_old = commit_old
876 .tree()
877 .map_err(|_| GitBackendError::TreeNotFound(oid_old.to_string()))?;
878 let tree_new = commit_new
879 .tree()
880 .map_err(|_| GitBackendError::TreeNotFound(oid_new.to_string()))?;
881
882 // Diff the two trees against each other
883 let diff = git
884 .diff_tree_to_tree(Some(&tree_old), Some(&tree_new), None)
885 .map_err(|_| {
886 GitBackendError::FailedDiffing(oid_old.to_string(), oid_new.to_string())
887 })?;
888
889 // Should be safe to unwrap?
890 let stats = diff.stats().unwrap();
891 let mut files: Vec<RepositoryDiffFile> = vec![];
892
893 diff.deltas().enumerate().for_each(|(i, delta)| {
894 // Parse the old file info from the delta
895 let old_file_info = match delta.old_file().exists() {
896 true => Some(RepositoryDiffFileInfo {
897 id: delta.old_file().id().to_string(),
898 path: delta
899 .old_file()
900 .path()
901 .unwrap()
902 .to_str()
903 .unwrap()
904 .to_string(),
905 size: delta.old_file().size(),
906 binary: delta.old_file().is_binary(),
907 }),
908 false => None,
909 };
910 // Parse the new file info from the delta
911 let new_file_info = match delta.new_file().exists() {
912 true => Some(RepositoryDiffFileInfo {
913 id: delta.new_file().id().to_string(),
914 path: delta
915 .new_file()
916 .path()
917 .unwrap()
918 .to_str()
919 .unwrap()
920 .to_string(),
921 size: delta.new_file().size(),
922 binary: delta.new_file().is_binary(),
923 }),
924 false => None,
925 };
926
927 let mut chunks: Vec<RepositoryDiffFileChunk> = vec![];
928 if let Some(patch) = git2::Patch::from_diff(&diff, i).ok().flatten() {
929 for chunk_num in 0..patch.num_hunks() {
930 if let Ok((chunk, chunk_num_lines)) = patch.hunk(chunk_num) {
931 let mut lines: Vec<RepositoryChunkLine> = vec![];
932
933 for line_num in 0..chunk_num_lines {
934 if let Ok(line) = patch.line_in_hunk(chunk_num, line_num) {
935 if let Ok(line_utf8) = String::from_utf8(line.content().to_vec()) {
936 lines.push(RepositoryChunkLine {
937 change_type: line.origin_value().into(),
938 content: line_utf8,
939 old_line_num: line.old_lineno(),
940 new_line_num: line.new_lineno(),
941 });
942 }
943
944 continue;
945 }
946 }
947
948 chunks.push(RepositoryDiffFileChunk {
949 header: String::from_utf8(chunk.header().to_vec()).ok(),
950 old_start: chunk.old_start(),
951 old_lines: chunk.old_lines(),
952 new_start: chunk.new_start(),
953 new_lines: chunk.new_lines(),
954 lines,
955 });
956 }
957 }
958 };
959
960 let file = RepositoryDiffFile {
961 status: RepositoryDiffFileStatus::from(delta.status()),
962 old_file_info,
963 new_file_info,
964 chunks,
965 };
966
967 files.push(file);
968 });
969
970 Ok(RepositoryDiff {
971 new_commit: Commit::from(commit_new),
972 files_changed: stats.files_changed(),
973 insertions: stats.insertions(),
974 deletions: stats.deletions(),
975 files,
976 })
977 }
978
979 async fn repository_diff_patch(
980 &mut self,
981 requester: &Option<AuthenticatedUser>,
982 repository: &Repository,
983 request: &RepositoryDiffPatchRequest,
984 ) -> Result<String, Error> {
985 let git = self
986 .open_repository_and_check_permissions(&repository.owner, &repository.name, requester)
987 .await?;
988
989 // Parse the passed object ids
990 let oid_old = git2::Oid::from_str(request.old_id.as_str())
991 .map_err(|_| GitBackendError::InvalidObjectId(request.old_id.clone()))?;
992 let oid_new = git2::Oid::from_str(request.new_id.as_str())
993 .map_err(|_| GitBackendError::InvalidObjectId(request.new_id.clone()))?;
994
995 // Get the ids associates commits
996 let commit_old = git
997 .find_commit(oid_old)
998 .map_err(|_| GitBackendError::CommitNotFound(oid_old.to_string()))?;
999 let commit_new = git
1000 .find_commit(oid_new)
1001 .map_err(|_| GitBackendError::CommitNotFound(oid_new.to_string()))?;
1002
1003 // Get the commit trees
1004 let tree_old = commit_old
1005 .tree()
1006 .map_err(|_| GitBackendError::TreeNotFound(oid_old.to_string()))?;
1007 let tree_new = commit_new
1008 .tree()
1009 .map_err(|_| GitBackendError::TreeNotFound(oid_new.to_string()))?;
1010
1011 // Diff the two trees against each other
1012 let diff = git
1013 .diff_tree_to_tree(Some(&tree_old), Some(&tree_new), None)
1014 .map_err(|_| {
1015 GitBackendError::FailedDiffing(oid_old.to_string(), oid_new.to_string())
1016 })?;
1017
1018 // Print the entire patch
1019 let mut patch = String::new();
1020
1021 diff.print(git2::DiffFormat::Patch, |_, _, line| {
1022 match line.origin() {
1023 '+' | '-' | ' ' => patch.push(line.origin()),
1024 _ => {}
1025 }
1026 patch.push_str(std::str::from_utf8(line.content()).unwrap());
1027 true
1028 })
1029 .unwrap();
1030
1031 Ok(patch)
1032 }
1033
1034 async fn repository_commit_before(
1035 &mut self,
1036 requester: &Option<AuthenticatedUser>,
1037 repository: &Repository,
1038 request: &RepositoryCommitBeforeRequest,
1039 ) -> Result<Commit, Error> {
1040 let git = self
1041 .open_repository_and_check_permissions(&repository.owner, &repository.name, requester)
1042 .await?;
1043
1044 // Parse the passed object id
1045 let oid = match git2::Oid::from_str(request.0.as_str()) {
1046 Ok(oid) => oid,
1047 Err(_) => {
1048 return Err(Box::new(GitBackendError::InvalidObjectId(request.0.clone())).into())
1049 }
1050 };
1051
1052 // Find the commit using the parsed oid
1053 let commit = match git.find_commit(oid) {
1054 Ok(commit) => commit,
1055 Err(_) => return Err(Box::new(GitBackendError::CommitNotFound(oid.to_string())).into()),
1056 };
1057
1058 // Get the first parent it has
1059 let parent = commit.parent(0);
1060 if let Ok(parent) = parent {
1061 return Ok(Commit::from(parent));
1062 } else {
1063 // TODO: See if can be done better
1064 // Walk through the repository commit graph starting at our current commit
1065 let mut revwalk = git.revwalk()?;
1066 revwalk.set_sorting(git2::Sort::TIME)?;
1067 revwalk.push(commit.id())?;
1068
1069 if let Some(Ok(before_commit_oid)) = revwalk.next() {
1070 // Find the commit using the parsed oid
1071 if let Ok(before_commit) = git.find_commit(before_commit_oid) {
1072 return Ok(Commit::from(before_commit));
1073 }
1074 }
1075
1076 Err(Box::new(GitBackendError::CommitParentNotFound(oid.to_string())).into())
1077 }
1078 }
1079 }
1080
1081 impl IssuesBackend for GitBackend {
1082 fn issues_count(
1083 &mut self,
1084 _requester: &Option<AuthenticatedUser>,
1085 _request: &RepositoryIssuesCountRequest,
1086 ) -> Result<u64, Error> {
1087 todo!()
1088 }
1089
1090 fn issue_labels(
1091 &mut self,
1092 _requester: &Option<AuthenticatedUser>,
1093 _request: &RepositoryIssueLabelsRequest,
1094 ) -> Result<Vec<IssueLabel>, Error> {
1095 todo!()
1096 }
1097
1098 fn issues(
1099 &mut self,
1100 _requester: &Option<AuthenticatedUser>,
1101 _request: &RepositoryIssuesRequest,
1102 ) -> Result<Vec<RepositoryIssue>, Error> {
1103 todo!()
1104 }
1105 }
1106
1107 #[allow(unused)]
1108 #[derive(Debug, sqlx::FromRow)]
1109 struct RepositoryMetadata {
1110 pub repository: String,
1111 pub name: String,
1112 pub value: String,
1113 }
1114