Skip to content

Commit

Permalink
Merge pull request #100 from wuseal/fix/issue89
Browse files Browse the repository at this point in the history
Fix issue #89
  • Loading branch information
kezhenxu94 authored Jan 12, 2019
2 parents 0eed657 + 2eea66e commit 07e3748
Show file tree
Hide file tree
Showing 7 changed files with 140 additions and 33 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ object KClassName : KName(), IKClassName {
/**
* keep " " character
*/
val pattern = "$illegalCharacter".replace(Regex(nameSeparator.toString()), "")
val pattern = illegalCharacter.toMutableList().apply { removeAll(nameSeparator) }.toRegex()

val temp = rawClassName.replace(Regex(pattern), "").let {
val temp = rawClassName.replace(pattern, "").let {

return@let removeStartNumberAndIllegalCharacter(it)

Expand All @@ -57,7 +57,7 @@ object KClassName : KName(), IKClassName {

val stringBuilder = StringBuilder()

temp.split(Regex(nameSeparator.toString())).forEach {
temp.split(nameSeparator.toRegex()).forEach {
if (it.isNotBlank()) {
stringBuilder.append(it.substring(0, 1).toUpperCase().plus(it.substring(1)))
}
Expand Down
26 changes: 14 additions & 12 deletions src/main/kotlin/wu/seal/jsontokotlin/codeelements/KName.kt
Original file line number Diff line number Diff line change
Expand Up @@ -23,33 +23,29 @@ abstract class KName : IKName {


protected val illegalCharacter = listOf<String>(
"\\+", "\\-", "\\*", "/", "%", "=", "&", "|", "!", "\\[", "\\]", "\\{", "\\}", "\\(", "\\)", "\\\\", "\"", "_"
, ",", ".", ":", "\\?", "\\>", "\\<", "@", ";", "'", "\\`", "\\~", "\\$", "^", "#", "\\", "/", " ", "\t", "\n"
"\\+", "\\-", "\\*", "/", "%", "=", "&", "\\|", "!", "\\[", "\\]", "\\{", "\\}", "\\(", "\\)", "\\\\", "\"", "_"
, ",", "\\.", ":", "\\?", "\\>", "\\<", "@", ";", "'", "\\`", "\\~", "\\$", "\\^", "#", "\\", "/", " ", "\t", "\n"
)


protected val nameSeparator = listOf<String>(" ", "_", "-")
protected val nameSeparator = listOf<String>(" ", "_", "\\-", ":")


/**
* remove the start number or whiteSpace characters in this string
*/
protected fun removeStartNumberAndIllegalCharacter(it: String): String {

return if (it.replace(Regex(illegalCharacter.toString()), "").indexOfFirst {
return@indexOfFirst it in '0'..'9'
} == 0) {
val numberAndIllegalCharacters = listOf<String>(*illegalCharacter.toTypedArray(), "\\d")

val numberAndIllegalCharacters = listOf<String>(*illegalCharacter.toTypedArray(), "\\d")
val firstNumberAndIllegalCharactersRegex = "^(${numberAndIllegalCharacters.toRegex()})+".toRegex()

return it.trim().replaceFirst(firstNumberAndIllegalCharactersRegex, "")

it.trim().replaceFirst(Regex("${numberAndIllegalCharacters.toString().trim()}{1,}"), "")
} else {
it
}
}

protected fun toBeLegalName(name: String): String {
val tempName = name.replace(illegalCharacter.toString(), "")
val tempName = name.replace(illegalCharacter.toRegex(), "")

val legalName = if (tempName in illegalNameList) {
tempName + suffix
Expand All @@ -59,4 +55,10 @@ abstract class KName : IKName {
return legalName
}

/**
* array string into regex match patten that could match any element of the array
*/
protected fun Iterable<String>.toRegex() = joinToString(separator = "|").toRegex()


}
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@ object KPropertyName : KName(), IPropertyNameMaker {
/**
* keep nameSeparator character
*/
val pattern = "${illegalCharacter}".replace(Regex(nameSeparator.toString()), "")
val pattern = illegalCharacter.toMutableList().apply { removeAll(nameSeparator) }.toRegex()

val temp = rawString.replace(Regex(pattern), "").let {
val temp = rawString.replace(pattern, "").let {

return@let removeStartNumberAndIllegalCharacter(it)

Expand All @@ -77,7 +77,7 @@ object KPropertyName : KName(), IPropertyNameMaker {

val stringBuilder = StringBuilder()

temp.split(Regex(nameSeparator.toString())).forEach {
temp.split(nameSeparator.toRegex()).forEach {
if (it.isNotBlank()) {
stringBuilder.append(it.substring(0, 1).toUpperCase().plus(it.substring(1)))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,45 +93,45 @@ class ClassCodeParser(private val classBlockString: String) {
}

private fun getPropertyKeyword(propertyLine: String): String {
val stringBeforeColon = propertyLine.substringBefore(":").trim()
val stringBeforeLastColonWithoutComment = propertyLine.substringBefore("//").substringBeforeLast(":").trim()
return when {
stringBeforeColon.contains(")") -> {
val noAnnotationString = stringBeforeColon.substringAfterLast(")").trim()
stringBeforeLastColonWithoutComment.contains(")") -> {
val noAnnotationString = stringBeforeLastColonWithoutComment.substringAfterLast(")").trim()
val keyword = noAnnotationString.split(" ").first()
keyword
}
stringBeforeColon.contains("@") -> {
val keyword = stringBeforeColon.split(" ")[1]
stringBeforeLastColonWithoutComment.contains("@") -> {
val keyword = stringBeforeLastColonWithoutComment.split(" ")[1]
keyword
}
else -> {
val keyword = stringBeforeColon.split(" ").first()
val keyword = stringBeforeLastColonWithoutComment.split(" ").first()
keyword
}
}.trim()
}

private fun getPropertyName(propertyLine: String): String {

val stringBeforeColon = propertyLine.substringBefore(":").trim()
val stringBeforeLastColonWithoutComment = propertyLine.substringBefore("//").substringBeforeLast(":").trim()
return when {
stringBeforeColon.contains(")") -> {
val noAnnotationString = stringBeforeColon.substringAfterLast(")").trim()
stringBeforeLastColonWithoutComment.contains(")") -> {
val noAnnotationString = stringBeforeLastColonWithoutComment.substringAfterLast(")").trim()
val splits = noAnnotationString.split(" ")
val propertyName =
splits.filterIndexed { index, s -> listOf(0).contains(index).not() }
.joinToString(" ")
propertyName
}
stringBeforeColon.contains("@") -> {
val splits = stringBeforeColon.split(" ")
stringBeforeLastColonWithoutComment.contains("@") -> {
val splits = stringBeforeLastColonWithoutComment.split(" ")
val propertyName =
splits.filterIndexed { index, s -> listOf(0, 1).contains(index).not() }
.joinToString(" ")
propertyName
}
else -> {
val splits = stringBeforeColon.split(" ")
val splits = stringBeforeLastColonWithoutComment.split(" ")
val propertyName =
splits.filterIndexed { index, s -> listOf(0).contains(index).not() }
.joinToString(" ")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package wu.seal.jsontokotlin.codeelements

import com.winterbe.expekt.should
import org.junit.Assert.assertTrue
import org.junit.Test

Expand Down Expand Up @@ -28,6 +29,9 @@ class KClassNameTest {

}

/**
* test get name logic works well when name contains illegal character
*/
@Test
fun getName() {
val rawClassName = """
Expand All @@ -36,13 +40,15 @@ class KClassNameTest {

val legalClassName = KClassName.getName(rawClassName)

assertTrue(legalClassName.startsWith("N"))
assertTrue(legalClassName == "NAM12335E431")
legalClassName.should.startWith("N")

legalClassName.should.be.equal("NAM12335E431")

val rawClassName1 = "341@!$#43214%$#@%34"

val legalClassName1 = KClassName.getName(rawClassName1)
assertTrue(legalClassName1.isNotEmpty())
assertTrue(legalClassName1 == "X3414321434")
legalClassName1.should.be.equal("X3414321434")

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,12 @@ class KPropertyNameTest {
resultCamelCaseNameUnderScore.should.be.equal("abcAbc")
resultCamelCaseNameWithMiddleScore.should.be.equal("abcAbc")
}

/**
* Test Property name camle case format if OK when there two colon inside string
*/
@Test
fun testPropertyNameCameCaseFormatWithTwoColon() {
KPropertyName.getName("hello:baby:come").should.be.equal("helloBabyCome")
}
}
91 changes: 91 additions & 0 deletions src/test/kotlin/wu/seal/jsontokotlin/regression/Issue089Test.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package wu.seal.jsontokotlin.regression

import com.winterbe.expekt.should
import org.junit.Before
import org.junit.Test
import wu.seal.jsontokotlin.KotlinDataClassCodeMaker
import wu.seal.jsontokotlin.test.TestConfig

class Issue089Test {

private val json = """{
"mime_type": "image/jpeg",
"file_name": "136149.jpg",
"source_type": "chk",
"source_id": 3000193,
"year_month": "201810",
"day": "31",
"type_document_id": 11,
"usr_id": 55572,
"file_desc": "текст примечания",
"bytes": "/9j/4AAQSkZ...Nd/VJ/Ef",
"description": {
"cmis:objectTypeId": "D:esp:act",
"esp:doc_name": "текст примечания",
"esp:iin_bin": "101040011256",
"esp:create_date": "2018.09.31",
"esp:reg_num": "181000000103012/00022",
"esp:reg_date": "2018.10.01",
"esp:author": "Уалиева Асель Мухаметбековна"
}
}"""

private val expected = """data class Test(
@SerializedName("bytes")
val bytes: String = "", // /9j/4AAQSkZ...Nd/VJ/Ef
@SerializedName("day")
val day: String = "", // 31
@SerializedName("description")
val description: Description = Description(),
@SerializedName("file_desc")
val fileDesc: String = "", // текст примечания
@SerializedName("file_name")
val fileName: String = "", // 136149.jpg
@SerializedName("mime_type")
val mimeType: String = "", // image/jpeg
@SerializedName("source_id")
val sourceId: Int = 0, // 3000193
@SerializedName("source_type")
val sourceType: String = "", // chk
@SerializedName("type_document_id")
val typeDocumentId: Int = 0, // 11
@SerializedName("usr_id")
val usrId: Int = 0, // 55572
@SerializedName("year_month")
val yearMonth: String = "" // 201810
) {
data class Description(
@SerializedName("cmis:objectTypeId")
val cmisObjectTypeId: String = "", // D:esp:act
@SerializedName("esp:author")
val espAuthor: String = "", // Уалиева Асель Мухаметбековна
@SerializedName("esp:create_date")
val espCreateDate: String = "", // 2018.09.31
@SerializedName("esp:doc_name")
val espDocName: String = "", // текст примечания
@SerializedName("esp:iin_bin")
val espIinBin: String = "", // 101040011256
@SerializedName("esp:reg_date")
val espRegDate: String = "", // 2018.10.01
@SerializedName("esp:reg_num")
val espRegNum: String = "" // 181000000103012/00022
)
}"""

/**
* init test environment before test
*/
@Before
fun setUp() {
TestConfig.setToTestInitState()
}

/**
* test issue #89 of Github Project issue
*/
@Test
fun testIssue089() {
val result = KotlinDataClassCodeMaker("Test", json).makeKotlinDataClassCode()
result.trim().should.be.equal(expected)
}
}

0 comments on commit 07e3748

Please sign in to comment.