Skip to content

Commit

Permalink
refactor(protobuf): extract and add field construction in ProtobufFul…
Browse files Browse the repository at this point in the history
…lIdentListener #122
  • Loading branch information
phodal committed Oct 25, 2024
1 parent f56a0f6 commit f9660f3
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import chapi.ast.antlr.Protobuf3BaseListener
import chapi.ast.antlr.Protobuf3Parser
import chapi.domain.core.CodeContainer
import chapi.domain.core.CodeDataStruct
import chapi.domain.core.CodeField

class ProtobufFullIdentListener(var fileName: String) : Protobuf3BaseListener() {
private var codeContainer: CodeContainer = CodeContainer(FullName = fileName)
Expand All @@ -14,13 +15,33 @@ class ProtobufFullIdentListener(var fileName: String) : Protobuf3BaseListener()
}

override fun enterMessageDef(ctx: Protobuf3Parser.MessageDefContext?) {
val codeDataStruct = constructMessageDef(ctx)

codeContainer.DataStructures += codeDataStruct
}

private fun constructMessageDef(ctx: Protobuf3Parser.MessageDefContext?): CodeDataStruct {
val messageName = ctx!!.messageName().text
codeContainer.DataStructures += CodeDataStruct(
val codeDataStruct = CodeDataStruct(
NodeName = messageName,
Module = codeContainer.PackageName,
FilePath = codeContainer.FullName,
Package = codeContainer.PackageName
)

/// since a message element will be all def
ctx.messageBody().messageElement().map {
when (val child = it.getChild(0)) {
is Protobuf3Parser.FieldContext -> {
codeDataStruct.Fields += CodeField(
TypeType = child.type_().text,
TypeKey = child.fieldName().text,
TypeValue = child.fieldNumber().text
)
}
}
}
return codeDataStruct
}

fun getNodeInfo(): CodeContainer {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
// Save this code in a file named ProtobufAnalyserTest.kt under test directory

package chapi.ast.protobuf

import org.junit.jupiter.api.Test
Expand All @@ -21,5 +19,17 @@ class ProtobufAnalyserTest {
assertNotNull(codeContainer)
assertEquals("example", codeContainer.PackageName)
assertTrue(codeContainer.DataStructures.isNotEmpty())

val dataStruct = codeContainer.DataStructures.first()
assertEquals("Person", dataStruct.NodeName)
assertEquals("example", dataStruct.Module)
assertEquals("path/to/file.proto", dataStruct.FilePath)
assertEquals("example", dataStruct.Package)
assertTrue(dataStruct.Fields.isNotEmpty())

val field = dataStruct.Fields.first()
assertEquals("string", field.TypeType)
assertEquals("name", field.TypeKey)
assertEquals("1", field.TypeValue)
}
}

0 comments on commit f9660f3

Please sign in to comment.