Skip to content

Commit

Permalink
Cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
wsxiaoys committed Apr 26, 2024
1 parent f59e42d commit 834a0cc
Show file tree
Hide file tree
Showing 13 changed files with 141 additions and 180 deletions.
14 changes: 14 additions & 0 deletions ee/tabby-db/src/github_repository_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,20 @@ impl DbConn {
Ok(())
}

pub async fn get_github_provided_repository(
&self,
id: i64,
) -> Result<GithubProvidedRepositoryDAO> {
let repo = query_as!(
GithubProvidedRepositoryDAO,
"SELECT id, vendor_id, name, git_url, active, github_repository_provider_id FROM github_provided_repositories WHERE id = ?",
id
)
.fetch_one(&self.pool)
.await?;
Ok(repo)
}

pub async fn list_github_provided_repositories(
&self,
provider_ids: Vec<i64>,
Expand Down
14 changes: 14 additions & 0 deletions ee/tabby-db/src/gitlab_repository_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,20 @@ impl DbConn {
Ok(())
}

pub async fn get_gitlab_provided_repository(
&self,
id: i64,
) -> Result<GitlabProvidedRepositoryDAO> {
let repo = query_as!(
GitlabProvidedRepositoryDAO,
"SELECT id, vendor_id, name, git_url, active, gitlab_repository_provider_id FROM gitlab_provided_repositories WHERE id = ?",
id
)
.fetch_one(&self.pool)
.await?;
Ok(repo)
}

pub async fn list_gitlab_provided_repositories(
&self,
provider_ids: Vec<i64>,
Expand Down
10 changes: 3 additions & 7 deletions ee/tabby-db/src/repositories.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,11 @@ impl DbConn {
}
}

pub async fn get_repository_by_name(&self, name: &str) -> Result<RepositoryDAO> {
pub async fn get_repository(&self, id: i64) -> Result<RepositoryDAO> {
let repository = sqlx::query_as!(
RepositoryDAO,
"SELECT id as 'id!: i64', name, git_url FROM repositories WHERE name = ?",
name
"SELECT id as 'id!: i64', name, git_url FROM repositories WHERE id = ?",
id
)
.fetch_one(&self.pool)
.await?;
Expand Down Expand Up @@ -112,9 +112,5 @@ mod tests {
.unwrap()[0];
assert_eq!(repository.git_url, "testurl2");
assert_eq!(repository.name, "test2");
assert_eq!(
conn.get_repository_by_name("test2").await.unwrap().git_url,
repository.git_url
);
}
}
3 changes: 1 addition & 2 deletions ee/tabby-webserver/src/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,7 @@ impl WebserverHandle {
)
.nest(
"/repositories",
// FIXME(boxbeam): repositories routes should support both git / github repositories, but currently only git repositories are supported.
repositories::routes(ctx.repository().git(), ctx.auth()),
repositories::routes(ctx.repository(), ctx.auth()),
)
.route(
"/avatar/:id",
Expand Down
14 changes: 5 additions & 9 deletions ee/tabby-webserver/src/repositories/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ use self::resolve::ResolveState;
use crate::{
handler::require_login_middleware,
repositories::resolve::ResolveParams,
schema::{auth::AuthenticationService, git_repository::GitRepositoryService},
schema::{auth::AuthenticationService, repository::RepositoryService},
};

pub fn routes(
repository: Arc<dyn GitRepositoryService>,
repository: Arc<dyn RepositoryService>,
auth: Arc<dyn AuthenticationService>,
) -> Router {
Router::new()
Expand All @@ -42,11 +42,11 @@ async fn resolve_path(
State(rs): State<Arc<ResolveState>>,
Path(repo): Path<ResolveParams>,
) -> Result<Response, StatusCode> {
let Some(conf) = rs.find_repository(repo.name_str()).await else {
let relpath = repo.os_path();
let Some(root) = rs.find_repository(&repo.kind, &repo.id).await else {
return Err(StatusCode::NOT_FOUND);
};
let root = conf.dir();
let full_path = root.join(repo.os_path());
let full_path = root.join(relpath);
let is_dir = tokio::fs::metadata(full_path.clone())
.await
.map(|m| m.is_dir())
Expand All @@ -70,7 +70,3 @@ async fn resolve_path(
}
}
}

async fn resolve(State(rs): State<Arc<ResolveState>>) -> Result<Response, StatusCode> {
rs.resolve_all().await.map_err(|_| StatusCode::NOT_FOUND)
}
40 changes: 9 additions & 31 deletions ee/tabby-webserver/src/repositories/resolve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,23 @@ use axum::{
Json,
};
use hyper::Body;
use juniper::ID;
use serde::{Deserialize, Serialize};
use tabby_common::config::RepositoryConfig;
use tower::ServiceExt;
use tower_http::services::ServeDir;

use crate::schema::git_repository::GitRepositoryService;
use crate::schema::repository::{RepositoryKind, RepositoryService};

const DIRECTORY_MIME_TYPE: &str = "application/vnd.directory+json";

#[derive(Deserialize, Debug)]
pub struct ResolveParams {
name: String,
pub kind: RepositoryKind,
pub id: ID,
path: Option<String>,
}

impl ResolveParams {
pub fn name_str(&self) -> &str {
self.name.as_str()
}

pub fn path_str(&self) -> &str {
self.path.as_deref().unwrap_or("")
}
Expand Down Expand Up @@ -60,11 +57,11 @@ struct DirEntry {
}

pub(super) struct ResolveState {
service: Arc<dyn GitRepositoryService>,
service: Arc<dyn RepositoryService>,
}

impl ResolveState {
pub fn new(service: Arc<dyn GitRepositoryService>) -> Self {
pub fn new(service: Arc<dyn RepositoryService>) -> Self {
Self { service }
}

Expand Down Expand Up @@ -128,27 +125,8 @@ impl ResolveState {
Ok(resp.map(boxed))
}

pub async fn resolve_all(&self) -> Result<Response> {
let repositories = self.service.list(None, None, None, None).await?;

let entries = repositories
.into_iter()
.map(|repo| DirEntry {
kind: DirEntryKind::Dir,
basename: repo.name.clone(),
})
.collect();

let body = Json(ListDir { entries }).into_response();
let resp = Response::builder()
.header(header::CONTENT_TYPE, DIRECTORY_MIME_TYPE)
.body(body.into_body())?;

Ok(resp)
}

pub async fn find_repository(&self, name: &str) -> Option<RepositoryConfig> {
let repository = self.service.get_by_name(name).await.ok()?;
Some(RepositoryConfig::new(repository.git_url.clone()))
pub async fn find_repository(&self, kind: &RepositoryKind, id: &ID) -> Option<PathBuf> {
let repository = self.service.get(kind, id).await.ok()?;
Some(repository.dir)
}
}
13 changes: 1 addition & 12 deletions ee/tabby-webserver/src/schema/git_repository.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@ use async_trait::async_trait;
use juniper::{GraphQLObject, ID};
use validator::Validate;

use super::{
repository::{FileEntrySearchResult, RepositoryProvider},
Context, Result,
};
use super::{repository::RepositoryProvider, Context, Result};
use crate::juniper::relay::NodeType;

#[derive(Validate)]
Expand Down Expand Up @@ -55,14 +52,6 @@ pub trait GitRepositoryService: Send + Sync + RepositoryProvider {
) -> Result<Vec<GitRepository>>;

async fn create(&self, name: String, git_url: String) -> Result<ID>;
async fn get_by_name(&self, name: &str) -> Result<GitRepository>;
async fn delete(&self, id: &ID) -> Result<bool>;
async fn update(&self, id: &ID, name: String, git_url: String) -> Result<bool>;

async fn search_files(
&self,
name: &str,
pattern: &str,
top_n: usize,
) -> Result<Vec<FileEntrySearchResult>>;
}
8 changes: 4 additions & 4 deletions ee/tabby-webserver/src/schema/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ use self::{
},
job::JobStats,
license::{IsLicenseValid, LicenseInfo, LicenseService, LicenseType},
repository::RepositoryService,
repository::{RepositoryKind, RepositoryService},
setting::{
NetworkSetting, NetworkSettingInput, SecuritySetting, SecuritySettingInput, SettingService,
},
Expand Down Expand Up @@ -357,14 +357,14 @@ impl Query {

async fn repository_search(
ctx: &Context,
repository_name: String,
kind: RepositoryKind,
id: ID,
pattern: String,
) -> Result<Vec<FileEntrySearchResult>> {
check_claims(ctx)?;
ctx.locator
.repository()
.git()
.search_files(&repository_name, &pattern, 40)
.search_files(&kind, &id, &pattern, 40)
.await
}

Expand Down
23 changes: 20 additions & 3 deletions ee/tabby-webserver/src/schema/repository.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use std::sync::Arc;
use std::{path::PathBuf, sync::Arc};

use async_trait::async_trait;
use juniper::{GraphQLEnum, GraphQLObject, ID};
use tabby_common::config::RepositoryAccess;
use serde::Deserialize;
use tabby_common::config::{RepositoryAccess, RepositoryConfig};
use tabby_search::FileSearch;

use super::{
Expand Down Expand Up @@ -31,7 +32,8 @@ impl From<FileSearch> for FileEntrySearchResult {
}
}

#[derive(GraphQLEnum)]
#[derive(GraphQLEnum, Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RepositoryKind {
Git,
GitHub,
Expand All @@ -43,6 +45,9 @@ pub struct Repository {
pub id: ID,
pub name: String,
pub kind: RepositoryKind,

#[graphql(skip)]
pub dir: PathBuf,
}

impl From<GitRepository> for Repository {
Expand All @@ -51,6 +56,7 @@ impl From<GitRepository> for Repository {
id: value.id,
name: value.name,
kind: RepositoryKind::Git,
dir: RepositoryConfig::new(value.git_url).dir(),
}
}
}
Expand All @@ -61,6 +67,7 @@ impl From<GithubProvidedRepository> for Repository {
id: value.id,
name: value.name,
kind: RepositoryKind::GitHub,
dir: RepositoryConfig::new(value.git_url).dir(),
}
}
}
Expand All @@ -71,18 +78,28 @@ impl From<GitlabProvidedRepository> for Repository {
id: value.id,
name: value.name,
kind: RepositoryKind::GitLab,
dir: RepositoryConfig::new(value.git_url).dir(),
}
}
}

#[async_trait]
pub trait RepositoryProvider {
async fn repository_list(&self) -> Result<Vec<Repository>>;
async fn get_repository(&self, id: &ID) -> Result<Repository>;
}

#[async_trait]
pub trait RepositoryService: Send + Sync + RepositoryAccess {
async fn repository_list(&self) -> Result<Vec<Repository>>;
async fn get(&self, kind: &RepositoryKind, id: &ID) -> Result<Repository>;
async fn search_files(
&self,
kind: &RepositoryKind,
id: &ID,
pattern: &str,
top_n: usize,
) -> Result<Vec<FileEntrySearchResult>>;

fn git(&self) -> Arc<dyn GitRepositoryService>;
fn github(&self) -> Arc<dyn GithubRepositoryProviderService>;
Expand Down
Loading

0 comments on commit 834a0cc

Please sign in to comment.