Skip to content

Instantly share code, notes, and snippets.

@theapache64
Created April 9, 2023 05:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theapache64/57a95dbd2c587239ba0eac77cade9cb0 to your computer and use it in GitHub Desktop.
Save theapache64/57a95dbd2c587239ba0eac77cade9cb0 to your computer and use it in GitHub Desktop.
// depends-on-plugin org.jetbrains.kotlin
import com.intellij.psi.util.parentOfType
import liveplugin.editor
import liveplugin.executeCommand
import liveplugin.psiFile
import liveplugin.registerAction
import liveplugin.show
import org.jetbrains.kotlin.analysis.api.fir.utils.addImportToFile
import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.FqNameUnsafe
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.resolve.ImportPath
registerAction(
id = "Add Rebugger Here", keyStroke = "shift W"
) { event ->
val project = event.project ?: return@registerAction
val editor = event.editor ?: return@registerAction
val ktFile = event.psiFile as? KtFile ?: return@registerAction
val offset = editor.caretModel.offset
val currentElement = ktFile.findElementAt(offset)
val function = currentElement?.parentOfType<KtNamedFunction>() ?: return@registerAction
val trackSet = mutableSetOf<String>()
// Adding function argument
function.valueParameters.mapNotNull { it.name }.toSet()?.let { argSet ->
trackSet.addAll(argSet)
}
// Adding code block
editor.document.executeCommand(project, description = "Add Rebugger Call") {
// Write code block
val trackMap = StringBuilder().apply {
for (varName in trackSet) {
this.append("\"$varName\" to $varName,\n")
}
}
val rebuggerCall = "Rebugger( trackMap = mapOf( $trackMap ), )"
insertString(offset, rebuggerCall)
val codeStyleManager = com.intellij.psi.codeStyle.CodeStyleManager.getInstance(project)
codeStyleManager.reformatText(ktFile, offset, offset + rebuggerCall.length)
// Add import statement
val classToImport = "com.theapache64.rebugger.Rebugger"
if (!ktFile.hasImport(classToImport)) {
// Hack due to https://twitter.com/theapache64/status/1644815369947824130
val fileContent = ktFile.text
val lastImportIndex = fileContent.lastIndexOf("import ")
insertString(lastImportIndex, "import $classToImport\n")
addImportToFile()
}
}
}
fun KtFile.hasImport(classToImport: String): Boolean {
return importDirectives.find { it.text.contains(classToImport) } != null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment