Merge pull request #223 from marhali/223-combat

223 combat
This commit is contained in:
Marcel 2023-02-19 15:38:19 +01:00 committed by GitHub
commit ce0b3d3e64
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 158 additions and 647 deletions

View File

@ -46,7 +46,7 @@ jobs:
# Validate wrapper
- name: Gradle Wrapper Validation
uses: gradle/wrapper-validation-action@v1.0.4
uses: gradle/wrapper-validation-action@v1.0.5
# Setup Java 11 environment for the next steps
- name: Setup Java
@ -77,7 +77,7 @@ jobs:
# Run tests
- name: Run Tests
run: ./gradlew test
run: ./gradlew check
# Collect Tests Result of failed tests
- name: Collect Tests Result
@ -87,6 +87,12 @@ jobs:
name: tests-result
path: ${{ github.workspace }}/build/reports/tests
# Upload Kover report to CodeCov
- name: Upload Code Coverage Report
uses: codecov/codecov-action@v3
with:
files: ${{ github.workspace }}/build/reports/kover/xml/report.xml
# Cache Plugin Verifier IDEs
- name: Setup Plugin Verifier IDEs Cache
uses: actions/cache@v3
@ -108,7 +114,7 @@ jobs:
# Run Qodana inspections
- name: Qodana - Code Inspection
uses: JetBrains/qodana-action@v2022.2.1
uses: JetBrains/qodana-action@v2022.2.3
# Prepare plugin archive content for creating artifact
- name: Prepare Plugin Artifact

View File

@ -77,6 +77,7 @@ jobs:
run: |
VERSION="${{ github.event.release.tag_name }}"
BRANCH="changelog-update-$VERSION"
LABEL="release changelog"
git config user.email "action@github.com"
git config user.name "GitHub Action"
@ -85,8 +86,12 @@ jobs:
git commit -am "Changelog update - $VERSION"
git push --set-upstream origin $BRANCH
gh label create "$LABEL" \
--description "Pull requests with release changelog update" \
|| true
gh pr create \
--title "Changelog update - \`$VERSION\`" \
--body "Current pull request contains patched \`CHANGELOG.md\` file for the \`$VERSION\` version." \
--base main \
--label "$LABEL" \
--head $BRANCH

View File

@ -48,7 +48,7 @@ jobs:
# Wait for IDEA to be started
- name: Health Check
uses: jtalk/url-health-check-action@v2
uses: jtalk/url-health-check-action@v3
with:
url: http://127.0.0.1:8082
max-attempts: 15

View File

@ -3,6 +3,16 @@
# easy-i18n Changelog
## [Unreleased]
### Changed
- Dropped support for IDE versions older than 2022.2
- Updated dependencies
- Removed deprecated API access (TranslatorToolWindowFactory)
- Replaced YAML mapping with own implementation
### Fixed
- Support for all 2023.1 builds (231.*)
- Exception on file change listener
- Broken badge link in README
## [4.4.0]
### Added

View File

@ -1,7 +1,7 @@
<div id="top"></div>
<!-- PROJECT SHIELDS -->
[![Build](https://img.shields.io/github/workflow/status/marhali/easy-i18n/Build?style=for-the-badge)](https://github.com/marhali/easy-i18n/actions)
[![Build](https://img.shields.io/github/actions/workflow/status/marhali/easy-i18n/build.yml?branch=main&style=for-the-badge)](https://github.com/marhali/easy-i18n/actions)
[![Version](https://img.shields.io/jetbrains/plugin/v/16316.svg?style=for-the-badge)](https://plugins.jetbrains.com/plugin/16316)
[![Downloads](https://img.shields.io/jetbrains/plugin/d/16316.svg?style=for-the-badge)](https://plugins.jetbrains.com/plugin/16316)
[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg?style=for-the-badge)](https://paypal.me/marhalide)

View File

@ -1,3 +1,4 @@
import org.jetbrains.changelog.Changelog
import org.jetbrains.changelog.markdownToHTML
fun properties(key: String) = project.findProperty(key).toString()
@ -6,13 +7,15 @@ plugins {
// Java support
id("java")
// Kotlin support
id("org.jetbrains.kotlin.jvm") version "1.7.10"
id("org.jetbrains.kotlin.jvm") version "1.7.21"
// Gradle IntelliJ Plugin
id("org.jetbrains.intellij") version "1.8.0"
id("org.jetbrains.intellij") version "1.13.0"
// Gradle Changelog Plugin
id("org.jetbrains.changelog") version "1.3.1"
id("org.jetbrains.changelog") version "2.0.0"
// Gradle Qodana Plugin
id("org.jetbrains.qodana") version "0.1.13"
// Gradle Kover Plugin
id("org.jetbrains.kotlinx.kover") version "0.6.1"
}
group = properties("pluginGroup")
@ -27,11 +30,9 @@ dependencies {
implementation("de.marhali:json5-java:2.0.0")
}
// Set the JVM language level used to compile sources and generate files - Java 11 is required since 2020.3
// Set the JVM language level used to build project. Use Java 11 for 2020.3+, and Java 17 for 2022.2+.
kotlin {
jvmToolchain {
languageVersion.set(JavaLanguageVersion.of(11))
}
jvmToolchain(17)
}
// Configure Gradle IntelliJ Plugin - read more: https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html
@ -46,18 +47,23 @@ intellij {
// Configure Gradle Changelog Plugin - read more: https://github.com/JetBrains/gradle-changelog-plugin
changelog {
version.set(properties("pluginVersion"))
groups.set(emptyList())
repositoryUrl.set(properties("pluginRepositoryUrl"))
}
// Configure Gradle Qodana Plugin - read more: https://github.com/JetBrains/gradle-qodana-plugin
qodana {
cachePath.set(projectDir.resolve(".qodana").canonicalPath)
reportPath.set(projectDir.resolve("build/reports/inspections").canonicalPath)
cachePath.set(file(".qodana").canonicalPath)
reportPath.set(file("build/reports/inspections").canonicalPath)
saveReport.set(true)
showReport.set(System.getenv("QODANA_SHOW_REPORT")?.toBoolean() ?: false)
}
// Configure Gradle Kover Plugin - read more: https://github.com/Kotlin/kotlinx-kover#configuration
kover.xmlReport {
onCheck.set(true)
}
tasks {
wrapper {
gradleVersion = properties("gradleVersion")
@ -70,22 +76,25 @@ tasks {
// Extract the <!-- Plugin description --> section from README.md and provide for the plugin's manifest
pluginDescription.set(
projectDir.resolve("README.md").readText().lines().run {
val start = "<!-- Plugin description -->"
val end = "<!-- Plugin description end -->"
file("README.md").readText().lines().run {
val start = "<!-- Plugin description -->"
val end = "<!-- Plugin description end -->"
if (!containsAll(listOf(start, end))) {
throw GradleException("Plugin description section not found in README.md:\n$start ... $end")
}
subList(indexOf(start) + 1, indexOf(end))
}.joinToString("\n").run { markdownToHTML(this) }
if (!containsAll(listOf(start, end))) {
throw GradleException("Plugin description section not found in README.md:\n$start ... $end")
}
subList(indexOf(start) + 1, indexOf(end))
}.joinToString("\n").let { markdownToHTML(it) }
)
// Get the latest available change notes from the changelog file
changeNotes.set(provider {
changelog.run {
getOrNull(properties("pluginVersion")) ?: getLatest()
}.toHTML()
with(changelog) {
renderItem(
getOrNull(properties("pluginVersion")) ?: getLatest(),
Changelog.OutputType.HTML,
)
}
})
}

View File

@ -1,28 +1,29 @@
# IntelliJ Platform Artifacts Repositories
# -> https://plugins.jetbrains.com/docs/intellij/intellij-artifacts.html
# IntelliJ Platform Artifacts Repositories -> https://plugins.jetbrains.com/docs/intellij/intellij-artifacts.html
pluginGroup = de.marhali.easyi18n
pluginName = easy-i18n
# SemVer format -> https://semver.org
pluginVersion = 4.4.0
pluginVersion = 4.4.1
# See https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
# for insight into build numbers and IntelliJ Platform versions.
pluginSinceBuild = 203
pluginUntilBuild = 223.*
pluginSinceBuild = 223
pluginUntilBuild = 231.*
# IntelliJ Platform Properties -> https://github.com/JetBrains/gradle-intellij-plugin#intellij-platform-properties
platformType = IU
platformVersion = 2022.2
platformVersion = 2022.3
# Plugin Dependencies -> https://plugins.jetbrains.com/docs/intellij/plugin-dependencies.html
# Example: platformPlugins = com.intellij.java, com.jetbrains.php:203.4449.22
platformPlugins = org.jetbrains.kotlin, JavaScriptLanguage, com.jetbrains.php:222.3345.118
platformPlugins = org.jetbrains.kotlin, JavaScript, com.jetbrains.php:223.7571.182
# Gradle Releases -> https://github.com/gradle/gradle/releases
gradleVersion = 7.5.1
# Opt-out flag for bundling Kotlin standard library.
# See https://plugins.jetbrains.com/docs/intellij/kotlin.html#kotlin-standard-library for details.
# Opt-out flag for bundling Kotlin standard library -> https://plugins.jetbrains.com/docs/intellij/kotlin.html#kotlin-standard-library
# suppress inspection "UnusedProperty"
kotlin.stdlib.default.dependency = false
# Enable Gradle Configuration Cache -> https://docs.gradle.org/current/userguide/configuration_cache.html
org.gradle.unsafe.configuration-cache = true

View File

@ -2,19 +2,16 @@ package de.marhali.easyi18n.io.parser.yaml;
import de.marhali.easyi18n.io.parser.ArrayMapper;
import thito.nodeflow.config.ListSection;
import java.util.ArrayList;
import java.util.List;
/**
* Map for yaml array values.
* @author marhali
*/
public class YamlArrayMapper extends ArrayMapper {
public static String read(ListSection list) {
public static String read(List<Object> list) {
return read(list.iterator(), Object::toString);
}
public static ListSection write(String concat) {
ListSection list = new ListSection();
public static List<Object> write(String concat) {
List<Object> list = new ArrayList<>();
write(concat, list::add);
return list;
}

View File

@ -7,31 +7,25 @@ import de.marhali.easyi18n.util.StringUtil;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.math.NumberUtils;
import thito.nodeflow.config.ListSection;
import thito.nodeflow.config.MapSection;
import thito.nodeflow.config.Section;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Mapper for mapping yaml files into translation nodes and backwards.
* @author marhali
*/
public class YamlMapper {
public static void read(String locale, Section section, TranslationNode node) {
for(String key : section.getKeys()) {
Object value = section.getInScope(key).get();
@SuppressWarnings("unchecked")
public static void read(String locale, Map<String, Object> section, TranslationNode node) {
for(String key : section.keySet()) {
Object value = section.get(key);
TranslationNode childNode = node.getOrCreateChildren(key);
if(value instanceof MapSection) {
// Nested element - run recursively
read(locale, (MapSection) value, childNode);
if(value instanceof Map) {
// Nested element run recursively
read(locale, (Map<String, Object>) value, childNode);
} else {
TranslationValue translation = childNode.getValue();
String content = value instanceof ListSection
? YamlArrayMapper.read((ListSection) value)
String content = value instanceof List
? YamlArrayMapper.read((List<Object>) value)
: StringUtil.escapeControls(String.valueOf(value), true);
translation.put(locale, content);
@ -40,17 +34,17 @@ public class YamlMapper {
}
}
public static void write(String locale, Section section, TranslationNode node) {
public static void write(String locale, Map<String, Object> section, TranslationNode node) {
for(Map.Entry<String, TranslationNode> entry : node.getChildren().entrySet()) {
String key = entry.getKey();
TranslationNode childNode = entry.getValue();
if(!childNode.isLeaf()) {
// Nested node - run recursively
MapSection childSection = new MapSection();
Map<String, Object> childSection = new HashMap<>();
write(locale, childSection, childNode);
if(childSection.size() > 0) {
section.setInScope(key, childSection);
section.put(key, childSection);
}
} else {
TranslationValue translation = childNode.getValue();
@ -58,11 +52,11 @@ public class YamlMapper {
if(content != null) {
if(YamlArrayMapper.isArray(content)) {
section.setInScope(key, YamlArrayMapper.write(content));
section.put(key, YamlArrayMapper.write(content));
} else if(NumberUtils.isNumber(content)) {
section.setInScope(key, NumberUtils.createNumber(content));
section.put(key, NumberUtils.createNumber(content));
} else {
section.setInScope(key, StringEscapeUtils.unescapeJava(content));
section.put(key, StringEscapeUtils.unescapeJava(content));
}
}
}

View File

@ -10,20 +10,32 @@ import de.marhali.easyi18n.model.TranslationNode;
import de.marhali.easyi18n.settings.ProjectSettings;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.error.YAMLException;
import thito.nodeflow.config.MapSection;
import thito.nodeflow.config.Section;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
/**
* Yaml / YML file format parser strategy.
* @author marhali
*/
public class YamlParserStrategy extends ParserStrategy {
private static DumperOptions dumperOptions() {
DumperOptions options = new DumperOptions();
options.setIndent(2);
options.setAllowUnicode(true);
options.setPrettyFlow(true);
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
return options;
}
private static final Yaml YAML = new Yaml(dumperOptions());
public YamlParserStrategy(@NotNull ProjectSettings settings) {
super(settings);
}
@ -36,11 +48,11 @@ public class YamlParserStrategy extends ParserStrategy {
TranslationNode targetNode = super.getOrCreateTargetNode(file, data);
try(Reader reader = new InputStreamReader(vf.getInputStream(), vf.getCharset())) {
Section input;
Map<String, Object> input;
try {
input = Section.parseToMap(reader);
} catch (YAMLException ex) {
input = YAML.load(reader);
} catch(YAMLException ex) {
throw new SyntaxException(ex.getMessage(), file);
}
@ -49,11 +61,12 @@ public class YamlParserStrategy extends ParserStrategy {
}
@Override
public @NotNull String write(@NotNull TranslationData data, @NotNull TranslationFile file) throws Exception {
public @Nullable String write(@NotNull TranslationData data, @NotNull TranslationFile file) throws Exception {
TranslationNode targetNode = super.getTargetNode(data, file);
Section output = new MapSection();
Map<String, Object> output = new HashMap<>();
YamlMapper.write(file.getLocale(), output, targetNode);
return Section.toString(output);
return YAML.dumpAsMap(output);
}
}

View File

@ -1,5 +1,6 @@
package de.marhali.easyi18n.service;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.AsyncFileListener;
@ -54,7 +55,9 @@ public class FileChangeListener implements AsyncFileListener {
events.forEach((e) -> {
if(e.getPath().contains(localesPath)) { // Perform reload
logger.debug("Detected file change. Reloading instance...");
InstanceManager.get(project).reload();
ApplicationManager.getApplication().invokeLater(() ->
InstanceManager.get(project).reload()
);
}
});
}

View File

@ -28,7 +28,7 @@ public class TranslatorToolWindowFactory implements ToolWindowFactory, DumbAware
@Override
public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) {
InstanceManager manager = InstanceManager.get(project);
ContentFactory contentFactory = ContentFactory.SERVICE.getInstance();
ContentFactory contentFactory = ContentFactory.getInstance();
// Translations tree view
TreeView treeView = new TreeView(project);

View File

@ -1,227 +0,0 @@
package thito.nodeflow.config;
import java.util.*;
import java.util.stream.*;
public class ListSection extends ArrayList<Object> implements Section {
private Section parent;
private String name;
public ListSection() {
super();
}
public ListSection(Collection<?> c) {
super();
addAll(c);
}
protected void setParent(Section parent, String name) {
this.parent = parent;
this.name = name;
}
@Override
public String getName() {
if (name == null && parent != null) {
if (parent instanceof ListSection) {
return String.valueOf(((ListSection) parent).indexOf(this));
}
if (parent instanceof MapSection) {
return ((MapSection) parent).entrySet().stream().filter(e -> Objects.equals(e.getValue(), this))
.findAny().map(Map.Entry::getKey).orElse(null);
}
}
return name;
}
public Optional<Object> getObject(int index) {
return index >= 0 && index < size() ? Optional.ofNullable(get(index)) : Optional.empty();
}
@Override
public Section getParent() {
return parent;
}
@Override
public Set<String> getKeys() {
return IntStream.range(0, size()).mapToObj(String::valueOf).collect(Collectors.toSet());
}
@Override
public Optional<?> getInScope(String key) {
try {
return Optional.ofNullable(get(Integer.parseInt(key)));
} catch (Throwable t) {
}
return Optional.empty();
}
@Override
public void setInScope(String key, Object value) {
try {
set(Integer.parseInt(key), value);
} catch (Throwable t) {
}
}
@Override
public Object set(int index, Object element) {
element = Section.wrap(element);
if (element instanceof Section) element = Section.wrapParent(this, null, (Section) element);
return super.set(index, element);
}
@Override
public boolean add(Object o) {
o = Section.wrap(o);
if (o instanceof Section) o = Section.wrapParent(this, null, (Section) o);
return super.add(o);
}
@Override
public void add(int index, Object element) {
element = Section.wrap(element);
if (element instanceof Section) element = Section.wrapParent(this, null, (Section) element);
super.add(index, element);
}
@Override
public boolean addAll(Collection<?> c) {
c.forEach(o -> add(o));
return !c.isEmpty();
}
@Override
public boolean addAll(int index, Collection<?> c) {
List<Object> wrapped = new ArrayList<>();
c.forEach(obj -> {
Object o = Section.wrap(obj);
if (o instanceof Section) o = Section.wrapParent(this, null, (Section) o);
wrapped.add(o);
});
return super.addAll(index, wrapped);
}
@Override
public String toString() {
return Section.toString(this);
}
public <T extends Enum<T>> Optional<T> getEnum(int index, Class<T> clz) {
return getObject(index).map(o -> {
try {
return Enum.valueOf(clz, String.valueOf(o));
} catch (Throwable t) {
return null;
}
});
}
public Optional<String> getString(int index) {
return getObject(index).map(String::valueOf);
}
public Optional<Integer> getInteger(int index) {
return getObject(index).map(o -> {
try {
return Integer.valueOf(String.valueOf(o));
} catch (Throwable t) {
return null;
}
});
}
public Optional<Double> getDouble(int index) {
return getObject(index).map(o -> {
try {
return Double.valueOf(String.valueOf(o));
} catch (Throwable t) {
return null;
}
});
}
public Optional<Long> getLong(int index) {
return getObject(index).map(o -> {
try {
return Long.valueOf(String.valueOf(o));
} catch (Throwable t) {
return null;
}
});
}
public Optional<Float> getFloat(int index) {
return getObject(index).map(o -> {
try {
return Float.valueOf(String.valueOf(o));
} catch (Throwable t) {
return null;
}
});
}
public Optional<Short> getShort(int index) {
return getObject(index).map(o -> {
try {
return Short.valueOf(String.valueOf(o));
} catch (Throwable t) {
return null;
}
});
}
public Optional<Byte> getByte(int index) {
return getObject(index).map(o -> {
try {
return Byte.valueOf(String.valueOf(o));
} catch (Throwable t) {
return null;
}
});
}
public Optional<Character> getCharacter(int index) {
return getObject(index).map(o -> {
String text = String.valueOf(o);
return text.isEmpty() ? null : text.charAt(0);
});
}
public Optional<Boolean> getBoolean(int index) {
return getObject(index).map(o -> {
String text = String.valueOf(o);
return text.equals("true") ? Boolean.TRUE : text.equals("false") ? Boolean.FALSE : null;
});
}
public Optional<MapSection> getMap(int index) {
return getObject(index).map(o -> {
if (o instanceof Map) {
if (o instanceof MapSection) return (MapSection) o;
MapSection mapSection = new MapSection((Map<?, ?>) o);
mapSection.setParent(this, null);
return mapSection;
}
return null;
});
}
public Optional<ListSection> getList(int index) {
return getObject(index).map(o -> {
if (o instanceof List) {
if (o instanceof ListSection) {
return (ListSection) o;
}
ListSection list = new ListSection((List<?>) o);
list.setParent(this, null);
return list;
}
ListSection list = new ListSection(Collections.singleton(o));
list.setParent(this, null);
return list;
});
}
}

View File

@ -1,78 +0,0 @@
package thito.nodeflow.config;
import org.jetbrains.annotations.Nullable;
import java.util.*;
public class MapSection extends HashMap<String, Object> implements Section {
private Section parent;
private String name;
public MapSection() {
super();
}
public MapSection(@Nullable Map<?, ?> m) {
super();
if(m != null) {
m.forEach((key, value) -> put(String.valueOf(key), value));
}
}
protected void setParent(Section parent, String name) {
this.parent = parent;
this.name = name;
}
@Override
public String getName() {
if (name == null && parent != null) {
if (parent instanceof ListSection) {
return String.valueOf(((ListSection) parent).indexOf(this));
}
if (parent instanceof MapSection) {
return ((MapSection) parent).entrySet().stream().filter(e -> Objects.equals(e.getValue(), this))
.findAny().map(Entry::getKey).orElse(null);
}
}
return name;
}
@Override
public Section getParent() {
return parent;
}
@Override
public void setInScope(String key, Object value) {
put(key, value);
}
@Override
public Object put(String key, Object value) {
value = Section.wrap(value);
if (value instanceof Section) value = Section.wrapParent(this, key, (Section) value);
return super.put(key, value);
}
@Override
public void putAll(Map<? extends String, ?> m) {
m.forEach(this::put);
}
@Override
public Set<String> getKeys() {
return keySet();
}
@Override
public Optional<?> getInScope(String key) {
return Optional.ofNullable(get(key));
}
@Override
public String toString() {
return Section.toString(this);
}
}

View File

@ -1,221 +0,0 @@
package thito.nodeflow.config;
import org.yaml.snakeyaml.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
public interface Section {
String SEPARATOR = ".";
static Object wrap(Object o) {
if (o instanceof Section) return o;
if (o instanceof List) {
return new ListSection((List<?>) o);
}
if (o instanceof Map) {
return new MapSection((Map<?, ?>) o);
}
return o;
}
static String getName(String path) {
String[] split = path.split(Pattern.quote(SEPARATOR));
return split[split.length - 1];
}
static Section wrapParent(Section parent, String name, Section current) {
if (current.getParent() != null && current.getParent() != parent) {
if (current instanceof MapSection) {
MapSection mapSection = new MapSection((MapSection) current);
mapSection.setParent(parent, name);
return mapSection;
}
if (current instanceof ListSection) {
ListSection objects = new ListSection((ListSection) current);
objects.setParent(parent, name);
return objects;
}
} else {
if (current instanceof MapSection) {
((MapSection) current).setParent(parent, name);
}
if (current instanceof ListSection) {
((ListSection) current).setParent(parent, name);
}
}
return current;
}
static String toString(Section section) {
DumperOptions options = new DumperOptions();
options.setIndent(2);
options.setAllowUnicode(true);
options.setPrettyFlow(true);
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(options);
return yaml.dumpAsMap(section);
}
static MapSection parseToMap(Reader reader) {
Yaml yaml = new Yaml();
return new MapSection(yaml.loadAs(reader, Map.class));
}
Set<String> getKeys();
default Set<String> getPaths() {
Set<String> paths = new HashSet<>();
for (String k : getKeys()) {
Object lookup = getInScope(k).orElse(null);
if (lookup instanceof Section) {
for (String p : ((Section) lookup).getPaths()) {
paths.add(k + "." + p);
}
}
}
return paths;
}
String getName();
default String getPath() {
StringBuilder path = new StringBuilder(getName());
Section parent;
while ((parent = getParent()) != null) {
path.insert(0, parent.getName() + SEPARATOR);
}
return path.toString();
}
Section getParent();
Optional<?> getInScope(String key);
void setInScope(String key, Object value);
default void set(String path, Object value) {
String[] paths = path.split(Pattern.quote(SEPARATOR));
Object lookup = this;
for (int i = 0; i < paths.length - 1; i++) {
Section oldLookup = (Section) lookup;
lookup = oldLookup.getInScope(paths[i]).orElse(null);
if (!(lookup instanceof Section)) {
oldLookup.setInScope(paths[i], lookup = new MapSection());
}
}
if (paths.length > 0) {
((Section) lookup).setInScope(paths[paths.length - 1], value);
}
}
default Optional<?> getObject(String path) {
String[] paths = path.split(Pattern.quote(SEPARATOR));
Object lookup = this;
for (String s : paths) {
if (lookup instanceof Section) {
lookup = ((Section) lookup).getInScope(s).orElse(null);
} else {
return Optional.empty();
}
}
return Optional.ofNullable(lookup);
}
default <T extends Enum<T>> Optional<T> getEnum(String path, Class<T> clz) {
return getObject(path).map(o -> {
try {
return Enum.valueOf(clz, String.valueOf(o));
} catch (Throwable t) {
return null;
}
});
}
default Optional<String> getString(String path) {
return getObject(path).map(String::valueOf);
}
default Optional<Integer> getInteger(String path) {
return getObject(path).map(o -> {
try {
return Integer.valueOf(String.valueOf(o));
} catch (Throwable t) {
return null;
}
});
}
default Optional<Double> getDouble(String path) {
return getObject(path).map(o -> {
try {
return Double.valueOf(String.valueOf(o));
} catch (Throwable t) {
return null;
}
});
}
default Optional<Long> getLong(String path) {
return getObject(path).map(o -> {
try {
return Long.valueOf(String.valueOf(o));
} catch (Throwable t) {
return null;
}
});
}
default Optional<Float> getFloat(String path) {
return getObject(path).map(o -> {
try {
return Float.valueOf(String.valueOf(o));
} catch (Throwable t) {
return null;
}
});
}
default Optional<Short> getShort(String path) {
return getObject(path).map(o -> {
try {
return Short.valueOf(String.valueOf(o));
} catch (Throwable t) {
return null;
}
});
}
default Optional<Byte> getByte(String path) {
return getObject(path).map(o -> {
try {
return Byte.valueOf(String.valueOf(o));
} catch (Throwable t) {
return null;
}
});
}
default Optional<Character> getCharacter(String path) {
return getObject(path).map(o -> {
String text = String.valueOf(o);
return text.isEmpty() ? null : text.charAt(0);
});
}
default Optional<Boolean> getBoolean(String path) {
return getObject(path).map(o -> {
String text = String.valueOf(o);
return text.equals("true") ? Boolean.TRUE : text.equals("false") ? Boolean.FALSE : null;
});
}
default Optional<MapSection> getMap(String path) {
return getObject(path).map(o -> {
if (o instanceof Map) {
if (o instanceof MapSection) return (MapSection) o;
MapSection mapSection = new MapSection((Map<?, ?>) o);
mapSection.setParent(this, Section.getName(path));
return mapSection;
}
return null;
});
}
default boolean isList(String path) {
Optional<?> o = getObject(path);
return o.isPresent() && o.get() instanceof List;
}
default Optional<ListSection> getList(String path) {
return getObject(path).map(o -> {
if (o instanceof List) {
if (o instanceof ListSection) {
return (ListSection) o;
}
ListSection list = new ListSection((List<?>) o);
list.setParent(this, Section.getName(path));
return list;
}
ListSection list = new ListSection(Collections.singleton(o));
list.setParent(this, Section.getName(path));
return list;
});
}
}

View File

@ -8,51 +8,47 @@ import org.apache.commons.lang.StringEscapeUtils;
import org.junit.Assert;
import thito.nodeflow.config.MapSection;
import thito.nodeflow.config.Section;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.*;
/**
* Unit tests for {@link YamlMapper}.
* @author marhali
*/
@SuppressWarnings("unchecked")
public class YamlMapperTest extends AbstractMapperTest {
@Override
public void testNonSorting() {
Section input = new MapSection();
input.set("zulu", "test");
input.set("alpha", "test");
input.set("bravo", "test");
Map<String, Object> input = new HashMap<>();
input.put("zulu", "test");
input.put("alpha", "test");
input.put("bravo", "test");
TranslationData data = new TranslationData(false);
YamlMapper.read("en", input, data.getRootNode());
Section output = new MapSection();
Map<String, Object> output = new HashMap<>();
YamlMapper.write("en", output, data.getRootNode());
Set<String> expect = new LinkedHashSet<>(Arrays.asList("zulu", "alpha", "bravo"));
Assert.assertEquals(expect, output.getKeys());
Assert.assertEquals(expect, output.keySet());
}
@Override
public void testSorting() {
Section input = new MapSection();
input.set("zulu", "test");
input.set("alpha", "test");
input.set("bravo", "test");
Map<String, Object> input = new HashMap<>();
input.put("zulu", "test");
input.put("alpha", "test");
input.put("bravo", "test");
TranslationData data = new TranslationData(true);
YamlMapper.read("en", input, data.getRootNode());
Section output = new MapSection();
Map<String, Object> output = new HashMap<>();
YamlMapper.write("en", output, data.getRootNode());
Set<String> expect = new LinkedHashSet<>(Arrays.asList("alpha", "bravo", "zulu"));
Assert.assertEquals(expect, output.getKeys());
Assert.assertEquals(expect, output.keySet());
}
@Override
@ -61,13 +57,13 @@ public class YamlMapperTest extends AbstractMapperTest {
data.setTranslation(new KeyPath("simple"), create(arraySimple));
data.setTranslation(new KeyPath("escaped"), create(arrayEscaped));
Section output = new MapSection();
Map<String, Object> output = new HashMap<>();
YamlMapper.write("en", output, data.getRootNode());
Assert.assertTrue(output.isList("simple"));
Assert.assertEquals(arraySimple, YamlArrayMapper.read(output.getList("simple").get()));
Assert.assertTrue(output.isList("escaped"));
Assert.assertEquals(arrayEscaped, StringEscapeUtils.unescapeJava(YamlArrayMapper.read(output.getList("escaped").get())));
Assert.assertTrue(output.get("simple") instanceof List);
Assert.assertEquals(arraySimple, YamlArrayMapper.read((List<Object>) output.get("simple")));
Assert.assertTrue(output.get("escaped") instanceof List);
Assert.assertEquals(arrayEscaped, StringEscapeUtils.unescapeJava(YamlArrayMapper.read((List<Object>) output.get("escaped"))));
TranslationData input = new TranslationData(true);
YamlMapper.read("en", output, input.getRootNode());
@ -81,10 +77,10 @@ public class YamlMapperTest extends AbstractMapperTest {
TranslationData data = new TranslationData(true);
data.setTranslation(new KeyPath("chars"), create(specialCharacters));
Section output = new MapSection();
Map<String, Object> output = new HashMap<>();
YamlMapper.write("en", output, data.getRootNode());
Assert.assertEquals(specialCharacters, output.getString("chars").get());
Assert.assertEquals(specialCharacters, output.get("chars"));
TranslationData input = new TranslationData(true);
YamlMapper.read("en", output, input.getRootNode());
@ -98,10 +94,13 @@ public class YamlMapperTest extends AbstractMapperTest {
TranslationData data = new TranslationData(true);
data.setTranslation(new KeyPath("nested", "key", "section"), create("test"));
Section output = new MapSection();
Map<String, Object> output = new HashMap<>();
YamlMapper.write("en", output, data.getRootNode());
Assert.assertEquals("test", output.getString("nested.key.section").get());
Assert.assertTrue(output.containsKey("nested"));
Assert.assertTrue(((Map<String, Object>) output.get("nested")).containsKey("key"));
Assert.assertEquals("test", ((Map)((Map)output.get("nested")).get("key")).get("section"));
TranslationData input = new TranslationData(true);
YamlMapper.read("en", output, input.getRootNode());
@ -114,10 +113,10 @@ public class YamlMapperTest extends AbstractMapperTest {
TranslationData data = new TranslationData(true);
data.setTranslation(new KeyPath("long.key.with.many.sections"), create("test"));
Section output = new MapSection();
Map<String, Object> output = new HashMap<>();
YamlMapper.write("en", output, data.getRootNode());
Assert.assertTrue(output.getKeys().contains("long.key.with.many.sections"));
Assert.assertTrue(output.containsKey("long.key.with.many.sections"));
TranslationData input = new TranslationData(true);
YamlMapper.read("en", output, input.getRootNode());
@ -130,10 +129,10 @@ public class YamlMapperTest extends AbstractMapperTest {
TranslationData data = new TranslationData(true);
data.setTranslation(new KeyPath("space"), create(leadingSpace));
Section output = new MapSection();
Map<String, Object> output = new HashMap<>();
YamlMapper.write("en", output, data.getRootNode());
Assert.assertEquals(leadingSpace, output.getString("space").get());
Assert.assertEquals(leadingSpace, output.get("space"));
TranslationData input = new TranslationData(true);
YamlMapper.read("en", output, input.getRootNode());
@ -146,13 +145,13 @@ public class YamlMapperTest extends AbstractMapperTest {
TranslationData data = new TranslationData(true);
data.setTranslation(new KeyPath("numbered"), create("15000"));
Section output = new MapSection();
Map<String, Object> output = new HashMap<>();
YamlMapper.write("en", output, data.getRootNode());
Assert.assertEquals(15000, output.getInteger("numbered").get().intValue());
Assert.assertEquals(15000, output.get("numbered"));
Section input = new MapSection();
input.set("numbered", 143.23);
Map<String, Object> input = new HashMap<>();
input.put("numbered", 143.23);
YamlMapper.read("en", input, data.getRootNode());
Assert.assertEquals("143.23", data.getTranslation(new KeyPath("numbered")).get("en"));