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

ambee/giterated

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

Fix path when branch has a / in it

We now just replace the current_path by using the rev instead of doing sketchy logic splitting on /

erremilia - ⁨2⁩ years ago

parent: tbd commit: ⁨d1b0ff7

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