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

ambee/giterated

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

Fixed imports!

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨ef0e853

⁨giterated-daemon/src/backend/git.rs⁩ - ⁨20757⁩ bytes
Raw
1 use anyhow::Error;
2 use async_trait::async_trait;
3 use futures_util::StreamExt;
4
5 use giterated_models::instance::{Instance, RepositoryCreateRequest};
6
7 use giterated_models::repository::{
8 Commit, IssueLabel, Repository, RepositoryDescription, RepositoryFileInspectRequest,
9 RepositoryIssue, RepositoryIssueLabelsRequest, RepositoryIssuesCountRequest,
10 RepositoryIssuesRequest, RepositorySummary, RepositoryTreeEntry, RepositoryVisibility,
11 RepositoryVisibilitySetting,
12 };
13 use giterated_models::settings::{AnySetting, Setting};
14 use giterated_models::user::{User, UserParseError};
15 use giterated_models::value::AnyValue;
16 use serde_json::Value;
17 use sqlx::{Either, PgPool};
18 use std::{
19 path::{Path, PathBuf},
20 sync::Arc,
21 };
22 use thiserror::Error;
23 use tokio::sync::Mutex;
24
25 use super::{IssuesBackend, MetadataBackend, 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 pub settings_provider: Arc<Mutex<dyn MetadataBackend + Send>>,
101 }
102
103 impl GitBackend {
104 pub fn new(
105 pg_pool: &PgPool,
106 repository_folder: &str,
107 instance: impl ToOwned<Owned = Instance>,
108 settings_provider: Arc<Mutex<dyn MetadataBackend + Send>>,
109 ) -> Self {
110 Self {
111 pg_pool: pg_pool.clone(),
112 repository_folder: repository_folder.to_string(),
113 instance: instance.to_owned(),
114 settings_provider,
115 }
116 }
117
118 pub async fn find_by_owner_user_name(
119 &self,
120 user: &User,
121 repository_name: &str,
122 ) -> Result<GitRepository, GitBackendError> {
123 if let Ok(repository) = sqlx::query_as!(GitRepository,
124 r#"SELECT owner_user, name, description, visibility as "visibility: _", default_branch FROM repositories WHERE owner_user = $1 AND name = $2"#,
125 user.to_string(), repository_name)
126 .fetch_one(&self.pg_pool.clone())
127 .await {
128 Ok(repository)
129 } else {
130 Err(GitBackendError::RepositoryNotFound {
131 owner_user: user.to_string(),
132 name: repository_name.to_string(),
133 })
134 }
135 }
136
137 pub async fn delete_by_owner_user_name(
138 &self,
139 user: &User,
140 repository_name: &str,
141 ) -> Result<u64, GitBackendError> {
142 if let Err(err) = std::fs::remove_dir_all(PathBuf::from(format!(
143 "{}/{}/{}/{}",
144 self.repository_folder, user.instance.url, user.username, repository_name
145 ))) {
146 let err = GitBackendError::CouldNotDeleteFromDisk(err);
147 error!(
148 "Couldn't delete repository from disk, this is bad! {:?}",
149 err
150 );
151
152 return Err(err);
153 }
154
155 // Delete the repository from the database
156 match sqlx::query!(
157 "DELETE FROM repositories WHERE owner_user = $1 AND name = $2",
158 user.to_string(),
159 repository_name
160 )
161 .execute(&self.pg_pool.clone())
162 .await
163 {
164 Ok(deleted) => Ok(deleted.rows_affected()),
165 Err(err) => Err(GitBackendError::FailedDeletingFromDatabase(err)),
166 }
167 }
168
169 // TODO: Find where this fits
170 // TODO: Cache this and general repository tree and invalidate select files on push
171 // TODO: Find better and faster technique for this
172 pub fn get_last_commit_of_file(
173 path: &str,
174 git: &git2::Repository,
175 start_commit: &git2::Commit,
176 ) -> anyhow::Result<Commit> {
177 let mut revwalk = git.revwalk()?;
178 revwalk.set_sorting(git2::Sort::TIME)?;
179 revwalk.push(start_commit.id())?;
180
181 for oid in revwalk {
182 let oid = oid?;
183 let commit = git.find_commit(oid)?;
184
185 // Merge commits have 2 or more parents
186 // Commits with 0 parents are handled different because we can't diff against them
187 if commit.parent_count() == 0 {
188 return Ok(commit.into());
189 } else if commit.parent_count() == 1 {
190 let tree = commit.tree()?;
191 let last_tree = commit.parent(0)?.tree()?;
192
193 // Get the diff between the current tree and the last one
194 let diff = git.diff_tree_to_tree(Some(&last_tree), Some(&tree), None)?;
195
196 for dd in diff.deltas() {
197 // Get the path of the current file we're diffing against
198 let current_path = dd.new_file().path().unwrap();
199
200 // Path or directory
201 if current_path.eq(Path::new(&path)) || current_path.starts_with(path) {
202 return Ok(commit.into());
203 }
204 }
205 }
206 }
207
208 Err(GitBackendError::LastCommitNotFound(path.to_string()))?
209 }
210 }
211
212 #[async_trait]
213 impl RepositoryBackend for GitBackend {
214 async fn exists(&mut self, repository: &Repository) -> Result<bool, Error> {
215 if let Ok(_repository) = self
216 .find_by_owner_user_name(&repository.owner, &repository.name)
217 .await
218 {
219 return Ok(true);
220 } else {
221 return Ok(false);
222 }
223 }
224 async fn create_repository(
225 &mut self,
226 _user: &User,
227 request: &RepositoryCreateRequest,
228 ) -> Result<Repository, GitBackendError> {
229 // Check if repository already exists in the database
230 if let Ok(repository) = self
231 .find_by_owner_user_name(&request.owner, &request.name)
232 .await
233 {
234 let err = GitBackendError::RepositoryAlreadyExists {
235 owner_user: repository.owner_user.to_string(),
236 name: repository.name,
237 };
238 error!("{:?}", err);
239
240 return Err(err);
241 }
242
243 // Insert the repository into the database
244 let _ = match sqlx::query_as!(GitRepository,
245 r#"INSERT INTO repositories VALUES ($1, $2, $3, $4, $5) RETURNING owner_user, name, description, visibility as "visibility: _", default_branch"#,
246 request.owner.to_string(), request.name, request.description, request.visibility as _, "master")
247 .fetch_one(&self.pg_pool.clone())
248 .await {
249 Ok(repository) => repository,
250 Err(err) => {
251 let err = GitBackendError::FailedInsertingIntoDatabase(err);
252 error!("Failed inserting into the database! {:?}", err);
253
254 return Err(err);
255 }
256 };
257
258 // Create bare (server side) repository on disk
259 match git2::Repository::init_bare(PathBuf::from(format!(
260 "{}/{}/{}/{}",
261 self.repository_folder,
262 request.owner.instance.url,
263 request.owner.username,
264 request.name
265 ))) {
266 Ok(_) => {
267 debug!(
268 "Created new repository with the name {}/{}/{}",
269 request.owner.instance.url, request.owner.username, request.name
270 );
271 Ok(Repository {
272 owner: request.owner.clone(),
273 name: request.name.clone(),
274 instance: request.instance.as_ref().unwrap_or(&self.instance).clone(),
275 })
276 }
277 Err(err) => {
278 let err = GitBackendError::FailedCreatingRepository(err);
279 error!("Failed creating repository on disk!? {:?}", err);
280
281 // Delete repository from database
282 self.delete_by_owner_user_name(&request.owner, request.name.as_str())
283 .await?;
284
285 // ???
286 Err(err)
287 }
288 }
289 }
290
291 async fn get_value(
292 &mut self,
293 repository: &Repository,
294 name: &str,
295 ) -> Result<AnyValue<Repository>, Error> {
296 Ok(match name {
297 "description" => unsafe {
298 AnyValue::from_raw(
299 self.get_setting(repository, RepositoryDescription::name())
300 .await?
301 .0,
302 )
303 },
304 "visibility" => unsafe {
305 AnyValue::from_raw(
306 self.get_setting(repository, RepositoryVisibilitySetting::name())
307 .await?
308 .0,
309 )
310 },
311 _ => {
312 return Err(UserParseError.into());
313 }
314 })
315 }
316 async fn get_setting(
317 &mut self,
318 repository: &Repository,
319 name: &str,
320 ) -> Result<AnySetting, Error> {
321 let mut provider = self.settings_provider.lock().await;
322
323 Ok(provider.repository_get(repository, name).await?)
324 }
325 async fn write_setting(
326 &mut self,
327 repository: &Repository,
328 name: &str,
329 setting: &Value,
330 ) -> Result<(), Error> {
331 let mut provider = self.settings_provider.lock().await;
332
333 provider
334 .repository_write(repository, name, AnySetting(setting.clone()))
335 .await
336 }
337 // async fn repository_info(
338 // &mut self,
339 // requester: Option<&User>,
340 // request: &RepositoryInfoRequest,
341 // ) -> Result<RepositoryView, Error> {
342 // let repository = match self
343 // .find_by_owner_user_name(
344 // // &request.owner.instance.url,
345 // &request.repository.owner,
346 // &request.repository.name,
347 // )
348 // .await
349 // {
350 // Ok(repository) => repository,
351 // Err(err) => return Err(Box::new(err).into()),
352 // };
353
354 // if let Some(requester) = requester {
355 // if !repository.can_user_view_repository(Some(&requester)) {
356 // return Err(Box::new(GitBackendError::RepositoryNotFound {
357 // owner_user: request.repository.owner.to_string(),
358 // name: request.repository.name.clone(),
359 // })
360 // .into());
361 // }
362 // } else if matches!(repository.visibility, RepositoryVisibility::Private) {
363 // info!("Unauthenticated");
364 // // Unauthenticated users can never view private repositories
365
366 // return Err(Box::new(GitBackendError::RepositoryNotFound {
367 // owner_user: request.repository.owner.to_string(),
368 // name: request.repository.name.clone(),
369 // })
370 // .into());
371 // }
372
373 // let git = match repository.open_git2_repository(&self.repository_folder) {
374 // Ok(git) => git,
375 // Err(err) => return Err(Box::new(err).into()),
376 // };
377
378 // let rev_name = match &request.rev {
379 // None => {
380 // if let Ok(head) = git.head() {
381 // head.name().unwrap().to_string()
382 // } else {
383 // // Nothing in database, render empty tree.
384 // return Ok(RepositoryView {
385 // name: repository.name,
386 // owner: request.repository.owner.clone(),
387 // description: repository.description,
388 // visibility: repository.visibility,
389 // default_branch: repository.default_branch,
390 // latest_commit: None,
391 // tree_rev: None,
392 // tree: vec![],
393 // });
394 // }
395 // }
396 // Some(rev_name) => {
397 // // Find the reference, otherwise return GitBackendError
398 // match git
399 // .find_reference(format!("refs/heads/{}", rev_name).as_str())
400 // .map_err(|_| GitBackendError::RefNotFound(rev_name.to_string()))
401 // {
402 // Ok(reference) => reference.name().unwrap().to_string(),
403 // Err(err) => return Err(Box::new(err).into()),
404 // }
405 // }
406 // };
407
408 // // Get the git object as a commit
409 // let rev = match git
410 // .revparse_single(rev_name.as_str())
411 // .map_err(|_| GitBackendError::RefNotFound(rev_name.to_string()))
412 // {
413 // Ok(rev) => rev,
414 // Err(err) => return Err(Box::new(err).into()),
415 // };
416 // let commit = rev.as_commit().unwrap();
417
418 // // this is stupid
419 // let mut current_path = rev_name.replace("refs/heads/", "");
420
421 // // Get the commit tree
422 // let git_tree = if let Some(path) = &request.path {
423 // // Add it to our full path string
424 // current_path.push_str(format!("/{}", path).as_str());
425 // // Get the specified path, return an error if it wasn't found.
426 // let entry = match commit
427 // .tree()
428 // .unwrap()
429 // .get_path(&PathBuf::from(path))
430 // .map_err(|_| GitBackendError::PathNotFound(path.to_string()))
431 // {
432 // Ok(entry) => entry,
433 // Err(err) => return Err(Box::new(err).into()),
434 // };
435 // // Turn the entry into a git tree
436 // entry.to_object(&git).unwrap().as_tree().unwrap().clone()
437 // } else {
438 // commit.tree().unwrap()
439 // };
440
441 // // Iterate over the git tree and collect it into our own tree types
442 // let mut tree = git_tree
443 // .iter()
444 // .map(|entry| {
445 // let object_type = match entry.kind().unwrap() {
446 // ObjectType::Tree => RepositoryObjectType::Tree,
447 // ObjectType::Blob => RepositoryObjectType::Blob,
448 // _ => unreachable!(),
449 // };
450 // let mut tree_entry =
451 // RepositoryTreeEntry::new(entry.name().unwrap(), object_type, entry.filemode());
452
453 // if request.extra_metadata {
454 // // Get the file size if It's a blob
455 // let object = entry.to_object(&git).unwrap();
456 // if let Some(blob) = object.as_blob() {
457 // tree_entry.size = Some(blob.size());
458 // }
459
460 // // Could possibly be done better
461 // let path = if let Some(path) = current_path.split_once('/') {
462 // format!("{}/{}", path.1, entry.name().unwrap())
463 // } else {
464 // entry.name().unwrap().to_string()
465 // };
466
467 // // Get the last commit made to the entry
468 // if let Ok(last_commit) =
469 // GitBackend::get_last_commit_of_file(&path, &git, commit)
470 // {
471 // tree_entry.last_commit = Some(last_commit);
472 // }
473 // }
474
475 // tree_entry
476 // })
477 // .collect::<Vec<RepositoryTreeEntry>>();
478
479 // // Sort the tree alphabetically and with tree first
480 // tree.sort_unstable_by_key(|entry| entry.name.to_lowercase());
481 // tree.sort_unstable_by_key(|entry| {
482 // std::cmp::Reverse(format!("{:?}", entry.object_type).to_lowercase())
483 // });
484
485 // Ok(RepositoryView {
486 // name: repository.name,
487 // owner: request.repository.owner.clone(),
488 // description: repository.description,
489 // visibility: repository.visibility,
490 // default_branch: repository.default_branch,
491 // latest_commit: Some(Commit::from(commit.clone())),
492 // tree_rev: Some(rev_name),
493 // tree,
494 // })
495 // }
496
497 async fn repository_file_inspect(
498 &mut self,
499 _requester: Option<&User>,
500 _request: &RepositoryFileInspectRequest,
501 ) -> Result<Vec<RepositoryTreeEntry>, Error> {
502 todo!()
503 }
504
505 async fn repositories_for_user(
506 &mut self,
507 requester: Option<&User>,
508 user: &User,
509 ) -> Result<Vec<RepositorySummary>, Error> {
510 let mut repositories = sqlx::query_as!(
511 GitRepository,
512 r#"SELECT visibility as "visibility: _", owner_user, name, description, default_branch FROM repositories WHERE owner_user = $1"#,
513 user.to_string()
514 )
515 .fetch_many(&self.pg_pool);
516
517 let mut result = vec![];
518
519 while let Some(Ok(Either::Right(repository))) = repositories.next().await {
520 // Check if the requesting user is allowed to see the repository
521 if !(matches!(
522 repository.visibility,
523 RepositoryVisibility::Unlisted | RepositoryVisibility::Private
524 ) && Some(&repository.owner_user.clone()) != requester)
525 {
526 result.push(RepositorySummary {
527 repository: Repository {
528 owner: repository.owner_user.clone(),
529 name: repository.name,
530 instance: self.instance.clone(),
531 },
532 owner: repository.owner_user.clone(),
533 visibility: repository.visibility,
534 description: repository.description,
535 // TODO
536 last_commit: None,
537 });
538 }
539 }
540
541 Ok(result)
542 }
543 }
544
545 impl IssuesBackend for GitBackend {
546 fn issues_count(
547 &mut self,
548 _requester: Option<&User>,
549 _request: &RepositoryIssuesCountRequest,
550 ) -> Result<u64, Error> {
551 todo!()
552 }
553
554 fn issue_labels(
555 &mut self,
556 _requester: Option<&User>,
557 _request: &RepositoryIssueLabelsRequest,
558 ) -> Result<Vec<IssueLabel>, Error> {
559 todo!()
560 }
561
562 fn issues(
563 &mut self,
564 _requester: Option<&User>,
565 _request: &RepositoryIssuesRequest,
566 ) -> Result<Vec<RepositoryIssue>, Error> {
567 todo!()
568 }
569 }
570
571 #[derive(Debug, sqlx::FromRow)]
572 struct RepositoryMetadata {
573 pub repository: String,
574 pub name: String,
575 pub value: String,
576 }
577