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

ambee/giterated

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

Fixes

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨863a1d7

⁨giterated-daemon/src/backend/git.rs⁩ - ⁨20795⁩ 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 info!("Description");
299 AnyValue::from_raw(
300 self.get_setting(repository, RepositoryDescription::name())
301 .await?
302 .0,
303 )
304 },
305 "visibility" => unsafe {
306 AnyValue::from_raw(
307 self.get_setting(repository, RepositoryVisibilitySetting::name())
308 .await?
309 .0,
310 )
311 },
312 _ => {
313 return Err(UserParseError.into());
314 }
315 })
316 }
317 async fn get_setting(
318 &mut self,
319 repository: &Repository,
320 name: &str,
321 ) -> Result<AnySetting, Error> {
322 let mut provider = self.settings_provider.lock().await;
323
324 Ok(provider.repository_get(repository, name).await?)
325 }
326 async fn write_setting(
327 &mut self,
328 repository: &Repository,
329 name: &str,
330 setting: &Value,
331 ) -> Result<(), Error> {
332 let mut provider = self.settings_provider.lock().await;
333
334 provider
335 .repository_write(repository, name, AnySetting(setting.clone()))
336 .await
337 }
338 // async fn repository_info(
339 // &mut self,
340 // requester: Option<&User>,
341 // request: &RepositoryInfoRequest,
342 // ) -> Result<RepositoryView, Error> {
343 // let repository = match self
344 // .find_by_owner_user_name(
345 // // &request.owner.instance.url,
346 // &request.repository.owner,
347 // &request.repository.name,
348 // )
349 // .await
350 // {
351 // Ok(repository) => repository,
352 // Err(err) => return Err(Box::new(err).into()),
353 // };
354
355 // if let Some(requester) = requester {
356 // if !repository.can_user_view_repository(Some(&requester)) {
357 // return Err(Box::new(GitBackendError::RepositoryNotFound {
358 // owner_user: request.repository.owner.to_string(),
359 // name: request.repository.name.clone(),
360 // })
361 // .into());
362 // }
363 // } else if matches!(repository.visibility, RepositoryVisibility::Private) {
364 // info!("Unauthenticated");
365 // // Unauthenticated users can never view private repositories
366
367 // return Err(Box::new(GitBackendError::RepositoryNotFound {
368 // owner_user: request.repository.owner.to_string(),
369 // name: request.repository.name.clone(),
370 // })
371 // .into());
372 // }
373
374 // let git = match repository.open_git2_repository(&self.repository_folder) {
375 // Ok(git) => git,
376 // Err(err) => return Err(Box::new(err).into()),
377 // };
378
379 // let rev_name = match &request.rev {
380 // None => {
381 // if let Ok(head) = git.head() {
382 // head.name().unwrap().to_string()
383 // } else {
384 // // Nothing in database, render empty tree.
385 // return Ok(RepositoryView {
386 // name: repository.name,
387 // owner: request.repository.owner.clone(),
388 // description: repository.description,
389 // visibility: repository.visibility,
390 // default_branch: repository.default_branch,
391 // latest_commit: None,
392 // tree_rev: None,
393 // tree: vec![],
394 // });
395 // }
396 // }
397 // Some(rev_name) => {
398 // // Find the reference, otherwise return GitBackendError
399 // match git
400 // .find_reference(format!("refs/heads/{}", rev_name).as_str())
401 // .map_err(|_| GitBackendError::RefNotFound(rev_name.to_string()))
402 // {
403 // Ok(reference) => reference.name().unwrap().to_string(),
404 // Err(err) => return Err(Box::new(err).into()),
405 // }
406 // }
407 // };
408
409 // // Get the git object as a commit
410 // let rev = match git
411 // .revparse_single(rev_name.as_str())
412 // .map_err(|_| GitBackendError::RefNotFound(rev_name.to_string()))
413 // {
414 // Ok(rev) => rev,
415 // Err(err) => return Err(Box::new(err).into()),
416 // };
417 // let commit = rev.as_commit().unwrap();
418
419 // // this is stupid
420 // let mut current_path = rev_name.replace("refs/heads/", "");
421
422 // // Get the commit tree
423 // let git_tree = if let Some(path) = &request.path {
424 // // Add it to our full path string
425 // current_path.push_str(format!("/{}", path).as_str());
426 // // Get the specified path, return an error if it wasn't found.
427 // let entry = match commit
428 // .tree()
429 // .unwrap()
430 // .get_path(&PathBuf::from(path))
431 // .map_err(|_| GitBackendError::PathNotFound(path.to_string()))
432 // {
433 // Ok(entry) => entry,
434 // Err(err) => return Err(Box::new(err).into()),
435 // };
436 // // Turn the entry into a git tree
437 // entry.to_object(&git).unwrap().as_tree().unwrap().clone()
438 // } else {
439 // commit.tree().unwrap()
440 // };
441
442 // // Iterate over the git tree and collect it into our own tree types
443 // let mut tree = git_tree
444 // .iter()
445 // .map(|entry| {
446 // let object_type = match entry.kind().unwrap() {
447 // ObjectType::Tree => RepositoryObjectType::Tree,
448 // ObjectType::Blob => RepositoryObjectType::Blob,
449 // _ => unreachable!(),
450 // };
451 // let mut tree_entry =
452 // RepositoryTreeEntry::new(entry.name().unwrap(), object_type, entry.filemode());
453
454 // if request.extra_metadata {
455 // // Get the file size if It's a blob
456 // let object = entry.to_object(&git).unwrap();
457 // if let Some(blob) = object.as_blob() {
458 // tree_entry.size = Some(blob.size());
459 // }
460
461 // // Could possibly be done better
462 // let path = if let Some(path) = current_path.split_once('/') {
463 // format!("{}/{}", path.1, entry.name().unwrap())
464 // } else {
465 // entry.name().unwrap().to_string()
466 // };
467
468 // // Get the last commit made to the entry
469 // if let Ok(last_commit) =
470 // GitBackend::get_last_commit_of_file(&path, &git, commit)
471 // {
472 // tree_entry.last_commit = Some(last_commit);
473 // }
474 // }
475
476 // tree_entry
477 // })
478 // .collect::<Vec<RepositoryTreeEntry>>();
479
480 // // Sort the tree alphabetically and with tree first
481 // tree.sort_unstable_by_key(|entry| entry.name.to_lowercase());
482 // tree.sort_unstable_by_key(|entry| {
483 // std::cmp::Reverse(format!("{:?}", entry.object_type).to_lowercase())
484 // });
485
486 // Ok(RepositoryView {
487 // name: repository.name,
488 // owner: request.repository.owner.clone(),
489 // description: repository.description,
490 // visibility: repository.visibility,
491 // default_branch: repository.default_branch,
492 // latest_commit: Some(Commit::from(commit.clone())),
493 // tree_rev: Some(rev_name),
494 // tree,
495 // })
496 // }
497
498 async fn repository_file_inspect(
499 &mut self,
500 _requester: Option<&User>,
501 _request: &RepositoryFileInspectRequest,
502 ) -> Result<Vec<RepositoryTreeEntry>, Error> {
503 todo!()
504 }
505
506 async fn repositories_for_user(
507 &mut self,
508 requester: Option<&User>,
509 user: &User,
510 ) -> Result<Vec<RepositorySummary>, Error> {
511 let mut repositories = sqlx::query_as!(
512 GitRepository,
513 r#"SELECT visibility as "visibility: _", owner_user, name, description, default_branch FROM repositories WHERE owner_user = $1"#,
514 user.to_string()
515 )
516 .fetch_many(&self.pg_pool);
517
518 let mut result = vec![];
519
520 while let Some(Ok(Either::Right(repository))) = repositories.next().await {
521 // Check if the requesting user is allowed to see the repository
522 if !(matches!(
523 repository.visibility,
524 RepositoryVisibility::Unlisted | RepositoryVisibility::Private
525 ) && Some(&repository.owner_user.clone()) != requester)
526 {
527 result.push(RepositorySummary {
528 repository: Repository {
529 owner: repository.owner_user.clone(),
530 name: repository.name,
531 instance: self.instance.clone(),
532 },
533 owner: repository.owner_user.clone(),
534 visibility: repository.visibility,
535 description: repository.description,
536 // TODO
537 last_commit: None,
538 });
539 }
540 }
541
542 Ok(result)
543 }
544 }
545
546 impl IssuesBackend for GitBackend {
547 fn issues_count(
548 &mut self,
549 _requester: Option<&User>,
550 _request: &RepositoryIssuesCountRequest,
551 ) -> Result<u64, Error> {
552 todo!()
553 }
554
555 fn issue_labels(
556 &mut self,
557 _requester: Option<&User>,
558 _request: &RepositoryIssueLabelsRequest,
559 ) -> Result<Vec<IssueLabel>, Error> {
560 todo!()
561 }
562
563 fn issues(
564 &mut self,
565 _requester: Option<&User>,
566 _request: &RepositoryIssuesRequest,
567 ) -> Result<Vec<RepositoryIssue>, Error> {
568 todo!()
569 }
570 }
571
572 #[derive(Debug, sqlx::FromRow)]
573 struct RepositoryMetadata {
574 pub repository: String,
575 pub name: String,
576 pub value: String,
577 }
578