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

ambee/giterated

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

Major post-refactor cleanup

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨f90d7fb

⁨src/backend/git.rs⁩ - ⁨18018⁩ bytes
Raw
1 use anyhow::Error;
2 use async_trait::async_trait;
3 use futures_util::StreamExt;
4 use git2::ObjectType;
5 use sqlx::{Either, PgPool};
6 use std::path::{Path, PathBuf};
7 use thiserror::Error;
8
9 use crate::model::instance::Instance;
10 use crate::model::repository::{
11 Commit, Repository, RepositoryObjectType, RepositorySummary, RepositoryTreeEntry,
12 RepositoryVisibility,
13 };
14 use crate::model::user::User;
15 use crate::{
16 messages::repository::{
17 CreateRepositoryRequest, CreateRepositoryResponse, RepositoryFileInspectRequest,
18 RepositoryFileInspectionResponse, RepositoryInfoRequest, RepositoryIssueLabelsRequest,
19 RepositoryIssueLabelsResponse, RepositoryIssuesCountRequest, RepositoryIssuesCountResponse,
20 RepositoryIssuesRequest, RepositoryIssuesResponse,
21 },
22 model::repository::RepositoryView,
23 };
24
25 use super::{IssuesBackend, RepositoryBackend};
26
27 // TODO: Handle this
28 //region database structures
29
30 /// Repository in the database
31 #[derive(Debug, sqlx::FromRow)]
32 pub struct GitRepository {
33 #[sqlx(try_from = "String")]
34 pub owner_user: User,
35 pub name: String,
36 pub description: Option<String>,
37 pub visibility: RepositoryVisibility,
38 pub default_branch: String,
39 }
40
41 impl GitRepository {
42 // Separate function because "Private" will be expanded later
43 /// Checks if the user is allowed to view this repository
44 pub fn can_user_view_repository(&self, user: Option<&User>) -> bool {
45 !matches!(self.visibility, RepositoryVisibility::Private)
46 || (matches!(self.visibility, RepositoryVisibility::Private)
47 && Some(&self.owner_user) == user)
48 }
49
50 // This is in it's own function because I assume I'll have to add logic to this later
51 pub fn open_git2_repository(
52 &self,
53 repository_directory: &str,
54 ) -> Result<git2::Repository, GitBackendError> {
55 match git2::Repository::open(format!(
56 "{}/{}/{}/{}",
57 repository_directory, self.owner_user.instance.url, self.owner_user.username, self.name
58 )) {
59 Ok(repository) => Ok(repository),
60 Err(err) => {
61 let err = GitBackendError::FailedOpeningFromDisk(err);
62 error!("Couldn't open a repository, this is bad! {:?}", err);
63
64 Err(err)
65 }
66 }
67 }
68 }
69
70 //endregion
71
72 #[derive(Error, Debug)]
73 pub enum GitBackendError {
74 #[error("Failed creating repository")]
75 FailedCreatingRepository(git2::Error),
76 #[error("Failed inserting into the database")]
77 FailedInsertingIntoDatabase(sqlx::Error),
78 #[error("Failed finding repository {owner_user:?}/{name:?}")]
79 RepositoryNotFound { owner_user: String, name: String },
80 #[error("Repository {owner_user:?}/{name:?} already exists")]
81 RepositoryAlreadyExists { owner_user: String, name: String },
82 #[error("Repository couldn't be deleted from the disk")]
83 CouldNotDeleteFromDisk(std::io::Error),
84 #[error("Failed deleting repository from database")]
85 FailedDeletingFromDatabase(sqlx::Error),
86 #[error("Failed opening repository on disk")]
87 FailedOpeningFromDisk(git2::Error),
88 #[error("Couldn't find ref with name `{0}`")]
89 RefNotFound(String),
90 #[error("Couldn't find path in repository `{0}`")]
91 PathNotFound(String),
92 #[error("Couldn't find commit for path `{0}`")]
93 LastCommitNotFound(String),
94 }
95
96 pub struct GitBackend {
97 pub pg_pool: PgPool,
98 pub repository_folder: String,
99 pub instance: Instance,
100 }
101
102 impl GitBackend {
103 pub fn new(
104 pg_pool: &PgPool,
105 repository_folder: &str,
106 instance: impl ToOwned<Owned = Instance>,
107 ) -> Self {
108 Self {
109 pg_pool: pg_pool.clone(),
110 repository_folder: repository_folder.to_string(),
111 instance: instance.to_owned(),
112 }
113 }
114
115 pub async fn find_by_owner_user_name(
116 &self,
117 user: &User,
118 repository_name: &str,
119 ) -> Result<GitRepository, GitBackendError> {
120 if let Ok(repository) = sqlx::query_as!(GitRepository,
121 r#"SELECT owner_user, name, description, visibility as "visibility: _", default_branch FROM repositories WHERE owner_user = $1 AND name = $2"#,
122 user.to_string(), repository_name)
123 .fetch_one(&self.pg_pool.clone())
124 .await {
125 Ok(repository)
126 } else {
127 Err(GitBackendError::RepositoryNotFound {
128 owner_user: user.to_string(),
129 name: repository_name.to_string(),
130 })
131 }
132 }
133
134 pub async fn delete_by_owner_user_name(
135 &self,
136 user: &User,
137 repository_name: &str,
138 ) -> Result<u64, GitBackendError> {
139 if let Err(err) = std::fs::remove_dir_all(PathBuf::from(format!(
140 "{}/{}/{}/{}",
141 self.repository_folder, user.instance.url, user.username, repository_name
142 ))) {
143 let err = GitBackendError::CouldNotDeleteFromDisk(err);
144 error!(
145 "Couldn't delete repository from disk, this is bad! {:?}",
146 err
147 );
148
149 return Err(err);
150 }
151
152 // Delete the repository from the database
153 match sqlx::query!(
154 "DELETE FROM repositories WHERE owner_user = $1 AND name = $2",
155 user.to_string(),
156 repository_name
157 )
158 .execute(&self.pg_pool.clone())
159 .await
160 {
161 Ok(deleted) => Ok(deleted.rows_affected()),
162 Err(err) => Err(GitBackendError::FailedDeletingFromDatabase(err)),
163 }
164 }
165
166 // TODO: Find where this fits
167 // TODO: Cache this and general repository tree and invalidate select files on push
168 // TODO: Find better and faster technique for this
169 pub fn get_last_commit_of_file(
170 path: &str,
171 git: &git2::Repository,
172 start_commit: &git2::Commit,
173 ) -> anyhow::Result<Commit> {
174 let mut revwalk = git.revwalk()?;
175 revwalk.set_sorting(git2::Sort::TIME)?;
176 revwalk.push(start_commit.id())?;
177
178 for oid in revwalk {
179 let oid = oid?;
180 let commit = git.find_commit(oid)?;
181
182 // Merge commits have 2 or more parents
183 // Commits with 0 parents are handled different because we can't diff against them
184 if commit.parent_count() == 0 {
185 return Ok(commit.into());
186 } else if commit.parent_count() == 1 {
187 let tree = commit.tree()?;
188 let last_tree = commit.parent(0)?.tree()?;
189
190 // Get the diff between the current tree and the last one
191 let diff = git.diff_tree_to_tree(Some(&last_tree), Some(&tree), None)?;
192
193 for dd in diff.deltas() {
194 // Get the path of the current file we're diffing against
195 let current_path = dd.new_file().path().unwrap();
196
197 // Path or directory
198 if current_path.eq(Path::new(&path)) || current_path.starts_with(path) {
199 return Ok(commit.into());
200 }
201 }
202 }
203 }
204
205 Err(GitBackendError::LastCommitNotFound(path.to_string()))?
206 }
207 }
208
209 #[async_trait]
210 impl RepositoryBackend for GitBackend {
211 async fn create_repository(
212 &mut self,
213 _user: &User,
214 request: &CreateRepositoryRequest,
215 ) -> Result<CreateRepositoryResponse, Error> {
216 // Check if repository already exists in the database
217 if let Ok(repository) = self
218 .find_by_owner_user_name(&request.owner, &request.name)
219 .await
220 {
221 let err = GitBackendError::RepositoryAlreadyExists {
222 owner_user: repository.owner_user.to_string(),
223 name: repository.name,
224 };
225 error!("{:?}", err);
226
227 return Ok(CreateRepositoryResponse::Failed);
228 }
229
230 // Insert the repository into the database
231 let _ = match sqlx::query_as!(GitRepository,
232 r#"INSERT INTO repositories VALUES ($1, $2, $3, $4, $5) RETURNING owner_user, name, description, visibility as "visibility: _", default_branch"#,
233 request.owner.to_string(), request.name, request.description, request.visibility as _, "master")
234 .fetch_one(&self.pg_pool.clone())
235 .await {
236 Ok(repository) => repository,
237 Err(err) => {
238 let err = GitBackendError::FailedInsertingIntoDatabase(err);
239 error!("Failed inserting into the database! {:?}", err);
240
241 return Ok(CreateRepositoryResponse::Failed);
242 }
243 };
244
245 // Create bare (server side) repository on disk
246 match git2::Repository::init_bare(PathBuf::from(format!(
247 "{}/{}/{}/{}",
248 self.repository_folder,
249 request.owner.instance.url,
250 request.owner.username,
251 request.name
252 ))) {
253 Ok(_) => {
254 debug!(
255 "Created new repository with the name {}/{}/{}",
256 request.owner.instance.url, request.owner.username, request.name
257 );
258 Ok(CreateRepositoryResponse::Created)
259 }
260 Err(err) => {
261 let err = GitBackendError::FailedCreatingRepository(err);
262 error!("Failed creating repository on disk!? {:?}", err);
263
264 // Delete repository from database
265 if let Err(err) = self
266 .delete_by_owner_user_name(&request.owner, request.name.as_str())
267 .await
268 {
269 return Err(Box::new(err).into());
270 }
271
272 // ???
273 Ok(CreateRepositoryResponse::Failed)
274 //Err(Box::new(err))
275 }
276 }
277 }
278
279 async fn repository_info(
280 &mut self,
281 requester: Option<&User>,
282 request: &RepositoryInfoRequest,
283 ) -> Result<RepositoryView, Error> {
284 let repository = match self
285 .find_by_owner_user_name(
286 // &request.owner.instance.url,
287 &request.repository.owner,
288 &request.repository.name,
289 )
290 .await
291 {
292 Ok(repository) => repository,
293 Err(err) => return Err(Box::new(err).into()),
294 };
295
296 if let Some(requester) = requester {
297 if !repository.can_user_view_repository(Some(&requester)) {
298 return Err(Box::new(GitBackendError::RepositoryNotFound {
299 owner_user: request.repository.owner.to_string(),
300 name: request.repository.name.clone(),
301 })
302 .into());
303 }
304 } else if matches!(repository.visibility, RepositoryVisibility::Private) {
305 // Unauthenticated users can never view private repositories
306
307 return Err(Box::new(GitBackendError::RepositoryNotFound {
308 owner_user: request.repository.owner.to_string(),
309 name: request.repository.name.clone(),
310 })
311 .into());
312 }
313
314 let git = match repository.open_git2_repository(&self.repository_folder) {
315 Ok(git) => git,
316 Err(err) => return Err(Box::new(err).into()),
317 };
318
319 let rev_name = match &request.rev {
320 None => {
321 if let Ok(head) = git.head() {
322 head.name().unwrap().to_string()
323 } else {
324 // Nothing in database, render empty tree.
325 return Ok(RepositoryView {
326 name: repository.name,
327 owner: request.repository.owner.clone(),
328 description: repository.description,
329 visibility: repository.visibility,
330 default_branch: repository.default_branch,
331 latest_commit: None,
332 tree_rev: None,
333 tree: vec![],
334 });
335 }
336 }
337 Some(rev_name) => {
338 // Find the reference, otherwise return GitBackendError
339 match git
340 .find_reference(format!("refs/heads/{}", rev_name).as_str())
341 .map_err(|_| GitBackendError::RefNotFound(rev_name.to_string()))
342 {
343 Ok(reference) => reference.name().unwrap().to_string(),
344 Err(err) => return Err(Box::new(err).into()),
345 }
346 }
347 };
348
349 // Get the git object as a commit
350 let rev = match git
351 .revparse_single(rev_name.as_str())
352 .map_err(|_| GitBackendError::RefNotFound(rev_name.to_string()))
353 {
354 Ok(rev) => rev,
355 Err(err) => return Err(Box::new(err).into()),
356 };
357 let commit = rev.as_commit().unwrap();
358
359 // this is stupid
360 let mut current_path = rev_name.replace("refs/heads/", "");
361
362 // Get the commit tree
363 let git_tree = if let Some(path) = &request.path {
364 // Add it to our full path string
365 current_path.push_str(format!("/{}", path).as_str());
366 // Get the specified path, return an error if it wasn't found.
367 let entry = match commit
368 .tree()
369 .unwrap()
370 .get_path(&PathBuf::from(path))
371 .map_err(|_| GitBackendError::PathNotFound(path.to_string()))
372 {
373 Ok(entry) => entry,
374 Err(err) => return Err(Box::new(err).into()),
375 };
376 // Turn the entry into a git tree
377 entry.to_object(&git).unwrap().as_tree().unwrap().clone()
378 } else {
379 commit.tree().unwrap()
380 };
381
382 // Iterate over the git tree and collect it into our own tree types
383 let mut tree = git_tree
384 .iter()
385 .map(|entry| {
386 let object_type = match entry.kind().unwrap() {
387 ObjectType::Tree => RepositoryObjectType::Tree,
388 ObjectType::Blob => RepositoryObjectType::Blob,
389 _ => unreachable!(),
390 };
391 let mut tree_entry =
392 RepositoryTreeEntry::new(entry.name().unwrap(), object_type, entry.filemode());
393
394 if request.extra_metadata {
395 // Get the file size if It's a blob
396 let object = entry.to_object(&git).unwrap();
397 if let Some(blob) = object.as_blob() {
398 tree_entry.size = Some(blob.size());
399 }
400
401 // Could possibly be done better
402 let path = if let Some(path) = current_path.split_once('/') {
403 format!("{}/{}", path.1, entry.name().unwrap())
404 } else {
405 entry.name().unwrap().to_string()
406 };
407
408 // Get the last commit made to the entry
409 if let Ok(last_commit) =
410 GitBackend::get_last_commit_of_file(&path, &git, commit)
411 {
412 tree_entry.last_commit = Some(last_commit);
413 }
414 }
415
416 tree_entry
417 })
418 .collect::<Vec<RepositoryTreeEntry>>();
419
420 // Sort the tree alphabetically and with tree first
421 tree.sort_unstable_by_key(|entry| entry.name.to_lowercase());
422 tree.sort_unstable_by_key(|entry| {
423 std::cmp::Reverse(format!("{:?}", entry.object_type).to_lowercase())
424 });
425
426 Ok(RepositoryView {
427 name: repository.name,
428 owner: request.repository.owner.clone(),
429 description: repository.description,
430 visibility: repository.visibility,
431 default_branch: repository.default_branch,
432 latest_commit: None,
433 tree_rev: Some(rev_name),
434 tree,
435 })
436 }
437
438 async fn repository_file_inspect(
439 &mut self,
440 _requester: Option<&User>,
441 _request: &RepositoryFileInspectRequest,
442 ) -> Result<RepositoryFileInspectionResponse, Error> {
443 todo!()
444 }
445
446 async fn repositories_for_user(
447 &mut self,
448 user: &User,
449 ) -> Result<Vec<RepositorySummary>, Error> {
450 let mut repositories = sqlx::query_as!(
451 GitRepository,
452 r#"SELECT visibility as "visibility: _", owner_user, name, description, default_branch FROM repositories WHERE owner_user = $1"#,
453 user.to_string()
454 )
455 .fetch_many(&self.pg_pool);
456
457 let mut result = vec![];
458
459 while let Some(Ok(Either::Right(repository))) = repositories.next().await {
460 result.push(RepositorySummary {
461 repository: Repository {
462 owner: repository.owner_user.clone(),
463 name: repository.name,
464 instance: self.instance.clone(),
465 },
466 owner: repository.owner_user.clone(),
467 visibility: repository.visibility,
468 description: repository.description,
469 // TODO
470 last_commit: None,
471 });
472 }
473
474 Ok(result)
475 }
476 }
477
478 impl IssuesBackend for GitBackend {
479 fn issues_count(
480 &mut self,
481 _requester: Option<&User>,
482 _request: &RepositoryIssuesCountRequest,
483 ) -> Result<RepositoryIssuesCountResponse, Error> {
484 todo!()
485 }
486
487 fn issue_labels(
488 &mut self,
489 _requester: Option<&User>,
490 _request: &RepositoryIssueLabelsRequest,
491 ) -> Result<RepositoryIssueLabelsResponse, Error> {
492 todo!()
493 }
494
495 fn issues(
496 &mut self,
497 _requester: Option<&User>,
498 _request: &RepositoryIssuesRequest,
499 ) -> Result<RepositoryIssuesResponse, Error> {
500 todo!()
501 }
502 }
503