Last active
July 19, 2020 03:41
-
-
Save rahul-lohra/5b680026de04b95926b4e8e1d913ac06 to your computer and use it in GitHub Desktop.
Logic for reading value from variable defined in kt file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class EditorLogic { | |
val nodeCreator = NodeCreator() | |
var expressionElement: PsiElement? = null | |
fun selectCurrentFile(variableName: String, project: Project, textArea: JTextArea) { | |
reset() | |
val fileEditorManager = FileEditorManager.getInstance(project) | |
val virtualFile = fileEditorManager.openFiles | |
if (!virtualFile.isNullOrEmpty()) { | |
val vf = fileEditorManager.selectedEditor?.file | |
vf?.let { file -> | |
val psiFile = PsiManager.getInstance(project).findFile(file) | |
if (psiFile != null) { | |
psiFile.accept(javaVisitor(textArea)) | |
kotlinVisitor(variableName, textArea, psiFile) | |
} | |
} | |
} | |
} | |
fun kotlinVisitor(variableName: String, textArea: JTextArea, psiFile: PsiFile) { | |
psiFile.accept(object : KtTreeVisitorVoid() { | |
override fun visitProperty(property: KtProperty) { | |
super.visitProperty(property) //yes | |
val localVariableName = property.name | |
if (property.type().toString() == "String" && localVariableName == variableName) { | |
val expressionElement = property.lastChild | |
this@EditorLogic.expressionElement = expressionElement | |
textArea.text = findTextInVariable(expressionElement) | |
} | |
} | |
}) | |
} | |
fun findTextInVariable(psiElement: PsiElement): String { | |
when (psiElement) { | |
is KtStringTemplateExpression -> { | |
val text = getTextFromKtStringTemplateExpression(psiElement) | |
val node = nodeCreator.createNode(text.replace("\\n", "")) | |
return nodeCreator.prettyPrint2(node) | |
} | |
is KtBinaryExpression -> { | |
val array = psiElement.text.split("+") | |
val sb = StringBuilder() | |
for (item in array) { | |
sb.append( | |
item.replaceFirst("\"", "") | |
.replace("\\t", "") | |
.replace("\\n", "") | |
.replace("\\", "") | |
.trimEnd() | |
.removeSuffix("\"") | |
) | |
} | |
val node = nodeCreator.createNode(sb.toString().replace("\\n", "")) | |
return nodeCreator.prettyPrint2(node) | |
} | |
is KtDotQualifiedExpression -> { | |
if (psiElement.firstChild is KtStringTemplateExpression) { | |
return findTextInVariable(psiElement.firstChild) | |
} | |
} | |
} | |
//todo Rahul throw exception - not supported | |
return "Type not supported" | |
} | |
fun reset() { | |
expressionElement = null | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment