Skip to content

Commit

Permalink
fix: updating logging and refactor types
Browse files Browse the repository at this point in the history
  • Loading branch information
acke committed Sep 19, 2024
1 parent f155b48 commit 6ae96a3
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 72 deletions.
22 changes: 19 additions & 3 deletions src/main/kotlin/io/snyk/plugin/DiffPatcher.kt
Original file line number Diff line number Diff line change
@@ -1,8 +1,24 @@
package io.snyk.plugin

import io.snyk.plugin.ui.jcef.Change
import io.snyk.plugin.ui.jcef.DiffPatch
import io.snyk.plugin.ui.jcef.Hunk
data class DiffPatch(
val originalFile: String,
val fixedFile: String,
val hunks: List<Hunk>
)

data class Hunk(
val startLineOriginal: Int,
val numLinesOriginal: Int,
val startLineFixed: Int,
val numLinesFixed: Int,
val changes: List<Change>
)

sealed class Change {
data class Addition(val line: String) : Change()
data class Deletion(val line: String) : Change()
data class Context(val line: String) : Change() // Unchanged line for context
}

class DiffPatcher {

Expand Down
93 changes: 31 additions & 62 deletions src/main/kotlin/io/snyk/plugin/ui/jcef/ApplyFixHandler.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package io.snyk.plugin.ui.jcef

import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.diagnostic.LogLevel
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.Project
Expand All @@ -14,34 +15,17 @@ import org.cef.browser.CefFrame
import org.cef.handler.CefLoadHandlerAdapter
import org.jetbrains.concurrency.runAsync
import io.snyk.plugin.ui.SnykBalloonNotificationHelper
import snyk.common.lsp.LanguageServerWrapper
import java.io.IOException


data class DiffPatch(
val originalFile: String,
val fixedFile: String,
val hunks: List<Hunk>
)

data class Hunk(
val startLineOriginal: Int,
val numLinesOriginal: Int,
val startLineFixed: Int,
val numLinesFixed: Int,
val changes: List<Change>
)

sealed class Change {
data class Addition(val line: String) : Change()
data class Deletion(val line: String) : Change()
data class Context(val line: String) : Change() // Unchanged line for context
}

class ApplyFixHandler(private val project: Project) {

private val enableDebug = Logger.getInstance("Snyk Language Server").isDebugEnabled
private val enableTrace = Logger.getInstance("Snyk Language Server").isTraceEnabled
private val logger = Logger.getInstance(this::class.java)
val logger = Logger.getInstance(this::class.java).apply {
// tie log level to language server log level
val languageServerWrapper = LanguageServerWrapper.getInstance()
if (languageServerWrapper.logger.isDebugEnabled) this.setLevel(LogLevel.DEBUG)
if (languageServerWrapper.logger.isTraceEnabled) this.setLevel(LogLevel.TRACE)
}


fun generateApplyFixCommand(jbCefBrowser: JBCefBrowserBase): CefLoadHandlerAdapter {
Expand All @@ -54,32 +38,30 @@ class ApplyFixHandler(private val project: Project) {

// Avoid blocking the UI thread
runAsync {
//var success = true
val result = try {
applyPatchAndSave(project, filePath, patch)
} catch (e: IOException) { // Catch specific file-related exceptions
log("Error applying patch to file: $filePath. e:$e")
logger.error("Error applying patch to file: $filePath. e:$e")
Result.failure(e)
} catch (e: Exception) {
log("Unexpected error applying patch. e:$e")
logger.error("Unexpected error applying patch. e:$e")
Result.failure(e)
}

ApplicationManager.getApplication().invokeLater {
if (result.isSuccess) {
val script = """
if (result.isSuccess) {
val script = """
window.receiveApplyFixResponse(true);
""".trimIndent()
jbCefBrowser.cefBrowser.executeJavaScript(script, jbCefBrowser.cefBrowser.url, 0)
} else {
val errorMessage = "Error applying fix: ${result.exceptionOrNull()?.message}"
SnykBalloonNotificationHelper.showError(errorMessage, project)
val errorScript = """
jbCefBrowser.cefBrowser.executeJavaScript(script, jbCefBrowser.cefBrowser.url, 0)
} else {
val errorMessage = "Error applying fix: ${result.exceptionOrNull()?.message}"
SnykBalloonNotificationHelper.showError(errorMessage, project)
val errorScript = """
window.receiveApplyFixResponse(false, "$errorMessage");
""".trimIndent()
jbCefBrowser.cefBrowser.executeJavaScript(errorScript, jbCefBrowser.cefBrowser.url, 0)
}
jbCefBrowser.cefBrowser.executeJavaScript(errorScript, jbCefBrowser.cefBrowser.url, 0)
}

}
return@addHandler JBCefJSQuery.Response("success")
}
Expand All @@ -105,34 +87,21 @@ class ApplyFixHandler(private val project: Project) {
val virtualFile = filePath.toVirtualFile()
val patcher = DiffPatcher()

return try {
WriteCommandAction.runWriteCommandAction(project) {
val document = FileDocumentManager.getInstance().getDocument(virtualFile)
if (document != null) {
val originalContent = document.text
val patchedContent = patcher.applyPatch(originalContent, patcher.parseDiff(patch))
if (originalContent != patchedContent) {
document.setText(patchedContent)
} else {
log("[applyPatchAndSave] Patch did not modify content: $filePath")
}
WriteCommandAction.runWriteCommandAction(project) {
val document = FileDocumentManager.getInstance().getDocument(virtualFile)
if (document != null) {
val originalContent = document.text
val patchedContent = patcher.applyPatch(originalContent, patcher.parseDiff(patch))
if (originalContent != patchedContent) {
document.setText(patchedContent)
} else {
log("[applyPatchAndSave] Failed to find document for: $filePath")
return@runWriteCommandAction
logger.warn("[applyPatchAndSave] Patch did not modify content: $filePath")
}
} else {
logger.error("[applyPatchAndSave] Failed to find document for: $filePath")
return@runWriteCommandAction
}
Result.success(Unit)
} catch (e: Exception) {
log("[applyPatchAndSave] Error applying patch to: $filePath. e: $e")
Result.failure(e)
}
}

private fun log(logMessage: String) {
when {
enableDebug -> logger.debug(logMessage)
enableTrace -> logger.trace(logMessage)
else -> logger.error(logMessage)
}
return Result.success(Unit)
}
}
7 changes: 0 additions & 7 deletions src/main/kotlin/snyk/common/lsp/LanguageServerWrapper.kt
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package snyk.common.lsp

import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
import com.google.gson.reflect.TypeToken
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.service
Expand Down Expand Up @@ -497,11 +495,6 @@ class LanguageServerWrapper(
return this.getFeatureFlagStatus("snykCodeConsistentIgnores")
}

data class Fix(
@SerializedName("fixId") val fixId: String,
@SerializedName("unifiedDiffsPerFile") val unifiedDiffsPerFile: Map<String, String>
)

@Suppress("UNCHECKED_CAST")
fun sendCodeFixDiffsCommand(folderURI: String, fileURI: String, issueID: String): List<Fix> {
if (!ensureLanguageServerInitialized()) return emptyList()
Expand Down
5 changes: 5 additions & 0 deletions src/main/kotlin/snyk/common/lsp/Types.kt
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,11 @@ data class ExampleCommitFix(
@SerializedName("lines") val lines: List<CommitChangeLine>,
)

data class Fix(
@SerializedName("fixId") val fixId: String,
@SerializedName("unifiedDiffsPerFile") val unifiedDiffsPerFile: Map<String, String>
)

data class CommitChangeLine(
@SerializedName("line") val line: String,
@SerializedName("lineNumber") val lineNumber: Int,
Expand Down

0 comments on commit 6ae96a3

Please sign in to comment.