Skip to content

Commit

Permalink
new json schema generator
Browse files Browse the repository at this point in the history
defaults for enums
  • Loading branch information
ovcharenko-di committed Aug 30, 2024
1 parent 0f33f96 commit 571b37b
Show file tree
Hide file tree
Showing 10 changed files with 400 additions and 385 deletions.
4 changes: 4 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ dependencies {
// jackson
implementation("com.fasterxml.jackson.module", "jackson-module-jsonSchema", jacksonVersion)

// jsonschema-generator
implementation("com.github.victools", "jsonschema-generator", "4.36.0")
implementation("com.github.victools", "jsonschema-module-jackson", "4.36.0")

// unit-tests
testImplementation("org.junit.jupiter", "junit-jupiter-api", junitVersion)
testRuntimeOnly("org.junit.jupiter", "junit-jupiter-engine", junitVersion)
Expand Down
686 changes: 339 additions & 347 deletions resources/schema.json

Large diffs are not rendered by default.

43 changes: 28 additions & 15 deletions src/JobConfigurationSchemaGenerator.java
Original file line number Diff line number Diff line change
@@ -1,27 +1,40 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.module.jsonSchema.JsonSchema;
import com.fasterxml.jackson.module.jsonSchema.JsonSchemaGenerator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.victools.jsonschema.generator.OptionPreset;
import com.github.victools.jsonschema.generator.SchemaGenerator;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder;
import com.github.victools.jsonschema.generator.SchemaVersion;
import com.github.victools.jsonschema.module.jackson.JacksonModule;

import com.github.victools.jsonschema.module.jackson.JacksonOption;
import ru.pulsar.jenkins.library.configuration.JobConfiguration;

import java.io.File;
import java.io.StringWriter;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class JobConfigurationSchemaGenerator {

public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
JsonSchemaGenerator generator = new JsonSchemaGenerator(mapper);
JsonSchema jsonSchema = generator.generateSchema(JobConfiguration.class);

StringWriter json = new StringWriter();
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
mapper.writeValue(json, jsonSchema);
SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_7, OptionPreset.PLAIN_JSON)
.with(new JacksonModule(JacksonOption.FLATTENED_ENUMS_FROM_JSONVALUE, JacksonOption.FLATTENED_ENUMS_FROM_JSONPROPERTY));

configBuilder.forFields().withDefaultResolver(field -> {
JsonProperty annotation = field.getAnnotationConsideringFieldAndGetter(JsonProperty.class);
return annotation == null || annotation.defaultValue().isEmpty() ? null : annotation.defaultValue();
});

File jsonSchemaFile = new File("./resources/schema.json");
mapper.writeValue(jsonSchemaFile, jsonSchema);
SchemaGenerator generator = new SchemaGenerator(configBuilder.build());
JsonNode jsonSchema = generator.generateSchema(JobConfiguration.class);

System.out.println(json);
String outputPath = "./resources/schema.json";
try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputPath))) {
writer.write(jsonSchema.toPrettyString());
System.out.println(jsonSchema.toPrettyString());
} catch (IOException e) {
e.printStackTrace();
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package ru.pulsar.jenkins.library.configuration

import com.cloudbees.groovy.cps.NonCPS
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonPropertyDescription

@JsonIgnoreProperties(ignoreUnknown = true)
Expand All @@ -14,6 +15,7 @@ class InitInfoBaseOptions implements Serializable {
* fromSource - инициализация информационной базы из исходников конфигурации;
* defaultBranchFromStorage - инициализация основной ветки из хранилища конфигурации, остальных - из исходников конфигурации.
По умолчанию содержит значение "fromStorage".""")
@JsonProperty(defaultValue = "fromStorage")
InitInfoBaseMethod initMethod = InitInfoBaseMethod.FROM_STORAGE

@JsonPropertyDescription("Запустить миграцию ИБ")
Expand Down
33 changes: 17 additions & 16 deletions src/ru/pulsar/jenkins/library/configuration/JobConfiguration.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -19,57 +19,58 @@ class JobConfiguration implements Serializable {
String srcDir

@JsonPropertyDescription("Формат исходников конфигурации")
SourceFormat sourceFormat;
@JsonProperty(defaultValue = "designer")
SourceFormat sourceFormat

@JsonProperty("stages")
@JsonPropertyDescription("Включение этапов сборок")
StageFlags stageFlags;
StageFlags stageFlags

@JsonProperty("timeout")
@JsonPropertyDescription("Настройка таймаутов для шагов")
TimeoutOptions timeoutOptions;
TimeoutOptions timeoutOptions

@JsonPropertyDescription("Имя ветки по умолчанию. Значение по умолчанию - main.")
String defaultBranch

@JsonPropertyDescription("Идентификаторы сохраненных секретов")
Secrets secrets;
Secrets secrets

@JsonProperty("initInfobase")
@JsonPropertyDescription("Настройки шага инициализации ИБ")
InitInfoBaseOptions initInfoBaseOptions;
InitInfoBaseOptions initInfoBaseOptions

@JsonProperty("bdd")
@JsonPropertyDescription("Настройки шага запуска BDD сценариев")
BddOptions bddOptions;
BddOptions bddOptions

@JsonProperty("sonarqube")
@JsonPropertyDescription("Настройки анализа SonarQube")
SonarQubeOptions sonarQubeOptions;
SonarQubeOptions sonarQubeOptions

@JsonProperty("syntaxCheck")
@JsonPropertyDescription("Настройки синтаксического контроля")
SyntaxCheckOptions syntaxCheckOptions;
SyntaxCheckOptions syntaxCheckOptions

@JsonProperty("smoke")
@JsonPropertyDescription("Настройки дымового тестирования")
SmokeTestOptions smokeTestOptions;
SmokeTestOptions smokeTestOptions

@JsonProperty("yaxunit")
@JsonPropertyDescription("Настройки YAXUnit")
YaxunitOptions yaxunitOptions;
YaxunitOptions yaxunitOptions

@JsonProperty("resultsTransform")
@JsonPropertyDescription("Настройки трансформации результатов анализа")
ResultsTransformOptions resultsTransformOptions;
ResultsTransformOptions resultsTransformOptions

@JsonProperty("notifications")
@JsonPropertyDescription("Настройки рассылки результатов сборки")
NotificationsOptions notificationsOptions;
NotificationsOptions notificationsOptions

@JsonProperty("logosConfig")
@JsonPropertyDescription("Конфигурация библиотеки logos. Применяется перед запуском каждой стадии сборки")
String logosConfig;
String logosConfig

@Override
@NonCPS
Expand All @@ -92,13 +93,13 @@ class JobConfiguration implements Serializable {
", resultsTransformOptions=" + resultsTransformOptions +
", notificationOptions=" + notificationsOptions +
", logosConfig='" + logosConfig + '\'' +
'}';
'}'
}

boolean infoBaseFromFiles() {
IStepExecutor steps = ContextRegistry.getContext().getStepExecutor()
def env = steps.env();
String branchName = env.BRANCH_NAME;
def env = steps.env()
String branchName = env.BRANCH_NAME
def initMethod = initInfoBaseOptions.initMethod

return (initMethod == InitInfoBaseMethod.FROM_SOURCE) ||
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package ru.pulsar.jenkins.library.configuration
import com.cloudbees.groovy.cps.NonCPS
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonPropertyDescription
import com.fasterxml.jackson.annotation.JsonProperty
import ru.pulsar.jenkins.library.configuration.sonarqube.GenericIssueFormat

@JsonIgnoreProperties(ignoreUnknown = true)
Expand All @@ -12,6 +13,7 @@ class ResultsTransformOptions implements Serializable {
Поддерживается stebi и edt-ripper.
По умолчанию содержит значение "stebi".
""")
@JsonProperty(defaultValue = "stebi")
ResultsTransformerType transformer = ResultsTransformerType.STEBI

@JsonPropertyDescription("Фильтровать замечания по уровню поддержки модуля. Только для stebi. По умолчанию включено.")
Expand All @@ -28,7 +30,8 @@ class ResultsTransformOptions implements Serializable {
Для SonarQube версии ниже 10.3 необходимо использовать Generic_Issue.
По умолчанию Generic_Issue_10_3
""")
GenericIssueFormat genericIssueFormat = GenericIssueFormat.GENERIC_ISSUE_10_3
@JsonProperty(defaultValue = "Generic_Issue_10_3")
GenericIssueFormat genericIssueFormat

@Override
@NonCPS
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package ru.pulsar.jenkins.library.configuration

import com.cloudbees.groovy.cps.NonCPS
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonPropertyDescription

@JsonIgnoreProperties(ignoreUnknown = true)
Expand All @@ -10,7 +11,7 @@ class SonarQubeOptions implements Serializable {
@JsonPropertyDescription(
"Имя настроенного SonarQube-сервера (SonarQube installations).\nЕсли настроен только один сервер, то может быть оставлено пустым."
)
String sonarQubeInstallation;
String sonarQubeInstallation

@JsonPropertyDescription("Использовать sonar-scanner, доступный в PATH")
Boolean useSonarScannerFromPath
Expand All @@ -30,6 +31,7 @@ class SonarQubeOptions implements Serializable {
* auto - применяется автоконфигурация sonar-scanner силами branchplugin. Так же может применяться для отключения конфигурирования, если branch plugin отсутствует;
* fromEnv - применяется ручная конфигурация sonar-scanner на основе переменных среды.
Значение по умолчанию: fromEnv.""")
@JsonProperty(defaultValue = "auto")
BranchAnalysisConfiguration branchAnalysisConfiguration

@JsonPropertyDescription("""Ожидать состояние Quality Gate от SonarQube после загрузки анализа. По умолчанию `false`.
Expand All @@ -47,6 +49,6 @@ class SonarQubeOptions implements Serializable {
", infoBaseUpdateModuleName='" + infoBaseUpdateModuleName + '\'' +
", branchAnalysisConfiguration='" + branchAnalysisConfiguration + '\'' +
", waitForQualityGate='" + waitForQualityGate + '\'' +
'}';
'}'
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package ru.pulsar.jenkins.library.configuration.sonarqube

import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonValue

enum GenericIssueFormat {
@JsonProperty("Generic_Issue")
Expand All @@ -16,7 +15,6 @@ enum GenericIssueFormat {
this.value = value
}


String getValue() {
return value
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ void testCreateJobConfigurationObject() throws IOException {

ResultsTransformOptions resultsTransformOptions = jobConfiguration.getResultsTransformOptions();
assertThat(resultsTransformOptions.getTransformer()).isEqualTo(ResultsTransformerType.STEBI);
assertThat(resultsTransformOptions.getGenericIssueFormat()).isEqualTo(GenericIssueFormat.GENERIC_ISSUE_10_3);
assertThat(resultsTransformOptions.getGenericIssueFormat()).isEqualTo(GenericIssueFormat.GENERIC_ISSUE);
assertThat(resultsTransformOptions.getRemoveSupport()).isFalse();
assertThat(resultsTransformOptions.getSupportLevel()).isZero();

Expand Down
2 changes: 1 addition & 1 deletion test/unit/resources/jobConfiguration.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
},
"resultsTransform": {
"transformer": "stebi",
"genericIssueFormat": "Generic_Issue_10_3",
"genericIssueFormat": "Generic_Issue",
"removeSupport": false
},
"smoke": {
Expand Down

0 comments on commit 571b37b

Please sign in to comment.