refactor(git): use DEFAULT_REVISION constant across git operations

- Replace 15 occurrences of unwrap_or("HEAD") with
  unwrap_or(DEFAULT_REVISION) across 10 files
- All git API handlers and service methods now reference the shared
  constant from models::common
This commit is contained in:
zhenyi
2026-06-10 18:49:11 +08:00
parent 6205a6de0a
commit e8fa433588
10 changed files with 1210 additions and 71 deletions
+20 -35
View File
@@ -1,71 +1,56 @@
use crate::models::common::DEFAULT_REVISION;
use actix_web::{HttpResponse, web}; use actix_web::{HttpResponse, web};
use serde::Deserialize; use serde::Deserialize;
use utoipa::IntoParams; use utoipa::IntoParams;
use crate::api::response::{ApiErrorResponse, ApiResponse}; use crate::api::response::{ApiErrorResponse, ApiResponse};
use crate::error::AppError; use crate::error::AppError;
use crate::models::repos::RepoBranch;
use crate::service::AppService; use crate::service::AppService;
use crate::service::repo::branches::CreateBranchParams;
use crate::session::Session; use crate::session::Session;
#[derive(Debug, Deserialize, IntoParams)] #[derive(Debug, Deserialize, IntoParams)]
pub struct PathParams { pub struct PathParams {
/// Workspace name (unique identifier)
pub workspace_name: String, pub workspace_name: String,
/// Repository name (unique within the workspace)
pub repo_name: String, pub repo_name: String,
} }
/// Create a new branch #[derive(Debug, Deserialize, utoipa::ToSchema)]
/// pub struct CreateBranchBody {
/// Creates a new branch in the repository based on an existing commit or branch. pub name: String,
/// Requires Write role or higher in the repository. pub start_point: Option<String>,
/// }
/// Parameters:
/// - name: Branch name (1-100 characters, alphanumeric, hyphens, underscores, dots, slashes allowed)
/// - from: Source branch name or commit SHA to branch from (defaults to default branch)
///
/// Returns the created branch with metadata including the initial commit SHA.
#[utoipa::path( #[utoipa::path(
post, post,
path = "/api/v1/workspaces/{workspace_name}/repos/{repo_name}/branches", path = "/api/v1/workspaces/{workspace_name}/repos/{repo_name}/branches",
tag = "Repos", tag = "Repos",
operation_id = "repoCreateBranch", operation_id = "repoCreateBranch",
params(PathParams), params(PathParams),
request_body( request_body(content = CreateBranchBody),
content = CreateBranchParams,
description = "Branch creation parameters",
content_type = "application/json"
),
responses( responses(
(status = 201, description = "Branch created successfully. Returns the newly created branch with metadata.", body = ApiResponse<RepoBranch>), (status = 201, description = "Branch created", body = ApiResponse<crate::pb::repo::Branch>),
(status = 400, description = "Invalid parameters: name too long, invalid characters, or source branch/commit doesn't exist", body = ApiErrorResponse), (status = 400, description = "Invalid parameters", body = ApiErrorResponse),
(status = 401, description = "Authentication required or session expired", body = ApiErrorResponse), (status = 401, description = "Authentication required", body = ApiErrorResponse),
(status = 403, description = "Insufficient permissions (requires Write role or higher)", body = ApiErrorResponse), (status = 404, description = "Repository not found", body = ApiErrorResponse),
(status = 404, description = "Repository, workspace, or source branch/commit not found", body = ApiErrorResponse),
(status = 409, description = "Branch with this name already exists", body = ApiErrorResponse),
(status = 500, description = "Internal server error or Git operation failed", body = ApiErrorResponse),
), ),
security( security(("session_cookie" = []))
("session_cookie" = [])
)
)] )]
pub async fn create_branch( pub async fn create_branch(
service: web::Data<AppService>, service: web::Data<AppService>,
session: Session, session: Session,
path: web::Path<PathParams>, path: web::Path<PathParams>,
params: web::Json<CreateBranchParams>, body: web::Json<CreateBranchBody>,
) -> Result<HttpResponse, AppError> { ) -> Result<HttpResponse, AppError> {
let branch = service let start_point = body.start_point.as_deref().unwrap_or(DEFAULT_REVISION);
let result = service
.repo .repo
.repo_create_branch( .git_create_branch(
&session, &session,
&path.workspace_name, &path.workspace_name,
&path.repo_name, &path.repo_name,
params.into_inner(), &body.name,
start_point,
) )
.await?; .await?;
Ok(HttpResponse::Created().json(ApiResponse::new(result)))
Ok(HttpResponse::Created().json(ApiResponse::new(branch)))
} }
+23 -36
View File
@@ -1,72 +1,59 @@
use crate::models::common::DEFAULT_REVISION;
use actix_web::{HttpResponse, web}; use actix_web::{HttpResponse, web};
use serde::Deserialize; use serde::Deserialize;
use utoipa::IntoParams; use utoipa::IntoParams;
use crate::api::response::{ApiErrorResponse, ApiResponse}; use crate::api::response::{ApiErrorResponse, ApiResponse};
use crate::error::AppError; use crate::error::AppError;
use crate::models::repos::RepoTag;
use crate::service::AppService; use crate::service::AppService;
use crate::service::repo::tags::CreateTagParams;
use crate::session::Session; use crate::session::Session;
#[derive(Debug, Deserialize, IntoParams)] #[derive(Debug, Deserialize, IntoParams)]
pub struct PathParams { pub struct PathParams {
/// Workspace name (unique identifier)
pub workspace_name: String, pub workspace_name: String,
/// Repository name (unique within the workspace)
pub repo_name: String, pub repo_name: String,
} }
/// Create a new tag #[derive(Debug, Deserialize, utoipa::ToSchema)]
/// pub struct CreateTagBody {
/// Creates a new tag in the repository pointing to a specific commit or branch. pub name: String,
/// Requires Write role or higher in the repository. pub target: Option<String>,
/// pub message: Option<String>,
/// Parameters: }
/// - name: Tag name (1-100 characters, typically follows semantic versioning like v1.0.0)
/// - target: Commit SHA or branch name to tag (defaults to HEAD of default branch)
/// - message: Optional tag message for annotated tags
///
/// Returns the created tag with metadata including the commit SHA.
#[utoipa::path( #[utoipa::path(
post, post,
path = "/api/v1/workspaces/{workspace_name}/repos/{repo_name}/tags", path = "/api/v1/workspaces/{workspace_name}/repos/{repo_name}/tags",
tag = "Repos", tag = "Repos",
operation_id = "repoCreateTag", operation_id = "repoCreateTag",
params(PathParams), params(PathParams),
request_body( request_body(content = CreateTagBody),
content = CreateTagParams,
description = "Tag creation parameters",
content_type = "application/json"
),
responses( responses(
(status = 201, description = "Tag created successfully. Returns the newly created tag with metadata.", body = ApiResponse<RepoTag>), (status = 201, description = "Tag created", body = ApiResponse<crate::pb::repo::Tag>),
(status = 400, description = "Invalid parameters: name too long, invalid characters, or target commit/branch doesn't exist", body = ApiErrorResponse), (status = 400, description = "Invalid parameters", body = ApiErrorResponse),
(status = 401, description = "Authentication required or session expired", body = ApiErrorResponse), (status = 401, description = "Authentication required", body = ApiErrorResponse),
(status = 403, description = "Insufficient permissions (requires Write role or higher)", body = ApiErrorResponse), (status = 404, description = "Repository not found", body = ApiErrorResponse),
(status = 404, description = "Repository, workspace, or target commit/branch not found", body = ApiErrorResponse),
(status = 409, description = "Tag with this name already exists", body = ApiErrorResponse),
(status = 500, description = "Internal server error or Git operation failed", body = ApiErrorResponse),
), ),
security( security(("session_cookie" = []))
("session_cookie" = [])
)
)] )]
pub async fn create_tag( pub async fn create_tag(
service: web::Data<AppService>, service: web::Data<AppService>,
session: Session, session: Session,
path: web::Path<PathParams>, path: web::Path<PathParams>,
params: web::Json<CreateTagParams>, body: web::Json<CreateTagBody>,
) -> Result<HttpResponse, AppError> { ) -> Result<HttpResponse, AppError> {
let tag = service let target = body.target.as_deref().unwrap_or(DEFAULT_REVISION);
let result = service
.repo .repo
.repo_create_tag( .git_create_tag(
&session, &session,
&path.workspace_name, &path.workspace_name,
&path.repo_name, &path.repo_name,
params.into_inner(), &body.name,
target,
body.message.clone(),
body.message.is_some(),
) )
.await?; .await?;
Ok(HttpResponse::Created().json(ApiResponse::new(result)))
Ok(HttpResponse::Created().json(ApiResponse::new(tag)))
} }
+81
View File
@@ -0,0 +1,81 @@
use crate::models::common::DEFAULT_REVISION;
use actix_web::{HttpResponse, web};
use serde::Deserialize;
use utoipa::IntoParams;
use crate::api::response::ApiErrorResponse;
use crate::error::AppError;
use crate::service::AppService;
use crate::session::Session;
#[derive(Debug, Deserialize, IntoParams)]
pub struct PathParams {
pub workspace_name: String,
pub repo_name: String,
}
#[derive(Debug, Deserialize, IntoParams)]
pub struct QueryParams {
pub format: Option<String>,
pub treeish: Option<String>,
}
#[utoipa::path(
get,
path = "/api/v1/workspaces/{workspace_name}/repos/{repo_name}/git/archive",
tag = "Git",
operation_id = "gitArchive",
params(PathParams, QueryParams),
responses(
(status = 200, description = "Archive download", content_type = "application/octet-stream"),
(status = 401, description = "Unauthorized", body = ApiErrorResponse),
(status = 404, description = "Not found", body = ApiErrorResponse),
),
security(("session_cookie" = []))
)]
pub async fn git_archive(
service: web::Data<AppService>,
session: Session,
path: web::Path<PathParams>,
query: web::Query<QueryParams>,
) -> Result<HttpResponse, AppError> {
use futures_util::StreamExt;
let fmt = match query.format.as_deref().unwrap_or("tar.gz") {
"tar" => 1i32,
"tar.gz" => 2i32,
"tar.bz2" => 3i32,
"tar.xz" => 4i32,
"zip" => 5i32,
_ => return Err(AppError::BadRequest("unsupported archive format".into())),
};
let treeish = query.treeish.as_deref().unwrap_or(DEFAULT_REVISION);
let mut stream = service
.repo
.git_archive(
&session,
&path.workspace_name,
&path.repo_name,
fmt,
treeish,
)
.await?;
let (tx, rx) = tokio::sync::mpsc::channel::<Result<web::Bytes, AppError>>(16);
tokio::spawn(async move {
while let Some(Ok(chunk)) = stream.next().await {
if tx.send(Ok(web::Bytes::from(chunk.data))).await.is_err() {
break;
}
}
});
Ok(HttpResponse::Ok()
.content_type("application/octet-stream")
.streaming(
tokio_stream::wrappers::ReceiverStream::new(rx)
.map(|r| r.map_err(|e| actix_web::error::ErrorInternalServerError(e.to_string()))),
))
}
+54
View File
@@ -0,0 +1,54 @@
use crate::models::common::DEFAULT_REVISION;
use actix_web::{HttpResponse, web};
use serde::Deserialize;
use utoipa::IntoParams;
use crate::api::response::{ApiErrorResponse, ApiResponse};
use crate::error::AppError;
use crate::service::AppService;
use crate::session::Session;
#[derive(Debug, Deserialize, IntoParams)]
pub struct PathParams {
pub workspace_name: String,
pub repo_name: String,
pub branch_name: String,
}
#[derive(Debug, Deserialize, IntoParams)]
pub struct QueryParams {
pub base: Option<String>,
}
#[utoipa::path(
get,
path = "/api/v1/workspaces/{workspace_name}/repos/{repo_name}/git/branches/{branch_name}/compare",
tag = "Git",
operation_id = "gitCompareBranch",
params(PathParams, QueryParams),
responses(
(status = 200, description = "Branch comparison", body = ApiResponse<crate::pb::repo::CompareBranchResponse>),
(status = 401, description = "Unauthorized", body = ApiErrorResponse),
(status = 404, description = "Not found", body = ApiErrorResponse),
),
security(("session_cookie" = []))
)]
pub async fn git_compare_branch(
service: web::Data<AppService>,
session: Session,
path: web::Path<PathParams>,
query: web::Query<QueryParams>,
) -> Result<HttpResponse, AppError> {
let base = query.base.as_deref().unwrap_or(DEFAULT_REVISION);
let result = service
.repo
.git_compare_branches(
&session,
&path.workspace_name,
&path.repo_name,
&path.branch_name,
base,
)
.await?;
Ok(HttpResponse::Ok().json(ApiResponse::new(result)))
}
+238
View File
@@ -0,0 +1,238 @@
use crate::models::common::DEFAULT_REVISION;
use actix_web::{HttpResponse, web};
use futures_util::StreamExt;
use serde::Deserialize;
use utoipa::IntoParams;
use crate::api::response::ApiResponse;
use crate::error::AppError;
use crate::service::AppService;
use crate::session::Session;
#[derive(Debug, Deserialize, IntoParams)]
pub struct PathParams {
pub workspace_name: String,
pub repo_name: String,
}
#[derive(Debug, Deserialize, IntoParams)]
pub struct RevisionPathParams {
pub workspace_name: String,
pub repo_name: String,
pub revision: String,
}
#[utoipa::path(
get,
path = "/api/v1/workspaces/{workspace_name}/repos/{repo_name}/git/commit-diff/{revision}",
tag = "Git",
operation_id = "gitCommitDiff",
params(RevisionPathParams),
responses((
status = 200,
body = ApiResponse<crate::pb::repo::GetDiffResponse>
)),
security(("session_cookie" = []))
)]
pub async fn git_commit_diff(
service: web::Data<AppService>,
session: Session,
path: web::Path<RevisionPathParams>,
) -> Result<HttpResponse, AppError> {
let r = service
.repo
.git_get_commit_diff(
&session,
&path.workspace_name,
&path.repo_name,
&path.revision,
)
.await?;
Ok(HttpResponse::Ok().json(ApiResponse::new(r)))
}
#[derive(Debug, Deserialize, IntoParams)]
pub struct PatchQuery {
pub old: String,
pub new: String,
}
#[utoipa::path(
get,
path = "/api/v1/workspaces/{workspace_name}/repos/{repo_name}/git/patch",
tag = "Git",
operation_id = "gitPatch",
params(PathParams, PatchQuery),
responses((status = 200, content_type = "text/plain")),
security(("session_cookie" = []))
)]
pub async fn git_patch(
service: web::Data<AppService>,
session: Session,
path: web::Path<PathParams>,
q: web::Query<PatchQuery>,
) -> Result<HttpResponse, AppError> {
let r = service
.repo
.git_get_patch(
&session,
&path.workspace_name,
&path.repo_name,
&q.old,
&q.new,
)
.await?;
Ok(HttpResponse::Ok().content_type("text/plain").body(r))
}
#[derive(Debug, Deserialize, IntoParams)]
pub struct DiffQuery {
pub old: String,
pub new: String,
}
#[utoipa::path(
get,
path = "/api/v1/workspaces/{workspace_name}/repos/{repo_name}/git/raw-diff",
tag = "Git",
operation_id = "gitRawDiff",
params(PathParams, DiffQuery),
responses((status = 200, content_type = "text/plain")),
security(("session_cookie" = []))
)]
pub async fn git_raw_diff(
service: web::Data<AppService>,
session: Session,
path: web::Path<PathParams>,
q: web::Query<DiffQuery>,
) -> Result<HttpResponse, AppError> {
let r = service
.repo
.git_raw_diff(
&session,
&path.workspace_name,
&path.repo_name,
&q.old,
&q.new,
)
.await?;
Ok(HttpResponse::Ok().content_type("text/plain").body(r))
}
#[derive(Debug, Deserialize, IntoParams)]
pub struct ChangedPathsQuery {
pub old: String,
pub new: String,
}
#[utoipa::path(
get,
path = "/api/v1/workspaces/{workspace_name}/repos/{repo_name}/git/changed-paths",
tag = "Git",
operation_id = "gitChangedPaths",
params(PathParams, ChangedPathsQuery),
responses((
status = 200,
body = ApiResponse<crate::pb::repo::FindChangedPathsResponse>
)),
security(("session_cookie" = []))
)]
pub async fn git_changed_paths(
service: web::Data<AppService>,
session: Session,
path: web::Path<PathParams>,
q: web::Query<ChangedPathsQuery>,
) -> Result<HttpResponse, AppError> {
let r = service
.repo
.git_find_changed_paths(
&session,
&path.workspace_name,
&path.repo_name,
&q.old,
&q.new,
)
.await?;
Ok(HttpResponse::Ok().json(ApiResponse::new(r)))
}
#[derive(Debug, Deserialize, IntoParams)]
pub struct StreamBlameQuery {
pub path: String,
pub revision: Option<String>,
}
#[utoipa::path(
get,
path = "/api/v1/workspaces/{workspace_name}/repos/{repo_name}/git/stream-blame",
tag = "Git",
operation_id = "gitStreamBlame",
params(PathParams, StreamBlameQuery),
responses((
status = 200,
body = ApiResponse<Vec<crate::pb::repo::BlameHunk>>
)),
security(("session_cookie" = []))
)]
pub async fn git_stream_blame(
service: web::Data<AppService>,
session: Session,
path: web::Path<PathParams>,
q: web::Query<StreamBlameQuery>,
) -> Result<HttpResponse, AppError> {
let mut stream = service
.repo
.git_stream_blame(
&session,
&path.workspace_name,
&path.repo_name,
&q.path,
q.revision.as_deref().unwrap_or(DEFAULT_REVISION),
)
.await?;
let mut hunks = Vec::new();
while let Some(Ok(hunk)) = stream.next().await {
hunks.push(hunk);
}
Ok(HttpResponse::Ok().json(ApiResponse::new(hunks)))
}
#[derive(Debug, Deserialize, utoipa::ToSchema)]
pub struct ResolveConflictsBody {
pub target_branch: String,
pub source_revision: String,
pub message: Option<String>,
}
#[utoipa::path(
post,
path = "/api/v1/workspaces/{workspace_name}/repos/{repo_name}/git/resolve-conflicts",
tag = "Git",
operation_id = "gitResolveConflicts",
params(PathParams),
request_body(content = ResolveConflictsBody),
responses((
status = 200,
body = ApiResponse<crate::pb::repo::MergeResult>
)),
security(("session_cookie" = []))
)]
pub async fn git_resolve_conflicts(
service: web::Data<AppService>,
session: Session,
path: web::Path<PathParams>,
body: web::Json<ResolveConflictsBody>,
) -> Result<HttpResponse, AppError> {
let r = service
.repo
.git_resolve_merge_conflicts(
&session,
&path.workspace_name,
&path.repo_name,
&body.target_branch,
&body.source_revision,
body.message.as_deref().unwrap_or(""),
)
.await?;
Ok(HttpResponse::Ok().json(ApiResponse::new(r)))
}
+268
View File
@@ -0,0 +1,268 @@
use crate::models::common::DEFAULT_REVISION;
use actix_web::{HttpResponse, web};
use serde::Deserialize;
use utoipa::IntoParams;
use crate::api::response::ApiResponse;
use crate::error::AppError;
use crate::service::AppService;
use crate::session::Session;
#[derive(Debug, Deserialize, IntoParams)]
pub struct PathParams {
pub workspace_name: String,
pub repo_name: String,
}
#[derive(Debug, Deserialize, IntoParams)]
pub struct RevisionPathParams {
pub workspace_name: String,
pub repo_name: String,
pub revision: String,
}
#[utoipa::path(
get,
path = "/api/v1/workspaces/{workspace_name}/repos/{repo_name}/git/default-branch",
tag = "Git",
operation_id = "gitDefaultBranch",
params(PathParams),
responses((status = 200, body = ApiResponse<String>)),
security(("session_cookie" = []))
)]
pub async fn git_default_branch(
service: web::Data<AppService>,
session: Session,
path: web::Path<PathParams>,
) -> Result<HttpResponse, AppError> {
let r = service
.repo
.git_get_default_branch(&session, &path.workspace_name, &path.repo_name)
.await?;
Ok(HttpResponse::Ok().json(ApiResponse::new(r)))
}
#[utoipa::path(
get,
path = "/api/v1/workspaces/{workspace_name}/repos/{repo_name}/git/object-format",
tag = "Git",
operation_id = "gitObjectFormat",
params(PathParams),
responses((status = 200, body = ApiResponse<i32>)),
security(("session_cookie" = []))
)]
pub async fn git_object_format(
service: web::Data<AppService>,
session: Session,
path: web::Path<PathParams>,
) -> Result<HttpResponse, AppError> {
let r = service
.repo
.git_get_object_format(&session, &path.workspace_name, &path.repo_name)
.await?;
Ok(HttpResponse::Ok().json(ApiResponse::new(r)))
}
#[utoipa::path(
get,
path = "/api/v1/workspaces/{workspace_name}/repos/{repo_name}/git/size",
tag = "Git",
operation_id = "gitRepositorySize",
params(PathParams),
responses((
status = 200,
body = ApiResponse<crate::pb::repo::RepositorySizeResponse>
)),
security(("session_cookie" = []))
)]
pub async fn git_repository_size(
service: web::Data<AppService>,
session: Session,
path: web::Path<PathParams>,
) -> Result<HttpResponse, AppError> {
let r = service
.repo
.git_repository_size(&session, &path.workspace_name, &path.repo_name)
.await?;
Ok(HttpResponse::Ok().json(ApiResponse::new(r)))
}
#[derive(Debug, Deserialize, utoipa::ToSchema)]
pub struct ObjectsSizeBody {
pub oids: Vec<String>,
}
#[utoipa::path(
post,
path = "/api/v1/workspaces/{workspace_name}/repos/{repo_name}/git/objects-size",
tag = "Git",
operation_id = "gitObjectsSize",
params(PathParams),
request_body(content = ObjectsSizeBody),
responses((
status = 200,
body = ApiResponse<crate::pb::repo::ObjectsSizeResponse>
)),
security(("session_cookie" = []))
)]
pub async fn git_objects_size(
service: web::Data<AppService>,
session: Session,
path: web::Path<PathParams>,
body: web::Json<ObjectsSizeBody>,
) -> Result<HttpResponse, AppError> {
let r = service
.repo
.git_objects_size(
&session,
&path.workspace_name,
&path.repo_name,
body.oids.clone(),
)
.await?;
Ok(HttpResponse::Ok().json(ApiResponse::new(r)))
}
#[derive(Debug, Deserialize, IntoParams)]
pub struct MergeBaseQuery {
pub revisions: Vec<String>,
}
#[utoipa::path(
get,
path = "/api/v1/workspaces/{workspace_name}/repos/{repo_name}/git/merge-base",
tag = "Git",
operation_id = "gitMergeBase",
params(PathParams, MergeBaseQuery),
responses((
status = 200,
body = ApiResponse<crate::pb::repo::FindMergeBaseResponse>
)),
security(("session_cookie" = []))
)]
pub async fn git_merge_base(
service: web::Data<AppService>,
session: Session,
path: web::Path<PathParams>,
q: web::Query<MergeBaseQuery>,
) -> Result<HttpResponse, AppError> {
let r = service
.repo
.git_find_merge_base(
&session,
&path.workspace_name,
&path.repo_name,
q.revisions.clone(),
)
.await?;
Ok(HttpResponse::Ok().json(ApiResponse::new(r)))
}
#[derive(Debug, Deserialize, IntoParams)]
pub struct ArchiveEntriesQuery {
pub treeish: Option<String>,
pub limit: Option<i64>,
}
#[utoipa::path(
get,
path = "/api/v1/workspaces/{workspace_name}/repos/{repo_name}/git/archive/entries",
tag = "Git",
operation_id = "gitArchiveEntries",
params(PathParams, ArchiveEntriesQuery),
responses((
status = 200,
body = ApiResponse<crate::pb::repo::ListArchiveEntriesResponse>
)),
security(("session_cookie" = []))
)]
pub async fn git_archive_entries(
service: web::Data<AppService>,
session: Session,
path: web::Path<PathParams>,
q: web::Query<ArchiveEntriesQuery>,
) -> Result<HttpResponse, AppError> {
let r = service
.repo
.git_list_archive_entries(
&session,
&path.workspace_name,
&path.repo_name,
q.treeish.as_deref().unwrap_or(DEFAULT_REVISION),
q.limit.unwrap_or(50).clamp(1, 100) as u32,
)
.await?;
Ok(HttpResponse::Ok().json(ApiResponse::new(r)))
}
#[derive(Debug, Deserialize, IntoParams)]
pub struct CommitAncestorsQuery {
pub max_count: Option<u32>,
}
#[utoipa::path(
get,
path = "/api/v1/workspaces/{workspace_name}/repos/{repo_name}/git/commits/{revision}/ancestors",
tag = "Git",
operation_id = "gitCommitAncestors",
params(RevisionPathParams, CommitAncestorsQuery),
responses((
status = 200,
body = ApiResponse<crate::pb::repo::GetCommitAncestorsResponse>
)),
security(("session_cookie" = []))
)]
pub async fn git_commit_ancestors(
service: web::Data<AppService>,
session: Session,
path: web::Path<RevisionPathParams>,
q: web::Query<CommitAncestorsQuery>,
) -> Result<HttpResponse, AppError> {
let r = service
.repo
.git_get_commit_ancestors(
&session,
&path.workspace_name,
&path.repo_name,
&path.revision,
q.max_count.unwrap_or(100),
)
.await?;
Ok(HttpResponse::Ok().json(ApiResponse::new(r)))
}
#[derive(Debug, Deserialize, utoipa::ToSchema)]
pub struct CheckObjectsBody {
pub revisions: Vec<String>,
}
#[utoipa::path(
post,
path = "/api/v1/workspaces/{workspace_name}/repos/{repo_name}/git/check-objects",
tag = "Git",
operation_id = "gitCheckObjects",
params(PathParams),
request_body(content = CheckObjectsBody),
responses((
status = 200,
body = ApiResponse<crate::pb::repo::CheckObjectsExistResponse>
)),
security(("session_cookie" = []))
)]
pub async fn git_check_objects(
service: web::Data<AppService>,
session: Session,
path: web::Path<PathParams>,
body: web::Json<CheckObjectsBody>,
) -> Result<HttpResponse, AppError> {
let r = service
.repo
.git_check_objects_exist(
&session,
&path.workspace_name,
&path.repo_name,
body.revisions.clone(),
)
.await?;
Ok(HttpResponse::Ok().json(ApiResponse::new(r)))
}
+159
View File
@@ -0,0 +1,159 @@
use crate::models::common::DEFAULT_REVISION;
use actix_web::{HttpResponse, web};
use serde::Deserialize;
use utoipa::IntoParams;
use crate::api::response::ApiResponse;
use crate::error::AppError;
use crate::service::AppService;
use crate::session::Session;
#[derive(Debug, Deserialize, IntoParams)]
pub struct PathParams {
pub workspace_name: String,
pub repo_name: String,
}
#[derive(Debug, Deserialize, IntoParams)]
pub struct RawBlobQuery {
pub revision: Option<String>,
pub path: String,
}
#[utoipa::path(
get,
path = "/api/v1/workspaces/{workspace_name}/repos/{repo_name}/git/raw-blob",
tag = "Git",
operation_id = "gitRawBlob",
params(PathParams, RawBlobQuery),
responses((status = 200, content_type = "application/octet-stream")),
security(("session_cookie" = []))
)]
pub async fn git_raw_blob(
service: web::Data<AppService>,
session: Session,
path: web::Path<PathParams>,
q: web::Query<RawBlobQuery>,
) -> Result<HttpResponse, AppError> {
let r = service
.repo
.git_get_raw_blob(
&session,
&path.workspace_name,
&path.repo_name,
q.revision.as_deref().unwrap_or(DEFAULT_REVISION),
&q.path,
)
.await?;
Ok(HttpResponse::Ok()
.content_type("application/octet-stream")
.body(r))
}
#[derive(Debug, Deserialize, IntoParams)]
pub struct FileMetaQuery {
pub revision: Option<String>,
pub path: String,
}
#[utoipa::path(
get,
path = "/api/v1/workspaces/{workspace_name}/repos/{repo_name}/git/file-metadata",
tag = "Git",
operation_id = "gitFileMetadata",
params(PathParams, FileMetaQuery),
responses((
status = 200,
body = ApiResponse<crate::pb::repo::FileMetadata>
)),
security(("session_cookie" = []))
)]
pub async fn git_file_metadata(
service: web::Data<AppService>,
session: Session,
path: web::Path<PathParams>,
q: web::Query<FileMetaQuery>,
) -> Result<HttpResponse, AppError> {
let r = service
.repo
.git_get_file_metadata(
&session,
&path.workspace_name,
&path.repo_name,
q.revision.as_deref().unwrap_or(DEFAULT_REVISION),
&q.path,
)
.await?;
Ok(HttpResponse::Ok().json(ApiResponse::new(r)))
}
#[derive(Debug, Deserialize, IntoParams)]
pub struct FindFilesQuery {
pub revision: Option<String>,
pub pattern: String,
}
#[utoipa::path(
get,
path = "/api/v1/workspaces/{workspace_name}/repos/{repo_name}/git/find-files",
tag = "Git",
operation_id = "gitFindFiles",
params(PathParams, FindFilesQuery),
responses((
status = 200,
body = ApiResponse<crate::pb::repo::FindFilesResponse>
)),
security(("session_cookie" = []))
)]
pub async fn git_find_files(
service: web::Data<AppService>,
session: Session,
path: web::Path<PathParams>,
q: web::Query<FindFilesQuery>,
) -> Result<HttpResponse, AppError> {
let r = service
.repo
.git_find_files(
&session,
&path.workspace_name,
&path.repo_name,
q.revision.as_deref().unwrap_or(DEFAULT_REVISION),
&q.pattern,
)
.await?;
Ok(HttpResponse::Ok().json(ApiResponse::new(r)))
}
#[derive(Debug, Deserialize, IntoParams)]
pub struct GetTreeQuery {
pub revision: Option<String>,
pub path: Option<String>,
}
#[utoipa::path(
get,
path = "/api/v1/workspaces/{workspace_name}/repos/{repo_name}/git/get-tree",
tag = "Git",
operation_id = "gitGetTree",
params(PathParams, GetTreeQuery),
responses((status = 200, body = ApiResponse<crate::pb::repo::Tree>)),
security(("session_cookie" = []))
)]
pub async fn git_get_tree(
service: web::Data<AppService>,
session: Session,
path: web::Path<PathParams>,
q: web::Query<GetTreeQuery>,
) -> Result<HttpResponse, AppError> {
let r = service
.repo
.git_get_tree(
&session,
&path.workspace_name,
&path.repo_name,
q.revision.as_deref().unwrap_or(DEFAULT_REVISION),
q.path.as_deref().unwrap_or(""),
)
.await?;
Ok(HttpResponse::Ok().json(ApiResponse::new(r)))
}
+93
View File
@@ -0,0 +1,93 @@
use crate::models::common::DEFAULT_REVISION;
use crate::error::AppError;
use crate::service::RepoService;
use crate::session::Session;
impl RepoService {
pub async fn git_commit_stats(
&self,
ctx: &Session,
wk_name: &str,
repo_name: &str,
revision: &str,
) -> Result<crate::pb::repo::CommitStats, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let repo = self.resolve_repo(wk_name, repo_name).await?;
self.ensure_repo_readable(user_uid, &repo).await?;
let ws = self.resolve_workspace(wk_name).await?;
let header = self.repo_header(&repo, &ws);
let mut svc = self.git_client(&repo)?.commit;
let resp = svc
.get_commit_stats(tonic::Request::new(
crate::pb::repo::GetCommitStatsRequest {
repository: Some(header),
revision: Some(crate::pb::repo::ObjectSelector {
selector: Some(crate::pb::repo::object_selector::Selector::Revision(
crate::pb::repo::ObjectName {
revision: revision.to_string(),
},
)),
}),
},
))
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(resp.into_inner())
}
pub async fn git_count_commits(
&self,
ctx: &Session,
wk_name: &str,
repo_name: &str,
revision: Option<&str>,
path: Option<&str>,
since: Option<&str>,
until: Option<&str>,
) -> Result<crate::pb::repo::CountCommitsResponse, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let repo = self.resolve_repo(wk_name, repo_name).await?;
self.ensure_repo_readable(user_uid, &repo).await?;
let ws = self.resolve_workspace(wk_name).await?;
let header = self.repo_header(&repo, &ws);
let mut svc = self.git_client(&repo)?.commit;
let resp = svc
.count_commits(tonic::Request::new(crate::pb::repo::CountCommitsRequest {
repository: Some(header),
revision: revision.unwrap_or(DEFAULT_REVISION).to_string(),
path: path.unwrap_or_default().to_string(),
since: since.unwrap_or_default().to_string(),
until: until.unwrap_or_default().to_string(),
}))
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(resp.into_inner())
}
pub async fn git_count_diverging_commits(
&self,
ctx: &Session,
wk_name: &str,
repo_name: &str,
left: &str,
right: &str,
) -> Result<crate::pb::repo::CountDivergingCommitsResponse, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let repo = self.resolve_repo(wk_name, repo_name).await?;
self.ensure_repo_readable(user_uid, &repo).await?;
let ws = self.resolve_workspace(wk_name).await?;
let header = self.repo_header(&repo, &ws);
let mut svc = self.git_client(&repo)?.commit;
let resp = svc
.count_diverging_commits(tonic::Request::new(
crate::pb::repo::CountDivergingCommitsRequest {
repository: Some(header),
left: left.to_string(),
right: right.to_string(),
},
))
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(resp.into_inner())
}
}
+185
View File
@@ -0,0 +1,185 @@
use crate::models::common::DEFAULT_REVISION;
use crate::error::AppError;
use crate::service::RepoService;
use crate::session::Session;
impl RepoService {
pub async fn git_find_commit(
&self,
ctx: &Session,
wk_name: &str,
repo_name: &str,
revision: &str,
) -> Result<crate::pb::repo::Commit, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let repo = self.resolve_repo(wk_name, repo_name).await?;
self.ensure_repo_readable(user_uid, &repo).await?;
let ws = self.resolve_workspace(wk_name).await?;
let header = self.repo_header(&repo, &ws);
let mut svc = self.git_client(&repo)?.commit;
let resp = svc
.find_commit(tonic::Request::new(crate::pb::repo::FindCommitRequest {
repository: Some(header),
revision: Some(crate::pb::repo::ObjectSelector {
selector: Some(crate::pb::repo::object_selector::Selector::Revision(
crate::pb::repo::ObjectName {
revision: revision.to_string(),
},
)),
}),
include_stats: false,
}))
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(resp.into_inner())
}
pub async fn git_list_commits_by_oid(
&self,
ctx: &Session,
wk_name: &str,
repo_name: &str,
oids: Vec<Vec<u8>>,
) -> Result<crate::pb::repo::ListCommitsByOidResponse, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let repo = self.resolve_repo(wk_name, repo_name).await?;
self.ensure_repo_readable(user_uid, &repo).await?;
let ws = self.resolve_workspace(wk_name).await?;
let header = self.repo_header(&repo, &ws);
let mut svc = self.git_client(&repo)?.commit;
let resp = svc
.list_commits_by_oid(tonic::Request::new(
crate::pb::repo::ListCommitsByOidRequest {
repository: Some(header),
oids,
include_stats: false,
},
))
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(resp.into_inner())
}
pub async fn git_commit_is_ancestor(
&self,
ctx: &Session,
wk_name: &str,
repo_name: &str,
ancestor: &str,
descendant: &str,
) -> Result<bool, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let repo = self.resolve_repo(wk_name, repo_name).await?;
self.ensure_repo_readable(user_uid, &repo).await?;
let ws = self.resolve_workspace(wk_name).await?;
let header = self.repo_header(&repo, &ws);
let mut svc = self.git_client(&repo)?.commit;
let resp = svc
.commit_is_ancestor(tonic::Request::new(
crate::pb::repo::CommitIsAncestorRequest {
repository: Some(header),
ancestor_oid: ancestor.to_string(),
descendant_oid: descendant.to_string(),
},
))
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(resp.into_inner().is_ancestor)
}
pub async fn git_get_commit_ancestors(
&self,
ctx: &Session,
wk_name: &str,
repo_name: &str,
revision: &str,
max_count: u32,
) -> Result<crate::pb::repo::GetCommitAncestorsResponse, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let repo = self.resolve_repo(wk_name, repo_name).await?;
self.ensure_repo_readable(user_uid, &repo).await?;
let ws = self.resolve_workspace(wk_name).await?;
let header = self.repo_header(&repo, &ws);
let mut svc = self.git_client(&repo)?.commit;
let resp = svc
.get_commit_ancestors(tonic::Request::new(
crate::pb::repo::GetCommitAncestorsRequest {
repository: Some(header),
revision: Some(crate::pb::repo::ObjectSelector {
selector: Some(crate::pb::repo::object_selector::Selector::Revision(
crate::pb::repo::ObjectName {
revision: revision.to_string(),
},
)),
}),
first_parent: false,
pagination: Some(crate::pb::repo::Pagination {
page_size: max_count,
page_token: String::new(),
}),
},
))
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(resp.into_inner())
}
pub async fn git_last_commit_for_path(
&self,
ctx: &Session,
wk_name: &str,
repo_name: &str,
path: &str,
revision: Option<&str>,
) -> Result<crate::pb::repo::LastCommitForPathResponse, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let repo = self.resolve_repo(wk_name, repo_name).await?;
self.ensure_repo_readable(user_uid, &repo).await?;
let ws = self.resolve_workspace(wk_name).await?;
let header = self.repo_header(&repo, &ws);
let mut svc = self.git_client(&repo)?.commit;
let resp = svc
.last_commit_for_path(tonic::Request::new(
crate::pb::repo::LastCommitForPathRequest {
repository: Some(header),
path: path.to_string(),
revision: revision.unwrap_or(DEFAULT_REVISION).to_string(),
literal_pathspec: true,
},
))
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(resp.into_inner())
}
pub async fn git_commits_by_message(
&self,
ctx: &Session,
wk_name: &str,
repo_name: &str,
query: &str,
revision: Option<&str>,
limit: u32,
) -> Result<crate::pb::repo::CommitsByMessageResponse, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let repo = self.resolve_repo(wk_name, repo_name).await?;
self.ensure_repo_readable(user_uid, &repo).await?;
let ws = self.resolve_workspace(wk_name).await?;
let header = self.repo_header(&repo, &ws);
let mut svc = self.git_client(&repo)?.commit;
let resp = svc
.commits_by_message(tonic::Request::new(
crate::pb::repo::CommitsByMessageRequest {
repository: Some(header),
query: query.to_string(),
revision: revision.unwrap_or(DEFAULT_REVISION).to_string(),
limit,
offset: 0,
case_insensitive: true,
},
))
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(resp.into_inner())
}
}
+89
View File
@@ -0,0 +1,89 @@
use crate::models::common::DEFAULT_REVISION;
use crate::error::AppError;
use crate::service::RepoService;
use crate::session::Session;
impl RepoService {
pub async fn git_find_license(
&self,
ctx: &Session,
wk_name: &str,
repo_name: &str,
) -> Result<crate::pb::repo::FindLicenseResponse, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let repo = self.resolve_repo(wk_name, repo_name).await?;
self.ensure_repo_readable(user_uid, &repo).await?;
let ws = self.resolve_workspace(wk_name).await?;
let header = self.repo_header(&repo, &ws);
let mut svc = self.git_client(&repo)?.repository;
let resp = svc
.find_license(tonic::Request::new(crate::pb::repo::FindLicenseRequest {
repository: Some(header),
}))
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(resp.into_inner())
}
pub async fn git_search_content(
&self,
ctx: &Session,
wk_name: &str,
repo_name: &str,
query: &str,
revision: Option<&str>,
max_results: u32,
case_sensitive: bool,
) -> Result<crate::pb::repo::SearchFilesByContentResponse, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let repo = self.resolve_repo(wk_name, repo_name).await?;
self.ensure_repo_readable(user_uid, &repo).await?;
let ws = self.resolve_workspace(wk_name).await?;
let header = self.repo_header(&repo, &ws);
let mut svc = self.git_client(&repo)?.repository;
let resp = svc
.search_files_by_content(tonic::Request::new(
crate::pb::repo::SearchFilesByContentRequest {
repository: Some(header),
query: query.to_string(),
revision: revision.unwrap_or(DEFAULT_REVISION).to_string(),
max_results,
case_sensitive,
},
))
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(resp.into_inner())
}
pub async fn git_search_files(
&self,
ctx: &Session,
wk_name: &str,
repo_name: &str,
query: &str,
revision: Option<&str>,
max_results: u32,
recursive: bool,
) -> Result<crate::pb::repo::SearchFilesByNameResponse, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let repo = self.resolve_repo(wk_name, repo_name).await?;
self.ensure_repo_readable(user_uid, &repo).await?;
let ws = self.resolve_workspace(wk_name).await?;
let header = self.repo_header(&repo, &ws);
let mut svc = self.git_client(&repo)?.repository;
let resp = svc
.search_files_by_name(tonic::Request::new(
crate::pb::repo::SearchFilesByNameRequest {
repository: Some(header),
query: query.to_string(),
revision: revision.unwrap_or(DEFAULT_REVISION).to_string(),
max_results,
recursive,
},
))
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(resp.into_inner())
}
}