Skip to content

Commit

Permalink
feat: init commits for changes
Browse files Browse the repository at this point in the history
  • Loading branch information
phodal committed Oct 16, 2023
1 parent 7d81858 commit a6d1d82
Show file tree
Hide file tree
Showing 5 changed files with 144 additions and 14 deletions.
Expand Up @@ -143,6 +143,7 @@ open class JavaContextPrompter : ContextPrompter() {

ChatActionType.CUSTOM_ACTION -> {}
ChatActionType.COUNIT -> {}
ChatActionType.CODE_REVIEW -> {}
}

return prompt
Expand Down
65 changes: 65 additions & 0 deletions src/main/kotlin/cc/unitmesh/devti/actions/vcs/CodeReviewAction.kt
@@ -0,0 +1,65 @@
package cc.unitmesh.devti.actions.vcs

import cc.unitmesh.devti.actions.chat.base.ChatBaseAction
import cc.unitmesh.devti.gui.chat.ChatActionType
import cc.unitmesh.devti.gui.chat.ChatContext
import cc.unitmesh.devti.gui.sendToChatPanel
import cc.unitmesh.devti.prompting.VcsPrompting
import cc.unitmesh.devti.provider.ContextPrompter
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.diff.impl.patch.IdeaTextPatchBuilder
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.vcs.VcsDataKeys
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ContentRevision
import com.intellij.openapi.vcs.changes.CurrentContentRevision
import com.intellij.vcs.log.VcsLogDataKeys
import org.jetbrains.annotations.NotNull

class CodeReviewAction : ChatBaseAction() {
override fun getActionType(): ChatActionType = ChatActionType.CODE_REVIEW

companion object {
val log = logger<CodeReviewAction>()
}

override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return

// Make changes available for diff action
val vcsLog = e.getData(VcsLogDataKeys.VCS_LOG)
val details = vcsLog?.let { log ->
log.selectedDetails
}?.toList() ?: return

val vcsPrompting = project.service<VcsPrompting>()
val diff = vcsPrompting.calculateDiff(details, project)

var prompt = """You are a seasoned software developer, and I'm seeking your expertise to review the following code:
|
|- Please provide an overview of the business objectives and the context behind this commit. This will ensure that the code aligns with the project's requirements and goals.
|- Focus on critical algorithms, logical flow, and design decisions within the code. Discuss how these changes impact the core functionality and the overall structure of the code.
|- Identify and highlight any potential issues or risks introduced by these code changes. This will help reviewers pay special attention to areas that may require improvement or further analysis.
|- Emphasize the importance of compatibility and consistency with the existing codebase. Ensure that the code adheres to the established standards and practices for code uniformity and long-term maintainability.
|- Lastly, provide a concise high-level summary that encapsulates the key aspects of this commit. This summary should enable reviewers to quickly grasp the major changes in this update.
|
|PS: Your insights and feedback are invaluable in ensuring the quality and reliability of this code. Thank you for your assistance.
|
""".trimMargin()

prompt += diff.second

log.info("prompt: $prompt")

sendToChatPanel(project) { panel, service ->
val chatContext = ChatContext(null, "", "")

service.handlePromptAndResponse(panel, object : ContextPrompter() {
override fun displayPrompt() = prompt
override fun requestPrompt() = prompt
}, chatContext)
}
}
}
13 changes: 6 additions & 7 deletions src/main/kotlin/cc/unitmesh/devti/gui/chat/ChatActionType.kt
Expand Up @@ -2,6 +2,7 @@ package cc.unitmesh.devti.gui.chat

import cc.unitmesh.devti.prompting.VcsPrompting
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.vcs.changes.ChangeListManagerImpl

Expand All @@ -16,7 +17,8 @@ enum class ChatActionType {
CREATE_CHANGELOG,
CUSTOM_COMPLETE,
CUSTOM_ACTION,
COUNIT
COUNIT,
CODE_REVIEW
;

override fun toString(): String {
Expand All @@ -25,13 +27,9 @@ enum class ChatActionType {

private fun prepareVcsContext(): String {
val project = ProjectManager.getInstance().openProjects.firstOrNull() ?: return ""
val changeListManager = ChangeListManagerImpl.getInstance(project)
val changes = changeListManager.changeLists.flatMap {
it.changes
}

val prompting = project.service<VcsPrompting>()
return prompting.calculateDiff(changes, project)

return prompting.prepareContext()
}

val old_commit_prompt = """suggest 10 commit messages based on the following diff:
Expand Down Expand Up @@ -82,6 +80,7 @@ $diff
CUSTOM_COMPLETE -> ""
CUSTOM_ACTION -> ""
COUNIT -> ""
CODE_REVIEW -> ""
}
}
}
71 changes: 64 additions & 7 deletions src/main/kotlin/cc/unitmesh/devti/prompting/VcsPrompting.kt
Expand Up @@ -28,10 +28,7 @@ import com.intellij.openapi.diff.impl.patch.UnifiedDiffWriter
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.CommitContext
import com.intellij.openapi.vcs.changes.ContentRevision
import com.intellij.openapi.vcs.changes.CurrentContentRevision
import com.intellij.openapi.vcs.changes.*
import com.intellij.project.stateStore
import com.intellij.vcs.log.VcsFullCommitDetails
import git4idea.repo.GitRepositoryManager
Expand Down Expand Up @@ -75,6 +72,51 @@ class VcsPrompting(private val project: Project) {
}
}

fun prepareContext(): String {
val changeListManager = ChangeListManagerImpl.getInstance(project)
val changes = changeListManager.changeLists.flatMap {
it.changes
}

return this.calculateDiff(changes, project)
}

@Throws(VcsException::class, IOException::class)
fun calculateDiff(list: List<VcsFullCommitDetails>, project: Project): Pair<List<String>, String> {
val writer = StringWriter()
val summary: MutableList<String> = ArrayList()
for (detail in list) {
writer.write("""Commit Message: ${detail.fullMessage}\n\nCode Changes:\n\n""")
val subject = detail.subject

summary.add('"'.toString() + subject + "\"")
val filteredChanges = detail.changes.stream()
.filter { change -> !isBinaryOrTooLarge(change!!) }
.toList()

val patches = IdeaTextPatchBuilder.buildPatch(
project,
filteredChanges.subList(0, min(filteredChanges.size, 500)),
Path.of(project.basePath!!),
false,
true
)

UnifiedDiffWriter.write(
project,
project.stateStore.projectBasePath,
patches,
writer,
"\n",
null, emptyList()
)
}

val stringWriter = writer.toString()
val diff = trimDiff(stringWriter)
return Pair<List<String>, String>(summary, diff)
}

fun computeDiff(includedChanges: List<Change>): String {
val changesByRepository = includedChanges
.mapNotNull { change ->
Expand Down Expand Up @@ -142,9 +184,25 @@ class VcsPrompting(private val project: Project) {
return Pair<List<String>, String>(summary, diff)
}

private fun trimDiff(@NotNull diffString: String): String {
val revisionRegex = Regex("\\(revision [^)]+\\)")

@NotNull
fun trimDiff(@NotNull diffString: String): String {
val lines = diffString.lines()
val destination = ArrayList<String>()
diffString.lines().filterNotTo(destination) { it.startsWith("diff --git ") || it.startsWith("index ") }
for (line in lines) {
if (line.startsWith("diff --git ") || line.startsWith("index ") || line.startsWith("Index ")) continue

if (line == "===================================================================") continue

if (line.startsWith("---") || line.startsWith("+++")) {
// remove revision number with regex
val result = revisionRegex.replace(line, "")
destination.add(result)
} else {
destination.add(line)
}
}
return destination.joinToString("\n")
}

Expand All @@ -158,5 +216,4 @@ class VcsPrompting(private val project: Project) {
virtualFile.length
)))
}

}
8 changes: 8 additions & 0 deletions src/main/resources/META-INF/autodev-core.xml
Expand Up @@ -197,6 +197,14 @@
<add-to-group group-id="Vcs.Log.ContextMenu" relative-to-action="Vcs.ShowDiffWithLocal" anchor="after"/>
</action>

<action id="autodev.Vcs.CodeReview"
class="cc.unitmesh.devti.actions.vcs.CodeReviewAction" text="CodeReview (AutoDev)"
icon="cc.unitmesh.devti.AutoDevIcons.AI_COPILOT"
description="Ask AI to review code">

<add-to-group group-id="Vcs.Log.ContextMenu" relative-to-action="Vcs.ShowDiffWithLocal" anchor="after"/>
</action>

<action id="cc.unitmesh.devti.actions.chat.CodeCompleteChatAction"
class="cc.unitmesh.devti.actions.chat.CodeCompleteChatAction" text="Code Complete (AutoDev)"
description="Ask AI about this code">
Expand Down

0 comments on commit a6d1d82

Please sign in to comment.