diff --git a/README.md b/README.md index 39167d564..8649144ae 100644 --- a/README.md +++ b/README.md @@ -163,34 +163,15 @@ Welcome to add your company here. ## License -Regarding the matter discussed in the LICENSE issue at the project's outset, we want to address the complexity of -JetBrain plugin development. In the process, we referenced certain code and API designs from the JetBrains Community -version and the JetBrains AI Assistant plugin. JetBrains understandably reserves the right to view this as potential -infringement on their intellectual property. +Inspired by: -Therefore, as of April 2024, AutoDev is no longer available on the JetBrains Plugin Marketplace. However, for older -versions' AutoDev, you can access downloads from our Releases page. - -Additionally, we extend a warm invitation to participate in the development of the VSCode version. Your contributions -are greatly appreciated. - -- ChatUI based - on: [https://github.com/Cspeisman/chatgpt-intellij-plugin](https://github.com/Cspeisman/chatgpt-intellij-plugin) - Multiple target inspired by: [https://github.com/intellij-rust/intellij-rust](https://github.com/intellij-rust/intellij-rust) -- SimilarFile inspired by: JetBrains and GitHub Copilot +- SimilarFile inspired by: GitHub Copilot - DevIn Language refs on [JetBrains' Markdown Util](https://github.com/JetBrains/intellij-community/tree/master/platform/markdown-utils), which is licensed under the Apache 2.0 license. - Stream Diff based on [Continue Dev](https://github.com/continuedev/continue) under the Apache 2.0 license. - Ripgrep inspired by [Cline](https://github.com/cline/cline) under the Apache 2.0 license. -**Known License issues**: JetBrain plugin development is no walk in the park! Oops, we cheekily borrowed some code from -the JetBrains Community version and the super cool JetBrains AI Assistant plugin in our codebase. -But fret not, we are working our magic to clean it up diligently! 🧙‍♂️✨. - -Those codes will be removed in the future, you -can check it in `src/main/kotlin/com/intellij/temporary`, if you want to use this plugin in your company, -please remove those codes to avoid any legal issues. - This code is distributed under the MPL 2.0 license. See `LICENSE` in this directory. diff --git a/core/src/main/kotlin/cc/unitmesh/devti/actions/console/FixThisAction.kt b/core/src/main/kotlin/cc/unitmesh/devti/actions/console/FixThisAction.kt index 050768945..4f5f9a4b2 100644 --- a/core/src/main/kotlin/cc/unitmesh/devti/actions/console/FixThisAction.kt +++ b/core/src/main/kotlin/cc/unitmesh/devti/actions/console/FixThisAction.kt @@ -9,13 +9,11 @@ import cc.unitmesh.devti.settings.locale.LanguageChangedCallback.presentationTex import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.diagnostic.logger -import com.intellij.temporary.error.ErrorDescription -import com.intellij.temporary.error.ErrorMessageProcessor import com.intellij.temporary.error.ErrorPromptBuilder class FixThisAction : ChatBaseAction() { - init{ + init { presentationText("settings.autodev.others.fixThis", templatePresentation) } @@ -26,22 +24,14 @@ class FixThisAction : ChatBaseAction() { val project = event.project ?: return val prompt: TextTemplatePrompt? - val description: ErrorDescription? = ErrorMessageProcessor.getErrorDescription(event) - if (description == null) { - val editor = event.getData(CommonDataKeys.EDITOR) ?: return - val text = editor.selectionModel.selectedText ?: return - - prompt = ErrorPromptBuilder.buildDisplayPrompt(text, text, "Fix this") - } else { - prompt = ErrorMessageProcessor.extracted(project, description) - if (prompt == null) { - logger.error("Prompt is null, description: $description") - return - } - } + val editor = event.getData(CommonDataKeys.EDITOR) ?: return + val selectionModel = editor.selectionModel + val text = selectionModel.selectedText ?: return + + prompt = ErrorPromptBuilder.buildDisplayPrompt(text, text, "Fix this") if (prompt.displayText.isBlank() || prompt.requestText.isBlank()) { - logger.error("Prompt is null, description: $description") + logger.error("Prompt is null, description: $text") return } diff --git a/core/src/main/kotlin/com/intellij/temporary/LICENSE.txt b/core/src/main/kotlin/com/intellij/temporary/LICENSE.txt deleted file mode 100644 index 77057df0f..000000000 --- a/core/src/main/kotlin/com/intellij/temporary/LICENSE.txt +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2000-2021 JetBrains s.r.o. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/core/src/main/kotlin/com/intellij/temporary/error/ErrorDescription.kt b/core/src/main/kotlin/com/intellij/temporary/error/ErrorDescription.kt deleted file mode 100644 index f02560a2c..000000000 --- a/core/src/main/kotlin/com/intellij/temporary/error/ErrorDescription.kt +++ /dev/null @@ -1,6 +0,0 @@ -// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. -package com.intellij.temporary.error - -import com.intellij.openapi.editor.Editor - -data class ErrorDescription(val text: String, val consoleLineFrom: Int, val consoleLineTo: Int, val editor: Editor) \ No newline at end of file diff --git a/core/src/main/kotlin/com/intellij/temporary/error/ErrorMessageProcessor.kt b/core/src/main/kotlin/com/intellij/temporary/error/ErrorMessageProcessor.kt deleted file mode 100644 index 342e12698..000000000 --- a/core/src/main/kotlin/com/intellij/temporary/error/ErrorMessageProcessor.kt +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. -package com.intellij.temporary.error - -import cc.unitmesh.devti.llms.tokenizer.TokenizerFactory -import cc.unitmesh.devti.util.isInProject -import cc.unitmesh.devti.prompting.TextTemplatePrompt -import cc.unitmesh.devti.settings.AutoDevSettingsState -import com.intellij.execution.filters.FileHyperlinkInfo -import com.intellij.execution.impl.ConsoleViewImpl -import com.intellij.execution.impl.EditorHyperlinkSupport -import com.intellij.execution.ui.RunContentManager.getInstance -import com.intellij.openapi.actionSystem.AnActionEvent -import com.intellij.openapi.actionSystem.CommonDataKeys -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.editor.markup.RangeHighlighter -import com.intellij.openapi.project.Project -import com.intellij.openapi.roots.ProjectFileIndex -import com.intellij.openapi.util.TextRange -import com.intellij.openapi.vfs.VirtualFile -import com.intellij.refactoring.suggested.range -import kotlin.math.max - -object ErrorMessageProcessor { - fun getErrorDescription(event: AnActionEvent): ErrorDescription? { - val editor = event.getData(CommonDataKeys.EDITOR) ?: return null - val selectionModel = editor.selectionModel - val text = selectionModel.selectedText ?: return null - val position = selectionModel.selectionStartPosition ?: return null - - val endPosition = selectionModel.selectionEndPosition ?: return null - return ErrorDescription(text, position.line, endPosition.line, editor) - } - - private fun extractTextFromRunPanel( - project: Project, lineFrom: Int, - lineTo: Int?, - consoleEditor: Editor? - ): String? { - val editor = consoleEditor ?: getConsoleEditor(project) ?: return null - val document = editor.document - - var end = if (lineTo == null) { - document.lineCount - 1 - } else { - if (lineTo >= document.lineCount - 1) document.lineCount - 1 else lineTo - } - - if(lineFrom >= document.lineCount) { - end = document.lineCount - 1 - } - - val textRange = TextRange( - document.getLineStartOffset(lineFrom), - document.getLineEndOffset(end) - ) - - return document.getText(textRange) - } - - private fun getConsoleEditor(project: Project): Editor? { - val executionConsole = getInstance(project).selectedContent?.executionConsole ?: return null - val consoleViewImpl: ConsoleViewImpl = executionConsole as? ConsoleViewImpl ?: return null - return consoleViewImpl.editor - } - - fun extracted( - project: Project, description: ErrorDescription, - ): TextTemplatePrompt? { - val consoleLineFrom = description.consoleLineFrom - val consoleLineTo = description.consoleLineTo - val consoleEditor = description.editor - - val extractedText = - extractTextFromRunPanel(project, consoleLineFrom, consoleLineTo, consoleEditor) ?: return null - - val extractedErrorPlaces: List = - extractErrorPlaces(project, consoleLineFrom, consoleLineTo, consoleEditor) - - val errorPromptBuilder = - ErrorPromptBuilder(AutoDevSettingsState.maxTokenLength, TokenizerFactory.createTokenizer()) - - return errorPromptBuilder.buildPrompt(extractedText, extractedErrorPlaces) - } - - private fun getFileHyperlinkInfo(rangeHighlighter: RangeHighlighter): FileHyperlinkInfo? { - val hyperlinkInfo = EditorHyperlinkSupport.getHyperlinkInfo(rangeHighlighter) - if (hyperlinkInfo !is FileHyperlinkInfo) return null - - return hyperlinkInfo - } - - private fun extractErrorPlaceFromHighlighter( - consoleText: String, highlighter: RangeHighlighter, project: Project - ): ErrorPlace? { - val fileHyperlinkInfo: FileHyperlinkInfo = getFileHyperlinkInfo(highlighter) ?: return null - val descriptor = fileHyperlinkInfo.descriptor ?: return null - - val virtualFile: VirtualFile = descriptor.file - val lineNumber = max(0.0, descriptor.line.toDouble()).toInt() - val range = highlighter.range!! - - val hyperlinkText = consoleText.substring(range.startOffset, range.endOffset) - val projectFileIndex: ProjectFileIndex = ProjectFileIndex.getInstance(project) - val isProjectFile = - isInProject(virtualFile, project) && !projectFileIndex.isInLibrary(virtualFile) - - return ErrorPlace(hyperlinkText, lineNumber, isProjectFile, virtualFile, project) - } - - private fun extractErrorPlaces( - project: Project, consoleLineFrom: Int, consoleLineTo: Int?, consoleEditor: Editor? - ): List { - val editor = consoleEditor ?: getConsoleEditor(project) ?: return emptyList() - - val text = editor.document.text - val highlighters: Array = editor.markupModel.allHighlighters - val result: MutableList = ArrayList() - - val startOffset = editor.document.getLineStartOffset(consoleLineFrom) - val endOffset = editor.document.getLineEndOffset(consoleLineTo ?: (editor.document.lineCount - 1)) - - val textRange = TextRange(startOffset, endOffset) - - for (highlighter in highlighters) { - if (textRange.contains(highlighter.range!!)) { - extractErrorPlaceFromHighlighter(text, highlighter, project)?.let { result.add(it) } - } - } - - return result - } -} \ No newline at end of file diff --git a/core/src/main/kotlin/com/intellij/temporary/error/ErrorPlace.kt b/core/src/main/kotlin/com/intellij/temporary/error/ErrorPlace.kt deleted file mode 100644 index 4d7d9d3f6..000000000 --- a/core/src/main/kotlin/com/intellij/temporary/error/ErrorPlace.kt +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. -package com.intellij.temporary.error - -import com.intellij.temporary.error.ErrorPlacePsiUtils -import com.intellij.openapi.project.Project -import com.intellij.openapi.vfs.VfsUtilCore -import com.intellij.openapi.vfs.VirtualFile -import com.intellij.psi.PsiElement -import com.intellij.psi.PsiFile -import com.intellij.psi.PsiManager - -data class ErrorPlace( - val hyperlinkText: String, - val lineNumber: Int, - val isProjectFile: Boolean, - val virtualFile: VirtualFile, - val project: Project -) { - val psiFile: PsiFile? - get() = PsiManager.getInstance(project).findFile(virtualFile) - - val programText: String - get() = VfsUtilCore.loadText(virtualFile) - - fun findContainingElement(): PsiElement? { - val psiFile = psiFile ?: return null - val lineStartOffset = ErrorPlacePsiUtils.getLineStartOffset(psiFile, lineNumber) ?: return null - val errorPlaceOffset: Int = lineStartOffset - return this.psiFile?.findElementAt(errorPlaceOffset) - } - - fun getMarkDownLanguageSlug(): String? { - val psiFile = psiFile ?: return null - val language = psiFile.language - - return when (val displayNameLowercase = language.displayName.lowercase()) { - "c#" -> "csharp" - "c++" -> "cpp" - else -> displayNameLowercase - } - } - -} \ No newline at end of file diff --git a/core/src/main/kotlin/com/intellij/temporary/error/ErrorPlacePsiUtils.kt b/core/src/main/kotlin/com/intellij/temporary/error/ErrorPlacePsiUtils.kt deleted file mode 100644 index ae4a66e55..000000000 --- a/core/src/main/kotlin/com/intellij/temporary/error/ErrorPlacePsiUtils.kt +++ /dev/null @@ -1,52 +0,0 @@ -package com.intellij.temporary.error - -import com.intellij.psi.PsiComment -import com.intellij.psi.PsiDocumentManager -import com.intellij.psi.PsiElement -import com.intellij.psi.PsiFile -import com.intellij.psi.PsiWhiteSpace -import com.intellij.psi.util.PsiTreeUtil - -object ErrorPlacePsiUtils { - private fun getStartOffset(element: PsiElement): Int = element.textRange.startOffset - private fun getEndOffset(element: PsiElement): Int = element.textRange.endOffset - - fun getLineStartOffset(psiFile: PsiFile, line: Int): Int? { - var document = psiFile.viewProvider.document - if (document == null) { - document = PsiDocumentManager.getInstance(psiFile.project).getDocument(psiFile) - } - - if (document == null) return null - if (line < 0 || line >= document.lineCount) return null - - val startOffset = document.getLineStartOffset(line) - val element = psiFile.findElementAt(startOffset) ?: return startOffset - - if (element !is PsiWhiteSpace && element !is PsiComment) { - return startOffset - } - - val skipSiblingsForward = PsiTreeUtil.skipSiblingsForward( - element, PsiWhiteSpace::class.java, PsiComment::class.java - ) - - return if (skipSiblingsForward != null) getStartOffset(skipSiblingsForward) else startOffset - } - - fun getLineNumber(element: PsiElement, start: Boolean): Int { - var document = element.containingFile.viewProvider.document - if (document == null) { - document = PsiDocumentManager.getInstance(element.project).getDocument(element.containingFile) - } - - if (document == null) return 0 - - val index = if (start) getStartOffset(element) else getEndOffset(element) - if (index > document.textLength) { - return 0 - } - - return document.getLineNumber(index) - } -} \ No newline at end of file diff --git a/core/src/main/kotlin/com/intellij/temporary/error/ErrorPromptBuilder.kt b/core/src/main/kotlin/com/intellij/temporary/error/ErrorPromptBuilder.kt deleted file mode 100644 index 1a27d9e6f..000000000 --- a/core/src/main/kotlin/com/intellij/temporary/error/ErrorPromptBuilder.kt +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. -package com.intellij.temporary.error - -import cc.unitmesh.devti.llms.tokenizer.Tokenizer -import cc.unitmesh.devti.prompting.TextTemplatePrompt -import cc.unitmesh.devti.template.GENIUS_ERROR -import cc.unitmesh.devti.template.TemplateRender -import cc.unitmesh.devti.template.context.TemplateContext -import com.intellij.openapi.application.ReadAction -import com.intellij.openapi.vfs.VirtualFile -import com.intellij.psi.PsiElement -import com.intellij.psi.PsiFile -import java.lang.String.format -import kotlin.math.min - -data class ErrorContext( - val errorText: String, - val sourceCode: String, -) : TemplateContext - -class ErrorPromptBuilder(private val maxLength: Int, private val tokenizer: Tokenizer) { - private val displayText = - "Please help me understand what the problem is and try to fix the code. Here's the console output and the program text:\nConsole output:\n%s\nTexts of programs:\n%s" - - @JvmSynthetic - fun buildPrompt(errorText: String, list: List): TextTemplatePrompt { - var sourceCode = "" - val requestLength = buildDisplayPrompt("", sourceCode, "").requestText.length ?: 0 - val maxLengthForPiece = (maxLength - requestLength) / 2 - var currentMaxTokenCount = maxLengthForPiece - val listOfIncludedDiapasons = mutableListOf() - - list.forEach { errorPlace -> - if (!errorPlace.isProjectFile) return@forEach - - val isLineIncluded = - listOfIncludedDiapasons.any { it.containsLineNumber(errorPlace.lineNumber, errorPlace.virtualFile) } - - if (!isLineIncluded) { - val trimmed = trimByGreedyScopeSelection(errorPlace, currentMaxTokenCount) ?: return@forEach - - currentMaxTokenCount -= tokenizer.count(trimmed.text) - sourceCode += trimmed.text - listOfIncludedDiapasons.add(trimmed) - } - } - - val errorTextTrimmed = trimTextByTokenizer(errorText, maxLengthForPiece) - val formattedDisplayText = format(displayText, "```\n$errorTextTrimmed\n```\n", sourceCode) - - return buildDisplayPrompt(errorTextTrimmed, sourceCode, formattedDisplayText) - } - - private fun trimByGreedyScopeSelection(errorPlace: ErrorPlace, maxTokenCount: Int): ErrorScope? { - return ReadAction.compute { - val language: String = errorPlace.getMarkDownLanguageSlug() ?: "" - - tryFitAllFile( - errorPlace.hyperlinkText, - errorPlace.programText, - maxTokenCount, - language, - errorPlace.virtualFile - ) ?: findEnclosingScopeGreedy(errorPlace, maxTokenCount, language) - } - } - - private fun findEnclosingScopeGreedy(errorPlace: ErrorPlace, maxTokenCount: Int, language: String): ErrorScope? { - var result: ErrorScope? = null - var containingElement = errorPlace.findContainingElement() - - while (true) { - if (containingElement is PsiFile || containingElement == null) break - - result = tryFitContainingElement( - errorPlace.hyperlinkText, - containingElement, - maxTokenCount, - language, - errorPlace.virtualFile - ) ?: break - - containingElement = containingElement.parent - } - - return result - } - - private fun tryFitContainingElement( - filename: String, - currentContainingElement: PsiElement, - maxTokenCount: Int, - language: String, - virtualFile: VirtualFile - ): ErrorScope? { - val lineNumberStart = ErrorPlacePsiUtils.getLineNumber(currentContainingElement, true) - val lineNumberFinish = ErrorPlacePsiUtils.getLineNumber(currentContainingElement, false) - - val prefix = "filename: $filename\n line: $lineNumberStart\n\n" - val candidate = """ - $prefix```$language - ${currentContainingElement.text} - ``` - """.trimIndent() - - return if (findTrimPositionForMaxTokens(candidate, maxTokenCount) >= candidate.length) { - ErrorScope( - lineNumberStart, - lineNumberFinish, - candidate, - virtualFile - ) - } else null - } - - private fun tryFitAllFile( - filename: String, - programText: String, - maxTokenCount: Int, - language: String, - virtualFile: VirtualFile - ): ErrorScope? { - val firstTry = "filename: $filename\n\n```$language\n$programText\n```\n" - if (findTrimPositionForMaxTokens(firstTry, maxTokenCount) < firstTry.length) return null - - return ErrorScope(0, programText.lines().size - 1, firstTry, virtualFile) - } - - private fun findTrimPositionForMaxTokens(text: String, maxTokenCount: Int): Int { - var tokenSum = 0 - var trimPosition = 0 - for (line in text.lines()) { - val tokenCountInLine = tokenizer.count(line) + 1 - if (tokenSum + tokenCountInLine > maxTokenCount) { - break - } - - trimPosition += line.length + 1 - tokenSum += tokenCountInLine - } - - return trimPosition - } - - private fun trimTextByTokenizer(text: String, maxTokenCount: Int): String { - val offset = findTrimPositionForMaxTokens(text, maxTokenCount) - return text.substring(0, min(text.length, offset)) - } - - companion object { - fun buildDisplayPrompt(errorTextTrimmed: String, sourceCode: String, displayText: String): TextTemplatePrompt { - val templateRender = TemplateRender(GENIUS_ERROR) - templateRender.context = ErrorContext(errorTextTrimmed, sourceCode) - val template = templateRender.getTemplate("fix-error.vm") - val prompt = templateRender.renderTemplate(template) - return TextTemplatePrompt(displayText, prompt) - } - } -} diff --git a/core/src/main/kotlin/com/intellij/temporary/error/ErrorScope.kt b/core/src/main/kotlin/com/intellij/temporary/error/ErrorScope.kt deleted file mode 100644 index e1d21b28e..000000000 --- a/core/src/main/kotlin/com/intellij/temporary/error/ErrorScope.kt +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. -package com.intellij.temporary.error - -import com.intellij.openapi.vfs.VirtualFile - -class ErrorScope(val lineStart: Int, val lineFinish: Int, val text: String, val thisVirtualFile: VirtualFile) { - fun containsLineNumber(lineNumber: Int, virtualFile: VirtualFile): Boolean { - return lineNumber in lineStart..lineFinish && thisVirtualFile == virtualFile - } -} \ No newline at end of file