├── .github └── workflows │ ├── build.yml │ └── publish.yml ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── README_ZH.md ├── arts ├── prismconfig.png ├── prismconfig_square.png ├── prismconfig_title.png └── prismconfig_title_lowheight.png ├── build.gradle.kts ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src ├── main ├── java │ └── io │ │ └── github │ │ └── prismwork │ │ └── prismconfig │ │ ├── api │ │ ├── PrismConfig.java │ │ └── config │ │ │ ├── DefaultDeserializers.java │ │ │ └── DefaultSerializers.java │ │ └── impl │ │ ├── PrismConfigImpl.java │ │ └── config │ │ ├── DefaultDeserializersImpl.java │ │ └── DefaultSerializersImpl.java └── resources │ └── fabric.mod.json └── test └── java └── io └── github └── prismwork └── prismconfig └── test └── PrismConfigTest.java /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | on: [pull_request, push] 3 | 4 | jobs: 5 | build: 6 | strategy: 7 | matrix: 8 | # Use these Java versions 9 | java: [17] 10 | os: [ubuntu-latest] 11 | runs-on: ${{ matrix.os }} 12 | steps: 13 | - name: Checkout Repository 14 | uses: actions/checkout@v2 15 | - name: Validate Gradle Wrapper 16 | uses: gradle/wrapper-validation-action@v1 17 | - name: Setup JDK ${{ matrix.java }} 18 | uses: actions/setup-java@v1 19 | with: 20 | java-version: ${{ matrix.java }} 21 | - name: Make Gradle Wrapper Executable 22 | if: ${{ runner.os != 'Windows' }} 23 | run: chmod +x ./gradlew 24 | - name: Build 25 | run: ./gradlew build 26 | - name: Capture Build Artifacts 27 | if: ${{ runner.os == 'Linux' && matrix.java == '17' }} # Only upload artifacts built from latest java on one OS 28 | uses: actions/upload-artifact@v2 29 | with: 30 | name: Prism Config - Dev Build 31 | path: build/libs/ 32 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: publish 2 | on: 3 | push: 4 | paths: 5 | - 'gradle.properties' 6 | branches: 7 | - 'main' 8 | 9 | jobs: 10 | build: 11 | strategy: 12 | matrix: 13 | # Use these Java versions 14 | java: [17] 15 | os: [ubuntu-latest] 16 | runs-on: ${{ matrix.os }} 17 | steps: 18 | - name: Checkout Repository 19 | uses: actions/checkout@v2 20 | - name: Validate Gradle Wrapper 21 | uses: gradle/wrapper-validation-action@v1 22 | - name: Setup JDK ${{ matrix.java }} 23 | uses: actions/setup-java@v1 24 | with: 25 | java-version: ${{ matrix.java }} 26 | - name: Make Gradle Wrapper Executable 27 | if: ${{ runner.os != 'Windows' }} 28 | run: chmod +x ./gradlew 29 | - name: Get Project Version 30 | id: project_version 31 | run: grep "project_version" gradle.properties | sed "s/\s//g" >> $GITHUB_OUTPUT 32 | - name: Publish 33 | run: ./gradlew build publish 34 | env: 35 | MAVEN_USERNAME: ${{ secrets.MAVEN_USERNAME }} 36 | MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }} 37 | - name: Create Release 38 | id: create_release 39 | uses: actions/create-release@v1 40 | env: 41 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 42 | with: 43 | tag_name: ${{ steps.project_version.outputs.project_version }} 44 | release_name: Prism Config ${{ steps.project_version.outputs.project_version }} 45 | body_path: CHANGELOG.md 46 | draft: false 47 | prerelease: false 48 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /build/ 3 | 4 | # Ignore Gradle GUI config 5 | gradle-app.setting 6 | 7 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 8 | !gradle-wrapper.jar 9 | 10 | # Cache of project 11 | .gradletasknamecache 12 | 13 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 14 | # gradle/wrapper/gradle-wrapper.properties 15 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | * Added TOML (0.4.0) serializer/deserializer via toml4j, with comment support. 2 | * Optimized code structure 3 | * Improved Javadoc -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Prismwork 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | Icon 4 | 5 | ![java8](https://cdn.jsdelivr.net/npm/@intergrav/devins-badges@2/assets/cozy/built-with/java8_vector.svg) 6 | ![gradle](https://cdn.jsdelivr.net/npm/@intergrav/devins-badges@2/assets/cozy/built-with/gradle_vector.svg) 7 | [![Release](https://img.shields.io/github/v/release/Prismwork/PrismConfig?style=for-the-badge&include_prereleases&sort=semver)][releases] 8 | 9 | **English** | [简体中文](README_ZH.md) 10 | 11 | A lightweight config library for Java to let you write your config elegantly and flexibly. 12 | 13 |
14 | 15 | ### Getting Started 16 | 17 | To add Prism Config to your project, you need to add following into your `build.gradle(.kts)`: 18 | 19 | Groovy DSL: 20 | ```groovy 21 | repositories { 22 | // ... 23 | maven { 24 | name = "Nova Committee - Release" 25 | url = "https://maven.nova-committee.cn/releases/" 26 | } 27 | maven { 28 | name = "Nova Committee - Snapshot" 29 | url = "https://maven.nova-committee.cn/snapshots/" 30 | } 31 | } 32 | 33 | dependencies { 34 | // ... 35 | implementation "io.github.prismwork:prismconfig:0.2.0:all" 36 | // Or use the slim jar if you have the libraries included in your project (Gson, Jankson...) 37 | // implementation "io.github.prismwork:prismconfig:0.2.0" 38 | } 39 | ``` 40 | 41 | Kotlin DSL: 42 | ```kotlin 43 | repositories { 44 | // ... 45 | maven { 46 | name = "Nova Committee - Release" 47 | url = uri("https://maven.nova-committee.cn/releases/") 48 | } 49 | maven { 50 | name = "Nova Committee - Snapshot" 51 | url = uri("https://maven.nova-committee.cn/snapshots/") 52 | } 53 | } 54 | 55 | dependencies { 56 | // ... 57 | implementation("io.github.prismwork:prismconfig:0.2.0:all") 58 | // Or use the slim jar if you have the libraries included in your project (Gson, Jankson...) 59 | // implementation("io.github.prismwork:prismconfig:0.2.0") 60 | } 61 | ``` 62 | 63 | Prism Config by default provides serializers and deserializers for JSON (Gson), JSON5 (Jankson) and TOML 0.4.0 (toml4j). 64 | 65 | To parse a config from string into object, you can do this: 66 | 67 | ```java 68 | String content; 69 | MyConfig config = PrismConfig.getInstance().serialize( 70 | MyConfig.class, 71 | content, 72 | DefaultSerializers.getInstance().json5(MyConfig.class) // We assume that your config is written in JSON5 73 | ); 74 | ``` 75 | 76 | To parse a config from object into string, you can do this: 77 | 78 | ```java 79 | MyConfig content; 80 | String config = PrismConfig.getInstance().deserialize( 81 | MyConfig.class, 82 | content, 83 | DefaultDeserializers.getInstance().json5(MyConfig.class) // We assume that your config is written in JSON5 84 | ); 85 | ``` 86 | 87 | You can also write it to a file: 88 | 89 | ```java 90 | MyConfig content; 91 | File configFile; 92 | PrismConfig.getInstance().deserializeAndWrite( 93 | MyConfig.class, 94 | content, 95 | DefaultDeserializers.getInstance().json5(MyConfig.class), // We assume that your config is written in JSON5 96 | configFile 97 | ); 98 | ``` 99 | 100 | To write your own serializer/deserializer, you can use the following code (we use serializing as an example): 101 | 102 | ```java 103 | String content; 104 | PrismConfig.getInstance().serialize( 105 | MyConfig.class, 106 | content, 107 | (string) -> { 108 | // Do your own parsing here 109 | } 110 | ); 111 | ``` 112 | 113 | ### Libraries Used 114 | 115 | * [Jankson](https://github.com/falkreon/Jankson) by falkreon, licensed under MIT. 116 | * [Gson](https://github.com/google/gson) by Google, licensed under Apache-2.0. 117 | * [toml4j](https://github.com/mwanji/toml4j) by Moandji Ezana, licensed under MIT. 118 | 119 | ### Star History 120 | 121 | [![Star History Chart](https://api.star-history.com/svg?repos=Prismwork/PrismConfig&type=Date)](https://star-history.com/#Prismwork/PrismConfig) 122 | 123 | [releases]: https://github.com/Prismwork/PrismConfig/releases 124 | -------------------------------------------------------------------------------- /README_ZH.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | Icon 4 | 5 | ![java8](https://cdn.jsdelivr.net/npm/@intergrav/devins-badges@2/assets/cozy/built-with/java8_vector.svg) 6 | ![gradle](https://cdn.jsdelivr.net/npm/@intergrav/devins-badges@2/assets/cozy/built-with/gradle_vector.svg) 7 | [![Release](https://img.shields.io/github/v/release/Prismwork/PrismConfig?style=for-the-badge&include_prereleases&sort=semver)][releases] 8 | 9 | [English](README.md) | **简体中文** 10 | 11 | 让你能够高效且优雅地编写你的配置文件的轻量级配置库。 12 | 13 |
14 | 15 | ### 与我共舞 16 | 17 | 要将 Prism Config 加入你的项目,需要在你的 `build.gradle(.kts)` 中加入以下内容: 18 | 19 | Groovy DSL: 20 | ```groovy 21 | repositories { 22 | // ... 23 | maven { 24 | name = "Nova Committee - Release" 25 | url = "https://maven.nova-committee.cn/releases/" 26 | } 27 | maven { 28 | name = "Nova Committee - Snapshot" 29 | url = "https://maven.nova-committee.cn/snapshots/" 30 | } 31 | } 32 | 33 | dependencies { 34 | // ... 35 | implementation "io.github.prismwork:prismconfig:0.2.0:all" 36 | // 如果你已经在你的项目中包含了 Prism Config 所需要的库的话,也可以选用较小的 Jar。 (Gson, Jankson...) 37 | // implementation "io.github.prismwork:prismconfig:0.2.0" 38 | } 39 | ``` 40 | 41 | Kotlin DSL: 42 | ```kotlin 43 | repositories { 44 | // ... 45 | maven { 46 | name = "Nova Committee - Release" 47 | url = uri("https://maven.nova-committee.cn/releases/") 48 | } 49 | maven { 50 | name = "Nova Committee - Snapshot" 51 | url = uri("https://maven.nova-committee.cn/snapshots/") 52 | } 53 | } 54 | 55 | dependencies { 56 | // ... 57 | implementation("io.github.prismwork:prismconfig:0.2.0:all") 58 | // 如果你已经在你的项目中包含了 Prism Config 所需要的库的话,也可以选用较小的 Jar。 (Gson, Jankson...) 59 | // implementation("io.github.prismwork:prismconfig:0.2.0") 60 | } 61 | ``` 62 | 63 | Prism Config 默认提供了适用于 JSON (Gson),JSON5 (Jankson) 和 TOML 0.4.0 (toml4j) 的序列化器和反序列化器。 64 | 65 | 可以通过以下代码来实现把字符串转换成配置文件对象: 66 | 67 | ```java 68 | String content; 69 | MyConfig config = PrismConfig.getInstance().serialize( 70 | MyConfig.class, 71 | content, 72 | DefaultSerializers.getInstance().json5(MyConfig.class) // 我们假定你的配置文件是用 JSON5 编写的 73 | ); 74 | ``` 75 | 76 | 可以通过以下代码来实现把配置文件对象转换成字符串: 77 | 78 | ```java 79 | MyConfig content; 80 | String config = PrismConfig.getInstance().deserialize( 81 | MyConfig.class, 82 | content, 83 | DefaultDeserializers.getInstance().json5(MyConfig.class) // 我们假定你的配置文件是用 JSON5 编写的 84 | ); 85 | ``` 86 | 87 | 你也可以把它直接写入文件: 88 | 89 | ```java 90 | MyConfig content; 91 | File configFile; 92 | PrismConfig.getInstance().deserializeAndWrite( 93 | MyConfig.class, 94 | content, 95 | DefaultDeserializers.getInstance().json5(MyConfig.class), // 我们假定你的配置文件是用 JSON5 编写的 96 | configFile 97 | ); 98 | ``` 99 | 100 | 要编写你自己的序列化/反序列化器,你可以使用以下代码(我们以序列化为例): 101 | 102 | ```java 103 | String content; 104 | PrismConfig.getInstance().serialize( 105 | MyConfig.class, 106 | content, 107 | (string) -> { 108 | // 在此自行解析 109 | } 110 | ); 111 | ``` 112 | 113 | ### 使用的库 114 | 115 | * falkreon 制作的 [Jankson](https://github.com/falkreon/Jankson),以 MIT 协议开源。 116 | * Google 制作的 [Gson](https://github.com/google/gson),以 Apache-2.0 协议开源。 117 | * Moandji Ezana 制作的 [toml4j](https://github.com/mwanji/toml4j),以 MIT 协议开源。 118 | 119 | ### 星标历史 120 | 121 | [![Star History Chart](https://api.star-history.com/svg?repos=Prismwork/PrismConfig&type=Date)](https://star-history.com/#Prismwork/PrismConfig) 122 | 123 | [releases]: https://github.com/Prismwork/PrismConfig/releases -------------------------------------------------------------------------------- /arts/prismconfig.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Prismwork/PrismConfig/fdde17e0b7cf3b8d4bca9d25d593b643b0eb6c07/arts/prismconfig.png -------------------------------------------------------------------------------- /arts/prismconfig_square.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Prismwork/PrismConfig/fdde17e0b7cf3b8d4bca9d25d593b643b0eb6c07/arts/prismconfig_square.png -------------------------------------------------------------------------------- /arts/prismconfig_title.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Prismwork/PrismConfig/fdde17e0b7cf3b8d4bca9d25d593b643b0eb6c07/arts/prismconfig_title.png -------------------------------------------------------------------------------- /arts/prismconfig_title_lowheight.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Prismwork/PrismConfig/fdde17e0b7cf3b8d4bca9d25d593b643b0eb6c07/arts/prismconfig_title_lowheight.png -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar 2 | 3 | plugins { 4 | id("java") 5 | id("maven-publish") 6 | id("com.github.johnrengelman.shadow").version("7.1.2") 7 | id("com.modrinth.minotaur").version("2.+") 8 | } 9 | 10 | group = "io.github.prismwork" 11 | version = property("project_version")!! 12 | 13 | val include: Configuration by configurations.creating 14 | 15 | fun relocatePackage(name: String) : String { 16 | return "$group.prismconfig.libs.$name" 17 | } 18 | 19 | tasks.named("shadowJar") { 20 | from("LICENSE") 21 | configurations = listOf(include) 22 | relocate("blue.endless.jankson", relocatePackage("jankson")) 23 | relocate("com.google.gson", relocatePackage("gson")) 24 | relocate("com.moandjiezana.toml", relocatePackage("toml4j")) 25 | relocate("org.jetbrains.annotations", relocatePackage("jb.annotations")) 26 | relocate("org.intellij.lang.annotations", relocatePackage("ij.annotations")) 27 | } 28 | 29 | repositories { 30 | mavenCentral() 31 | maven { 32 | name = "QuiltMC Release" // quilt-json5, though unused 33 | url = uri("https://maven.quiltmc.org/repository/release/") 34 | } 35 | maven { 36 | name = "QuiltMC Snapshot" // quilt-json5, though unused 37 | url = uri("https://maven.quiltmc.org/repository/snapshot/") 38 | } 39 | maven { 40 | name = "unascribed" // kdl4j, though unused 41 | url = uri("https://repo.unascribed.com/") 42 | } 43 | } 44 | 45 | dependencies { 46 | /* Utilities */ 47 | include("org.jetbrains:annotations:23.1.0")?.let { implementation(it) } 48 | 49 | /* Serialization */ 50 | include("com.google.code.gson:gson:2.10")?.let { implementation(it) } 51 | include("blue.endless:jankson:1.2.1")?.let { implementation(it) } 52 | include("com.moandjiezana.toml:toml4j:0.7.2")?.let { implementation(it) } 53 | // include("org.yaml:snakeyaml:1.33")?.let { implementation(it) } 54 | // include("dev.hbeck.kdl:kdl4j:0.2.0")?.let { implementation(it) } 55 | // include("org.quiltmc:quilt-json5:1.0.2")?.let { implementation(it) } 56 | 57 | /* Test */ 58 | testImplementation("org.junit.jupiter:junit-jupiter-api:5.9.0") 59 | testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.9.0") 60 | } 61 | 62 | tasks.getByName("test") { 63 | useJUnitPlatform() 64 | } 65 | 66 | tasks.jar { 67 | from("LICENSE") 68 | finalizedBy(tasks.shadowJar) 69 | } 70 | 71 | tasks.processResources { 72 | inputs.property("version", project.version) 73 | 74 | filesMatching("fabric.mod.json") { 75 | expand(mutableMapOf("version" to project.version)) 76 | } 77 | } 78 | 79 | java { 80 | withSourcesJar() 81 | sourceCompatibility = JavaVersion.VERSION_1_8 82 | targetCompatibility = JavaVersion.VERSION_1_8 83 | } 84 | 85 | modrinth { 86 | token.set(System.getenv("MODRINTH_TOKEN")) 87 | projectId.set("prism-config") 88 | versionNumber.set("$version") 89 | versionName.set("Prism Config $version") 90 | versionType.set("release") 91 | uploadFile.set(tasks.shadowJar as Any) 92 | changelog.set(file("CHANGELOG.md").readText()) 93 | detectLoaders.set(false) 94 | gameVersions.addAll( 95 | "1.14", 96 | "1.14.1", 97 | "1.14.2", 98 | "1.14.3", 99 | "1.14.4", 100 | "1.15", 101 | "1.15.1", 102 | "1.15.2", 103 | "1.16", 104 | "1.16.1", 105 | "1.16.2", 106 | "1.16.3", 107 | "1.16.4", 108 | "1.16.5", 109 | "1.17", 110 | "1.17.1", 111 | "1.18", 112 | "1.18.1", 113 | "1.18.2", 114 | "1.19", 115 | "1.19.1", 116 | "1.19.2", 117 | "1.19.3" 118 | ) 119 | loaders.addAll("fabric", "forge", "quilt") 120 | } 121 | 122 | publishing { 123 | publications { 124 | create("prismconfig") { 125 | groupId = "$group" 126 | artifactId = name 127 | version = version 128 | 129 | from(components["java"]) 130 | } 131 | } 132 | 133 | repositories { 134 | mavenLocal() 135 | if (System.getenv("MAVEN_USERNAME") != null && System.getenv("MAVEN_PASSWORD") != null) { 136 | maven { 137 | name = "release" 138 | url = uri("https://maven.nova-committee.cn/releases") 139 | 140 | credentials { 141 | username = System.getenv("MAVEN_USERNAME") 142 | password = System.getenv("MAVEN_PASSWORD") 143 | } 144 | } 145 | maven { 146 | name = "snapshot" 147 | url = uri("https://maven.nova-committee.cn/snapshots") 148 | 149 | credentials { 150 | username = System.getenv("MAVEN_USERNAME") 151 | password = System.getenv("MAVEN_PASSWORD") 152 | } 153 | } 154 | } 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Only used for version bump so that we can tell GitHub Actions when to publish a new version 2 | project_version = 0.2.0 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Prismwork/PrismConfig/fdde17e0b7cf3b8d4bca9d25d593b643b0eb6c07/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | gradlePluginPortal() 4 | } 5 | } 6 | 7 | rootProject.name = "PrismConfig" 8 | 9 | -------------------------------------------------------------------------------- /src/main/java/io/github/prismwork/prismconfig/api/PrismConfig.java: -------------------------------------------------------------------------------- 1 | package io.github.prismwork.prismconfig.api; 2 | 3 | import io.github.prismwork.prismconfig.impl.PrismConfigImpl; 4 | import org.jetbrains.annotations.ApiStatus; 5 | import org.jetbrains.annotations.NotNull; 6 | 7 | import java.io.*; 8 | import java.lang.reflect.InvocationTargetException; 9 | import java.util.function.Function; 10 | 11 | /** 12 | * The core of Prism Config library, involving the basic config parse utilities. 13 | *

14 | * To work with it, you can get an instance via the {@code getInstance()} method: 15 | *

{@code
 16 |  * PrismConfig prism = PrismConfig.getInstance();
 17 |  * }
18 | * To parse a config, you may simply call the {@code serialize()} method (we assume that your config is written in JSON): 19 | *
{@code
 20 |  * String content;
 21 |  * MyConfig config = prism.serialize(MyConfig.class, content, DefaultSerializers.getInstance().json(MyConfig.class));
 22 |  * }
23 | * To convert a config instance to a string, you may simply call the {@code deserialize()} method (we assume that your config is written in JSON): 24 | *
{@code
 25 |  * MyConfig config;
 26 |  * String content = prism.deserialize(MyConfig.class, config, DefaultDeserializers.getInstance().json(MyConfig.class));
 27 |  * }
28 | * You can also make your own serializer/deserializer. For example: 29 | *
{@code
 30 |  * prism.serialize(MyConfig.class, content, (string) -> {
 31 |  *     // Implement your own serializing mechanics here
 32 |  * });
 33 |  * }
34 | * To serialize comments, Prism Config uses {@link blue.endless.jankson.Comment} from Jankson, 35 | * so if you want to make your own comment parser, you should use this as well. 36 | * 37 | * @since 0.1.0 38 | */ 39 | @SuppressWarnings("unused") 40 | public interface PrismConfig { 41 | /** 42 | * Lazily get the instance of {@link PrismConfig}. 43 | * 44 | * @return an instance of {@link PrismConfig}. 45 | * If the instance cache does not exist, it will try to create one. 46 | */ 47 | static PrismConfig getInstance() { 48 | if (PrismConfigImpl.INSTANCE_CACHE != null) { 49 | return PrismConfigImpl.INSTANCE_CACHE; 50 | } 51 | return new PrismConfigImpl(); 52 | } 53 | 54 | /** 55 | * Cast the given config content to an instance of the config whose type is specified by the "clazz" parameter and cache the serializer for the given type. 56 | * 57 | * @param clazz the class of the config instance type 58 | * @param content the content of the config as a string 59 | * @param serializer the serializer used to parse the config string 60 | * @param the type of the config instance 61 | * @return an instance of the config 62 | */ 63 | T serialize(Class clazz, String content, Function serializer); 64 | 65 | /** 66 | * Cast the given config content to an instance of the config whose type is specified by the "clazz" parameter and cache the serializer for the given type. 67 | * 68 | * @param clazz the class of the config instance type 69 | * @param file the content of the config as a file 70 | * @param serializer the serializer used to parse the config string 71 | * @param the type of the config instance 72 | * @return an instance of the config 73 | */ 74 | default T serialize(Class clazz, File file, Function serializer) { 75 | try (BufferedReader reader = new BufferedReader(new FileReader(file))) { 76 | String content = Utils.readFromFile(reader); 77 | return serialize(clazz, content, serializer); 78 | } catch (IOException e) { 79 | try { 80 | return clazz.getDeclaredConstructor().newInstance(); 81 | } catch (InvocationTargetException | 82 | InstantiationException | 83 | IllegalAccessException | 84 | NoSuchMethodException ex) { 85 | throw new RuntimeException("Failed to parse config", ex); 86 | } 87 | } 88 | } 89 | 90 | /** 91 | * Cast the given config content to an instance of the config whose type is specified by the "clazz" parameter, using the cached serializer. 92 | *

If the serializer for this class is not cached, a {@link RuntimeException} is thrown. 93 | * 94 | * @param clazz the class of the config instance type 95 | * @param content the content of the config as a string 96 | * @param the type of the config instance 97 | * @return an instance of the config 98 | */ 99 | T serializeCached(Class clazz, String content); 100 | 101 | /** 102 | * Cast the given config content to an instance of the config whose type is specified by the "clazz" parameter and cache the serializer for the given type. 103 | * 104 | * @param clazz the class of the config instance type 105 | * @param file the content of the config as a file 106 | * @param the type of the config instance 107 | * @return an instance of the config 108 | */ 109 | default T serializeCached(Class clazz, File file) { 110 | try (BufferedReader reader = new BufferedReader(new FileReader(file))) { 111 | String content = Utils.readFromFile(reader); 112 | return serializeCached(clazz, content); 113 | } catch (IOException e) { 114 | try { 115 | return clazz.getDeclaredConstructor().newInstance(); 116 | } catch (InvocationTargetException | 117 | InstantiationException | 118 | IllegalAccessException | 119 | NoSuchMethodException ex) { 120 | throw new RuntimeException("Failed to parse config", ex); 121 | } 122 | } 123 | } 124 | 125 | /** 126 | * Convert the given config instance to a string representing the config content and cache the deserializer for the given type. 127 | * 128 | * @param clazz the class of the config instance type 129 | * @param content the content of the config as an instance 130 | * @param deserializer the deserializer used to parse the config instance 131 | * @param the type of the config instance 132 | * @return the content of the config as a string 133 | */ 134 | String deserialize(Class clazz, T content, Function deserializer); 135 | 136 | /** 137 | * Convert the given config instance to a string representing the config content, using the cached deserializer. 138 | *

If the deserializer for this class is not cached, a {@link RuntimeException} is thrown. 139 | * 140 | * @param clazz the class of the config instance type 141 | * @param content the content of the config as an instance 142 | * @param the type of the config instance 143 | * @return the content of the config as a string 144 | */ 145 | String deserializeCached(Class clazz, T content); 146 | 147 | /** 148 | * Write the given config instance to the target file as a string representing the config content and cache the deserializer for the given type. 149 | * 150 | * @param clazz the class of the config instance type 151 | * @param content the content of the config as an instance 152 | * @param deserializer the deserializer used to parse the config instance 153 | * @param file the target file the config is written to 154 | * @param the type of the config instance 155 | */ 156 | default void deserializeAndWrite(Class clazz, T content, Function deserializer, File file) { 157 | String string = deserialize(clazz, content, deserializer); 158 | Utils.writeToConfigFile(file, string); 159 | } 160 | 161 | /** 162 | * Write the given config instance to the target file as a string representing the config content, using the cached deserializer. 163 | *

If the deserializer for this class is not cached, a {@link RuntimeException} is thrown. 164 | * 165 | * @param clazz the class of the config instance type 166 | * @param content the content of the config as an instance 167 | * @param file the target file the config is written to 168 | * @param the type of the config instance 169 | */ 170 | default void deserializeAndWriteCached(Class clazz, T content, File file) { 171 | String string = deserializeCached(clazz, content); 172 | Utils.writeToConfigFile(file, string); 173 | } 174 | 175 | @ApiStatus.Internal 176 | class Utils { 177 | private static @NotNull String readFromFile(@NotNull BufferedReader reader) throws IOException { 178 | StringBuilder stringBuilder = new StringBuilder(); 179 | String line; 180 | String ls = System.getProperty("line.separator"); 181 | while ((line = reader.readLine()) != null) { 182 | stringBuilder.append(line); 183 | stringBuilder.append(ls); 184 | } 185 | stringBuilder.deleteCharAt(stringBuilder.length() - 1); 186 | reader.close(); 187 | 188 | return stringBuilder.toString(); 189 | } 190 | 191 | private static void writeToConfigFile(@NotNull File file, String string) { 192 | if (!file.exists()) { 193 | try { 194 | file.createNewFile(); 195 | } catch (IOException e) { 196 | throw new RuntimeException("Failed to create file", e); 197 | } 198 | } 199 | try (FileWriter writer = new FileWriter(file)) { 200 | writer.write(""); // Empty the file 201 | writer.write(string); 202 | writer.flush(); 203 | } catch (IOException e) { 204 | throw new RuntimeException("Failed to write config"); 205 | } 206 | } 207 | } 208 | } 209 | -------------------------------------------------------------------------------- /src/main/java/io/github/prismwork/prismconfig/api/config/DefaultDeserializers.java: -------------------------------------------------------------------------------- 1 | package io.github.prismwork.prismconfig.api.config; 2 | 3 | import io.github.prismwork.prismconfig.impl.config.DefaultDeserializersImpl; 4 | 5 | import java.util.function.Function; 6 | 7 | /** 8 | * The default deserializers Prism Config provides. 9 | *

For now there are three: JSON, JSON5 and TOML (0.4.0). 10 | * 11 | * @since 0.1.0 12 | */ 13 | @SuppressWarnings("unused") 14 | public interface DefaultDeserializers { 15 | /** 16 | * Lazily get the instance of {@link DefaultDeserializers}. 17 | * 18 | * @return an instance of {@link DefaultDeserializers}. 19 | * If the instance cache does not exist, it will try to create one. 20 | */ 21 | static DefaultDeserializers getInstance() { 22 | if (DefaultDeserializersImpl.INSTANCE_CACHE != null) { 23 | return DefaultDeserializersImpl.INSTANCE_CACHE; 24 | } 25 | return new DefaultDeserializersImpl(); 26 | } 27 | 28 | /** 29 | * Returns a JSON deserializer for the given config class. 30 | * 31 | * @param clazz the config class the deserializer is going to handle 32 | * @param the type of the config class 33 | * @return the JSON deserializer for the given config class 34 | */ 35 | Function json(Class clazz); 36 | 37 | /** 38 | * Returns a JSON5 deserializer for the given config class. 39 | * 40 | * @param clazz the config class the deserializer is going to handle 41 | * @param the type of the config class 42 | * @return the JSON5 deserializer for the given config class 43 | */ 44 | Function json5(Class clazz); 45 | 46 | /** 47 | * Returns a TOML (0.4.0) deserializer for the given config class. 48 | * 49 | * @param clazz the config class the deserializer is going to handle 50 | * @param the type of the config class 51 | * @return the TOML deserializer for the given config class 52 | */ 53 | Function toml(Class clazz); 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/io/github/prismwork/prismconfig/api/config/DefaultSerializers.java: -------------------------------------------------------------------------------- 1 | package io.github.prismwork.prismconfig.api.config; 2 | 3 | import io.github.prismwork.prismconfig.impl.config.DefaultSerializersImpl; 4 | 5 | import java.util.function.Function; 6 | 7 | /** 8 | * The default serializers Prism Config provides. 9 | *

For now there are three: JSON, JSON5 and TOML (0.4.0). 10 | * 11 | * @since 0.1.0 12 | */ 13 | @SuppressWarnings("unused") 14 | public interface DefaultSerializers { 15 | /** 16 | * Lazily get the instance of {@link DefaultSerializers}. 17 | * 18 | * @return an instance of {@link DefaultSerializers}. 19 | * If the instance cache does not exist, it will try to create one. 20 | */ 21 | static DefaultSerializers getInstance() { 22 | if (DefaultSerializersImpl.INSTANCE_CACHE != null) { 23 | return DefaultSerializersImpl.INSTANCE_CACHE; 24 | } 25 | return new DefaultSerializersImpl(); 26 | } 27 | 28 | /** 29 | * Returns a JSON serializer for the given config class. 30 | * 31 | * @param clazz the config class the serializer is going to handle 32 | * @param the type of the config class 33 | * @return the JSON serializer for the given config class 34 | */ 35 | Function json(Class clazz); 36 | 37 | /** 38 | * Returns a JSON5 serializer for the given config class. 39 | * 40 | * @param clazz the config class the serializer is going to handle 41 | * @param the type of the config class 42 | * @return the JSON5 serializer for the given config class 43 | */ 44 | Function json5(Class clazz); 45 | 46 | /** 47 | * Returns a TOML (0.4.0) serializer for the given config class. 48 | * 49 | * @param clazz the config class the serializer is going to handle 50 | * @param the type of the config class 51 | * @return the TOML serializer for the given config class 52 | */ 53 | Function toml(Class clazz); 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/io/github/prismwork/prismconfig/impl/PrismConfigImpl.java: -------------------------------------------------------------------------------- 1 | package io.github.prismwork.prismconfig.impl; 2 | 3 | import io.github.prismwork.prismconfig.api.PrismConfig; 4 | import org.jetbrains.annotations.ApiStatus; 5 | import org.jetbrains.annotations.Nullable; 6 | 7 | import java.util.HashMap; 8 | import java.util.Map; 9 | import java.util.function.Function; 10 | 11 | @ApiStatus.Internal 12 | @SuppressWarnings("unchecked") 13 | public final class PrismConfigImpl implements PrismConfig { 14 | public static @Nullable PrismConfig INSTANCE_CACHE; 15 | 16 | private final Map, Function> cachedSerializers; 17 | private final Map, Function> cachedDeserializers; 18 | 19 | public PrismConfigImpl() { 20 | this.cachedSerializers = new HashMap<>(); 21 | this.cachedDeserializers = new HashMap<>(); 22 | PrismConfigImpl.INSTANCE_CACHE = this; 23 | } 24 | 25 | @Override 26 | public T serialize(Class clazz, String content, Function serializer) { 27 | if (!cachedSerializers.containsKey(clazz)) { 28 | cachedSerializers.put(clazz, (Function) serializer); 29 | } 30 | return serializer.apply(content); 31 | } 32 | 33 | @Override 34 | public T serializeCached(Class clazz, String content) { 35 | if (!cachedSerializers.containsKey(clazz)) throw new RuntimeException("Cached serializer not found"); 36 | return (T) cachedSerializers.get(clazz).apply(content); 37 | } 38 | 39 | @Override 40 | public String deserialize(Class clazz, T content, Function deserializer) { 41 | if (!cachedDeserializers.containsKey(clazz)) { 42 | cachedDeserializers.put(clazz, (Function) deserializer); 43 | } 44 | return deserializer.apply(content); 45 | } 46 | 47 | @Override 48 | public String deserializeCached(Class clazz, T content) { 49 | if (!cachedDeserializers.containsKey(clazz)) throw new RuntimeException("Cached deserializer not found"); 50 | return cachedDeserializers.get(clazz).apply(content); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/io/github/prismwork/prismconfig/impl/config/DefaultDeserializersImpl.java: -------------------------------------------------------------------------------- 1 | package io.github.prismwork.prismconfig.impl.config; 2 | 3 | import blue.endless.jankson.Comment; 4 | import blue.endless.jankson.Jankson; 5 | import com.google.gson.Gson; 6 | import com.google.gson.GsonBuilder; 7 | import com.moandjiezana.toml.TomlWriter; 8 | import io.github.prismwork.prismconfig.api.config.DefaultDeserializers; 9 | import org.jetbrains.annotations.ApiStatus; 10 | import org.jetbrains.annotations.Nullable; 11 | 12 | import java.lang.reflect.Field; 13 | import java.util.HashMap; 14 | import java.util.Map; 15 | import java.util.function.Function; 16 | 17 | @ApiStatus.Internal 18 | public final class DefaultDeserializersImpl implements DefaultDeserializers { 19 | public static @Nullable DefaultDeserializers INSTANCE_CACHE; 20 | 21 | private final Gson gson; 22 | private final Jankson jankson; 23 | private final TomlWriter toml; 24 | 25 | public DefaultDeserializersImpl() { 26 | this.gson = new GsonBuilder().setPrettyPrinting().create(); 27 | this.jankson = new Jankson.Builder().build(); 28 | this.toml = new TomlWriter.Builder().build(); 29 | DefaultDeserializersImpl.INSTANCE_CACHE = this; 30 | } 31 | 32 | @Override 33 | public Function json(Class clazz) { 34 | return gson::toJson; 35 | } 36 | 37 | @Override 38 | public Function json5(Class clazz) { 39 | return (config) -> jankson.toJson(config).toJson(true, true); 40 | } 41 | 42 | @Override 43 | public Function toml(Class clazz) { 44 | // toml4j does not support adding comments, so we will do our own, using the @Comment from Jankson 45 | return (config) -> { 46 | try { 47 | StringBuilder sb = new StringBuilder(); 48 | for (Field field : clazz.getDeclaredFields()) { 49 | field.setAccessible(true); // Make protected and private fields accessible 50 | if (field.isAnnotationPresent(Comment.class)) { 51 | sb.append("# ") 52 | .append(field.getDeclaredAnnotation(Comment.class).value()) 53 | .append("\n"); 54 | } 55 | Map map = new HashMap<>(); 56 | map.put(field.getName(), field.get(config)); 57 | sb.append(toml.write(map)); 58 | } 59 | return sb.toString(); 60 | } catch (IllegalAccessException e) { 61 | throw new RuntimeException(e); 62 | } 63 | }; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/io/github/prismwork/prismconfig/impl/config/DefaultSerializersImpl.java: -------------------------------------------------------------------------------- 1 | package io.github.prismwork.prismconfig.impl.config; 2 | 3 | import blue.endless.jankson.Jankson; 4 | import blue.endless.jankson.api.SyntaxError; 5 | import com.google.gson.Gson; 6 | import com.google.gson.GsonBuilder; 7 | import com.google.gson.JsonSyntaxException; 8 | import com.moandjiezana.toml.Toml; 9 | import io.github.prismwork.prismconfig.api.config.DefaultSerializers; 10 | import org.jetbrains.annotations.ApiStatus; 11 | import org.jetbrains.annotations.Nullable; 12 | 13 | import java.lang.reflect.InvocationTargetException; 14 | import java.util.function.Function; 15 | 16 | @ApiStatus.Internal 17 | public final class DefaultSerializersImpl implements DefaultSerializers { 18 | public static @Nullable DefaultSerializers INSTANCE_CACHE; 19 | 20 | private final Gson gson; 21 | private final Jankson jankson; 22 | private final Toml toml; 23 | 24 | public DefaultSerializersImpl() { 25 | this.gson = new GsonBuilder().setPrettyPrinting().create(); 26 | this.jankson = new Jankson.Builder().build(); 27 | this.toml = new Toml(); 28 | DefaultSerializersImpl.INSTANCE_CACHE = this; 29 | } 30 | 31 | @Override 32 | public Function json(Class clazz) { 33 | return (content) -> { 34 | try { 35 | T ret = gson.fromJson(content, clazz); 36 | if (ret == null) { 37 | return clazz.getDeclaredConstructor().newInstance(); 38 | } 39 | return ret; 40 | } catch (JsonSyntaxException | 41 | InvocationTargetException | 42 | InstantiationException | 43 | IllegalAccessException | 44 | NoSuchMethodException e) { 45 | throw new RuntimeException("Failed to parse JSON", e); 46 | } 47 | }; 48 | } 49 | 50 | @Override 51 | public Function json5(Class clazz) { 52 | return (content) -> { 53 | try { 54 | T ret = jankson.fromJson(content, clazz); 55 | if (ret == null) { 56 | return clazz.getDeclaredConstructor().newInstance(); 57 | } 58 | return ret; 59 | } catch (SyntaxError | 60 | InvocationTargetException | 61 | InstantiationException | 62 | IllegalAccessException | 63 | NoSuchMethodException e) { 64 | throw new RuntimeException("Failed to parse JSON5", e); 65 | } 66 | }; 67 | } 68 | 69 | @Override 70 | public Function toml(Class clazz) { 71 | return (content) -> { 72 | try { 73 | T ret = toml.read(content).to(clazz); 74 | if (ret == null) { 75 | return clazz.getDeclaredConstructor().newInstance(); 76 | } 77 | return ret; 78 | } catch (InvocationTargetException | 79 | InstantiationException | 80 | IllegalAccessException | 81 | IllegalStateException | 82 | NoSuchMethodException e) { 83 | throw new RuntimeException("Failed to parse TOML", e); 84 | } 85 | }; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/resources/fabric.mod.json: -------------------------------------------------------------------------------- 1 | { 2 | "schemaVersion": 1, 3 | "id": "prismconfig", 4 | "version": "${version}", 5 | "name": "Prism Config", 6 | "description": "A lightweight config library for Java to let you write your config elegantly and flexibly.", 7 | "authors": [ 8 | "Prismwork" 9 | ], 10 | "contact": { 11 | "homepage": "https://github.com/Prismwork/", 12 | "sources": "https://github.com/Prismwork/PrismConfig" 13 | }, 14 | "license": "MIT", 15 | "environment": "*" 16 | } -------------------------------------------------------------------------------- /src/test/java/io/github/prismwork/prismconfig/test/PrismConfigTest.java: -------------------------------------------------------------------------------- 1 | package io.github.prismwork.prismconfig.test; 2 | 3 | import blue.endless.jankson.Comment; 4 | import io.github.prismwork.prismconfig.api.PrismConfig; 5 | import io.github.prismwork.prismconfig.api.config.DefaultDeserializers; 6 | import io.github.prismwork.prismconfig.api.config.DefaultSerializers; 7 | import org.junit.jupiter.api.Test; 8 | 9 | import java.io.*; 10 | 11 | public class PrismConfigTest { 12 | @Test 13 | void testConfig() { 14 | File configFile = new File("config.json"); 15 | if (!configFile.exists()) { 16 | try { 17 | configFile.createNewFile(); 18 | } catch (IOException e) { 19 | throw new RuntimeException(e); 20 | } 21 | } 22 | try (BufferedReader reader = new BufferedReader(new FileReader(configFile));) { 23 | StringBuilder stringBuilder = new StringBuilder(); 24 | String line; 25 | String ls = System.getProperty("line.separator"); 26 | while ((line = reader.readLine()) != null) { 27 | stringBuilder.append(line); 28 | stringBuilder.append(ls); 29 | } 30 | // stringBuilder.deleteCharAt(stringBuilder.length() - 1); 31 | reader.close(); 32 | 33 | String content = stringBuilder.toString(); 34 | TestConfig config = PrismConfig.getInstance().serialize( 35 | TestConfig.class, 36 | content, 37 | DefaultSerializers.getInstance().json(TestConfig.class) 38 | ); 39 | System.out.println(config.string); 40 | } catch (IOException e) { 41 | throw new RuntimeException(e); 42 | } 43 | 44 | File configFile1 = new File("config1.json5"); 45 | if (!configFile1.exists()) { 46 | try { 47 | configFile1.createNewFile(); 48 | } catch (IOException e) { 49 | throw new RuntimeException(e); 50 | } 51 | } 52 | TestConfig config1 = new TestConfig(); 53 | PrismConfig.getInstance().deserializeAndWrite( 54 | TestConfig.class, 55 | config1, 56 | DefaultDeserializers.getInstance().json5(TestConfig.class), 57 | configFile1 58 | ); 59 | 60 | TestConfig config2 = PrismConfig.getInstance().serialize( 61 | TestConfig.class, 62 | configFile1, 63 | DefaultSerializers.getInstance().json5(TestConfig.class) 64 | ); 65 | System.out.println(config2.bool1); 66 | 67 | File configFile2 = new File("config2.toml"); 68 | if (!configFile2.exists()) { 69 | try { 70 | configFile2.createNewFile(); 71 | } catch (IOException e) { 72 | throw new RuntimeException(e); 73 | } 74 | } 75 | PrismConfig.getInstance().deserializeAndWrite( 76 | TestConfig.class, 77 | config2, 78 | DefaultDeserializers.getInstance().toml(TestConfig.class), 79 | configFile2 80 | ); 81 | System.out.println(PrismConfig.getInstance().serialize( 82 | TestConfig.class, 83 | configFile2, 84 | DefaultSerializers.getInstance().toml(TestConfig.class) 85 | ).nested.hello); 86 | } 87 | 88 | public static class TestConfig { 89 | public boolean bool1 = false; 90 | public boolean bool2 = true; 91 | @Comment("Hello from comment") 92 | public String string = "Hi"; 93 | public SimpleNested nested = new SimpleNested(); 94 | 95 | public static class SimpleNested { 96 | public String hello = "Hello from nested"; 97 | public int number = 114514; 98 | } 99 | } 100 | } 101 | --------------------------------------------------------------------------------