Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add repositories info so the generation of docs TIP and overall TIR have the info they need to render the doc. #100

Draft
wants to merge 26 commits into
base: feature/moveLevaDoc
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
a6bd3d9
Enables tests previously disabled.
Apr 12, 2022
1a4cf0f
Load repositories test data 4 TIP and overall_TIR
Apr 13, 2022
f29d06b
ProjectRepositoryFixture
Apr 13, 2022
42e8385
Need better examples.
Apr 18, 2022
c87ed12
Need to save generated pdf when not as expected one.
Apr 18, 2022
1e20f00
Generates doInstall info before calling to generate doc.
Apr 18, 2022
b9a871f
Do not update pdfs if they are still valid.
Apr 18, 2022
ba6df8b
Improves example input data.
Apr 18, 2022
e7812ea
Updates expected pdf only if changes detected.
Apr 18, 2022
9f3f3ef
Renames method name.
Apr 18, 2022
8dcb4c8
Generated repos urls in docGen.
Apr 18, 2022
badfc5d
Fixes typo in urls, TIP docs.
Apr 18, 2022
03db887
computeRepositoriesDataNeededInDocs
Apr 18, 2022
9a4a6f9
Expected overall TIR.
Apr 18, 2022
3ee8932
Changed expected pdfs, since input data changed.
Apr 18, 2022
24ebad9
changelog
Apr 18, 2022
aedf1ed
Merge branch 'feature/moveLevaDoc' into feature/add-component-params-…
victorpablosceruelo Apr 18, 2022
c1f6462
Changes method name.
Apr 19, 2022
b26ff81
Merge branch 'feature/add-component-params-to-overall-tir-and-tip' of…
Apr 19, 2022
9952740
Loads repositories metadata from repositories yml files.
Apr 20, 2022
e874179
Fixes download method for templates.
Apr 20, 2022
84746f3
This seems to be a bug inherited from sharedLib
Apr 20, 2022
429d5d0
Change in tmp file name.
Apr 20, 2022
5a7eb06
Needed to ensure we do not use uncontrolled field values.
Apr 20, 2022
7b946bc
Fixes incorrect data.
Apr 20, 2022
2f47b39
Wiremock resources.
Apr 20, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,8 @@
- Added IT (Docker tests)
- Added performance tests
- logback.xml can be overridden from command line
- removed unused params from payloads.
- removed param jekins to jenkins
- Removed byte[] use
- removed unused params from payloads, jekins -> jenkins, computes values gitUrl and doInstall for each repository.
- Removed byte[] usage

## [4.0] - 2021-18-11
=======
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,11 @@ interface BitBucketRepository {
@Param("repo") String repo,
@Param("branch") String branch)

@Headers("Accept: application/octet-stream")
@RequestLine("GET /rest/api/latest/projects/{project}/repos/{repo}/archive?at={branch}&format=zip&path={filePath}")
Response getRepoFileInZipArchive(@Param("project") String project,
@Param("repo") String repo,
@Param("branch") String branch,
@Param("filePath") String filePath)

}
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@ import java.nio.file.StandardCopyOption
@Service
class BitbucketService {

private static final String MAIN_BRANCH = "master"

private ZipFacade zipFacade
private final BitBucketClientConfig bitBucketClientConfig

Expand All @@ -44,8 +42,8 @@ class BitbucketService {
return new JsonSlurperClassic().parseText(response)
}

String buildReleaseManagerUrl(String projectId, String releaseManagerRepo) {
URI uri = new URI([getBitbucketURLForDocs(), projectId, releaseManagerRepo].join("/"))
String buildRepositoryUrl(String projectId, String repositoryName) {
URI uri = new URI([getBitbucketURLForDocs(), projectId, repositoryName].join("/"))
return "${uri.normalize().toString()}.git"
}

Expand All @@ -54,36 +52,70 @@ class BitbucketService {
}

void downloadRepo(String project, String repo, String branch, String tmpFolder) {
downloadRepoWithFallBack(project, repo, branch, null, tmpFolder)
}

void downloadRepoWithFallBack(String project, String repo, String branch, String defaultBranch,
String tmpFolder) {
log.info("downloadRepo: project:${project}, repo:${repo} and branch:${branch}")
Path zipArchive = Files.createTempFile("archive-", ".zip")
Path zipArchive = Files.createTempFile("archive-${repo}", ".zip")
try {
downloadRepoWithFallBack(project, repo, branch, zipArchive)
try {
bitBucketClientConfig
.getClient()
.getRepoZipArchive(project, repo, branch)
.withCloseable { Response response ->
streamResult(response, zipArchive)
}
} catch (Exception firstTryException) {
if (defaultBranch) {
log.warn("Branch [${branch}] doesn't exist, using branch: [${defaultBranch}]")
bitBucketClientConfig
.getClient()
.getRepoZipArchive(project, repo, defaultBranch)
.withCloseable { Response response ->
streamResult(response, zipArchive)
}
} else {
throw firstTryException
}
}
zipFacade.extractZipArchive(zipArchive, Paths.get(tmpFolder))
} catch (FeignException callException) {
checkError(repo, branch, callException)
} finally {
Files.delete(zipArchive)
}

}

protected void downloadRepoWithFallBack(String project, String repo, String branch, Path zipArchive) {
void downloadRepoMetadata(String project, String repo, String branch, String defaultBranch, String tmpFolder) {
log.info("downloadRepo: project:${project}, repo:${repo} and branch:${branch}")
Path zipArchive = Files.createTempFile("archive-${repo}", ".zip")
try {
bitBucketClientConfig
.getClient()
.getRepoZipArchive(project, repo, branch)
.withCloseable { Response response ->
streamResult(response, zipArchive)
}
} catch (Exception callException) {
log.warn("Branch [${branch}] doesn't exist, using branch: [${MAIN_BRANCH}]")
bitBucketClientConfig
.getClient()
.getRepoZipArchive(project, repo, MAIN_BRANCH)
.withCloseable { Response response ->
streamResult(response, zipArchive)
}
}
try {
bitBucketClientConfig
.getClient()
.getRepoFileInZipArchive(project, repo, branch, "metadata.yml")
.withCloseable { Response response ->
streamResult(response, zipArchive)
}
} catch (e) {
log.warn("Branch [${branch}] doesn't exist, using branch: [${defaultBranch}]")
bitBucketClientConfig
.getClient()
.getRepoFileInZipArchive(project, repo, defaultBranch, "metadata.yml")
.withCloseable { Response response ->
streamResult(response, zipArchive)
}
}

zipFacade.extractZipArchive(zipArchive, Paths.get(tmpFolder))
} catch (FeignException callException) {
checkError(repo, branch, callException)
} finally {
Files.delete(zipArchive)
}
}

protected void streamResult(Response response, Path zipArchive){
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package org.ods.doc.gen.leva.doc.services

import groovy.util.logging.Slf4j
import groovy.xml.XmlUtil
import org.ods.doc.gen.external.modules.git.BitbucketService
import org.ods.doc.gen.external.modules.git.BitbucketTraceabilityUseCase
import org.ods.doc.gen.external.modules.jira.CustomIssueFields
import org.ods.doc.gen.external.modules.jira.IssueTypes
Expand Down Expand Up @@ -63,6 +64,7 @@ class LeVADocumentService {
private final LeVADocumentChaptersFileService levaFiles
private final BitbucketTraceabilityUseCase bbt
private final NexusService nexus
private final BitbucketService bitbucketService

@Inject
Clock clock
Expand All @@ -74,14 +76,16 @@ class LeVADocumentService {
JiraUseCase jiraUseCase,
JUnitReportsService junit,
LeVADocumentChaptersFileService levaFiles,
BitbucketTraceabilityUseCase bbt) {
BitbucketTraceabilityUseCase bbt,
BitbucketService bitbucketService) {
this.project = project
this.docGenUseCase = docGenUseCase
this.nexus = nexus
this.jiraUseCase = jiraUseCase
this.junit = junit
this.levaFiles = levaFiles
this.bbt = bbt
this.bitbucketService = bitbucketService
}

@SuppressWarnings('CyclomaticComplexity')
Expand Down Expand Up @@ -364,14 +368,14 @@ class LeVADocumentService {
def keysInDoc = this.computeKeysInDocForIPV(installationTestIssues)
def docHistory = this.getAndStoreDocumentHistory(documentType, keysInDoc, projectData)

def installedRepos = projectData.repositories.collect {
it << [ doInstall: !Constants.COMPONENT_TYPE_IS_NOT_INSTALLED.contains(it.type?.toLowerCase())]
}
updateProjectRepositoriesDoInstall(projectData)

def data_ = [
metadata: this.getDocumentMetadata(projectData, Constants.DOCUMENT_TYPE_NAMES[documentType]),
data : [
repositories : installedRepos.collect { [id: it.id, type: it.type, doInstall: it.doInstall, data: [git: [url: it.data.git == null ? null : it.data.git.url]]] },
repositories : projectData.repositories.collect {
[id: it.id, type: it.type, doInstall: it.doInstall,
data: [git: [url: it.metadata.gitUrl]]] },
sections : sections,
tests : SortUtil.sortIssuesByKey(installationTestIssues.collect { testIssue ->
[
Expand Down Expand Up @@ -522,6 +526,8 @@ class LeVADocumentService {
def keysInDoc = this.computeKeysInDocForTIP(projectData.getComponents())
def docHistory = this.getAndStoreDocumentHistory(documentType, keysInDoc, projectData)

updateRepositoriesData(data)

def data_ = [
metadata: this.getDocumentMetadata(projectData, Constants.DOCUMENT_TYPE_NAMES[documentType]),
data : [
Expand Down Expand Up @@ -753,14 +759,14 @@ class LeVADocumentService {
def keysInDoc = this.computeKeysInDocForIVR(installationTestIssues)
def docHistory = this.getAndStoreDocumentHistory(documentType, keysInDoc, projectData)

def installedRepos = projectData.repositories.collect {
it << [ doInstall: !Constants.COMPONENT_TYPE_IS_NOT_INSTALLED.contains(it.type?.toLowerCase())]
}
updateProjectRepositoriesDoInstall(projectData)

def data_ = [
metadata: this.getDocumentMetadata(projectData, Constants.DOCUMENT_TYPE_NAMES[documentType]),
data : [
repositories : installedRepos.collect { [id: it.id, type: it.type, doInstall: it.doInstall, data: [git: [url: it.data.git == null ? null : it.data.git.url]]] },
repositories : projectData.repositories.collect {
[id: it.id, type: it.type, doInstall: it.doInstall,
data: [git: [url: it.metadata.gitUrl]]] },
sections : sections,
tests : buildTestResultsIVR(installationTestIssues),
numAdditionalTests: getNumAdditionalTest(installationTestData, installationTestIssues),
Expand Down Expand Up @@ -945,6 +951,8 @@ class LeVADocumentService {

def watermarkText = this.getWatermarkText(projectData)

updateRepositoriesData(data)

def visitor = { data_ ->
// Prepend a section for the Jenkins build log
data_.sections.add(0, [
Expand Down Expand Up @@ -1243,7 +1251,7 @@ class LeVADocumentService {
projectData.repositories.collect {
[
id: it.id,
description: it.metadata?.description,
description: it.metadata.description,
tests: componentTestMapping[it.id]? componentTestMapping[it.id].join(", "): "None defined"
]
}
Expand Down Expand Up @@ -1639,4 +1647,21 @@ class LeVADocumentService {
junit.getNumberOfTestCases(testData.testResults) - testIssues.count { !it.isUnexecuted }
}

private void updateProjectRepositoriesDoInstall(ProjectData projectData) {
projectData.repositories.forEach({
it.doInstall = !Constants.COMPONENT_TYPE_IS_NOT_INSTALLED.contains(it.type?.toLowerCase())
})
}

private updateRepositoriesData(Map data) {
String projectId = data.projectId as String

data.repositories.each { Map repo ->
String repoName = repo.id as String
repoName = "${projectId}-${repoName}"
repo["data"]["git"]["url"] = bitbucketService.buildRepositoryUrl(projectId, repoName)

repo["doInstall"] = !Constants.COMPONENT_TYPE_IS_NOT_INSTALLED.contains(repo.type?.toLowerCase())
}
}
}
83 changes: 51 additions & 32 deletions src/main/groovy/org/ods/doc/gen/project/data/ProjectData.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ import org.yaml.snakeyaml.Yaml

import java.nio.file.Paths

import static groovy.json.JsonOutput.prettyPrint
import static groovy.json.JsonOutput.toJson

@SuppressWarnings(['LineLength',
'AbcMetric',
'IfStatementBraces',
Expand All @@ -32,8 +35,10 @@ import java.nio.file.Paths
@Service
class ProjectData {

static final String DEFAULT_TEMPLATE_VERSION = '1.2'
static final String BUILD_PARAM_VERSION_DEFAULT = 'WIP'
static final String METADATA_FILE_NAME = 'metadata.yml'
private static final String DEFAULT_BRANCH_RELEASE_MANAGER = "master"

protected Map config
protected Boolean isVersioningEnabled = false
Expand Down Expand Up @@ -69,18 +74,19 @@ class ProjectData {
this.data.jira = [project: [ : ]]
this.data.repo = data.repo
this.data.git = data.git
this.data.git.url = bitbucketService.buildReleaseManagerUrl(
this.data.git.url = bitbucketService.buildRepositoryUrl(
data.projectId as String,
data.git.releaseManagerRepo as String
)
return this
}

ProjectData load() {
bitbucketService.downloadRepo(
bitbucketService.downloadRepoWithFallBack(
data.projectId as String,
data.git.releaseManagerRepo as String,
data.git.releaseManagerBranch as String,
DEFAULT_BRANCH_RELEASE_MANAGER,
tmpFolder + "/releasemanager")

this.data.metadata = loadMetadata(tmpFolder + "/releasemanager")
Expand Down Expand Up @@ -136,8 +142,7 @@ class ProjectData {
private Map loadMetadata(String workspace){
Map result = parseMetadataFile(workspace)
result.description = (result.description)?: ""
result.repositories = (result.repositories)?: ""
updateRepositories(result)
result.repositories = loadRepositories(result.repositories)
result.capabilities = (result.capabilities )?: []
updateLevaDocCapability(result)
result.environments = (result.environments)?: [:]
Expand Down Expand Up @@ -167,37 +172,51 @@ class ProjectData {
}
}

private void updateRepositories(Map result) {
result.repositories.eachWithIndex { repo, index ->
// Check for existence of required attribute 'repositories[i].id'
if (!repo.id?.trim()) {
throw new IllegalArgumentException(
"Error: unable to parse project meta data. Required attribute 'repositories[${index}].id' is undefined.")
}

repo.data = [
openshift: [:],
documents: [:],
]

// Set repo type, if not provided
if (!repo.type?.trim()) {
repo.type = PipelineConfig.REPO_TYPE_ODS_CODE
}

repo.metadata = loadMetadataRepo(repo)
private loadRepositories(List repositories) {
List<RepoData> reposData = []
for(Map repo : repositories) {
def repoMetadata = loadRepoMetadataFromRepo(repo)
RepoData repoData = new RepoData(repo, repoMetadata)
reposData.add(repoData)
}
return reposData
}

private Map<String, String> loadMetadataRepo(repo) {
return [
private RepoMetadata loadRepoMetadataFromRepo(repo) {
if ((! repo) || (! repo.id)) {
throw new RuntimeException("Repository id cannot be blank or null.")
}
String projectId = data.projectId as String
String repoId = "${projectId}-${repo.id}"
String branch = data.git.releaseManagerBranch as String
String targetFolder = tmpFolder + "/" + repoId

String defaultBranch = repo.branch ?: "master"
bitbucketService.downloadRepoMetadata(projectId, repoId, branch, defaultBranch, targetFolder)
Map repoMetadata = parseRepoMetadataFile(targetFolder)
log.debug(prettyPrint(toJson(repoMetadata)))

String gitUrl = bitbucketService.buildRepositoryUrl(projectId, repoId)
return new RepoMetadata([
id: repo.id,
name: repo.name,
description: "myDescription-A",
supplier: "mySupplier-A",
version: "myVersion-A",
references: "myReferences-A"
]
name: repoMetadata.name,
description: repoMetadata.description,
supplier: repoMetadata.supplier,
version: repoMetadata.version,
references: repoMetadata.references,
gitUrl: gitUrl
])
}

private Map parseRepoMetadataFile(String repoFolder) {
String filename = METADATA_FILE_NAME
def file = Paths.get(repoFolder, filename).toFile()
if (!file.exists()) {
throw new RuntimeException("Error: unable to load project meta data. File '${repoFolder}/${filename}' does not exist.")
}

Map result = new Yaml().load(file.text)
return result
}

private Map parseMetadataFile(String workspace) {
Expand Down Expand Up @@ -467,7 +486,7 @@ class ProjectData {
return this.data.metadata.name
}

List<Map> getRepositories() {
List<RepoData> getRepositories() {
return this.data.metadata.repositories
}

Expand Down
Loading