GitlabVcsProvider.kt

/*

  Copyright (C) 2026 Sber

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  In any derivative products, you must retain the information of
  owner of the original code and provide clear attribution to the project

  https://dochub.info

  The use of this product or its derivatives for any purpose cannot be a secret.


  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

  Maintainers:
      Марат Ниязматов <mrusniyazmatov@sberbank.ru>, Sber - 2026

  Contributors:
      Марат Ниязматов <mrusniyazmatov@sberbank.ru>, Sber - 2026
*/

package org.archtool.provider.gitlab

import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.plugins.defaultRequest
import io.ktor.client.request.get
import io.ktor.client.request.parameter
import kotlinx.coroutines.withContext
import org.archtool.data.exception.ErrorCode
import org.archtool.data.exception.SeafException
import org.archtool.data.model.RepoInfoModel
import org.archtool.helper.VcsHttpClientFactory
import org.archtool.provider.FileRequest
import org.archtool.provider.RepoRef
import org.archtool.provider.VcsCredentials
import org.archtool.provider.VcsProvider
import org.archtool.provider.VcsApiUtils
import org.archtool.provider.VcsProviderType
import org.archtool.provider.gitlab.dto.GitlabProjectDto
import org.springframework.core.PropagationContextElement
import org.springframework.stereotype.Component

@Component
@ConditionalOnGitlab
class GitlabVcsProvider(
    private val properties: GitlabProperties,
    private val vcsHttpClientFactory: VcsHttpClientFactory,
) : VcsProvider {
    private val httpClient: HttpClient = vcsHttpClientFactory.createClient(PRIVATE_TOKEN_HEADER) {
        defaultRequest {
            headers.append(PRIVATE_TOKEN_HEADER, properties.token)
        }
    }

    override fun parse(repoUrl: String): RepoRef {
        val projectId = parseProjectId(repoUrl)
        return RepoRef(localPath = localPath(projectId))
    }

    override fun tempBranchSuffix(repoUrl: String): String = parseProjectId(repoUrl)

    override fun parseFileRequest(project: String?, repo: String, branch: String): FileRequest {
        if (!repo.matches(PROJECT_ID_REGEX)) {
            throw SeafException(ErrorCode.BAD_REQUEST, "Неверный формат project_id GitLab: $repo (ожидается число)")
        }
        return FileRequest(
            repoRef = RepoRef(localPath = localPath(repo)),
            branch = branch,
        )
    }

    override suspend fun listRepositories(): List<RepoInfoModel> {
        val repositories = mutableListOf<RepoInfoModel>()
        var page = 1
        while (true) {
            val projectsUrl = "${properties.apiBaseUrl}/projects"
            val response = withContext(PropagationContextElement()) {
                vcsHttpClientFactory.execute(httpClient) { client ->
                    client.get(projectsUrl) {
                        parameter("page", page)
                        parameter("per_page", properties.perPage)
                        parameter("membership", properties.membership)
                        parameter("simple", true)
                    }
                }
            }
            VcsApiUtils.requireSuccess(response, VcsProviderType.GITLAB, projectsUrl)
            val projects = response.body<List<GitlabProjectDto>>()
            if (projects.isEmpty()) {
                break
            }
            for (project in projects) {
                repositories.add(
                    RepoInfoModel(
                        localPath = localPath(project.id.toString()),
                        name = project.name,
                        description = project.description,
                        cloneLink = project.httpUrlToRepo,
                        webLink = project.webUrl,
                    )
                )
            }
            val nextPage = response.headers["X-Next-Page"]?.toIntOrNull() ?: break
            page = nextPage
        }
        return repositories
    }

    override fun credentials(): VcsCredentials = VcsCredentials(
        username = "oauth2",
        password = properties.token,
    )

    override fun defaultBranch(): String = properties.defaultBranch

    private fun localPath(projectId: String) = "$MIRROR_PREFIX/$projectId"

    private fun parseProjectId(repoUrl: String): String {
        val match = REPO_URL_REGEX.matchEntire(repoUrl)
            ?: throw SeafException(ErrorCode.BAD_REQUEST, "Неверный формат ссылки GitLab: $repoUrl")
        return match.destructured.component1()
    }

    companion object {
        private const val MIRROR_PREFIX = "gitlab"
        private const val PRIVATE_TOKEN_HEADER = "PRIVATE-TOKEN"
        private val REPO_URL_REGEX = GitlabLinkPatterns.REPO_REGEX
        private val PROJECT_ID_REGEX = GitlabLinkPatterns.PROJECT_ID_REGEX
    }
}