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 |
RepositoryCreateRequest, RepositoryCreateResponse, 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 |
|
28 |
|
29 |
|
30 |
|
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 |
|
43 |
|
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 |
|
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 |
|
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 |
|
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 |
|
167 |
|
168 |
|
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 |
|
183 |
|
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 |
|
191 |
let diff = git.diff_tree_to_tree(Some(&last_tree), Some(&tree), None)?;
|
192 |
|
193 |
for dd in diff.deltas() {
|
194 |
|
195 |
let current_path = dd.new_file().path().unwrap();
|
196 |
|
197 |
|
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: &RepositoryCreateRequest,
|
215 |
) -> Result<RepositoryCreateResponse, GitBackendError> {
|
216 |
|
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 Err(err);
|
228 |
}
|
229 |
|
230 |
|
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 Err(err);
|
242 |
}
|
243 |
};
|
244 |
|
245 |
|
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(RepositoryCreateResponse)
|
259 |
}
|
260 |
Err(err) => {
|
261 |
let err = GitBackendError::FailedCreatingRepository(err);
|
262 |
error!("Failed creating repository on disk!? {:?}", err);
|
263 |
|
264 |
|
265 |
self.delete_by_owner_user_name(&request.owner, request.name.as_str())
|
266 |
.await?;
|
267 |
|
268 |
|
269 |
Err(err)
|
270 |
}
|
271 |
}
|
272 |
}
|
273 |
|
274 |
async fn repository_info(
|
275 |
&mut self,
|
276 |
requester: Option<&User>,
|
277 |
request: &RepositoryInfoRequest,
|
278 |
) -> Result<RepositoryView, Error> {
|
279 |
let repository = match self
|
280 |
.find_by_owner_user_name(
|
281 |
|
282 |
&request.repository.owner,
|
283 |
&request.repository.name,
|
284 |
)
|
285 |
.await
|
286 |
{
|
287 |
Ok(repository) => repository,
|
288 |
Err(err) => return Err(Box::new(err).into()),
|
289 |
};
|
290 |
|
291 |
if let Some(requester) = requester {
|
292 |
if !repository.can_user_view_repository(Some(&requester)) {
|
293 |
return Err(Box::new(GitBackendError::RepositoryNotFound {
|
294 |
owner_user: request.repository.owner.to_string(),
|
295 |
name: request.repository.name.clone(),
|
296 |
})
|
297 |
.into());
|
298 |
}
|
299 |
} else if matches!(repository.visibility, RepositoryVisibility::Private) {
|
300 |
|
301 |
|
302 |
return Err(Box::new(GitBackendError::RepositoryNotFound {
|
303 |
owner_user: request.repository.owner.to_string(),
|
304 |
name: request.repository.name.clone(),
|
305 |
})
|
306 |
.into());
|
307 |
}
|
308 |
|
309 |
let git = match repository.open_git2_repository(&self.repository_folder) {
|
310 |
Ok(git) => git,
|
311 |
Err(err) => return Err(Box::new(err).into()),
|
312 |
};
|
313 |
|
314 |
let rev_name = match &request.rev {
|
315 |
None => {
|
316 |
if let Ok(head) = git.head() {
|
317 |
head.name().unwrap().to_string()
|
318 |
} else {
|
319 |
|
320 |
return Ok(RepositoryView {
|
321 |
name: repository.name,
|
322 |
owner: request.repository.owner.clone(),
|
323 |
description: repository.description,
|
324 |
visibility: repository.visibility,
|
325 |
default_branch: repository.default_branch,
|
326 |
latest_commit: None,
|
327 |
tree_rev: None,
|
328 |
tree: vec![],
|
329 |
});
|
330 |
}
|
331 |
}
|
332 |
Some(rev_name) => {
|
333 |
|
334 |
match git
|
335 |
.find_reference(format!("refs/heads/{}", rev_name).as_str())
|
336 |
.map_err(|_| GitBackendError::RefNotFound(rev_name.to_string()))
|
337 |
{
|
338 |
Ok(reference) => reference.name().unwrap().to_string(),
|
339 |
Err(err) => return Err(Box::new(err).into()),
|
340 |
}
|
341 |
}
|
342 |
};
|
343 |
|
344 |
|
345 |
let rev = match git
|
346 |
.revparse_single(rev_name.as_str())
|
347 |
.map_err(|_| GitBackendError::RefNotFound(rev_name.to_string()))
|
348 |
{
|
349 |
Ok(rev) => rev,
|
350 |
Err(err) => return Err(Box::new(err).into()),
|
351 |
};
|
352 |
let commit = rev.as_commit().unwrap();
|
353 |
|
354 |
|
355 |
let mut current_path = rev_name.replace("refs/heads/", "");
|
356 |
|
357 |
|
358 |
let git_tree = if let Some(path) = &request.path {
|
359 |
|
360 |
current_path.push_str(format!("/{}", path).as_str());
|
361 |
|
362 |
let entry = match commit
|
363 |
.tree()
|
364 |
.unwrap()
|
365 |
.get_path(&PathBuf::from(path))
|
366 |
.map_err(|_| GitBackendError::PathNotFound(path.to_string()))
|
367 |
{
|
368 |
Ok(entry) => entry,
|
369 |
Err(err) => return Err(Box::new(err).into()),
|
370 |
};
|
371 |
|
372 |
entry.to_object(&git).unwrap().as_tree().unwrap().clone()
|
373 |
} else {
|
374 |
commit.tree().unwrap()
|
375 |
};
|
376 |
|
377 |
|
378 |
let mut tree = git_tree
|
379 |
.iter()
|
380 |
.map(|entry| {
|
381 |
let object_type = match entry.kind().unwrap() {
|
382 |
ObjectType::Tree => RepositoryObjectType::Tree,
|
383 |
ObjectType::Blob => RepositoryObjectType::Blob,
|
384 |
_ => unreachable!(),
|
385 |
};
|
386 |
let mut tree_entry =
|
387 |
RepositoryTreeEntry::new(entry.name().unwrap(), object_type, entry.filemode());
|
388 |
|
389 |
if request.extra_metadata {
|
390 |
|
391 |
let object = entry.to_object(&git).unwrap();
|
392 |
if let Some(blob) = object.as_blob() {
|
393 |
tree_entry.size = Some(blob.size());
|
394 |
}
|
395 |
|
396 |
|
397 |
let path = if let Some(path) = current_path.split_once('/') {
|
398 |
format!("{}/{}", path.1, entry.name().unwrap())
|
399 |
} else {
|
400 |
entry.name().unwrap().to_string()
|
401 |
};
|
402 |
|
403 |
|
404 |
if let Ok(last_commit) =
|
405 |
GitBackend::get_last_commit_of_file(&path, &git, commit)
|
406 |
{
|
407 |
tree_entry.last_commit = Some(last_commit);
|
408 |
}
|
409 |
}
|
410 |
|
411 |
tree_entry
|
412 |
})
|
413 |
.collect::<Vec<RepositoryTreeEntry>>();
|
414 |
|
415 |
|
416 |
tree.sort_unstable_by_key(|entry| entry.name.to_lowercase());
|
417 |
tree.sort_unstable_by_key(|entry| {
|
418 |
std::cmp::Reverse(format!("{:?}", entry.object_type).to_lowercase())
|
419 |
});
|
420 |
|
421 |
Ok(RepositoryView {
|
422 |
name: repository.name,
|
423 |
owner: request.repository.owner.clone(),
|
424 |
description: repository.description,
|
425 |
visibility: repository.visibility,
|
426 |
default_branch: repository.default_branch,
|
427 |
latest_commit: None,
|
428 |
tree_rev: Some(rev_name),
|
429 |
tree,
|
430 |
})
|
431 |
}
|
432 |
|
433 |
async fn repository_file_inspect(
|
434 |
&mut self,
|
435 |
_requester: Option<&User>,
|
436 |
_request: &RepositoryFileInspectRequest,
|
437 |
) -> Result<RepositoryFileInspectionResponse, Error> {
|
438 |
todo!()
|
439 |
}
|
440 |
|
441 |
async fn repositories_for_user(
|
442 |
&mut self,
|
443 |
requester: Option<&User>,
|
444 |
user: &User,
|
445 |
) -> Result<Vec<RepositorySummary>, Error> {
|
446 |
let mut repositories = sqlx::query_as!(
|
447 |
GitRepository,
|
448 |
r#"SELECT visibility as "visibility: _", owner_user, name, description, default_branch FROM repositories WHERE owner_user = $1"#,
|
449 |
user.to_string()
|
450 |
)
|
451 |
.fetch_many(&self.pg_pool);
|
452 |
|
453 |
let mut result = vec![];
|
454 |
|
455 |
while let Some(Ok(Either::Right(repository))) = repositories.next().await {
|
456 |
|
457 |
if matches!(
|
458 |
repository.visibility,
|
459 |
RepositoryVisibility::Unlisted | RepositoryVisibility::Private
|
460 |
) && Some(&repository.owner_user.clone()) != requester
|
461 |
{
|
462 |
result.push(RepositorySummary {
|
463 |
repository: Repository {
|
464 |
owner: repository.owner_user.clone(),
|
465 |
name: repository.name,
|
466 |
instance: self.instance.clone(),
|
467 |
},
|
468 |
owner: repository.owner_user.clone(),
|
469 |
visibility: repository.visibility,
|
470 |
description: repository.description,
|
471 |
|
472 |
last_commit: None,
|
473 |
});
|
474 |
}
|
475 |
}
|
476 |
|
477 |
Ok(result)
|
478 |
}
|
479 |
}
|
480 |
|
481 |
impl IssuesBackend for GitBackend {
|
482 |
fn issues_count(
|
483 |
&mut self,
|
484 |
_requester: Option<&User>,
|
485 |
_request: &RepositoryIssuesCountRequest,
|
486 |
) -> Result<RepositoryIssuesCountResponse, Error> {
|
487 |
todo!()
|
488 |
}
|
489 |
|
490 |
fn issue_labels(
|
491 |
&mut self,
|
492 |
_requester: Option<&User>,
|
493 |
_request: &RepositoryIssueLabelsRequest,
|
494 |
) -> Result<RepositoryIssueLabelsResponse, Error> {
|
495 |
todo!()
|
496 |
}
|
497 |
|
498 |
fn issues(
|
499 |
&mut self,
|
500 |
_requester: Option<&User>,
|
501 |
_request: &RepositoryIssuesRequest,
|
502 |
) -> Result<RepositoryIssuesResponse, Error> {
|
503 |
todo!()
|
504 |
}
|
505 |
}
|
506 |
|