Skip to content

Commit

Permalink
Merge pull request #3 from TheProgramSrc/feat/main-color
Browse files Browse the repository at this point in the history
  • Loading branch information
Francisco Solis authored Feb 24, 2022
2 parents 32279c1 + 4c71b8f commit 45330f6
Show file tree
Hide file tree
Showing 9 changed files with 222 additions and 113 deletions.
5 changes: 5 additions & 0 deletions .github/workflows/gradle-build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ jobs:
with:
name: TranslationsModule
path: ./build/libs/TranslationsModule-${{ env.VERSION }}.jar
# Here we upload the binary to the release
- name: Upload to release
uses: JasonEtco/upload-to-release@master
with:
args: ./build/libs/TranslationsModule-${{ env.VERSION }}.jar application/java-archive
# Now we deploy the documents to GitHub pages
- name: Deploy Dokka
uses: JamesIves/[email protected]
Expand Down
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
# v0.1.3 - Snapshot
* Moved Translation from objects/
* Added new register methods to TranslationManager
* Added mainColor to Translation
* Now Translation can be automatically registered!
* Removed TranslationManagerTest.kt
* Created new Tests (TranslationColorTest.kt and TranslationTest.kt)
* Now the Jar is automatically uploaded to the release!

# v0.1.2 - Snapshots
* Fixed dependency FilesModule

Expand Down
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ plugins {
id 'org.jetbrains.dokka' version '1.6.0'
}

def projectVersion = (System.getenv("VERSION") ?: '0.1.2-SNAPSHOT').replaceFirst("v", "").replace('/', '')
def projectVersion = (System.getenv("VERSION") ?: '0.1.3-SNAPSHOT').replaceFirst("v", "").replace('/', '')

group 'xyz.theprogramsrc'
version projectVersion
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package xyz.theprogramsrc.translationsmodule

import xyz.theprogramsrc.filesmodule.config.YmlConfig
import xyz.theprogramsrc.filesmodule.utils.folder
import java.io.File

/**
* Representation of a translation.
* @param id The id of the translation
* @param defaultValue The default value of the translation.
* @param group The group (folder) of the translation. Defaults to "common"
* @param language The language of the translation. (Defaults to "en")
* @param mainColor The main color of the translation. (Defaults to null)
* @param colors The colors to use in the translation replacing strings. Example (using color '&c'): '**test**' should return '&ctest'. Defaults to empty array.
* @param autoRegister If the translation should be automatically registered. (Defaults to true) It is recommended to disable if you're going to initialize the same translation multiple times (for example inside a loop)
*/
data class Translation(
val id: String,
val defaultValue: String,
val group: String = "common",
val language: String = "en",
val mainColor: String? = null,
val colors: Array<String> = emptyArray(),
val autoRegister: Boolean = true
) {

init {
if(autoRegister) {
TranslationManager.instance.registerTranslations(group, this)
}
}

/**
* Translates this [Translation] to the current language.
* @param language The language of the translation. Set to null to use the default language. Defaults to null
* @param placeholders The placeholders to use in the translation replacing strings. Example (using placeholder id 'test' and value 'test_value'): '{test}' should return 'test_value'.
* You can use '{}' or '%%' as placeholder identifiers like '{test}' or '%test%'. Defaults to empty map.
* @return The translated string.
*/
fun translate(language: String? = null, placeholders: Map<String, String> = emptyMap()): String {
val file = YmlConfig(File(File("translations/${if(group.endsWith("/")) group else "$group/"}").folder(), (language ?: TranslationManager.getCurrentLanguage()) + ".lang")) // Get the file of the translation
val mainColor = this.mainColor ?: "" // Get the main color of the translation
var translation = mainColor.plus(
if(file.has(id)) { // If the translation exists
file.getString(id) // Get the translation from the file
} else { // If the translation doesn't exist
defaultValue // Get the default value
}
)
for(i in colors.indices) { // For each color
try {
val color = colors[i] // Get the color
val string = Regex("\\*\\*(.+?)\\*\\*").findAll(translation).first().groupValues[1] // Get the string to replace
translation = translation.replaceFirst("**$string**", "$color$string$mainColor") // Replace the first match with the colorized string
}catch (_: Exception){} // Ignore errors
}

placeholders.forEach { (key, value) -> // For each placeholder
translation = translation.replace("{$key}", value).replace("%$key%", value) // Replace the placeholder using %% and {}
}

return translation // Return the translated string
}

override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false

other as Translation

if (id != other.id) return false
if (defaultValue != other.defaultValue) return false
if (!colors.contentEquals(other.colors)) return false
if (group != other.group) return false
if (language != other.language) return false
if (mainColor != other.mainColor) return false
if (autoRegister != other.autoRegister) return false

return true
}

override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + defaultValue.hashCode()
result = 31 * result + colors.contentHashCode()
result = 31 * result + group.hashCode()
result = 31 * result + language.hashCode()
result = 31 * result + (mainColor?.hashCode() ?: 0)
result = 31 * result + autoRegister.hashCode()
return result
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package xyz.theprogramsrc.translationsmodule

import xyz.theprogramsrc.filesmodule.config.YmlConfig
import xyz.theprogramsrc.filesmodule.utils.folder
import xyz.theprogramsrc.translationsmodule.objects.Translation
import java.io.File

/**
Expand All @@ -16,6 +15,7 @@ class TranslationManager {
companion object {
private val translationSettings = YmlConfig(File(File("plugins/SimpleCoreAPI").folder(), "TranslationSettings.yml")).add("language", "en")
lateinit var instance: TranslationManager
private set

fun getCurrentLanguage(): String = translationSettings.getStringOrSet("language", "en")
}
Expand All @@ -25,6 +25,20 @@ class TranslationManager {
loadTranslations()
}

/**
* Register the given translations to the given group id
* @param group The group (folder) of the translation. Defaults to "common"
* @param translation The translations to register
*/
fun registerTranslation(group: String = "common", translation: Translation) = this.registerTranslations(group, listOf(translation))

/**
* Register the given translations to the given group id
* @param group The group (folder) of the translation. Defaults to "common"
* @param translations The translations to register
*/
fun registerTranslations(group: String = "common", vararg translations: Translation) = this.registerTranslations(group, translations.toList())

/**
* Register the given translations to the given group id
* @param group The group (folder) of the translation. Defaults to "common"
Expand Down Expand Up @@ -81,7 +95,7 @@ class TranslationManager {
cfg.keys(true).forEach { id ->
val t = translationsCache[groupFolder.name]?.find { t1 -> t1.id == id }
if(t != null){
langCache[id] = t.translate(groupFolder.name, it.nameWithoutExtension)
langCache[id] = t.translate(it.nameWithoutExtension)
}
}
if(langCache.isNotEmpty()){
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package xyz.theprogramsrc.translationsmodule

import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.Test

internal class TranslationColorTest {

companion object {
@BeforeAll
@JvmStatic
fun setUp() {
TranslationManager()
}

}

@Test
fun testMainColorTranslation(){
val translation = Translation(
id = "identifier",
defaultValue = "defaultValue",
mainColor = "&7"
)
assertEquals("&7defaultValue", translation.translate())
}

@Test
fun testMainColorWithColorizedText(){
val translation = Translation(
id = "identifier2",
defaultValue = "defaultValue is **colorized**.",
colors = arrayOf("&c"),
mainColor = "&7"
)
assertEquals("&7defaultValue is &ccolorized&7.", translation.translate())
}

@Test
fun testMainColorWithMultipleColorizedTexts(){
val translation = Translation(
id = "identifier3",
defaultValue = "defaultValue is **colorized** and **colorized**.",
colors = arrayOf("&c", "&a"),
mainColor = "&7"
)
assertEquals("&7defaultValue is &ccolorized&7 and &acolorized&7.", translation.translate())

}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package xyz.theprogramsrc.translationsmodule

import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import java.io.File

internal class TranslationTest {

companion object {
@BeforeAll
@JvmStatic
fun setUp() {
TranslationManager()
}
}

@BeforeEach
fun beforeEach() {
File("translations").deleteRecursively()
}

@Test
fun testAutoRegister() {
val translation = Translation(
id = "identifier",
defaultValue = "defaultValue",
)
val folder = File("translations/${translation.group}")
val file = File(folder, "${translation.language}.lang")
assertTrue(file.exists())
}

@Test
fun testManualRegistration() {
val translation = Translation(
id = "identifier2",
defaultValue = "defaultValue",
autoRegister = false,
)
val folder = File("translations/${translation.group}")
val file = File(folder, "${translation.language}.lang")
assertFalse(file.exists())
TranslationManager.instance.registerTranslation(translation = translation)
assertTrue(file.exists())
}
}

0 comments on commit 45330f6

Please sign in to comment.