Skip to content

Add YAML support for configuration file format #1682

New issue

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

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

Already on GitHub? Sign in to your account

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ public class ProjectRequestDocument {

private String language;

private String configurationFileFormat;

private String packaging;

private String packageName;
Expand Down Expand Up @@ -116,6 +118,14 @@ public void setLanguage(String language) {
this.language = language;
}

public String getConfigurationFileFormat() {
return this.configurationFileFormat;
}

public void setConfigurationFileFormat(String configurationFileFormat) {
this.configurationFileFormat = configurationFileFormat;
}

public String getPackaging() {
return this.packaging;
}
Expand Down Expand Up @@ -177,6 +187,7 @@ public String toString() {
.add("artifactId='" + this.artifactId + "'")
.add("javaVersion='" + this.javaVersion + "'")
.add("language='" + this.language + "'")
.add("configurationFileFormat='" + this.configurationFileFormat + "'")
.add("packaging='" + this.packaging + "'")
.add("packageName='" + this.packageName + "'")
.add("version=" + this.version)
Expand Down Expand Up @@ -331,6 +342,8 @@ public static class ErrorStateInformation {

private Boolean language;

private Boolean configurationFileFormat;

private Boolean packaging;

private Boolean type;
Expand Down Expand Up @@ -359,6 +372,14 @@ public void setLanguage(Boolean language) {
this.language = language;
}

public Boolean getConfigurationFileFormat() {
return this.configurationFileFormat;
}

public void setConfigurationFileFormat(Boolean configurationFileFormat) {
this.configurationFileFormat = configurationFileFormat;
}

public Boolean getPackaging() {
return this.packaging;
}
Expand Down Expand Up @@ -396,6 +417,7 @@ public String toString() {
return new StringJoiner(", ", "{", "}").add("invalid=" + this.invalid)
.add("javaVersion=" + this.javaVersion)
.add("language=" + this.language)
.add("configurationFileFormat=" + this.configurationFileFormat)
.add("packaging=" + this.packaging)
.add("type=" + this.type)
.add("dependencies=" + this.dependencies)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,12 @@ public ProjectRequestDocument createDocument(ProjectRequestEvent event) {
document.triggerError().setLanguage(true);
}

document.setConfigurationFileFormat(request.getConfigurationFileFormat());
if (StringUtils.hasText(request.getConfigurationFileFormat())
&& metadata.getConfigurationFileFormats().get(request.getConfigurationFileFormat()) == null) {
document.triggerError().setConfigurationFileFormat(true);
}

document.setPackaging(request.getPackaging());
if (StringUtils.hasText(request.getPackaging())
&& metadata.getPackagings().get(request.getPackaging()) == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"artifactId": "test",
"javaVersion": "1.8",
"language": "java",
"configurationFileFormat": "properties",
"packaging": "jar",
"packageName": "com.example.acme.test",
"version": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"artifactId": "test",
"javaVersion": "1.2",
"language": "java",
"configurationFileFormat": "properties",
"packaging": "jar",
"packageName": "com.example.acme.test",
"version": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"artifactId": "test",
"javaVersion": "1.8",
"language": "c",
"configurationFileFormat": "properties",
"packaging": "jar",
"packageName": "com.example.acme.test",
"version": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"artifactId": "test",
"javaVersion": "1.8",
"language": "java",
"configurationFileFormat": "properties",
"packaging": "jar",
"packageName": "com.example.acme.test",
"version": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"artifactId": "test",
"javaVersion": "1.8",
"language": "java",
"configurationFileFormat": "properties",
"packaging": "jar",
"packageName": "com.example.acme.test",
"version": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"artifactId": "project",
"javaVersion": "1.8",
"language": "java",
"configurationFileFormat": "properties",
"packaging": "jar",
"packageName": "com.example.acme.project",
"version": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@
*/
public class ApplicationProperties {

private static final String YAML_SPACE = " ";

private final Map<String, Object> properties = new HashMap<>();

/**
Expand Down Expand Up @@ -73,6 +75,52 @@ void writeTo(PrintWriter writer) {
}
}

void writeYaml(PrintWriter writer) {
Map<String, Object> nested = flattenToNestedMap(this.properties);
writeYamlRecursive(nested, writer, 0);
}

private static Map<String, Object> flattenToNestedMap(Map<String, Object> flatMap) {
Map<String, Object> nested = new HashMap<>();
flatMap.forEach((key, value) -> {
String[] path = parseKeyPath(key);
insertValueAtPath(nested, path, value);
});
return nested;
}

private static String[] parseKeyPath(String key) {
return key.split("\\.");
}

@SuppressWarnings("unchecked")
private static void insertValueAtPath(Map<String, Object> map, String[] path, Object value) {
Map<String, Object> current = map;
for (int i = 0; i < path.length - 1; i++) {
String segment = path[i];
current = (Map<String, Object>) current.computeIfAbsent(segment, (k) -> new HashMap<>());
}
current.put(path[path.length - 1], value);
}

private static void writeYamlRecursive(Map<String, Object> map, PrintWriter writer, int indent) {
map.entrySet().forEach((entry) -> writeEntry(entry, writer, indent));
}

@SuppressWarnings("unchecked")
private static void writeEntry(Map.Entry<String, Object> entry, PrintWriter writer, int indent) {
String indentStr = YAML_SPACE.repeat(indent);
Object value = entry.getValue();

if (value instanceof Map<?, ?> nestedMap) {
writer.printf("%s%s:%n", indentStr, entry.getKey());
writeYamlRecursive((Map<String, Object>) nestedMap, writer, indent + 1);
}
else {
writer.printf("%s%s: %s%n", indentStr, entry.getKey(), value);
}
}

private void add(String key, Object value) {
Assert.state(!this.properties.containsKey(key), () -> "Property '%s' already exists".formatted(key));
this.properties.put(key, value);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@

package io.spring.initializr.generator.spring.properties;

import io.spring.initializr.generator.condition.ConditionalOnConfigurationFileFormat;
import io.spring.initializr.generator.configuration.format.properties.PropertiesFormat;
import io.spring.initializr.generator.configuration.format.yaml.YamlFormat;
import io.spring.initializr.generator.project.ProjectGenerationConfiguration;

import org.springframework.beans.factory.ObjectProvider;
Expand All @@ -37,8 +40,16 @@ ApplicationProperties applicationProperties(ObjectProvider<ApplicationProperties
}

@Bean
@ConditionalOnConfigurationFileFormat(PropertiesFormat.ID)
ApplicationPropertiesContributor applicationPropertiesContributor(ApplicationProperties applicationProperties) {
return new ApplicationPropertiesContributor(applicationProperties);
}

@Bean
@ConditionalOnConfigurationFileFormat(YamlFormat.ID)
ApplicationYamlPropertiesContributor applicationYamlPropertiesContributor(
ApplicationProperties applicationProperties) {
return new ApplicationYamlPropertiesContributor(applicationProperties);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Copyright 2012 - present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.spring.initializr.generator.spring.properties;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

import io.spring.initializr.generator.project.contributor.ProjectContributor;

/**
* A {@link ProjectContributor} that contributes a {@code application.yml} file to a
* project.
*
* @author Sijun Yang
*/
public class ApplicationYamlPropertiesContributor implements ProjectContributor {

private static final String FILE = "src/main/resources/application.yml";

private final ApplicationProperties properties;

public ApplicationYamlPropertiesContributor(ApplicationProperties properties) {
this.properties = properties;
}

@Override
public void contribute(Path projectRoot) throws IOException {
Path output = projectRoot.resolve(FILE);
if (!Files.exists(output)) {
Files.createDirectories(output.getParent());
Files.createFile(output);
}
try (PrintWriter writer = new PrintWriter(Files.newOutputStream(output, StandardOpenOption.APPEND), false,
StandardCharsets.UTF_8)) {
this.properties.writeYaml(writer);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
import io.spring.initializr.generator.buildsystem.BuildSystem;
import io.spring.initializr.generator.buildsystem.gradle.GradleBuildSystem;
import io.spring.initializr.generator.buildsystem.maven.MavenBuildSystem;
import io.spring.initializr.generator.configuration.format.properties.PropertiesFormat;
import io.spring.initializr.generator.configuration.format.yaml.YamlFormat;
import io.spring.initializr.generator.language.java.JavaLanguage;
import io.spring.initializr.generator.project.MutableProjectDescription;
import io.spring.initializr.generator.project.ProjectGenerationConfiguration;
Expand Down Expand Up @@ -80,10 +82,27 @@ void customBaseDirectoryIsUsedWhenGeneratingProject() {
"test/demo-app/src/test/java/com/example/demo/DemoApplicationTests.java", "test/demo-app/HELP.md");
}

@Test
void yaml() {
MutableProjectDescription description = initProjectDescription();
description.setBuildSystem(new MavenBuildSystem());
description.setBaseDirectory("test/demo-app");
description.setConfigurationFileFormat(new YamlFormat());
ProjectStructure project = this.projectTester.generate(description);
assertThat(project).filePaths()
.containsOnly("test/demo-app/.gitignore", "test/demo-app/.gitattributes", "test/demo-app/pom.xml",
"test/demo-app/mvnw", "test/demo-app/mvnw.cmd",
"test/demo-app/.mvn/wrapper/maven-wrapper.properties",
"test/demo-app/src/main/java/com/example/demo/DemoApplication.java",
"test/demo-app/src/main/resources/application.yml",
"test/demo-app/src/test/java/com/example/demo/DemoApplicationTests.java", "test/demo-app/HELP.md");
}

@Test
void generatedMavenProjectBuilds(@TempDir Path mavenHome) throws Exception {
MutableProjectDescription description = initProjectDescription();
description.setBuildSystem(new MavenBuildSystem());
description.setConfigurationFileFormat(new YamlFormat());
ProjectStructure project = this.projectTester.generate(description);
Path projectDirectory = project.getProjectDirectory();
runBuild(mavenHome, projectDirectory, description);
Expand Down Expand Up @@ -146,6 +165,7 @@ private MutableProjectDescription initProjectDescription() {
description.setApplicationName("DemoApplication");
description.setPlatformVersion(Version.parse(SpringBootVersion.getVersion()));
description.setLanguage(new JavaLanguage(JAVA_VERSION));
description.setConfigurationFileFormat(new PropertiesFormat());
description.setGroupId("com.example");
return description;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,7 @@ void currentGenerationJar(Language language) {
String.format("src/main/%s/com/example/demo/DemoApplication.%s", language.id(),
language.sourceFileExtension()),
String.format("src/test/%s/com/example/demo/DemoApplicationTests.%s", language.id(),
language.sourceFileExtension()),
"src/main/resources/application.properties");
language.sourceFileExtension()));
}

@ParameterizedTest
Expand All @@ -73,8 +72,7 @@ void currentGenerationWar(Language language) {
String.format("src/main/%s/com/example/demo/DemoApplication.%s", language.id(),
language.sourceFileExtension()),
String.format("src/test/%s/com/example/demo/DemoApplicationTests.%s", language.id(),
language.sourceFileExtension()),
"src/main/resources/application.properties");
language.sourceFileExtension()));
}

@ParameterizedTest
Expand Down
Loading