From 6b0bb9367714de82945f591d3c5a0853d248c021 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Thu, 18 Nov 2021 17:19:01 +0300 Subject: [PATCH 01/22] =?UTF-8?q?=D0=A7=D0=B5=D1=80=D0=BD=D0=BE=D0=B2?= =?UTF-8?q?=D0=B0=D1=8F=20=D1=80=D0=B5=D0=B0=D0=BB=D0=B8=D0=B7=D0=B0=D1=86?= =?UTF-8?q?=D0=B8=D1=8F=20=D0=B7=D0=B0=D0=BF=D1=83=D1=81=D0=BA=D0=B0=20?= =?UTF-8?q?=D0=B4=D1=8B=D0=BC=D0=BE=D0=B2=D1=8B=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- resources/globalConfiguration.json | 5 + resources/schema.json | 19 ++++ .../jenkins/library/IStepExecutor.groovy | 4 + .../jenkins/library/StepExecutor.groovy | 7 +- .../configuration/JobConfiguration.groovy | 6 +- .../configuration/SmokeTestOptions.groovy | 34 +++++++ .../library/steps/PublishAllure.groovy | 5 +- .../jenkins/library/steps/SmokeTest.groovy | 98 +++++++++++++++++++ .../jenkins/library/utils/VRunner.groovy | 7 ++ .../library/utils/VersionParser.groovy | 2 +- vars/pipeline1C.groovy | 2 + vars/smoke.groovy | 17 +--- 12 files changed, 188 insertions(+), 18 deletions(-) create mode 100644 src/ru/pulsar/jenkins/library/configuration/SmokeTestOptions.groovy create mode 100644 src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy diff --git a/resources/globalConfiguration.json b/resources/globalConfiguration.json index 8f79812..d5a8f69 100644 --- a/resources/globalConfiguration.json +++ b/resources/globalConfiguration.json @@ -50,6 +50,11 @@ ], "vrunnerSettings": "./tools/vrunner.json" }, + "smoke": { + "vrunnerSettings": "./tools/vrunner.json", + "publishToAllureReport": false, + "publishToJUnitReport": true + }, "resultsTransform": { "removeSupport": true, "supportLevel": 0 diff --git a/resources/schema.json b/resources/schema.json index 0532694..d45308b 100644 --- a/resources/schema.json +++ b/resources/schema.json @@ -151,6 +151,25 @@ } } }, + "smoke" : { + "type" : "object", + "id" : "urn:jsonschema:ru:pulsar:jenkins:library:configuration:SmokeTestOptions", + "description" : "Настройки дымового тестирования", + "properties" : { + "vrunnerSettings" : { + "type" : "string", + "description" : "Путь к конфигурационному файлу vanessa-runner.\n По умолчанию содержит значение \"./tools/vrunner.json\".\n " + }, + "publishToAllureReport" : { + "type" : "boolean", + "description" : "Выполнять публикацию результатов в отчет Allure.\n По умолчанию выключено.\n " + }, + "publishToJUnitReport" : { + "type" : "boolean", + "description" : "Выполнять публикацию результатов в отчет JUnit.\n По умолчанию включено.\n " + } + } + }, "resultsTransform" : { "type" : "object", "id" : "urn:jsonschema:ru:pulsar:jenkins:library:configuration:ResultsTransformOptions", diff --git a/src/ru/pulsar/jenkins/library/IStepExecutor.groovy b/src/ru/pulsar/jenkins/library/IStepExecutor.groovy index 243763b..a41cbeb 100644 --- a/src/ru/pulsar/jenkins/library/IStepExecutor.groovy +++ b/src/ru/pulsar/jenkins/library/IStepExecutor.groovy @@ -17,6 +17,8 @@ interface IStepExecutor { FileWrapper[] findFiles(String glob, String excludes) + String readFile(String file) + String readFile(String file, String encoding) boolean fileExists(String file) @@ -73,5 +75,7 @@ interface IStepExecutor { def allure(List results) + def junit(String testResults, boolean allowEmptyResults) + def installLocalDependencies() } \ No newline at end of file diff --git a/src/ru/pulsar/jenkins/library/StepExecutor.groovy b/src/ru/pulsar/jenkins/library/StepExecutor.groovy index c5b6368..8d1ab2a 100644 --- a/src/ru/pulsar/jenkins/library/StepExecutor.groovy +++ b/src/ru/pulsar/jenkins/library/StepExecutor.groovy @@ -33,7 +33,7 @@ class StepExecutor implements IStepExecutor { } @Override - String readFile(String file, String encoding) { + String readFile(String file, String encoding = 'UTF-8') { steps.readFile encoding: encoding, file: file } @@ -174,6 +174,11 @@ class StepExecutor implements IStepExecutor { ]) } + @Override + def junit(String testResults, boolean allowEmptyResults) { + steps.junit testResults: testResults, allowEmptyResults: allowEmptyResults + } + @Override def installLocalDependencies() { steps.installLocalDependencies() diff --git a/src/ru/pulsar/jenkins/library/configuration/JobConfiguration.groovy b/src/ru/pulsar/jenkins/library/configuration/JobConfiguration.groovy index 4689a6f..34c06c2 100644 --- a/src/ru/pulsar/jenkins/library/configuration/JobConfiguration.groovy +++ b/src/ru/pulsar/jenkins/library/configuration/JobConfiguration.groovy @@ -1,7 +1,6 @@ package ru.pulsar.jenkins.library.configuration import com.cloudbees.groovy.cps.NonCPS -import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.annotation.JsonPropertyDescription @@ -45,6 +44,10 @@ class JobConfiguration implements Serializable { @JsonPropertyDescription("Настройки синтаксического контроля") SyntaxCheckOptions syntaxCheckOptions; + @JsonProperty("smoke") + @JsonPropertyDescription("Настройки дымового тестирования") + SmokeTestOptions smokeTestOptions; + @JsonProperty("resultsTransform") @JsonPropertyDescription("Настройки трансформации результатов анализа") ResultsTransformOptions resultsTransformOptions; @@ -67,6 +70,7 @@ class JobConfiguration implements Serializable { ", bddOptions=" + bddOptions + ", sonarQubeOptions=" + sonarQubeOptions + ", syntaxCheckOptions=" + syntaxCheckOptions + + ", smokeTestOptions=" + smokeTestOptions + ", resultsTransformOptions=" + resultsTransformOptions + ", logosConfig=" + logosConfig + '}'; diff --git a/src/ru/pulsar/jenkins/library/configuration/SmokeTestOptions.groovy b/src/ru/pulsar/jenkins/library/configuration/SmokeTestOptions.groovy new file mode 100644 index 0000000..f58efb0 --- /dev/null +++ b/src/ru/pulsar/jenkins/library/configuration/SmokeTestOptions.groovy @@ -0,0 +1,34 @@ +package ru.pulsar.jenkins.library.configuration + +import com.cloudbees.groovy.cps.NonCPS +import com.fasterxml.jackson.annotation.JsonIgnoreProperties +import com.fasterxml.jackson.annotation.JsonPropertyDescription + +@JsonIgnoreProperties(ignoreUnknown = true) +class SmokeTestOptions implements Serializable { + + @JsonPropertyDescription("""Путь к конфигурационному файлу vanessa-runner. + По умолчанию содержит значение "./tools/vrunner.json". + """) + String vrunnerSettings + + @JsonPropertyDescription("""Выполнять публикацию результатов в отчет Allure. + По умолчанию выключено. + """) + boolean publishToAllureReport + + @JsonPropertyDescription("""Выполнять публикацию результатов в отчет JUnit. + По умолчанию включено. + """) + boolean publishToJUnitReport + + @Override + @NonCPS + String toString() { + return "SyntaxCheckOptions{" + + "vrunnerSettings=" + vrunnerSettings + + ", publishToAllureReport=" + publishToAllureReport + + ", publishToJUnitReport=" + publishToJUnitReport + + '}'; + } +} diff --git a/src/ru/pulsar/jenkins/library/steps/PublishAllure.groovy b/src/ru/pulsar/jenkins/library/steps/PublishAllure.groovy index 2c6360d..8d55fe7 100644 --- a/src/ru/pulsar/jenkins/library/steps/PublishAllure.groovy +++ b/src/ru/pulsar/jenkins/library/steps/PublishAllure.groovy @@ -23,6 +23,9 @@ class PublishAllure implements Serializable { safeUnstash('init-allure') safeUnstash('bdd-allure') + if (config.smokeTestOptions.publishToAllureReport) { + safeUnstash(SmokeTest.SMOKE_ALLURE_STASH) + } def env = steps.env(); @@ -47,7 +50,7 @@ class PublishAllure implements Serializable { private void safeUnstash(String stashName) { try { steps.unstash(stashName) - } catch (Exception ex) { + } catch (Exception ignored) { Logger.println("Can't unstash $stashName") } } diff --git a/src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy b/src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy new file mode 100644 index 0000000..116fedb --- /dev/null +++ b/src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy @@ -0,0 +1,98 @@ +package ru.pulsar.jenkins.library.steps + +import hudson.FilePath +import ru.pulsar.jenkins.library.IStepExecutor +import ru.pulsar.jenkins.library.configuration.JobConfiguration +import ru.pulsar.jenkins.library.ioc.ContextRegistry +import ru.pulsar.jenkins.library.utils.FileUtils +import ru.pulsar.jenkins.library.utils.Logger +import ru.pulsar.jenkins.library.utils.VRunner + +class SmokeTest implements Serializable { + + public static final String SMOKE_ALLURE_STASH = 'smoke-allure' + + private final JobConfiguration config; + + SmokeTest(JobConfiguration config) { + this.config = config + } + + def run() { + IStepExecutor steps = ContextRegistry.getContext().getStepExecutor() + + Logger.printLocation() + + if (!config.stageFlags.smoke) { + Logger.println("Smoke test step is disabled") + return + } + + List logosConfig = ["LOGOS_CONFIG=$config.logosConfig"] + steps.withEnv(logosConfig) { + steps.installLocalDependencies() + } + + def options = config.smokeTestOptions + def env = steps.env() + + String vrunnerPath = VRunner.getVRunnerPath() + String command = "$vrunnerPath xunit --ibconnection \"/F./build/ib\"" + + String vrunnerSettings = options.vrunnerSettings + if (steps.fileExists(vrunnerSettings)) { + command += " --settings $vrunnerSettings"; + } + + String xddTestRunnerPath = "./oscript_modules/add/xddTestRunner.epf" + if (steps.fileExists(xddTestRunnerPath)) { + command += " --pathxunit $xddTestRunnerPath" + } + + String xddConfigPath = "./tools/xUnitParams.json" + if (steps.fileExists(xddConfigPath)) { + command += " --xddConfig $xddConfigPath" + } + + String junitReport = "build/out/jUnit/smoke/smoke.xml" + FilePath pathToJUnitReport = FileUtils.getFilePath("$env.WORKSPACE/$junitReport") + String junitReportDir = FileUtils.getLocalPath(pathToJUnitReport.getParent()) + + steps.createDir(junitReportDir) + + String allureReport = "build/out/allure/smoke/allure.xml" + FilePath pathToAllureReport = FileUtils.getFilePath("$env.WORKSPACE/$allureReport") + String allureReportDir = FileUtils.getLocalPath(pathToAllureReport.getParent()) + + steps.createDir(allureReportDir) + + command += " --reportsxunit \"ГенераторОтчетаJUnitXML{$junitReport};ГенераторОтчетаAllureXMLВерсия2{$allureReport}\"" + if (steps.isUnix()) { + command = command.replace(';', '\\;') + } + + if (!VRunner.configContainsSetting(vrunnerSettings, "testsPath")) { + String testsPath = "oscript_modules/add/tests/smoke" + if (!steps.fileExists(testsPath)) { + testsPath = '$addRoot/tests/smoke' + if (steps.isUnix()) { + testsPath = '\\' + testsPath + } + } + command += " $testsPath" + } + + steps.withEnv(logosConfig) { + VRunner.exec(command) + } + + steps.stash(SMOKE_ALLURE_STASH, "$allureReportDir/**", true) + + if (options.publishToJUnitReport) { + steps.junit("$junitReportDir/*.xml", true) + } + + steps.archiveArtifacts("$junitReportDir/**") + steps.archiveArtifacts("$allureReportDir/**") + } +} diff --git a/src/ru/pulsar/jenkins/library/utils/VRunner.groovy b/src/ru/pulsar/jenkins/library/utils/VRunner.groovy index d9b48ab..f59b7fd 100644 --- a/src/ru/pulsar/jenkins/library/utils/VRunner.groovy +++ b/src/ru/pulsar/jenkins/library/utils/VRunner.groovy @@ -27,4 +27,11 @@ class VRunner { return steps.cmd(command, returnStatus) } as int } + + static boolean configContainsSetting(String configPath, String settingName) { + IStepExecutor steps = ContextRegistry.getContext().getStepExecutor() + + String fileContent = steps.readFile(configPath) + return fileContent.contains("\"$settingName\"") + } } diff --git a/src/ru/pulsar/jenkins/library/utils/VersionParser.groovy b/src/ru/pulsar/jenkins/library/utils/VersionParser.groovy index 7183967..74054aa 100644 --- a/src/ru/pulsar/jenkins/library/utils/VersionParser.groovy +++ b/src/ru/pulsar/jenkins/library/utils/VersionParser.groovy @@ -28,7 +28,7 @@ class VersionParser implements Serializable { return "" } - def configurationText = steps.readFile(filePath, 'UTF-8'); + def configurationText = steps.readFile(filePath); return version(configurationText, regexp) } diff --git a/vars/pipeline1C.groovy b/vars/pipeline1C.groovy index efab2c4..2314045 100644 --- a/vars/pipeline1C.groovy +++ b/vars/pipeline1C.groovy @@ -183,6 +183,8 @@ void call() { expression { config.stageFlags.smoke } } steps { + unzipInfobase() + smoke config } } diff --git a/vars/smoke.groovy b/vars/smoke.groovy index fc204f6..f43802f 100644 --- a/vars/smoke.groovy +++ b/vars/smoke.groovy @@ -1,23 +1,12 @@ import ru.pulsar.jenkins.library.configuration.JobConfiguration import ru.pulsar.jenkins.library.ioc.ContextRegistry +import ru.pulsar.jenkins.library.steps.SmokeTest def call(JobConfiguration config) { ContextRegistry.registerDefaultContext(this) - // TODO: Вынести в отдельный класс по аналогии с SonarScanner - - printLocation() - - if (!config.stageFlags.smoke) { - echo("Smoke tests step is disabled") - return - } - - def options = config.syntaxCheckOptions - - installLocalDependencies() - - unzipInfobase() + def smokeTest = new SmokeTest(config) + smokeTest.run() } From f1b3094ea5fb86d02afc8282164d44bc3428c1fe Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Wed, 24 Nov 2021 19:07:27 +0300 Subject: [PATCH 02/22] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=20=D1=83=D1=87=D0=B5=D1=82=20=D0=BD=D0=BE=D0=B2?= =?UTF-8?q?=D0=BE=D0=B3=D0=BE=20=D0=B8=D0=BC=D0=B5=D0=BD=D0=B8=20=D0=BC?= =?UTF-8?q?=D0=B0=D1=81=D1=82=D0=B5=D1=80-=D0=BD=D0=BE=D0=B4=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ru/pulsar/jenkins/library/utils/FileUtils.groovy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ru/pulsar/jenkins/library/utils/FileUtils.groovy b/src/ru/pulsar/jenkins/library/utils/FileUtils.groovy index 43d475b..c0fba7b 100644 --- a/src/ru/pulsar/jenkins/library/utils/FileUtils.groovy +++ b/src/ru/pulsar/jenkins/library/utils/FileUtils.groovy @@ -18,7 +18,7 @@ class FileUtils { steps.error 'Переменная среды NODE_NAME не задана. Запуск вне node или без agent?' } - if (nodeName == "master") { + if (nodeName == "master" || nodeName == "built-in") { return new FilePath(new File(path)); } else { return new FilePath(Jenkins.getInstanceOrNull().getComputer(nodeName).getChannel(), path); From 50ad29c4fece4da77d258f3df9f8470f74356900 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Thu, 25 Nov 2021 15:13:41 +0300 Subject: [PATCH 03/22] =?UTF-8?q?=D0=97=D0=B0=D0=BC=D0=B5=D0=BD=D0=B0=20?= =?UTF-8?q?=D0=BE=D0=B4=D0=B8=D0=BD=D0=B0=D1=80=D0=BD=D1=8B=D1=85=20=D0=BA?= =?UTF-8?q?=D0=B0=D0=B2=D1=8B=D1=87=D0=B5=D0=BA=20=D0=BD=D0=B0=20=D0=B4?= =?UTF-8?q?=D0=B2=D0=BE=D0=B9=D0=BD=D1=8B=D0=B5=20=D0=B4=D0=BB=D1=8F=20?= =?UTF-8?q?=D0=BF=D0=BE=D0=B4=D0=B4=D0=B5=D1=80=D0=B6=D0=BA=D0=B8=20=D1=80?= =?UTF-8?q?=D0=B0=D0=B1=D0=BE=D1=82=D1=8B=20=D0=B2=20cmd?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../library/steps/DesignerToEdtFormatTransformation.groovy | 2 +- .../library/steps/EdtToDesignerFormatTransformation.groovy | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ru/pulsar/jenkins/library/steps/DesignerToEdtFormatTransformation.groovy b/src/ru/pulsar/jenkins/library/steps/DesignerToEdtFormatTransformation.groovy index bfee6f0..5b79ecf 100644 --- a/src/ru/pulsar/jenkins/library/steps/DesignerToEdtFormatTransformation.groovy +++ b/src/ru/pulsar/jenkins/library/steps/DesignerToEdtFormatTransformation.groovy @@ -38,7 +38,7 @@ class DesignerToEdtFormatTransformation implements Serializable { Logger.println("Конвертация исходников из формата конфигуратора в формат EDT") - def ringCommand = "ring edt workspace import --configuration-files '$configurationRoot' --project-name $PROJECT_NAME --workspace-location '$workspaceDir'" + def ringCommand = "ring edt workspace import --configuration-files \"$configurationRoot\" --project-name $PROJECT_NAME --workspace-location \"$workspaceDir\"" def ringOpts = ['RING_OPTS=-Dfile.encoding=UTF-8 -Dosgi.nl=ru -Duser.language=ru'] steps.withEnv(ringOpts) { diff --git a/src/ru/pulsar/jenkins/library/steps/EdtToDesignerFormatTransformation.groovy b/src/ru/pulsar/jenkins/library/steps/EdtToDesignerFormatTransformation.groovy index a925b64..051c7c6 100644 --- a/src/ru/pulsar/jenkins/library/steps/EdtToDesignerFormatTransformation.groovy +++ b/src/ru/pulsar/jenkins/library/steps/EdtToDesignerFormatTransformation.groovy @@ -43,7 +43,7 @@ class EdtToDesignerFormatTransformation implements Serializable { Logger.println("Конвертация исходников из формата EDT в формат Конфигуратора") - def ringCommand = "ring edt workspace export --workspace-location '$workspaceDir' --project '$projectDir' --configuration-files '$configurationRoot'" + def ringCommand = "ring edt workspace export --workspace-location \"$workspaceDir\" --project \"$projectDir\" --configuration-files \"$configurationRoot\"" def ringOpts =[Constants.DEFAULT_RING_OPTS] steps.withEnv(ringOpts) { From 8ce19be80cf1de44d3e63caba01bc9a05f1260c5 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Thu, 25 Nov 2021 15:41:19 +0300 Subject: [PATCH 04/22] =?UTF-8?q?=D0=97=D0=B0=D0=BC=D0=B5=D0=BD=D0=B0=20?= =?UTF-8?q?=D0=BA=D0=B0=D0=B2=D1=8B=D1=87=D0=B5=D0=BA=20=D0=B4=D0=BB=D1=8F?= =?UTF-8?q?=20EDT=20Validate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ru/pulsar/jenkins/library/steps/EdtValidate.groovy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ru/pulsar/jenkins/library/steps/EdtValidate.groovy b/src/ru/pulsar/jenkins/library/steps/EdtValidate.groovy index 4f30a22..93f9858 100644 --- a/src/ru/pulsar/jenkins/library/steps/EdtValidate.groovy +++ b/src/ru/pulsar/jenkins/library/steps/EdtValidate.groovy @@ -46,7 +46,7 @@ class EdtValidate implements Serializable { Logger.println("Выполнение валидации EDT") - def ringCommand = "ring edt workspace validate --workspace-location '$workspaceLocation' --file '$resultFile' $projectList" + def ringCommand = "ring edt workspace validate --workspace-location \"$workspaceLocation\" --file \"$resultFile\" $projectList" def ringOpts = ['RING_OPTS=-Dfile.encoding=UTF-8 -Dosgi.nl=ru -Duser.language=ru'] steps.withEnv(ringOpts) { steps.catchError { From e10c4627b6520ab5d44a99af06438ee603edd7e4 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Thu, 25 Nov 2021 17:03:48 +0300 Subject: [PATCH 05/22] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=BE=D0=BF?= =?UTF-8?q?=D1=80=D0=B5=D0=B4=D0=B5=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20sun.jn?= =?UTF-8?q?u.encoding=20=D0=B4=D0=BB=D1=8F=20ring?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../library/steps/DesignerToEdtFormatTransformation.groovy | 3 ++- .../library/steps/EdtToDesignerFormatTransformation.groovy | 2 +- src/ru/pulsar/jenkins/library/steps/EdtValidate.groovy | 3 ++- src/ru/pulsar/jenkins/library/utils/Constants.groovy | 2 +- 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/ru/pulsar/jenkins/library/steps/DesignerToEdtFormatTransformation.groovy b/src/ru/pulsar/jenkins/library/steps/DesignerToEdtFormatTransformation.groovy index 5b79ecf..e62a336 100644 --- a/src/ru/pulsar/jenkins/library/steps/DesignerToEdtFormatTransformation.groovy +++ b/src/ru/pulsar/jenkins/library/steps/DesignerToEdtFormatTransformation.groovy @@ -4,6 +4,7 @@ package ru.pulsar.jenkins.library.steps import ru.pulsar.jenkins.library.IStepExecutor import ru.pulsar.jenkins.library.configuration.JobConfiguration import ru.pulsar.jenkins.library.ioc.ContextRegistry +import ru.pulsar.jenkins.library.utils.Constants import ru.pulsar.jenkins.library.utils.Logger class DesignerToEdtFormatTransformation implements Serializable { @@ -40,7 +41,7 @@ class DesignerToEdtFormatTransformation implements Serializable { def ringCommand = "ring edt workspace import --configuration-files \"$configurationRoot\" --project-name $PROJECT_NAME --workspace-location \"$workspaceDir\"" - def ringOpts = ['RING_OPTS=-Dfile.encoding=UTF-8 -Dosgi.nl=ru -Duser.language=ru'] + def ringOpts = [Constants.DEFAULT_RING_OPTS] steps.withEnv(ringOpts) { steps.cmd(ringCommand) } diff --git a/src/ru/pulsar/jenkins/library/steps/EdtToDesignerFormatTransformation.groovy b/src/ru/pulsar/jenkins/library/steps/EdtToDesignerFormatTransformation.groovy index 051c7c6..57ccf62 100644 --- a/src/ru/pulsar/jenkins/library/steps/EdtToDesignerFormatTransformation.groovy +++ b/src/ru/pulsar/jenkins/library/steps/EdtToDesignerFormatTransformation.groovy @@ -45,7 +45,7 @@ class EdtToDesignerFormatTransformation implements Serializable { def ringCommand = "ring edt workspace export --workspace-location \"$workspaceDir\" --project \"$projectDir\" --configuration-files \"$configurationRoot\"" - def ringOpts =[Constants.DEFAULT_RING_OPTS] + def ringOpts = [Constants.DEFAULT_RING_OPTS] steps.withEnv(ringOpts) { steps.cmd(ringCommand) } diff --git a/src/ru/pulsar/jenkins/library/steps/EdtValidate.groovy b/src/ru/pulsar/jenkins/library/steps/EdtValidate.groovy index 93f9858..1e29990 100644 --- a/src/ru/pulsar/jenkins/library/steps/EdtValidate.groovy +++ b/src/ru/pulsar/jenkins/library/steps/EdtValidate.groovy @@ -4,6 +4,7 @@ import ru.pulsar.jenkins.library.IStepExecutor import ru.pulsar.jenkins.library.configuration.JobConfiguration import ru.pulsar.jenkins.library.configuration.SourceFormat import ru.pulsar.jenkins.library.ioc.ContextRegistry +import ru.pulsar.jenkins.library.utils.Constants import ru.pulsar.jenkins.library.utils.Logger class EdtValidate implements Serializable { @@ -47,7 +48,7 @@ class EdtValidate implements Serializable { Logger.println("Выполнение валидации EDT") def ringCommand = "ring edt workspace validate --workspace-location \"$workspaceLocation\" --file \"$resultFile\" $projectList" - def ringOpts = ['RING_OPTS=-Dfile.encoding=UTF-8 -Dosgi.nl=ru -Duser.language=ru'] + def ringOpts = [Constants.DEFAULT_RING_OPTS] steps.withEnv(ringOpts) { steps.catchError { steps.cmd(ringCommand) diff --git a/src/ru/pulsar/jenkins/library/utils/Constants.groovy b/src/ru/pulsar/jenkins/library/utils/Constants.groovy index 82dc25f..1443474 100644 --- a/src/ru/pulsar/jenkins/library/utils/Constants.groovy +++ b/src/ru/pulsar/jenkins/library/utils/Constants.groovy @@ -1,6 +1,6 @@ package ru.pulsar.jenkins.library.utils final class Constants { - public static final String DEFAULT_RING_OPTS = "RING_OPTS=-Dfile.encoding=UTF-8 -Dosgi.nl=ru -Duser.language=ru" + public static final String DEFAULT_RING_OPTS = "RING_OPTS=-Dfile.encoding=UTF-8 -Dsun.jnu.encoding=UTF8 -Dosgi.nl=ru -Duser.language=ru" } From 7499c3ab4a03573bf762f7e0b13c8370da047752 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Fri, 26 Nov 2021 12:57:22 +0300 Subject: [PATCH 06/22] =?UTF-8?q?=D0=A0=D0=B0=D0=B7=D1=80=D0=B5=D1=88?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BB=D0=BE=D0=BA=D0=B0=D0=BB=D1=8C?= =?UTF-8?q?=D0=BD=D0=BE=D0=B3=D0=BE=20=D0=BF=D1=83=D1=82=D0=B8=20=D0=BD?= =?UTF-8?q?=D0=B0=20windows?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ru/pulsar/jenkins/library/utils/FileUtils.groovy | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/ru/pulsar/jenkins/library/utils/FileUtils.groovy b/src/ru/pulsar/jenkins/library/utils/FileUtils.groovy index c0fba7b..e7a0f6c 100644 --- a/src/ru/pulsar/jenkins/library/utils/FileUtils.groovy +++ b/src/ru/pulsar/jenkins/library/utils/FileUtils.groovy @@ -5,6 +5,8 @@ import jenkins.model.Jenkins import ru.pulsar.jenkins.library.IStepExecutor import ru.pulsar.jenkins.library.ioc.ContextRegistry +import java.nio.file.Path + class FileUtils { static FilePath getFilePath(String path) { @@ -30,6 +32,13 @@ class FileUtils { def env = steps.env(); - return filePath.getRemote().replaceAll("^$env.WORKSPACE/", "").toString() + Path workspacePath = new File(env.WORKSPACE).toPath() + Path rawFilePath = new File(filePath.getRemote()).toPath() + + return workspacePath.relativize(rawFilePath) + .toString() + .replaceAll('\\\\\\\\', '/') + .replaceAll('\\\\', '/') + .toString() } } From b94e104a55cf17845e843e163f2459a0b2f5e05e Mon Sep 17 00:00:00 2001 From: Dima Ovcharenko Date: Tue, 30 Nov 2021 15:24:44 +0300 Subject: [PATCH 07/22] =?UTF-8?q?=D1=80=D0=B5=D0=B0=D0=BB=D0=B8=D0=B7?= =?UTF-8?q?=D0=BE=D0=B2=D0=B0=D0=BB=20=D0=B3=D0=B5=D0=BD=D0=B5=D1=80=D0=B0?= =?UTF-8?q?=D1=86=D0=B8=D1=8E=20=D0=BE=D1=82=D1=87=D0=B5=D1=82=D0=BE=D0=B2?= =?UTF-8?q?=20=D1=82=D0=BE=D0=BB=D1=8C=D0=BA=D0=BE=20=D0=BF=D1=80=D0=B8=20?= =?UTF-8?q?=D0=BD=D0=B0=D0=BB=D0=B8=D1=87=D0=B8=D0=B8=20=D0=BD=D1=83=D0=B6?= =?UTF-8?q?=D0=BD=D1=8B=D1=85=20=D1=84=D0=BB=D0=B0=D0=B3=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../jenkins/library/steps/SmokeTest.groovy | 39 ++++++++++++++----- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy b/src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy index 116fedb..abe1dad 100644 --- a/src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy +++ b/src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy @@ -54,19 +54,40 @@ class SmokeTest implements Serializable { command += " --xddConfig $xddConfigPath" } - String junitReport = "build/out/jUnit/smoke/smoke.xml" - FilePath pathToJUnitReport = FileUtils.getFilePath("$env.WORKSPACE/$junitReport") - String junitReportDir = FileUtils.getLocalPath(pathToJUnitReport.getParent()) + if (options.publishToAllureReport || options.publishToJUnitReport) { + + command += " --reportsxunit \"%REPORTS%\"" - steps.createDir(junitReportDir) + String allureReportCommand = "" + if (options.publishToAllureReport) { - String allureReport = "build/out/allure/smoke/allure.xml" - FilePath pathToAllureReport = FileUtils.getFilePath("$env.WORKSPACE/$allureReport") - String allureReportDir = FileUtils.getLocalPath(pathToAllureReport.getParent()) + String allureReport = "build/out/allure/smoke/allure.xml" + FilePath pathToAllureReport = FileUtils.getFilePath("$env.WORKSPACE/$allureReport") + String allureReportDir = FileUtils.getLocalPath(pathToAllureReport.getParent()) - steps.createDir(allureReportDir) + steps.createDir(allureReportDir) - command += " --reportsxunit \"ГенераторОтчетаJUnitXML{$junitReport};ГенераторОтчетаAllureXMLВерсия2{$allureReport}\"" + allureReportCommand = "ГенераторОтчетаAllureXMLВерсия2{$allureReport}" + + } + + String junitReportCommand = "" + if (options.publishToJUnitReport) { + + String junitReport = "build/out/jUnit/smoke/smoke.xml" + FilePath pathToJUnitReport = FileUtils.getFilePath("$env.WORKSPACE/$junitReport") + String junitReportDir = FileUtils.getLocalPath(pathToJUnitReport.getParent()) + + steps.createDir(junitReportDir) + + junitReportCommand = "ГенераторОтчетаJUnitXML{$junitReport}" + } + + def commandsList = [allureReportCommand, junitReportCommand] + commandsList.removeAll([""]) + def reportsCommand = commandsList.join(";") + command.replace("%REPORTS%", reportsCommand) + } if (steps.isUnix()) { command = command.replace(';', '\\;') } From e72184c17e7af7549c522af3b0c73b00414a1bcb Mon Sep 17 00:00:00 2001 From: Dima Date: Tue, 30 Nov 2021 21:08:19 +0300 Subject: [PATCH 08/22] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D1=82=D0=B5=D1=81=D1=82=D1=8B,=20=D0=B8=D1=81=D0=BF?= =?UTF-8?q?=D1=80=D0=B0=D0=B2=D0=B8=D0=BB=20=D0=BE=D0=BF=D0=B5=D1=87=D0=B0?= =?UTF-8?q?=D1=82=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + README.md | 8 +++++--- .../library/configuration/ConfigurationReader.groovy | 1 + .../jenkins/library/configuration/JobConfiguration.groovy | 1 + .../jenkins/library/configuration/SmokeTestOptions.groovy | 4 ++-- src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy | 4 ++-- src/ru/pulsar/jenkins/library/utils/VersionParser.groovy | 2 +- .../library/configuration/ConfigurationReaderTest.java | 4 ++++ test/unit/resources/jobConfiguration.json | 5 +++++ 9 files changed, 22 insertions(+), 8 deletions(-) diff --git a/.gitignore b/.gitignore index 3bb6fce..0bd1052 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ build/ bin/ lib/ +out/ *.iml .classpath diff --git a/README.md b/README.md index 959b046..518a94c 100644 --- a/README.md +++ b/README.md @@ -112,7 +112,7 @@ pipeline1C() * `STORAGE_USER` - параметры авторизации в хранилище вида "username with password" (для `secrets` -> `storage`). * Все "шаги" по умолчанию выключены (`stages`). * Если в корне репозитория существует файл `packagedef`, то в шагах, работающих с информационной базой, будет выполнена попытка установки локальных зависимостей средствами `opm`. - * Если после установки локальных зависимостей в каталоге `oscript_modules/bin` сушествует файл `vrunner`, то для выполнения команд работы с информационной базой будет использоваться он, а не глобально установленный `vrunner` из `PATH`. + * Если после установки локальных зависимостей в каталоге `oscript_modules/bin` существует файл `vrunner`, то для выполнения команд работы с информационной базой будет использоваться он, а не глобально установленный `vrunner` из `PATH`. * Результаты в формате `allure` ожидаются в каталоге `build/out/allure` или его подкаталогах. * Инициализация: * Информационная база инициализируется только в том случае, если в сборочной линии включены шаги, работающие с базой (например, `bdd` или `syntaxCheck`). @@ -121,14 +121,16 @@ pipeline1C() * Первичный запуск информационной базы: * Если информационная база нужна для запуска в режиме "Предприятие" (например, для шагов `bdd` или `smoke`), то будет запущен шаг "Миграция ИБ". * После загрузки конфигурации в ИБ будет выполняться запуск ИБ с целью запуска обработчиков обновления из БСП (`initInfobase` -> `runMigration`). - * Если в настройках шага инициализации не заполнен массив дополнительных шагов миграции (`initInfobase` -> `additionalInitializationSteps`), но в каталоге `tools` присутствуют файлы с именами, удовлетворяющими шаблону `vrunner.init*.json`, то автоматически выполняется запуск `vrunner vanessa` с передачей найденных файлов в качестве значения настроек (параметр `--settings`) в порядке лексиграфической сортировки имен файлов. + * Если в настройках шага инициализации не заполнен массив дополнительных шагов миграции (`initInfobase` -> `additionalInitializationSteps`), но в каталоге `tools` присутствуют файлы с именами, удовлетворяющими шаблону `vrunner.init*.json`, то автоматически выполняется запуск `vrunner vanessa` с передачей найденных файлов в качестве значения настроек (параметр `--settings`) в порядке лексикографической сортировки имен файлов. * BDD: * Если в конфигурационном файле проекта не заполнена настройка `bdd` -> `vrunnerSteps`, то автоматически выполняется запуск `vrunner vanessa --settings tools/vrunner.json`. +* Дымовые тесты + * Если в конфигурационном файле проекта не заполнена настройка `smoke` -> `vrunnerSettings`, то автоматически выполняется запуск `vrunner vanessa --settings tools/vrunner.json`, а на выходе формируется только отчет в формате JUnit * Синтаксический контроль: * Если в репозитории существует файл `tools/vrunner.json`, то синтаксический контроль конфигурации с помощью конфигуратора будет выполняться с передачей файла в параметры запуска `vrunner syntax-check --settings tools/vrunner.json` (`syntaxCheck` -> `vrunnerSettings`). * Применяется группировка ошибок по метаданным (`syntaxCheck` -> `groupErrorsByMetadata`). * Выгрузка результатов в формат `jUnit` осуществляется в файл `./build/out/jUnit/syntax.xml` (`syntaxCheck` -> `pathToJUnitReport`). - * Если в репозитории существует файл `./tools/syntax-check-exception-file.txt`, то команде запука синтаксического контроля конфигурации данный файл будет передаваться как файл с исключениями сообщений об ошибках (параметр `--exception-file`) (`syntaxCheck` -> `exceptionFile`). + * Если в репозитории существует файл `./tools/syntax-check-exception-file.txt`, то команде запуска синтаксического контроля конфигурации данный файл будет передаваться как файл с исключениями сообщений об ошибках (параметр `--exception-file`) (`syntaxCheck` -> `exceptionFile`). * Конфигурационный файл по умолчанию уже содержит ряд "режимов проверки" для синтаксического контроля конфигурации (`syntaxCheck` -> `checkModes`). * Трансформация результатов валидации EDT: * По умолчанию из результатов анализа исключаются замечания, сработавшие на модулях с включенным запретом редактирования (желтый куб с замком) (параметры `resultsTransform` -> `removeSupport` и `resultsTransform` -> `supportLevel`). diff --git a/src/ru/pulsar/jenkins/library/configuration/ConfigurationReader.groovy b/src/ru/pulsar/jenkins/library/configuration/ConfigurationReader.groovy index 09776bd..a737a64 100644 --- a/src/ru/pulsar/jenkins/library/configuration/ConfigurationReader.groovy +++ b/src/ru/pulsar/jenkins/library/configuration/ConfigurationReader.groovy @@ -59,6 +59,7 @@ class ConfigurationReader implements Serializable { "initInfobaseOptions", "bddOptions", "sonarQubeOptions", + "smokeTestOptions", "syntaxCheckOptions", "resultsTransformOptions" ).toSet() diff --git a/src/ru/pulsar/jenkins/library/configuration/JobConfiguration.groovy b/src/ru/pulsar/jenkins/library/configuration/JobConfiguration.groovy index 34c06c2..dbbdcd1 100644 --- a/src/ru/pulsar/jenkins/library/configuration/JobConfiguration.groovy +++ b/src/ru/pulsar/jenkins/library/configuration/JobConfiguration.groovy @@ -69,6 +69,7 @@ class JobConfiguration implements Serializable { ", initInfobaseOptions=" + initInfobaseOptions + ", bddOptions=" + bddOptions + ", sonarQubeOptions=" + sonarQubeOptions + + ", smokeTestOptions=" + smokeTestOptions + ", syntaxCheckOptions=" + syntaxCheckOptions + ", smokeTestOptions=" + smokeTestOptions + ", resultsTransformOptions=" + resultsTransformOptions + diff --git a/src/ru/pulsar/jenkins/library/configuration/SmokeTestOptions.groovy b/src/ru/pulsar/jenkins/library/configuration/SmokeTestOptions.groovy index f58efb0..081c9be 100644 --- a/src/ru/pulsar/jenkins/library/configuration/SmokeTestOptions.groovy +++ b/src/ru/pulsar/jenkins/library/configuration/SmokeTestOptions.groovy @@ -25,10 +25,10 @@ class SmokeTestOptions implements Serializable { @Override @NonCPS String toString() { - return "SyntaxCheckOptions{" + + return "SmokeTestOptions{" + "vrunnerSettings=" + vrunnerSettings + ", publishToAllureReport=" + publishToAllureReport + ", publishToJUnitReport=" + publishToJUnitReport + - '}'; + '}' } } diff --git a/src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy b/src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy index abe1dad..507cc7d 100644 --- a/src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy +++ b/src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy @@ -12,7 +12,7 @@ class SmokeTest implements Serializable { public static final String SMOKE_ALLURE_STASH = 'smoke-allure' - private final JobConfiguration config; + private final JobConfiguration config SmokeTest(JobConfiguration config) { this.config = config @@ -41,7 +41,7 @@ class SmokeTest implements Serializable { String vrunnerSettings = options.vrunnerSettings if (steps.fileExists(vrunnerSettings)) { - command += " --settings $vrunnerSettings"; + command += " --settings $vrunnerSettings" } String xddTestRunnerPath = "./oscript_modules/add/xddTestRunner.epf" diff --git a/src/ru/pulsar/jenkins/library/utils/VersionParser.groovy b/src/ru/pulsar/jenkins/library/utils/VersionParser.groovy index 74054aa..9afc196 100644 --- a/src/ru/pulsar/jenkins/library/utils/VersionParser.groovy +++ b/src/ru/pulsar/jenkins/library/utils/VersionParser.groovy @@ -28,7 +28,7 @@ class VersionParser implements Serializable { return "" } - def configurationText = steps.readFile(filePath); + def configurationText = steps.readFile(filePath, 'UTF-8') return version(configurationText, regexp) } diff --git a/test/unit/groovy/ru/pulsar/jenkins/library/configuration/ConfigurationReaderTest.java b/test/unit/groovy/ru/pulsar/jenkins/library/configuration/ConfigurationReaderTest.java index a1fe3b2..8d5292b 100644 --- a/test/unit/groovy/ru/pulsar/jenkins/library/configuration/ConfigurationReaderTest.java +++ b/test/unit/groovy/ru/pulsar/jenkins/library/configuration/ConfigurationReaderTest.java @@ -44,6 +44,10 @@ class ConfigurationReaderTest { assertThat(jobConfiguration.getResultsTransformOptions().isRemoveSupport()).isFalse(); assertThat(jobConfiguration.getResultsTransformOptions().getSupportLevel()).isZero(); + assertThat(jobConfiguration.getSmokeTestOptions().getVrunnerSettings()).contains("./tools/vrunner-smoke.json"); + assertThat(jobConfiguration.getSmokeTestOptions().isPublishToAllureReport()).isFalse(); + assertThat(jobConfiguration.getSmokeTestOptions().isPublishToJUnitReport()).isTrue(); + assertThat(jobConfiguration.getInitInfobaseOptions().getRunMigration()).isFalse(); assertThat(jobConfiguration.getInitInfobaseOptions().getAdditionalInitializationSteps()).contains("vanessa --settings ./tools/vrunner.first.json"); diff --git a/test/unit/resources/jobConfiguration.json b/test/unit/resources/jobConfiguration.json index 947e8ba..f9b28a0 100644 --- a/test/unit/resources/jobConfiguration.json +++ b/test/unit/resources/jobConfiguration.json @@ -18,5 +18,10 @@ "resultsTransform": { "removeSupport": false }, + "smoke": { + "vrunnerSettings": "./tools/vrunner-smoke.json", + "publishToAllureReport": false, + "publishToJUnitReport": true + }, "logosConfig": "logger.rootLogger=DEBUG" } \ No newline at end of file From c352bb2228073ec2c8f1c7214b96e199fd5c2077 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Thu, 2 Dec 2021 11:42:46 +0300 Subject: [PATCH 09/22] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B0=20=D0=BF=D0=B5=D1=80=D0=B5=D0=B4=D0=B0?= =?UTF-8?q?=D1=87=D0=B0=20=D1=84=D0=B0=D0=B9=D0=BB=D0=B0=20=D1=81=20=D0=B8?= =?UTF-8?q?=D1=81=D0=BA=D0=BB=D1=8E=D1=87=D0=B5=D0=BD=D0=B8=D1=8F=D0=BC?= =?UTF-8?q?=D0=B8.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --modes должен быть последним параметром вызова --- vars/syntaxCheck.groovy | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/vars/syntaxCheck.groovy b/vars/syntaxCheck.groovy index 636b837..b879fdb 100644 --- a/vars/syntaxCheck.groovy +++ b/vars/syntaxCheck.groovy @@ -46,15 +46,15 @@ def call(JobConfiguration config) { command += " --settings $vrunnerSettings"; } + if (!options.exceptionFile.empty && fileExists(options.exceptionFile)) { + command += " --exception-file $options.exceptionFile" + } + if (options.checkModes.length > 0) { def checkModes = options.checkModes.join(" ") command += " --mode $checkModes" } - if (!options.exceptionFile.empty && fileExists(options.exceptionFile)) { - command += " --exception-file $options.exceptionFile" - } - // Запуск синтакс-проверки VRunner.exec(command, true) From 0e48633cb0f18d71c7191898c62748f9e54cefca Mon Sep 17 00:00:00 2001 From: Nikita Fedkin Date: Fri, 3 Dec 2021 17:02:33 +0300 Subject: [PATCH 10/22] =?UTF-8?q?=D0=A3=D0=BF=D1=80=D0=BE=D1=89=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D1=84=D0=BE=D1=80=D0=BC=D0=B8=D1=80=D0=BE?= =?UTF-8?q?=D0=B2=D0=B0=D0=BD=D0=B8=D1=8F=20=D1=81=D1=82=D1=80=D0=BE=D0=BA?= =?UTF-8?q?=D0=B8=20=D0=BD=D0=B0=D1=81=D1=82=D1=80=D0=BE=D0=B5=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../jenkins/library/steps/SmokeTest.groovy | 61 +++++++++---------- 1 file changed, 30 insertions(+), 31 deletions(-) diff --git a/src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy b/src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy index 507cc7d..ead9aa0 100644 --- a/src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy +++ b/src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy @@ -54,40 +54,37 @@ class SmokeTest implements Serializable { command += " --xddConfig $xddConfigPath" } - if (options.publishToAllureReport || options.publishToJUnitReport) { - - command += " --reportsxunit \"%REPORTS%\"" + String junitReport = "build/out/jUnit/smoke/smoke.xml" + FilePath pathToJUnitReport = FileUtils.getFilePath("$env.WORKSPACE/$junitReport") + String junitReportDir = FileUtils.getLocalPath(pathToJUnitReport.getParent()) - String allureReportCommand = "" - if (options.publishToAllureReport) { + String allureReport = "build/out/allure/smoke/allure.xml" + FilePath pathToAllureReport = FileUtils.getFilePath("$env.WORKSPACE/$allureReport") + String allureReportDir = FileUtils.getLocalPath(pathToAllureReport.getParent()) - String allureReport = "build/out/allure/smoke/allure.xml" - FilePath pathToAllureReport = FileUtils.getFilePath("$env.WORKSPACE/$allureReport") - String allureReportDir = FileUtils.getLocalPath(pathToAllureReport.getParent()) + StringJoiner reportsConfigConstructor = new StringJoiner(";") - steps.createDir(allureReportDir) + if (options.publishToJUnitReport) { + steps.createDir(junitReportDir) - allureReportCommand = "ГенераторОтчетаAllureXMLВерсия2{$allureReport}" + String junitReportCommand = "ГенераторОтчетаJUnitXML{$junitReport}" - } - - String junitReportCommand = "" - if (options.publishToJUnitReport) { - - String junitReport = "build/out/jUnit/smoke/smoke.xml" - FilePath pathToJUnitReport = FileUtils.getFilePath("$env.WORKSPACE/$junitReport") - String junitReportDir = FileUtils.getLocalPath(pathToJUnitReport.getParent()) - - steps.createDir(junitReportDir) - - junitReportCommand = "ГенераторОтчетаJUnitXML{$junitReport}" - } - - def commandsList = [allureReportCommand, junitReportCommand] - commandsList.removeAll([""]) - def reportsCommand = commandsList.join(";") - command.replace("%REPORTS%", reportsCommand) + reportsConfigConstructor.add(junitReportCommand) } + + if (options.publishToAllureReport) { + steps.createDir(allureReportDir) + + String allureReportCommand = "ГенераторОтчетаAllureXMLВерсия2{$allureReport}" + + reportsConfigConstructor.add(allureReportCommand) + } + + if (reportsConfigConstructor.length() > 0) { + String reportsConfig = reportsConfigConstructor.toString() + command += " --reportsxunit \"$reportsConfig\"" + } + if (steps.isUnix()) { command = command.replace(';', '\\;') } @@ -107,13 +104,15 @@ class SmokeTest implements Serializable { VRunner.exec(command) } - steps.stash(SMOKE_ALLURE_STASH, "$allureReportDir/**", true) + if (options.publishToAllureReport) { + steps.stash(SMOKE_ALLURE_STASH, "$allureReportDir/**", true) + steps.archiveArtifacts("$allureReportDir/**") + } if (options.publishToJUnitReport) { steps.junit("$junitReportDir/*.xml", true) + steps.archiveArtifacts("$junitReportDir/**") } - steps.archiveArtifacts("$junitReportDir/**") - steps.archiveArtifacts("$allureReportDir/**") } } From e45dba097a78f0d601d801b032e1d37146d7c7b4 Mon Sep 17 00:00:00 2001 From: Nikita Fedkin Date: Fri, 3 Dec 2021 17:06:54 +0300 Subject: [PATCH 11/22] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20readFile=20=D0=B2=20=D1=82?= =?UTF-8?q?=D0=B5=D1=81=D1=82=D0=B0=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ru/pulsar/jenkins/library/utils/VersionParser.groovy | 2 +- .../groovy/ru/pulsar/jenkins/library/utils/TestUtils.java | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/ru/pulsar/jenkins/library/utils/VersionParser.groovy b/src/ru/pulsar/jenkins/library/utils/VersionParser.groovy index 9afc196..93c49da 100644 --- a/src/ru/pulsar/jenkins/library/utils/VersionParser.groovy +++ b/src/ru/pulsar/jenkins/library/utils/VersionParser.groovy @@ -28,7 +28,7 @@ class VersionParser implements Serializable { return "" } - def configurationText = steps.readFile(filePath, 'UTF-8') + def configurationText = steps.readFile(filePath) return version(configurationText, regexp) } diff --git a/test/unit/groovy/ru/pulsar/jenkins/library/utils/TestUtils.java b/test/unit/groovy/ru/pulsar/jenkins/library/utils/TestUtils.java index 6d2e88b..92f5a4b 100644 --- a/test/unit/groovy/ru/pulsar/jenkins/library/utils/TestUtils.java +++ b/test/unit/groovy/ru/pulsar/jenkins/library/utils/TestUtils.java @@ -34,6 +34,11 @@ public class TestUtils { return FileUtils.readFileToString(new File(file), encoding); }); + when(steps.readFile(anyString())).thenAnswer(invocation -> { + String file = invocation.getArgument(0); + return FileUtils.readFileToString(new File(file), StandardCharsets.UTF_8); + }); + when(steps.fileExists(anyString())).thenAnswer(invocation -> { String file = invocation.getArgument(0); return new File(file).exists(); From f783a2156131fffa7c7d4e0357c776a5b5a6b691 Mon Sep 17 00:00:00 2001 From: Nikita Fedkin Date: Fri, 3 Dec 2021 17:12:28 +0300 Subject: [PATCH 12/22] Update src/ru/pulsar/jenkins/library/configuration/JobConfiguration.groovy --- .../pulsar/jenkins/library/configuration/JobConfiguration.groovy | 1 - 1 file changed, 1 deletion(-) diff --git a/src/ru/pulsar/jenkins/library/configuration/JobConfiguration.groovy b/src/ru/pulsar/jenkins/library/configuration/JobConfiguration.groovy index dbbdcd1..34c06c2 100644 --- a/src/ru/pulsar/jenkins/library/configuration/JobConfiguration.groovy +++ b/src/ru/pulsar/jenkins/library/configuration/JobConfiguration.groovy @@ -69,7 +69,6 @@ class JobConfiguration implements Serializable { ", initInfobaseOptions=" + initInfobaseOptions + ", bddOptions=" + bddOptions + ", sonarQubeOptions=" + sonarQubeOptions + - ", smokeTestOptions=" + smokeTestOptions + ", syntaxCheckOptions=" + syntaxCheckOptions + ", smokeTestOptions=" + smokeTestOptions + ", resultsTransformOptions=" + resultsTransformOptions + From e711293e7973dd6faa7ba883366648db82cb7309 Mon Sep 17 00:00:00 2001 From: Nikita Fedkin Date: Fri, 3 Dec 2021 17:40:34 +0300 Subject: [PATCH 13/22] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=20smoke=20->=20xddConfigPath?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 8 ++++++-- resources/globalConfiguration.json | 1 + resources/schema.json | 4 ++++ .../jenkins/library/configuration/SmokeTestOptions.groovy | 8 +++++++- src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy | 5 ++--- 5 files changed, 20 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 518a94c..91b789b 100644 --- a/README.md +++ b/README.md @@ -124,8 +124,12 @@ pipeline1C() * Если в настройках шага инициализации не заполнен массив дополнительных шагов миграции (`initInfobase` -> `additionalInitializationSteps`), но в каталоге `tools` присутствуют файлы с именами, удовлетворяющими шаблону `vrunner.init*.json`, то автоматически выполняется запуск `vrunner vanessa` с передачей найденных файлов в качестве значения настроек (параметр `--settings`) в порядке лексикографической сортировки имен файлов. * BDD: * Если в конфигурационном файле проекта не заполнена настройка `bdd` -> `vrunnerSteps`, то автоматически выполняется запуск `vrunner vanessa --settings tools/vrunner.json`. -* Дымовые тесты - * Если в конфигурационном файле проекта не заполнена настройка `smoke` -> `vrunnerSettings`, то автоматически выполняется запуск `vrunner vanessa --settings tools/vrunner.json`, а на выходе формируется только отчет в формате JUnit +* Дымовые тесты: + * Если в репозитории существует файл `tools/vrunner.json`, то запуск дымовых тестов будет выполняться с передачей файла в параметры запуска `vrunner xunit --settings tools/vrunner.json` (`smoke` -> `vrunnerSettings`). + * Если установка локальных зависимостей `opm` установит пакет `add`, то будет использоваться обработка `xddTestRunner.epf` из локальных зависимостей. + * Если в репозитории существует файл `tools/xUnitParams.json`, то этот путь к файлу будет передан в параметр запуска `vrunner xunit --xddConfig ./tools/xUnitParams.json` (`smoke -> xUnitParams`). + * Если используемый конфигурационный файл (`vrunner.json`) не содержит настройку `testsPath`, то запускается полный комплект дымовых тестов, расположенных в `$addRoot/tests/smoke`. + * По умолчанию включено формирование отчета в формате `jUnit` (`smoke` -> `publishToJUnitReport`) и выключено формирование отчета в формате Allure (`smoke` -> `publishToAllureReport`). * Синтаксический контроль: * Если в репозитории существует файл `tools/vrunner.json`, то синтаксический контроль конфигурации с помощью конфигуратора будет выполняться с передачей файла в параметры запуска `vrunner syntax-check --settings tools/vrunner.json` (`syntaxCheck` -> `vrunnerSettings`). * Применяется группировка ошибок по метаданным (`syntaxCheck` -> `groupErrorsByMetadata`). diff --git a/resources/globalConfiguration.json b/resources/globalConfiguration.json index d5a8f69..ebdbfe9 100644 --- a/resources/globalConfiguration.json +++ b/resources/globalConfiguration.json @@ -52,6 +52,7 @@ }, "smoke": { "vrunnerSettings": "./tools/vrunner.json", + "xddConfigPath": "./tools/xUnitParams.json", "publishToAllureReport": false, "publishToJUnitReport": true }, diff --git a/resources/schema.json b/resources/schema.json index d45308b..f009b5f 100644 --- a/resources/schema.json +++ b/resources/schema.json @@ -160,6 +160,10 @@ "type" : "string", "description" : "Путь к конфигурационному файлу vanessa-runner.\n По умолчанию содержит значение \"./tools/vrunner.json\".\n " }, + "xddConfigPath" : { + "type" : "string", + "description" : "Путь к конфигурационному файлу для xddTestRunner.\n По умолчанию содержит значение \"./tools/xUnitParams.json\".\n " + }, "publishToAllureReport" : { "type" : "boolean", "description" : "Выполнять публикацию результатов в отчет Allure.\n По умолчанию выключено.\n " diff --git a/src/ru/pulsar/jenkins/library/configuration/SmokeTestOptions.groovy b/src/ru/pulsar/jenkins/library/configuration/SmokeTestOptions.groovy index 081c9be..fd07c2a 100644 --- a/src/ru/pulsar/jenkins/library/configuration/SmokeTestOptions.groovy +++ b/src/ru/pulsar/jenkins/library/configuration/SmokeTestOptions.groovy @@ -12,6 +12,11 @@ class SmokeTestOptions implements Serializable { """) String vrunnerSettings + @JsonPropertyDescription("""Путь к конфигурационному файлу для xddTestRunner. + По умолчанию содержит значение "./tools/xUnitParams.json". + """) + String xddConfigPath; + @JsonPropertyDescription("""Выполнять публикацию результатов в отчет Allure. По умолчанию выключено. """) @@ -26,7 +31,8 @@ class SmokeTestOptions implements Serializable { @NonCPS String toString() { return "SmokeTestOptions{" + - "vrunnerSettings=" + vrunnerSettings + + "vrunnerSettings='" + vrunnerSettings + '\'' + + ", xddConfigPath='" + xddConfigPath + '\'' + ", publishToAllureReport=" + publishToAllureReport + ", publishToJUnitReport=" + publishToJUnitReport + '}' diff --git a/src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy b/src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy index ead9aa0..e50257a 100644 --- a/src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy +++ b/src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy @@ -49,9 +49,8 @@ class SmokeTest implements Serializable { command += " --pathxunit $xddTestRunnerPath" } - String xddConfigPath = "./tools/xUnitParams.json" - if (steps.fileExists(xddConfigPath)) { - command += " --xddConfig $xddConfigPath" + if (steps.fileExists(options.xddConfigPath)) { + command += " --xddConfig $options.xddConfigPath" } String junitReport = "build/out/jUnit/smoke/smoke.xml" From 05cb6bd05da5359620bdb13133325d19751a6207 Mon Sep 17 00:00:00 2001 From: Nikita Fedkin Date: Fri, 3 Dec 2021 19:34:46 +0300 Subject: [PATCH 14/22] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BF=D0=B5=D1=80=D0=B5=D0=B4?= =?UTF-8?q?=D0=B0=D1=87=D0=B8=20$runnerRoot=20=D0=BD=D0=B0=20windows?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pulsar/jenkins/library/steps/InitInfobase.groovy | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/ru/pulsar/jenkins/library/steps/InitInfobase.groovy b/src/ru/pulsar/jenkins/library/steps/InitInfobase.groovy index f85c9ea..1a5d49e 100644 --- a/src/ru/pulsar/jenkins/library/steps/InitInfobase.groovy +++ b/src/ru/pulsar/jenkins/library/steps/InitInfobase.groovy @@ -35,9 +35,17 @@ class InitInfobase implements Serializable { if (config.initInfobaseOptions.runMigration) { Logger.println("Запуск миграции ИБ") + String command = vrunnerPath + ' run --command "ЗапуститьОбновлениеИнформационнойБазы;ЗавершитьРаботуСистемы;" --execute ' + String executeParameter = '$runnerRoot/epf/ЗакрытьПредприятие.epf' + if (steps.isUnix()) { + executeParameter = '\\' + executeParameter + } + command += executeParameter; + command += ' --ibconnection "/F./build/ib"' + // Запуск миграции steps.catchError { - VRunner.exec(vrunnerPath + ' run --command "ЗапуститьОбновлениеИнформационнойБазы;ЗавершитьРаботуСистемы;" --execute \\$runnerRoot/epf/ЗакрытьПредприятие.epf --ibconnection "/F./build/ib"') + VRunner.exec(command) } } else { Logger.println("Шаг миграции ИБ выключен") From ba5bc457b60ea3387c53d107c999f75636ec1f3d Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Sat, 4 Dec 2021 13:00:10 +0300 Subject: [PATCH 15/22] =?UTF-8?q?=D0=97=D0=B0=D0=BC=D0=B5=D0=BD=D0=B0=20?= =?UTF-8?q?=D0=BD=D0=B5=D1=81=D0=B5=D1=80=D0=B8=D0=B0=D0=BB=D0=B8=D0=B7?= =?UTF-8?q?=D1=83=D0=B5=D0=BC=D0=BE=D0=B3=D0=BE=20StringJoiner=20=D0=BD?= =?UTF-8?q?=D0=B0=20=D1=81=D0=B5=D1=80=D0=B8=D0=B0=D0=BB=D0=B8=D0=B7=D1=83?= =?UTF-8?q?=D0=B5=D0=BC=D1=8B=D0=B9=20StringBuilder?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy b/src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy index e50257a..3fbf107 100644 --- a/src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy +++ b/src/ru/pulsar/jenkins/library/steps/SmokeTest.groovy @@ -61,14 +61,14 @@ class SmokeTest implements Serializable { FilePath pathToAllureReport = FileUtils.getFilePath("$env.WORKSPACE/$allureReport") String allureReportDir = FileUtils.getLocalPath(pathToAllureReport.getParent()) - StringJoiner reportsConfigConstructor = new StringJoiner(";") + StringBuilder reportsConfigConstructor = new StringBuilder() if (options.publishToJUnitReport) { steps.createDir(junitReportDir) String junitReportCommand = "ГенераторОтчетаJUnitXML{$junitReport}" - reportsConfigConstructor.add(junitReportCommand) + reportsConfigConstructor.append(junitReportCommand) } if (options.publishToAllureReport) { @@ -76,7 +76,10 @@ class SmokeTest implements Serializable { String allureReportCommand = "ГенераторОтчетаAllureXMLВерсия2{$allureReport}" - reportsConfigConstructor.add(allureReportCommand) + if (reportsConfigConstructor.length() > 0) { + reportsConfigConstructor.append(';') + } + reportsConfigConstructor.append(allureReportCommand) } if (reportsConfigConstructor.length() > 0) { From 826d6bc62bc9398593a703d1f8edcf56690a4a48 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Sat, 4 Dec 2021 13:00:24 +0300 Subject: [PATCH 16/22] =?UTF-8?q?=D0=9F=D1=80=D0=BE=D0=B2=D0=B5=D1=80?= =?UTF-8?q?=D0=BA=D0=B0=20=D0=BD=D0=B0=20=D1=81=D1=83=D1=89=D0=B5=D1=81?= =?UTF-8?q?=D1=82=D0=B2=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8=D0=B5=20=D1=84=D0=B0?= =?UTF-8?q?=D0=B9=D0=BB=D0=B0=20vrunner=20=D0=BF=D0=B5=D1=80=D0=B5=D0=B4?= =?UTF-8?q?=20=D1=87=D1=82=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B5=D0=B3=D0=BE=20?= =?UTF-8?q?=D1=81=D0=B2=D0=BE=D0=B9=D1=81=D1=82=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ru/pulsar/jenkins/library/utils/VRunner.groovy | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/ru/pulsar/jenkins/library/utils/VRunner.groovy b/src/ru/pulsar/jenkins/library/utils/VRunner.groovy index f59b7fd..fdf37e2 100644 --- a/src/ru/pulsar/jenkins/library/utils/VRunner.groovy +++ b/src/ru/pulsar/jenkins/library/utils/VRunner.groovy @@ -31,6 +31,10 @@ class VRunner { static boolean configContainsSetting(String configPath, String settingName) { IStepExecutor steps = ContextRegistry.getContext().getStepExecutor() + if (!steps.fileExists(configPath)) { + return false + } + String fileContent = steps.readFile(configPath) return fileContent.contains("\"$settingName\"") } From 756b95350074e935263872ee4a264c46fc395c23 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Thu, 25 Nov 2021 11:33:47 +0300 Subject: [PATCH 17/22] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=BE=D0=BF?= =?UTF-8?q?=D1=80=D0=B5=D0=B4=D0=B5=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20timeou?= =?UTF-8?q?t=20=D0=B4=D0=BB=D1=8F=20=D0=BA=D0=B0=D0=B6=D0=B4=D0=BE=D0=B9?= =?UTF-8?q?=20stages?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- resources/globalConfiguration.json | 1 + resources/schema.json | 4 + .../configuration/JobConfiguration.groovy | 5 ++ .../ConfigurationReaderTest.java | 2 + vars/pipeline1C.groovy | 75 ++++++++++++------- 5 files changed, 61 insertions(+), 26 deletions(-) diff --git a/resources/globalConfiguration.json b/resources/globalConfiguration.json index ebdbfe9..2c411f4 100644 --- a/resources/globalConfiguration.json +++ b/resources/globalConfiguration.json @@ -16,6 +16,7 @@ "edtValidate": false, "smoke": false }, + "stageTimeout": 2, "initInfobase": { "initMethod": "fromStorage", "runMigration": true, diff --git a/resources/schema.json b/resources/schema.json index f009b5f..e9cc53e 100644 --- a/resources/schema.json +++ b/resources/schema.json @@ -192,6 +192,10 @@ "logosConfig" : { "type" : "string", "description" : "Конфигурация библиотеки logos. Применяется перед запуском каждой стадии сборки" + }, + "stageTimeout" : { + "type" : "integer", + "description" : "Таймаут для выполнения шагов (в часах)" } } } \ No newline at end of file diff --git a/src/ru/pulsar/jenkins/library/configuration/JobConfiguration.groovy b/src/ru/pulsar/jenkins/library/configuration/JobConfiguration.groovy index 34c06c2..46ed541 100644 --- a/src/ru/pulsar/jenkins/library/configuration/JobConfiguration.groovy +++ b/src/ru/pulsar/jenkins/library/configuration/JobConfiguration.groovy @@ -56,6 +56,10 @@ class JobConfiguration implements Serializable { @JsonPropertyDescription("Конфигурация библиотеки logos. Применяется перед запуском каждой стадии сборки") String logosConfig; + @JsonProperty("stageTimeout") + @JsonPropertyDescription("Таймаут для выполнения шагов (в часах)") + Integer stageTimeout; + @Override @NonCPS String toString() { @@ -73,6 +77,7 @@ class JobConfiguration implements Serializable { ", smokeTestOptions=" + smokeTestOptions + ", resultsTransformOptions=" + resultsTransformOptions + ", logosConfig=" + logosConfig + + ", stageTimeout=" + stageTimeout + '}'; } diff --git a/test/unit/groovy/ru/pulsar/jenkins/library/configuration/ConfigurationReaderTest.java b/test/unit/groovy/ru/pulsar/jenkins/library/configuration/ConfigurationReaderTest.java index 8d5292b..4736075 100644 --- a/test/unit/groovy/ru/pulsar/jenkins/library/configuration/ConfigurationReaderTest.java +++ b/test/unit/groovy/ru/pulsar/jenkins/library/configuration/ConfigurationReaderTest.java @@ -54,6 +54,8 @@ class ConfigurationReaderTest { assertThat(jobConfiguration.getBddOptions().getVrunnerSteps()).contains("vanessa --settings ./tools/vrunner.json"); assertThat(jobConfiguration.getLogosConfig()).isEqualTo("logger.rootLogger=DEBUG"); + + assertThat(jobConfiguration.getStageTimeout()).isEqualTo(2); } } \ No newline at end of file diff --git a/vars/pipeline1C.groovy b/vars/pipeline1C.groovy index 2314045..34afc52 100644 --- a/vars/pipeline1C.groovy +++ b/vars/pipeline1C.groovy @@ -19,7 +19,6 @@ void call() { options { buildDiscarder(logRotator(numToKeepStr: '30')) - timeout(time: 2, unit: TimeUnit.HOURS) timestamps() } @@ -29,6 +28,9 @@ void call() { agent { label 'agent' } + options { + timeout(time: 1, unit: TimeUnit.HOURS) + } steps { script { @@ -59,22 +61,25 @@ void call() { expression { config.stageFlags.needInfobase() && config.infobaseFromFiles() && config.sourceFormat == SourceFormat.EDT } } steps { - edtToDesignerFormatTransformation config + timeout(time: config.stageTimeout, unit: TimeUnit.HOURS) { + edtToDesignerFormatTransformation config + } } } stage('Создание ИБ') { steps { - createDir('build/out') + timeout(time: config.stageTimeout, unit: TimeUnit.HOURS) { + createDir('build/out') - script { - if (config.infobaseFromFiles()){ - // Создание базы загрузкой из файлов - initFromFiles config - } - else{ - // Создание базы загрузкой конфигурации из хранилища - initFromStorage config + script { + if (config.infobaseFromFiles()) { + // Создание базы загрузкой из файлов + initFromFiles config + } else { + // Создание базы загрузкой конфигурации из хранилища + initFromStorage config + } } } } @@ -86,16 +91,20 @@ void call() { expression { config.stageFlags.initSteps } } steps { - // Инициализация и первичная миграция - initInfobase config + timeout(time: config.stageTimeout, unit: TimeUnit.HOURS) { + // Инициализация и первичная миграция + initInfobase config + } } } stage('Архивация ИБ') { steps { - printLocation() + timeout(time: config.stageTimeout, unit: TimeUnit.HOURS) { + printLocation() - zipInfobase() + zipInfobase() + } } } @@ -109,10 +118,12 @@ void call() { } when { beforeAgent true - expression { config.sourceFormat == SourceFormat.DESIGNER && config.stageFlags.edtValidate} + expression { config.sourceFormat == SourceFormat.DESIGNER && config.stageFlags.edtValidate } } steps { - designerToEdtFormatTransformation config + timeout(time: config.stageTimeout, unit: TimeUnit.HOURS) { + designerToEdtFormatTransformation config + } } } } @@ -131,7 +142,9 @@ void call() { label 'edt' } steps { - edtValidate config + timeout(time: config.stageTimeout, unit: TimeUnit.HOURS) { + edtValidate config + } } } @@ -140,7 +153,9 @@ void call() { label 'oscript' } steps { - transform config + timeout(time: config.stageTimeout, unit: TimeUnit.HOURS) { + transform config + } } } } @@ -155,9 +170,11 @@ void call() { expression { config.stageFlags.bdd } } steps { - unzipInfobase() - - bdd config + timeout(time: config.stageTimeout, unit: TimeUnit.HOURS) { + unzipInfobase() + + bdd config + } } } @@ -170,7 +187,9 @@ void call() { expression { config.stageFlags.syntaxCheck } } steps { - syntaxCheck config + timeout(time: config.stageTimeout, unit: TimeUnit.HOURS) { + syntaxCheck config + } } } @@ -183,9 +202,11 @@ void call() { expression { config.stageFlags.smoke } } steps { - unzipInfobase() + timeout(time: config.stageTimeout, unit: TimeUnit.HOURS) { + unzipInfobase() - smoke config + smoke config + } } } } @@ -200,7 +221,9 @@ void call() { expression { config.stageFlags.sonarqube } } steps { - sonarScanner config + timeout(time: config.stageTimeout, unit: TimeUnit.HOURS) { + sonarScanner config + } } } } From 94580316524f1185df49f6a6ec55023fd4e6e1dd Mon Sep 17 00:00:00 2001 From: Nikita Fedkin Date: Tue, 7 Dec 2021 18:07:36 +0300 Subject: [PATCH 18/22] =?UTF-8?q?=D0=A0=D0=B0=D0=B7=D0=B4=D0=B5=D0=BB?= =?UTF-8?q?=D1=8C=D0=BD=D1=8B=D0=B5=20=D1=82=D0=B0=D0=B9=D0=BC=D0=B0=D1=83?= =?UTF-8?q?=D1=82=D1=8B=20=D0=B4=D0=BB=D1=8F=20=D0=BA=D0=B0=D0=B6=D0=B4?= =?UTF-8?q?=D0=BE=D0=B3=D0=BE=20stage?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- resources/globalConfiguration.json | 14 ++++- resources/schema.json | 55 ++++++++++++++-- .../configuration/ConfigurationReader.groovy | 1 + .../configuration/JobConfiguration.groovy | 16 ++--- .../configuration/TimeoutOptions.groovy | 63 +++++++++++++++++++ .../ConfigurationReaderTest.java | 3 +- test/unit/resources/jobConfiguration.json | 3 + vars/pipeline1C.groovy | 22 +++---- 8 files changed, 152 insertions(+), 25 deletions(-) create mode 100644 src/ru/pulsar/jenkins/library/configuration/TimeoutOptions.groovy diff --git a/resources/globalConfiguration.json b/resources/globalConfiguration.json index 2c411f4..fb4979a 100644 --- a/resources/globalConfiguration.json +++ b/resources/globalConfiguration.json @@ -16,7 +16,19 @@ "edtValidate": false, "smoke": false }, - "stageTimeout": 2, + "timeout": { + "smoke": 240, + "bdd": 120, + "createInfoBase": 60, + "designerToEdtFormatTransformation": 60, + "edtToDesignerFormatTransformation": 60, + "edtValidate": 240, + "initInfoBase": 60, + "resultTransformation": 10, + "sonarqube": 90, + "syntaxCheck": 240, + "zipInfoBase": 60 + }, "initInfobase": { "initMethod": "fromStorage", "runMigration": true, diff --git a/resources/schema.json b/resources/schema.json index e9cc53e..7f5d9ab 100644 --- a/resources/schema.json +++ b/resources/schema.json @@ -65,6 +65,57 @@ } } }, + "timeout" : { + "type" : "object", + "id" : "urn:jsonschema:ru:pulsar:jenkins:library:configuration:TimeoutOptions", + "description" : "Настройка таймаутов для шагов", + "properties" : { + "edtToDesignerFormatTransformation" : { + "type" : "integer", + "description" : "Таймаут шага трансформации исходников из формата EDT в формат Конфигуратора, в минутах.\n По умолчанию содержит значение 60.\n " + }, + "createInfoBase" : { + "type" : "integer", + "description" : "Таймаут шага создания информационной базы, в минутах.\n По умолчанию содержит значение 60.\n " + }, + "initInfoBase" : { + "type" : "integer", + "description" : "Таймаут шага инициализации информационной базы, в минутах.\n По умолчанию содержит значение 60.\n " + }, + "zipInfoBase" : { + "type" : "integer", + "description" : "Таймаут шага архивирования информационной базы, в минутах.\n По умолчанию содержит значение 60.\n " + }, + "designerToEdtFormatTransformation" : { + "type" : "integer", + "description" : "Таймаут шага трансформации исходников из формата Конфигуратора в формат EDT, в минутах.\n По умолчанию содержит значение 60.\n " + }, + "edtValidate" : { + "type" : "integer", + "description" : "Таймаут шага валидации EDT, в минутах.\n По умолчанию содержит значение 240.\n " + }, + "resultTransformation" : { + "type" : "integer", + "description" : "Таймаут шага трансформации результатов EDT, в минутах.\n По умолчанию содержит значение 10.\n " + }, + "bdd" : { + "type" : "integer", + "description" : "Таймаут шага проверки сценариев поведения, в минутах.\n По умолчанию содержит значение 120.\n " + }, + "syntaxCheck" : { + "type" : "integer", + "description" : "Таймаут шага синтаксического контроля, в минутах.\n По умолчанию содержит значение 240.\n " + }, + "smoke" : { + "type" : "integer", + "description" : "Таймаут шага дымовых тестов, в минутах.\n По умолчанию содержит значение 240.\n " + }, + "sonarqube" : { + "type" : "integer", + "description" : "Таймаут шага статического анализа SonarQube, в минутах.\n По умолчанию содержит значение 90.\n " + } + } + }, "initInfobase" : { "type" : "object", "id" : "urn:jsonschema:ru:pulsar:jenkins:library:configuration:InitInfobaseOptions", @@ -192,10 +243,6 @@ "logosConfig" : { "type" : "string", "description" : "Конфигурация библиотеки logos. Применяется перед запуском каждой стадии сборки" - }, - "stageTimeout" : { - "type" : "integer", - "description" : "Таймаут для выполнения шагов (в часах)" } } } \ No newline at end of file diff --git a/src/ru/pulsar/jenkins/library/configuration/ConfigurationReader.groovy b/src/ru/pulsar/jenkins/library/configuration/ConfigurationReader.groovy index a737a64..82c743e 100644 --- a/src/ru/pulsar/jenkins/library/configuration/ConfigurationReader.groovy +++ b/src/ru/pulsar/jenkins/library/configuration/ConfigurationReader.groovy @@ -56,6 +56,7 @@ class ConfigurationReader implements Serializable { def nonMergeableSettings = Arrays.asList( "secrets", "stageFlags", + "timeoutOptions", "initInfobaseOptions", "bddOptions", "sonarQubeOptions", diff --git a/src/ru/pulsar/jenkins/library/configuration/JobConfiguration.groovy b/src/ru/pulsar/jenkins/library/configuration/JobConfiguration.groovy index 46ed541..b93d4f1 100644 --- a/src/ru/pulsar/jenkins/library/configuration/JobConfiguration.groovy +++ b/src/ru/pulsar/jenkins/library/configuration/JobConfiguration.groovy @@ -22,6 +22,10 @@ class JobConfiguration implements Serializable { @JsonPropertyDescription("Включение этапов сборок") StageFlags stageFlags; + @JsonProperty("timeout") + @JsonPropertyDescription("Настройка таймаутов для шагов") + TimeoutOptions timeoutOptions; + @JsonPropertyDescription("Имя ветки по умолчанию. Значение по умолчанию - main.") String defaultBranch @@ -56,10 +60,6 @@ class JobConfiguration implements Serializable { @JsonPropertyDescription("Конфигурация библиотеки logos. Применяется перед запуском каждой стадии сборки") String logosConfig; - @JsonProperty("stageTimeout") - @JsonPropertyDescription("Таймаут для выполнения шагов (в часах)") - Integer stageTimeout; - @Override @NonCPS String toString() { @@ -67,8 +67,9 @@ class JobConfiguration implements Serializable { "v8version='" + v8version + '\'' + ", srcDir='" + srcDir + '\'' + ", sourceFormat=" + sourceFormat + - ", defaultBranch=" + defaultBranch + ", stageFlags=" + stageFlags + + ", timeoutOptions=" + timeoutOptions + + ", defaultBranch='" + defaultBranch + '\'' + ", secrets=" + secrets + ", initInfobaseOptions=" + initInfobaseOptions + ", bddOptions=" + bddOptions + @@ -76,12 +77,11 @@ class JobConfiguration implements Serializable { ", syntaxCheckOptions=" + syntaxCheckOptions + ", smokeTestOptions=" + smokeTestOptions + ", resultsTransformOptions=" + resultsTransformOptions + - ", logosConfig=" + logosConfig + - ", stageTimeout=" + stageTimeout + + ", logosConfig='" + logosConfig + '\'' + '}'; } - boolean infobaseFromFiles(){ + boolean infobaseFromFiles() { IStepExecutor steps = ContextRegistry.getContext().getStepExecutor() def env = steps.env(); String branchName = env.BRANCH_NAME; diff --git a/src/ru/pulsar/jenkins/library/configuration/TimeoutOptions.groovy b/src/ru/pulsar/jenkins/library/configuration/TimeoutOptions.groovy new file mode 100644 index 0000000..4def6ec --- /dev/null +++ b/src/ru/pulsar/jenkins/library/configuration/TimeoutOptions.groovy @@ -0,0 +1,63 @@ +package ru.pulsar.jenkins.library.configuration + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties +import com.fasterxml.jackson.annotation.JsonPropertyDescription + +@JsonIgnoreProperties(ignoreUnknown = true) +class TimeoutOptions implements Serializable { + + @JsonPropertyDescription('''Таймаут шага трансформации исходников из формата EDT в формат Конфигуратора, в минутах. + По умолчанию содержит значение 60. + ''') + Integer edtToDesignerFormatTransformation + + @JsonPropertyDescription('''Таймаут шага создания информационной базы, в минутах. + По умолчанию содержит значение 60. + ''') + Integer createInfoBase + + @JsonPropertyDescription('''Таймаут шага инициализации информационной базы, в минутах. + По умолчанию содержит значение 60. + ''') + Integer initInfoBase + + @JsonPropertyDescription('''Таймаут шага архивирования информационной базы, в минутах. + По умолчанию содержит значение 60. + ''') + Integer zipInfoBase + + @JsonPropertyDescription('''Таймаут шага трансформации исходников из формата Конфигуратора в формат EDT, в минутах. + По умолчанию содержит значение 60. + ''') + Integer designerToEdtFormatTransformation + + @JsonPropertyDescription('''Таймаут шага валидации EDT, в минутах. + По умолчанию содержит значение 240. + ''') + Integer edtValidate + + @JsonPropertyDescription('''Таймаут шага трансформации результатов EDT, в минутах. + По умолчанию содержит значение 10. + ''') + Integer resultTransformation + + @JsonPropertyDescription('''Таймаут шага проверки сценариев поведения, в минутах. + По умолчанию содержит значение 120. + ''') + Integer bdd + + @JsonPropertyDescription('''Таймаут шага синтаксического контроля, в минутах. + По умолчанию содержит значение 240. + ''') + Integer syntaxCheck + + @JsonPropertyDescription('''Таймаут шага дымовых тестов, в минутах. + По умолчанию содержит значение 240. + ''') + Integer smoke + + @JsonPropertyDescription('''Таймаут шага статического анализа SonarQube, в минутах. + По умолчанию содержит значение 90. + ''') + Integer sonarqube +} diff --git a/test/unit/groovy/ru/pulsar/jenkins/library/configuration/ConfigurationReaderTest.java b/test/unit/groovy/ru/pulsar/jenkins/library/configuration/ConfigurationReaderTest.java index 4736075..ca4484b 100644 --- a/test/unit/groovy/ru/pulsar/jenkins/library/configuration/ConfigurationReaderTest.java +++ b/test/unit/groovy/ru/pulsar/jenkins/library/configuration/ConfigurationReaderTest.java @@ -55,7 +55,8 @@ class ConfigurationReaderTest { assertThat(jobConfiguration.getLogosConfig()).isEqualTo("logger.rootLogger=DEBUG"); - assertThat(jobConfiguration.getStageTimeout()).isEqualTo(2); + assertThat(jobConfiguration.getTimeoutOptions().getBdd()).isEqualTo(120); + assertThat(jobConfiguration.getTimeoutOptions().getZipInfoBase()).isEqualTo(123); } } \ No newline at end of file diff --git a/test/unit/resources/jobConfiguration.json b/test/unit/resources/jobConfiguration.json index f9b28a0..e49e884 100644 --- a/test/unit/resources/jobConfiguration.json +++ b/test/unit/resources/jobConfiguration.json @@ -6,6 +6,9 @@ "stages": { "syntaxCheck": true }, + "timeout": { + "zipInfoBase": 123 + }, "initInfobase": { "runMigration": false, "additionalInitializationSteps": [ diff --git a/vars/pipeline1C.groovy b/vars/pipeline1C.groovy index 34afc52..03a9111 100644 --- a/vars/pipeline1C.groovy +++ b/vars/pipeline1C.groovy @@ -61,7 +61,7 @@ void call() { expression { config.stageFlags.needInfobase() && config.infobaseFromFiles() && config.sourceFormat == SourceFormat.EDT } } steps { - timeout(time: config.stageTimeout, unit: TimeUnit.HOURS) { + timeout(time: config.timeoutOptions.edtToDesignerFormatTransformation, unit: TimeUnit.MINUTES) { edtToDesignerFormatTransformation config } } @@ -69,7 +69,7 @@ void call() { stage('Создание ИБ') { steps { - timeout(time: config.stageTimeout, unit: TimeUnit.HOURS) { + timeout(time: config.timeoutOptions.createInfoBase, unit: TimeUnit.MINUTES) { createDir('build/out') script { @@ -91,7 +91,7 @@ void call() { expression { config.stageFlags.initSteps } } steps { - timeout(time: config.stageTimeout, unit: TimeUnit.HOURS) { + timeout(time: config.timeoutOptions.initInfoBase, unit: TimeUnit.MINUTES) { // Инициализация и первичная миграция initInfobase config } @@ -100,7 +100,7 @@ void call() { stage('Архивация ИБ') { steps { - timeout(time: config.stageTimeout, unit: TimeUnit.HOURS) { + timeout(time: config.timeoutOptions.zipInfoBase, unit: TimeUnit.MINUTES) { printLocation() zipInfobase() @@ -121,7 +121,7 @@ void call() { expression { config.sourceFormat == SourceFormat.DESIGNER && config.stageFlags.edtValidate } } steps { - timeout(time: config.stageTimeout, unit: TimeUnit.HOURS) { + timeout(time: config.timeoutOptions.designerToEdtFormatTransformation, unit: TimeUnit.MINUTES) { designerToEdtFormatTransformation config } } @@ -142,7 +142,7 @@ void call() { label 'edt' } steps { - timeout(time: config.stageTimeout, unit: TimeUnit.HOURS) { + timeout(time: config.timeoutOptions.edtValidate, unit: TimeUnit.MINUTES) { edtValidate config } } @@ -153,7 +153,7 @@ void call() { label 'oscript' } steps { - timeout(time: config.stageTimeout, unit: TimeUnit.HOURS) { + timeout(time: config.timeoutOptions.resultTransformation, unit: TimeUnit.MINUTES) { transform config } } @@ -170,7 +170,7 @@ void call() { expression { config.stageFlags.bdd } } steps { - timeout(time: config.stageTimeout, unit: TimeUnit.HOURS) { + timeout(time: config.timeoutOptions.bdd, unit: TimeUnit.MINUTES) { unzipInfobase() bdd config @@ -187,7 +187,7 @@ void call() { expression { config.stageFlags.syntaxCheck } } steps { - timeout(time: config.stageTimeout, unit: TimeUnit.HOURS) { + timeout(time: config.timeoutOptions.syntaxCheck, unit: TimeUnit.MINUTES) { syntaxCheck config } } @@ -202,7 +202,7 @@ void call() { expression { config.stageFlags.smoke } } steps { - timeout(time: config.stageTimeout, unit: TimeUnit.HOURS) { + timeout(time: config.timeoutOptions.smoke, unit: TimeUnit.MINUTES) { unzipInfobase() smoke config @@ -221,7 +221,7 @@ void call() { expression { config.stageFlags.sonarqube } } steps { - timeout(time: config.stageTimeout, unit: TimeUnit.HOURS) { + timeout(time: config.timeoutOptions.sonarqube, unit: TimeUnit.MINUTES) { sonarScanner config } } From 9e624f3669e563f4ab95812ff4a022c7c89696b0 Mon Sep 17 00:00:00 2001 From: Nikita Fedkin Date: Wed, 8 Dec 2021 16:13:09 +0300 Subject: [PATCH 19/22] =?UTF-8?q?=D0=9F=D0=B0=D1=80=D0=B0=20=D1=81=D0=BB?= =?UTF-8?q?=D0=BE=D0=B2=20=D0=BF=D1=80=D0=BE=20=D1=82=D0=B0=D0=B9=D0=BC?= =?UTF-8?q?=D0=B0=D1=83=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 91b789b..b2c0385 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,7 @@ pipeline1C() * Если в корне репозитория существует файл `packagedef`, то в шагах, работающих с информационной базой, будет выполнена попытка установки локальных зависимостей средствами `opm`. * Если после установки локальных зависимостей в каталоге `oscript_modules/bin` существует файл `vrunner`, то для выполнения команд работы с информационной базой будет использоваться он, а не глобально установленный `vrunner` из `PATH`. * Результаты в формате `allure` ожидаются в каталоге `build/out/allure` или его подкаталогах. + * Каждый шаг имеет свой таймаут в минутах (от 10 до 240 в зависимости от "тяжёлости" шага сборки), но может быть переопределен в секции настроек `timeout`. * Инициализация: * Информационная база инициализируется только в том случае, если в сборочной линии включены шаги, работающие с базой (например, `bdd` или `syntaxCheck`). * Информационная база инициализируется конфигурацией из хранилища конфигурации (`initInfobase` -> `initMethod`). From 54a070feac5f48e8e453c5bfd54864dfd15c9d63 Mon Sep 17 00:00:00 2001 From: Nikita Fedkin Date: Wed, 8 Dec 2021 17:02:29 +0300 Subject: [PATCH 20/22] =?UTF-8?q?=D0=A0=D0=B5=D1=84=D0=B0=D0=BA=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=B8=D0=BD=D0=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../library/configuration/ConfigurationReader.groovy | 6 +++--- ...fobaseMethod.groovy => InitInfoBaseMethod.groovy} | 2 +- ...baseOptions.groovy => InitInfoBaseOptions.groovy} | 6 +++--- .../library/configuration/JobConfiguration.groovy | 12 ++++++------ .../jenkins/library/configuration/StageFlags.groovy | 2 +- .../jenkins/library/steps/InitFromFiles.groovy | 2 +- .../jenkins/library/steps/InitFromStorage.groovy | 2 +- .../{InitInfobase.groovy => InitInfoBase.groovy} | 10 +++++----- .../configuration/ConfigurationReaderTest.java | 4 ++-- vars/initInfobase.groovy | 4 ++-- vars/pipeline1C.groovy | 6 +++--- 11 files changed, 28 insertions(+), 28 deletions(-) rename src/ru/pulsar/jenkins/library/configuration/{InitInfobaseMethod.groovy => InitInfoBaseMethod.groovy} (91%) rename src/ru/pulsar/jenkins/library/configuration/{InitInfobaseOptions.groovy => InitInfoBaseOptions.groovy} (91%) rename src/ru/pulsar/jenkins/library/steps/{InitInfobase.groovy => InitInfoBase.groovy} (90%) diff --git a/src/ru/pulsar/jenkins/library/configuration/ConfigurationReader.groovy b/src/ru/pulsar/jenkins/library/configuration/ConfigurationReader.groovy index 82c743e..ca75e17 100644 --- a/src/ru/pulsar/jenkins/library/configuration/ConfigurationReader.groovy +++ b/src/ru/pulsar/jenkins/library/configuration/ConfigurationReader.groovy @@ -57,7 +57,7 @@ class ConfigurationReader implements Serializable { "secrets", "stageFlags", "timeoutOptions", - "initInfobaseOptions", + "initInfoBaseOptions", "bddOptions", "sonarQubeOptions", "smokeTestOptions", @@ -66,7 +66,7 @@ class ConfigurationReader implements Serializable { ).toSet() mergeObjects(baseConfiguration, configurationToMerge, nonMergeableSettings) - mergeInitInfobaseOptions(baseConfiguration.initInfobaseOptions, configurationToMerge.initInfobaseOptions); + mergeInitInfoBaseOptions(baseConfiguration.initInfoBaseOptions, configurationToMerge.initInfoBaseOptions); mergeBddOptions(baseConfiguration.bddOptions, configurationToMerge.bddOptions); return baseConfiguration; @@ -93,7 +93,7 @@ class ConfigurationReader implements Serializable { } @NonCPS - private static void mergeInitInfobaseOptions(InitInfobaseOptions baseObject, InitInfobaseOptions objectToMerge) { + private static void mergeInitInfoBaseOptions(InitInfoBaseOptions baseObject, InitInfoBaseOptions objectToMerge) { if (objectToMerge == null || objectToMerge.additionalInitializationSteps == null) { return } diff --git a/src/ru/pulsar/jenkins/library/configuration/InitInfobaseMethod.groovy b/src/ru/pulsar/jenkins/library/configuration/InitInfoBaseMethod.groovy similarity index 91% rename from src/ru/pulsar/jenkins/library/configuration/InitInfobaseMethod.groovy rename to src/ru/pulsar/jenkins/library/configuration/InitInfoBaseMethod.groovy index c13be07..30986ad 100644 --- a/src/ru/pulsar/jenkins/library/configuration/InitInfobaseMethod.groovy +++ b/src/ru/pulsar/jenkins/library/configuration/InitInfoBaseMethod.groovy @@ -2,7 +2,7 @@ package ru.pulsar.jenkins.library.configuration import com.fasterxml.jackson.annotation.JsonProperty -enum InitInfobaseMethod { +enum InitInfoBaseMethod { @JsonProperty("fromStorage") FROM_STORAGE, diff --git a/src/ru/pulsar/jenkins/library/configuration/InitInfobaseOptions.groovy b/src/ru/pulsar/jenkins/library/configuration/InitInfoBaseOptions.groovy similarity index 91% rename from src/ru/pulsar/jenkins/library/configuration/InitInfobaseOptions.groovy rename to src/ru/pulsar/jenkins/library/configuration/InitInfoBaseOptions.groovy index d36a3bf..d01d3b9 100644 --- a/src/ru/pulsar/jenkins/library/configuration/InitInfobaseOptions.groovy +++ b/src/ru/pulsar/jenkins/library/configuration/InitInfoBaseOptions.groovy @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonPropertyDescription @JsonIgnoreProperties(ignoreUnknown = true) -class InitInfobaseOptions implements Serializable { +class InitInfoBaseOptions implements Serializable { @JsonPropertyDescription(""" Способ инициализации информационной базы. @@ -14,7 +14,7 @@ class InitInfobaseOptions implements Serializable { * fromSource - инициализация информационной базы из исходников конфигурации; * defaultBranchFromStorage - инициализация основной ветки из хранилища конфигурации, остальных - из исходников конфигурации. По умолчанию содержит значение "fromStorage".""") - InitInfobaseMethod initMethod = InitInfobaseMethod.FROM_STORAGE; + InitInfoBaseMethod initMethod = InitInfoBaseMethod.FROM_STORAGE; @JsonPropertyDescription("Запустить миграцию ИБ") boolean runMigration = true @@ -28,7 +28,7 @@ class InitInfobaseOptions implements Serializable { @Override @NonCPS String toString() { - return "InitInfobaseOptions{" + + return "InitInfoBaseOptions{" + "initMethod=" + initMethod + ", runMigration=" + runMigration + ", additionalInitializationSteps=" + additionalInitializationSteps + diff --git a/src/ru/pulsar/jenkins/library/configuration/JobConfiguration.groovy b/src/ru/pulsar/jenkins/library/configuration/JobConfiguration.groovy index b93d4f1..82b148a 100644 --- a/src/ru/pulsar/jenkins/library/configuration/JobConfiguration.groovy +++ b/src/ru/pulsar/jenkins/library/configuration/JobConfiguration.groovy @@ -34,7 +34,7 @@ class JobConfiguration implements Serializable { @JsonProperty("initInfobase") @JsonPropertyDescription("Настройки шага инициализации ИБ") - InitInfobaseOptions initInfobaseOptions; + InitInfoBaseOptions initInfoBaseOptions; @JsonProperty("bdd") @JsonPropertyDescription("Настройки шага запуска BDD сценариев") @@ -71,7 +71,7 @@ class JobConfiguration implements Serializable { ", timeoutOptions=" + timeoutOptions + ", defaultBranch='" + defaultBranch + '\'' + ", secrets=" + secrets + - ", initInfobaseOptions=" + initInfobaseOptions + + ", initInfoBaseOptions=" + initInfoBaseOptions + ", bddOptions=" + bddOptions + ", sonarQubeOptions=" + sonarQubeOptions + ", syntaxCheckOptions=" + syntaxCheckOptions + @@ -81,13 +81,13 @@ class JobConfiguration implements Serializable { '}'; } - boolean infobaseFromFiles() { + boolean infoBaseFromFiles() { IStepExecutor steps = ContextRegistry.getContext().getStepExecutor() def env = steps.env(); String branchName = env.BRANCH_NAME; - def initMethod = initInfobaseOptions.initMethod + def initMethod = initInfoBaseOptions.initMethod - return (initMethod == InitInfobaseMethod.FROM_SOURCE) || - (initMethod == InitInfobaseMethod.DEFAULT_BRANCH_FROM_STORAGE && branchName != defaultBranch) + return (initMethod == InitInfoBaseMethod.FROM_SOURCE) || + (initMethod == InitInfoBaseMethod.DEFAULT_BRANCH_FROM_STORAGE && branchName != defaultBranch) } } \ No newline at end of file diff --git a/src/ru/pulsar/jenkins/library/configuration/StageFlags.groovy b/src/ru/pulsar/jenkins/library/configuration/StageFlags.groovy index 2fdcbe7..8dd2949 100644 --- a/src/ru/pulsar/jenkins/library/configuration/StageFlags.groovy +++ b/src/ru/pulsar/jenkins/library/configuration/StageFlags.groovy @@ -37,7 +37,7 @@ class StageFlags implements Serializable { '}'; } - boolean needInfobase() { + boolean needInfoBase() { return smoke || syntaxCheck || initSteps || bdd } } diff --git a/src/ru/pulsar/jenkins/library/steps/InitFromFiles.groovy b/src/ru/pulsar/jenkins/library/steps/InitFromFiles.groovy index a8ce35d..e08fa32 100644 --- a/src/ru/pulsar/jenkins/library/steps/InitFromFiles.groovy +++ b/src/ru/pulsar/jenkins/library/steps/InitFromFiles.groovy @@ -20,7 +20,7 @@ class InitFromFiles implements Serializable { Logger.printLocation() - if (!config.infobaseFromFiles()) { + if (!config.infoBaseFromFiles()) { Logger.println("init infoBase from files is disabled") return } diff --git a/src/ru/pulsar/jenkins/library/steps/InitFromStorage.groovy b/src/ru/pulsar/jenkins/library/steps/InitFromStorage.groovy index 6ed2b39..18b310d 100644 --- a/src/ru/pulsar/jenkins/library/steps/InitFromStorage.groovy +++ b/src/ru/pulsar/jenkins/library/steps/InitFromStorage.groovy @@ -27,7 +27,7 @@ class InitFromStorage implements Serializable { Logger.printLocation() - if (config.infobaseFromFiles()) { + if (config.infoBaseFromFiles()) { Logger.println("init infoBase from storage is disabled") return } diff --git a/src/ru/pulsar/jenkins/library/steps/InitInfobase.groovy b/src/ru/pulsar/jenkins/library/steps/InitInfoBase.groovy similarity index 90% rename from src/ru/pulsar/jenkins/library/steps/InitInfobase.groovy rename to src/ru/pulsar/jenkins/library/steps/InitInfoBase.groovy index 1a5d49e..981e52e 100644 --- a/src/ru/pulsar/jenkins/library/steps/InitInfobase.groovy +++ b/src/ru/pulsar/jenkins/library/steps/InitInfoBase.groovy @@ -7,11 +7,11 @@ import ru.pulsar.jenkins.library.ioc.ContextRegistry import ru.pulsar.jenkins.library.utils.Logger import ru.pulsar.jenkins.library.utils.VRunner -class InitInfobase implements Serializable { +class InitInfoBase implements Serializable { private final JobConfiguration config; - InitInfobase(JobConfiguration config) { + InitInfoBase(JobConfiguration config) { this.config = config } @@ -32,7 +32,7 @@ class InitInfobase implements Serializable { String vrunnerPath = VRunner.getVRunnerPath(); - if (config.initInfobaseOptions.runMigration) { + if (config.initInfoBaseOptions.runMigration) { Logger.println("Запуск миграции ИБ") String command = vrunnerPath + ' run --command "ЗапуститьОбновлениеИнформационнойБазы;ЗавершитьРаботуСистемы;" --execute ' @@ -52,7 +52,7 @@ class InitInfobase implements Serializable { } steps.catchError { - if (config.initInfobaseOptions.additionalInitializationSteps.length == 0) { + if (config.initInfoBaseOptions.additionalInitializationSteps.length == 0) { FileWrapper[] files = steps.findFiles("tools/vrunner.init*.json") files = files.sort new OrderBy( { it.name }) files.each { @@ -60,7 +60,7 @@ class InitInfobase implements Serializable { VRunner.exec("$vrunnerPath vanessa --settings ${it.path} --ibconnection \"/F./build/ib\"") } } else { - config.initInfobaseOptions.additionalInitializationSteps.each { + config.initInfoBaseOptions.additionalInitializationSteps.each { Logger.println("Первичная инициализация командой ${it}") VRunner.exec("$vrunnerPath ${it} --ibconnection \"/F./build/ib\"") } diff --git a/test/unit/groovy/ru/pulsar/jenkins/library/configuration/ConfigurationReaderTest.java b/test/unit/groovy/ru/pulsar/jenkins/library/configuration/ConfigurationReaderTest.java index ca4484b..43c34aa 100644 --- a/test/unit/groovy/ru/pulsar/jenkins/library/configuration/ConfigurationReaderTest.java +++ b/test/unit/groovy/ru/pulsar/jenkins/library/configuration/ConfigurationReaderTest.java @@ -48,8 +48,8 @@ class ConfigurationReaderTest { assertThat(jobConfiguration.getSmokeTestOptions().isPublishToAllureReport()).isFalse(); assertThat(jobConfiguration.getSmokeTestOptions().isPublishToJUnitReport()).isTrue(); - assertThat(jobConfiguration.getInitInfobaseOptions().getRunMigration()).isFalse(); - assertThat(jobConfiguration.getInitInfobaseOptions().getAdditionalInitializationSteps()).contains("vanessa --settings ./tools/vrunner.first.json"); + assertThat(jobConfiguration.getInitInfoBaseOptions().getRunMigration()).isFalse(); + assertThat(jobConfiguration.getInitInfoBaseOptions().getAdditionalInitializationSteps()).contains("vanessa --settings ./tools/vrunner.first.json"); assertThat(jobConfiguration.getBddOptions().getVrunnerSteps()).contains("vanessa --settings ./tools/vrunner.json"); diff --git a/vars/initInfobase.groovy b/vars/initInfobase.groovy index 7eabdcb..bb6bdd8 100644 --- a/vars/initInfobase.groovy +++ b/vars/initInfobase.groovy @@ -1,10 +1,10 @@ import ru.pulsar.jenkins.library.configuration.JobConfiguration import ru.pulsar.jenkins.library.ioc.ContextRegistry -import ru.pulsar.jenkins.library.steps.InitInfobase +import ru.pulsar.jenkins.library.steps.InitInfoBase def call(JobConfiguration config) { ContextRegistry.registerDefaultContext(this) - def initInfobase = new InitInfobase(config) + def initInfobase = new InitInfoBase(config) initInfobase.run() } \ No newline at end of file diff --git a/vars/pipeline1C.groovy b/vars/pipeline1C.groovy index 03a9111..227924d 100644 --- a/vars/pipeline1C.groovy +++ b/vars/pipeline1C.groovy @@ -48,7 +48,7 @@ void call() { } when { beforeAgent true - expression { config.stageFlags.needInfobase() } + expression { config.stageFlags.needInfoBase() } } stages { @@ -58,7 +58,7 @@ void call() { } when { beforeAgent true - expression { config.stageFlags.needInfobase() && config.infobaseFromFiles() && config.sourceFormat == SourceFormat.EDT } + expression { config.stageFlags.needInfoBase() && config.infoBaseFromFiles() && config.sourceFormat == SourceFormat.EDT } } steps { timeout(time: config.timeoutOptions.edtToDesignerFormatTransformation, unit: TimeUnit.MINUTES) { @@ -73,7 +73,7 @@ void call() { createDir('build/out') script { - if (config.infobaseFromFiles()) { + if (config.infoBaseFromFiles()) { // Создание базы загрузкой из файлов initFromFiles config } else { From c567cca7ab09ecc47fd8d616ee7219a6326548d4 Mon Sep 17 00:00:00 2001 From: Nikita Fedkin Date: Wed, 8 Dec 2021 17:11:07 +0300 Subject: [PATCH 21/22] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=20=D0=BC=D0=B5=D1=80=D0=B6=20=D0=BF=D1=80?= =?UTF-8?q?=D0=B8=D0=BC=D0=B8=D1=82=D0=B8=D0=B2=D0=BE=D0=B2=20=D0=B2=20?= =?UTF-8?q?=D0=BA=D0=BE=D0=BD=D1=84=D0=B8=D0=B3=D1=83=D1=80=D0=B0=D1=86?= =?UTF-8?q?=D0=B8=D1=8F=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../library/configuration/InitInfoBaseOptions.groovy | 2 +- .../configuration/ResultsTransformOptions.groovy | 4 ++-- .../library/configuration/SonarQubeOptions.groovy | 2 +- .../jenkins/library/configuration/StageFlags.groovy | 12 ++++++------ .../configuration/ConfigurationReaderTest.java | 4 +++- test/unit/resources/jobConfiguration.json | 3 +++ 6 files changed, 16 insertions(+), 11 deletions(-) diff --git a/src/ru/pulsar/jenkins/library/configuration/InitInfoBaseOptions.groovy b/src/ru/pulsar/jenkins/library/configuration/InitInfoBaseOptions.groovy index d01d3b9..f0874a6 100644 --- a/src/ru/pulsar/jenkins/library/configuration/InitInfoBaseOptions.groovy +++ b/src/ru/pulsar/jenkins/library/configuration/InitInfoBaseOptions.groovy @@ -17,7 +17,7 @@ class InitInfoBaseOptions implements Serializable { InitInfoBaseMethod initMethod = InitInfoBaseMethod.FROM_STORAGE; @JsonPropertyDescription("Запустить миграцию ИБ") - boolean runMigration = true + Boolean runMigration = true @JsonPropertyDescription("""Дополнительные шаги, запускаемые через vrunner. В каждой строке передается отдельная команда diff --git a/src/ru/pulsar/jenkins/library/configuration/ResultsTransformOptions.groovy b/src/ru/pulsar/jenkins/library/configuration/ResultsTransformOptions.groovy index 08168fc..f450d84 100644 --- a/src/ru/pulsar/jenkins/library/configuration/ResultsTransformOptions.groovy +++ b/src/ru/pulsar/jenkins/library/configuration/ResultsTransformOptions.groovy @@ -8,14 +8,14 @@ import com.fasterxml.jackson.annotation.JsonPropertyDescription class ResultsTransformOptions implements Serializable { @JsonPropertyDescription("Фильтровать замечания по уровню поддержки модуля. По умолчанию включено.") - boolean removeSupport = true + Boolean removeSupport = true @JsonPropertyDescription("""Настройка фильтрации замечаний по уровню поддержки. 0 - удалить файлы на замке; 1 - удалить файлы на замке и на поддержке; 2 - удалить файлы на замке, на поддержке и снятые с поддержки. """) - int supportLevel + Integer supportLevel @Override @NonCPS diff --git a/src/ru/pulsar/jenkins/library/configuration/SonarQubeOptions.groovy b/src/ru/pulsar/jenkins/library/configuration/SonarQubeOptions.groovy index 7dcbb37..cb25672 100644 --- a/src/ru/pulsar/jenkins/library/configuration/SonarQubeOptions.groovy +++ b/src/ru/pulsar/jenkins/library/configuration/SonarQubeOptions.groovy @@ -13,7 +13,7 @@ class SonarQubeOptions implements Serializable { String sonarQubeInstallation; @JsonPropertyDescription("Использовать sonar-scanner, доступный в PATH") - boolean useSonarScannerFromPath + Boolean useSonarScannerFromPath @JsonPropertyDescription( "Имя настроенной утилиты sonar-scanner.\nПрименяется, если useSonarScannerFromPath установлено в false." diff --git a/src/ru/pulsar/jenkins/library/configuration/StageFlags.groovy b/src/ru/pulsar/jenkins/library/configuration/StageFlags.groovy index 8dd2949..f52cb76 100644 --- a/src/ru/pulsar/jenkins/library/configuration/StageFlags.groovy +++ b/src/ru/pulsar/jenkins/library/configuration/StageFlags.groovy @@ -7,22 +7,22 @@ import com.fasterxml.jackson.annotation.JsonPropertyDescription @JsonIgnoreProperties(ignoreUnknown = true) class StageFlags implements Serializable { @JsonPropertyDescription("Анализ SonarQube включен") - boolean sonarqube + Boolean sonarqube @JsonPropertyDescription("Синтаксический контроль включен") - boolean syntaxCheck + Boolean syntaxCheck @JsonPropertyDescription("Валидация EDT включена") - boolean edtValidate + Boolean edtValidate @JsonPropertyDescription("Дымовые тесты включены") - boolean smoke + Boolean smoke @JsonPropertyDescription("Предварительные шаги инициализации включены") - boolean initSteps + Boolean initSteps @JsonPropertyDescription("Запуск BDD сценариев включен") - boolean bdd + Boolean bdd @Override @NonCPS diff --git a/test/unit/groovy/ru/pulsar/jenkins/library/configuration/ConfigurationReaderTest.java b/test/unit/groovy/ru/pulsar/jenkins/library/configuration/ConfigurationReaderTest.java index 43c34aa..64d2d3b 100644 --- a/test/unit/groovy/ru/pulsar/jenkins/library/configuration/ConfigurationReaderTest.java +++ b/test/unit/groovy/ru/pulsar/jenkins/library/configuration/ConfigurationReaderTest.java @@ -33,6 +33,8 @@ class ConfigurationReaderTest { assertThat(jobConfiguration.getV8version()).isEqualTo("8.3.14.1944"); assertThat(jobConfiguration.getSonarQubeOptions().getSonarScannerToolName()).isEqualTo("sonar-scanner"); + assertThat(jobConfiguration.getSonarQubeOptions().getSonarQubeInstallation()).isEqualTo("qa"); + assertThat(jobConfiguration.getSonarQubeOptions().getUseSonarScannerFromPath()).isTrue(); assertThat(jobConfiguration.getSecrets()) .hasFieldOrPropertyWithValue("storage", "1234") @@ -41,7 +43,7 @@ class ConfigurationReaderTest { assertThat(jobConfiguration.getSyntaxCheckOptions().getCheckModes()).hasSize(1); - assertThat(jobConfiguration.getResultsTransformOptions().isRemoveSupport()).isFalse(); + assertThat(jobConfiguration.getResultsTransformOptions().getRemoveSupport()).isFalse(); assertThat(jobConfiguration.getResultsTransformOptions().getSupportLevel()).isZero(); assertThat(jobConfiguration.getSmokeTestOptions().getVrunnerSettings()).contains("./tools/vrunner-smoke.json"); diff --git a/test/unit/resources/jobConfiguration.json b/test/unit/resources/jobConfiguration.json index e49e884..a4205c1 100644 --- a/test/unit/resources/jobConfiguration.json +++ b/test/unit/resources/jobConfiguration.json @@ -15,6 +15,9 @@ "vanessa --settings ./tools/vrunner.first.json" ] }, + "sonarqube": { + "sonarQubeInstallation": "qa" + }, "syntaxCheck": { "checkModes": ["-ThinClient"] }, From 0e2e9d0705d79372d223c22a0a2a477c6a76020e Mon Sep 17 00:00:00 2001 From: kuzja086 <51016001+kuzja086@users.noreply.github.com> Date: Thu, 9 Dec 2021 11:58:24 +0500 Subject: [PATCH 22/22] =?UTF-8?q?=D0=9E=D0=BF=D1=80=D0=B5=D0=B4=D0=B5?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B2=D0=B5=D1=80=D1=81=D0=B8?= =?UTF-8?q?=D0=B8=20(#58)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: kuzja086 Co-authored-by: Nikita Fedkin --- README.md | 3 +- resources/globalConfiguration.json | 3 +- resources/schema.json | 4 ++ .../configuration/SonarQubeOptions.groovy | 6 +++ .../jenkins/library/steps/SonarScanner.groovy | 41 ++++++++++++------- .../library/utils/VersionParser.groovy | 5 +++ 6 files changed, 45 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index b2c0385..a2fe76e 100644 --- a/README.md +++ b/README.md @@ -143,5 +143,6 @@ pipeline1C() * Предполагается наличие единственной настройки `SonarQube installation` (`sonarqube` -> `sonarQubeInstallation`). * Используется `sonar-scanner` из переменной окружения `PATH` (`sonarqube` -> `useSonarScannerFromPath`). * Если использование `sonar-scanner` из переменной окружения `PATH` выключено, предполагается наличие настроенного глобального инструмента `SonarQube Scanner` с идентификатором инструмента `sonar-scanner` (`sonarqube` -> `sonarScannerToolName`). - * Версия из корня конфигурации передается утилите `sonar-scanner` как значение параметра `sonar.projectVersion=$configurationVersion`. + * Если разработка ведется с использованием подсистемы [БСП "Обновление версии ИБ"](https://its.1c.ru/db/bsp315doc#content:4:1:issogl1_обновление_версии_иб), то в значение параметра `sonar.projectVersion=$configurationVersion` утилиты `sonar-scanner` можно передавать версию из созданного общего модуля. + Для этого необходимо заполнить параметр (`sonarqube` -> `infoBaseUpdateModuleName`). Если параметр не заполнен, версия передается из корня конфигурации. * Если выполнялась валидация EDT, результаты валидации в формате `generic issues` передаются утилите `sonar-scanner` как значение параметра `sonar.externalIssuesReportPaths`. diff --git a/resources/globalConfiguration.json b/resources/globalConfiguration.json index fb4979a..7ed9f03 100644 --- a/resources/globalConfiguration.json +++ b/resources/globalConfiguration.json @@ -42,7 +42,8 @@ "sonarqube": { "sonarQubeInstallation": "", "useSonarScannerFromPath": true, - "sonarScannerToolName": "sonar-scanner" + "sonarScannerToolName": "sonar-scanner", + "infoBaseUpdateModuleName" : "" }, "syntaxCheck": { "groupErrorsByMetadata": true, diff --git a/resources/schema.json b/resources/schema.json index 7f5d9ab..5d2c076 100644 --- a/resources/schema.json +++ b/resources/schema.json @@ -169,6 +169,10 @@ "sonarScannerToolName" : { "type" : "string", "description" : "Имя настроенной утилиты sonar-scanner.\nПрименяется, если useSonarScannerFromPath установлено в false." + }, + "infoBaseUpdateModuleName" : { + "type" : "string", + "description" : "Имя общего модуля (например, ОбновлениеИнформационнойБазыXXX), в котором указана версия библиотеки.\n Версия должна задаваться в виде присвоения `Описание.Версия = \"ваш номер версии\";`\n " } } }, diff --git a/src/ru/pulsar/jenkins/library/configuration/SonarQubeOptions.groovy b/src/ru/pulsar/jenkins/library/configuration/SonarQubeOptions.groovy index cb25672..dad4964 100644 --- a/src/ru/pulsar/jenkins/library/configuration/SonarQubeOptions.groovy +++ b/src/ru/pulsar/jenkins/library/configuration/SonarQubeOptions.groovy @@ -20,6 +20,11 @@ class SonarQubeOptions implements Serializable { ) String sonarScannerToolName + @JsonPropertyDescription("""Имя общего модуля (например, ОбновлениеИнформационнойБазыXXX), в котором указана версия библиотеки. + Версия должна задаваться в виде присвоения `Описание.Версия = "ваш номер версии";` + """) + String infoBaseUpdateModuleName + @Override @NonCPS String toString() { @@ -27,6 +32,7 @@ class SonarQubeOptions implements Serializable { "useSonarScannerFromPath=" + useSonarScannerFromPath + ", sonarScannerToolName='" + sonarScannerToolName + '\'' + ", sonarQubeInstallation='" + sonarQubeInstallation + '\'' + + ", infoBaseUpdateModuleName='" + infoBaseUpdateModuleName + '\'' + '}'; } } diff --git a/src/ru/pulsar/jenkins/library/steps/SonarScanner.groovy b/src/ru/pulsar/jenkins/library/steps/SonarScanner.groovy index bac8532..022e187 100644 --- a/src/ru/pulsar/jenkins/library/steps/SonarScanner.groovy +++ b/src/ru/pulsar/jenkins/library/steps/SonarScanner.groovy @@ -10,15 +10,9 @@ import ru.pulsar.jenkins.library.utils.VersionParser class SonarScanner implements Serializable { private final JobConfiguration config; - private final String rootFile SonarScanner(JobConfiguration config) { this.config = config - if (config.sourceFormat == SourceFormat.EDT){ - this.rootFile = "$config.srcDir/src/Configuration/Configuration.mdo" - } else { - this.rootFile = "$config.srcDir/Configuration.xml" - } } def run() { @@ -44,15 +38,9 @@ class SonarScanner implements Serializable { String sonarCommand = "$sonarScannerBinary -Dsonar.branch.name=$env.BRANCH_NAME" - String configurationVersion - if (config.sourceFormat == SourceFormat.EDT) { - configurationVersion = VersionParser.edt(rootFile) - } else { - configurationVersion = VersionParser.configuration(rootFile) - } - - if (configurationVersion) { - sonarCommand += " -Dsonar.projectVersion=$configurationVersion" + String projectVersion = computeProjectVersion() + if (projectVersion) { + sonarCommand += " -Dsonar.projectVersion=$projectVersion" } if (config.stageFlags.edtValidate) { @@ -69,4 +57,27 @@ class SonarScanner implements Serializable { steps.cmd(sonarCommand) } } + + private String computeProjectVersion() { + String projectVersion + String nameOfModule = config.sonarQubeOptions.infoBaseUpdateModuleName + + if (!nameOfModule.isEmpty()) { + String rootFile + if (config.sourceFormat == SourceFormat.EDT) { + rootFile = "$config.srcDir/src/CommonModules/$nameOfModule/Module.bsl" + } else { + rootFile = "$config.srcDir/CommonModules/$nameOfModule/Ext/Module.bsl" + } + projectVersion = VersionParser.ssl(rootFile) + } else if (config.sourceFormat == SourceFormat.EDT) { + String rootFile = "$config.srcDir/src/Configuration/Configuration.mdo" + projectVersion = VersionParser.edt(rootFile) + } else { + String rootFile = "$config.srcDir/Configuration.xml" + projectVersion = VersionParser.configuration(rootFile) + } + + return projectVersion + } } diff --git a/src/ru/pulsar/jenkins/library/utils/VersionParser.groovy b/src/ru/pulsar/jenkins/library/utils/VersionParser.groovy index 93c49da..4914cdf 100644 --- a/src/ru/pulsar/jenkins/library/utils/VersionParser.groovy +++ b/src/ru/pulsar/jenkins/library/utils/VersionParser.groovy @@ -8,6 +8,7 @@ import java.util.regex.Pattern class VersionParser implements Serializable { final static VERSION_REGEXP = ~/(?i)(.*)<\/version>/ + final static VERSION_REGEXP_SSL = ~/(?i)Описание.Версия = "(.*)";/ static String configuration(rootFile = 'src/cf/Configuration.xml') { return extractVersionFromFile(rootFile, VERSION_REGEXP) @@ -21,6 +22,10 @@ class VersionParser implements Serializable { return extractVersionFromFile(versionFile, VERSION_REGEXP) } + static String ssl(versionFile) { + return extractVersionFromFile(versionFile, VERSION_REGEXP_SSL) + } + private static String extractVersionFromFile(String filePath, Pattern regexp) { IStepExecutor steps = ContextRegistry.getContext().getStepExecutor()