0


使用GPT开发Idea自动写注释插件

  1. 拥有一个OpenAI账号(注册不过多解释)
  2. 获取openai提供的API key,用于访问openai的API。OpenAI API​​​​​​
  3. 创建一个idea基本插件项目,项目随便命名

创建后的文件结构,CommentWriter是自己添加的

  1. 开发准备,导入OKHttp(原生的http访问在打包后会报400错误,HttpClient访问的接口在参数一致的情况下获取的结果非常蠢,无法之间使用)
  2. 点击project structure
  3. 点击加号,再点击library
  4. 点击new library
  5. 点击form maven
  6. 直接搜索Okhttp导入就可以了,依赖的环境只有这个
  7. 然后修改一下plugin.xml,这里actions里面有两个方法,一个是局部添加注释,一个是全文添加注释,但是有限制,后面会提到
<idea-plugin>
    <id>com.main.CommentWriter</id>
    <name>CommentWriter</name>
    <description><![CDATA[
      Use the GPT create a auto comment writer.
    ]]></description>
    <version>1.5</version>
    <vendor email="" url=""></vendor>
    <change-notes><![CDATA[no.]]>
    </change-notes>

    <!-- please see https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html for description -->
    <idea-version since-build="173.0"/>

    <!-- please see https://plugins.jetbrains.com/docs/intellij/plugin-compatibility.html
         on how to target different products -->
    <depends>com.intellij.modules.platform</depends>

    <extensions defaultExtensionNs="com.intellij">

    </extensions>
    <actions>
        <action id="AddCommentAction" class="com.main.CommentWriter" text="Add Comment">
            <add-to-group group-id="EditorPopupMenu" anchor="first"/>
        </action>
        <action id="AddCommentActionSelect" class="com.main.CommentWriterSelector" text="Add Comment To Select Code">
            <add-to-group group-id="EditorPopupMenu" anchor="first"/>
        </action>
    </actions>

</idea-plugin>
  1. 然后把CommentWriter的代码添加一些,两段代码我没做优化,直接复制粘贴的,有兴趣的可以自己优化一些
  2. package com.main;import com.google.gson.Gson;import com.intellij.openapi.actionSystem.AnAction;import com.intellij.openapi.actionSystem.AnActionEvent;import com.intellij.openapi.actionSystem.LangDataKeys;import com.intellij.openapi.application.ApplicationManager;import com.intellij.openapi.editor.Editor;import com.intellij.openapi.fileEditor.FileEditorManager;import com.intellij.openapi.project.Project;import com.intellij.openapi.wm.StatusBar;import com.intellij.openapi.wm.WindowManager;import net.minidev.json.JSONArray;import net.minidev.json.JSONObject;import net.minidev.json.JSONValue;import okhttp3.*;import java.io.*;import java.util.HashMap;import java.util.Map;import java.util.concurrent.TimeUnit;public class CommentWriter extends AnAction { @Override public void actionPerformed(AnActionEvent e) { Editor editor = e.getData(LangDataKeys.EDITOR); // 获取编辑器 if (editor != null) { StatusBar statusBar = WindowManager.getInstance().getStatusBar(editor.getProject()); // 获取状态栏 ApplicationManager.getApplication().runWriteAction(() -> { statusBar.setInfo("正在添加"); // 设置状态栏信息 System.out.println(editor.getDocument().getText().length()); // 输出文本长度 System.out.println(editor.getDocument().getText()); // 输出文本 if (editor.getDocument().getText().length() < 2000) { // 判断文本长度是否小于2000 String code = Comment_4(editor.getDocument().getText()); // 调用Comment_4函数 System.out.println(code); // 输出code if (code.length() >= editor.getDocument().getText().length()) { // 判断code长度是否大于等于文本长度 editor.getDocument().setText(code); // 设置文本 } statusBar.setInfo("添加完毕"); // 设置状态栏信息 } else { statusBar.setInfo("选中的文本太长无法添加注释"); // 设置状态栏信息 } }); } } public static String Comment_4(String code) { // 获取需要输出的文本 String prompt = "Please add Chinese comments above each line of the following Java code. Do not add comment symbols before import and package statements. Then return the complete code with comments. The code must not have fewer lines than the original." + code; // 调用generateText_3方法,获取返回的文本 String result = generateText_3(prompt); // 解析JSON JSONObject jsonObject = (JSONObject) JSONValue.parse(result); JSONArray choices = (JSONArray) jsonObject.get("choices"); JSONObject firstChoice = (JSONObject) choices.get(0); Object textObj = firstChoice.get("text"); String textStr = textObj.toString(); // 返回带中文注释的代码 return textStr; } private static String generateText_3(String prompt) { // API相关参数 String API_KEY = "替换成你自己的APIkey"; String MODEL_ENDPOINT = "https://api.openai.com/v1/"; String MODEL_NAME = "text-davinci-003"; int MAX_TOKENS = 2048; double TEMPERATURE = 0; String response = ""; try { // 创建OkHttpClient OkHttpClient client = new OkHttpClient.Builder() .readTimeout(500, TimeUnit.SECONDS) .build(); // 创建RequestBody RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), createRequestBody(prompt, TEMPERATURE, MAX_TOKENS)); // 创建Request Request request = new Request.Builder() .url(MODEL_ENDPOINT + "engines/" + MODEL_NAME + "/completions") .post(requestBody) .addHeader("Content-Type", "application/json") .addHeader("Authorization", "Bearer " + API_KEY).build(); // 发送请求 Response httpResponse = client.newCall(request).execute(); // 判断请求是否成功 if (httpResponse.isSuccessful()) { response = httpResponse.body().string(); } else { throw new RuntimeException("Failed : HTTP error code : " + httpResponse.code()); } } catch (IOException e) { e.printStackTrace(); } // 返回响应 return response; } private static String createRequestBody(String prompt, double temperature, int maxTokens) { // 创建Map Map<String, Object> requestBody = new HashMap<>(); // 添加参数 requestBody.put("prompt", prompt); requestBody.put("temperature", temperature); requestBody.put("max_tokens", maxTokens); // 转换为JSON return new Gson().toJson(requestBody); }}``````package com.main;import com.google.gson.Gson;import com.intellij.openapi.actionSystem.AnAction;import com.intellij.openapi.actionSystem.AnActionEvent;import com.intellij.openapi.actionSystem.LangDataKeys;import com.intellij.openapi.application.ApplicationManager;import com.intellij.openapi.editor.Document;import com.intellij.openapi.editor.Editor;import com.intellij.openapi.editor.SelectionModel;import com.intellij.openapi.fileEditor.FileEditorManager;import com.intellij.openapi.project.Project;import com.intellij.openapi.wm.StatusBar;import com.intellij.openapi.wm.WindowManager;import net.minidev.json.JSONArray;import net.minidev.json.JSONObject;import net.minidev.json.JSONValue;import okhttp3.*;import java.io.IOException;import java.util.HashMap;import java.util.Map;import java.util.concurrent.TimeUnit;public class CommentWriterSelector extends AnAction { @Override public void actionPerformed(AnActionEvent e) { ApplicationManager.getApplication().runWriteAction(() -> { Project project = e.getProject(); if (project == null) { return; } StatusBar statusBar = WindowManager.getInstance().getStatusBar(project); statusBar.setInfo("正在局部添加"); Editor editor = e.getData(LangDataKeys.EDITOR); if (editor != null) { SelectionModel selectionModel = editor.getSelectionModel(); String selectedText = selectionModel.getSelectedText(); System.out.println(selectedText.length()); System.out.println(selectedText); if (selectedText != null) { Document document = editor.getDocument(); if (editor.getSelectionModel().getSelectedText().length() > 2000) { statusBar.setInfo("文本过长"); return; } String code = Comment_4(editor.getSelectionModel().getSelectedText()); System.out.println(code); if (code.length() >= editor.getSelectionModel().getSelectedText().length()) { String allCode = document.getText(); System.out.println(allCode); allCode = allCode.replace(selectedText, code); System.out.println(allCode); document.setText(allCode); } statusBar.setInfo("局部添加完毕"); } } }); } public static String Comment_4(String code) { String prompt = "Please add Chinese comments above each line of the following Java code. Do not add comment symbols before import and package statements. Then return the complete code with comments. The code must not have fewer lines than the original." + code; String result = generateText_3(prompt); JSONObject jsonObject = (JSONObject) JSONValue.parse(result); JSONArray choices = (JSONArray) jsonObject.get("choices"); JSONObject firstChoice = (JSONObject) choices.get(0); Object textObj = firstChoice.get("text"); String textStr = textObj.toString(); return textStr; } private static String generateText_3(String prompt) { // API相关参数 String API_KEY = "替换成你自己的APIkey"; String MODEL_ENDPOINT = "https://api.openai.com/v1/"; String MODEL_NAME = "text-davinci-003"; int MAX_TOKENS = 2048; double TEMPERATURE = 0; String response = ""; try { // 创建OkHttpClient OkHttpClient client = new OkHttpClient.Builder() .readTimeout(500, TimeUnit.SECONDS) .build(); // 创建RequestBody RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), createRequestBody(prompt, TEMPERATURE, MAX_TOKENS)); // 创建Request Request request = new Request.Builder() .url(MODEL_ENDPOINT + "engines/" + MODEL_NAME + "/completions") .post(requestBody) .addHeader("Content-Type", "application/json") .addHeader("Authorization", "Bearer " + API_KEY).build(); // 发送请求 Response httpResponse = client.newCall(request).execute(); // 判断请求是否成功 if (httpResponse.isSuccessful()) { response = httpResponse.body().string(); } else { throw new RuntimeException("Failed : HTTP error code : " + httpResponse.code()); } } catch (IOException e) { e.printStackTrace(); } // 返回响应 return response; } // 创建一个请求体 private static String createRequestBody(String prompt, double temperature, int maxTokens) { // 创建一个Map对象 Map<String, Object> requestBody = new HashMap<>(); // 将prompt放入Map中 requestBody.put("prompt", prompt); // 将temperature放入Map中 requestBody.put("temperature", temperature); // 将maxTokens放入Map中 requestBody.put("max_tokens", maxTokens); // 将Map转换为Json格式 return new Gson().toJson(requestBody); }}然后就可以直接打包了右键点击项目,点击最下面那个,然后过一会就会自动打包好一个zip文件,就在项目的目录。
  3. 测试:有两种方法,一种是直接部署试试,但是会有代码被直接替换的风险,建议先备份
  4. 第一种;直接部署
  5. 点击File-》Settings-》plugins-》instelled右边的设置图标,然后点击install plugin from disk,选中那个打包好的zip,点击OK,然后重启IDEA,然后鼠标右键点击任意一个代码,就出现两个按钮,第一格是为选中片段添加注释,第二个是全文添加注释,由于OpenAI的API访问限制,一次最大只能接收2048长度的字符串,所以对于过长的代码无法添加注释。
  6. 第二种运行方法是测试运行,直接部署的是没有办法看到除了报错以外的其他信息的,但是测试运行可以看到打印在控制台的内容,首先点击run-》然后edit configurations

进入后点击左侧的加号,点击plugins,然后点击plugins,在右侧页面点击add new run plugins,

然后再VM option写入-Didea.is.internal=true -Didea.plugin.name=CommentWriter,name可以随便写。点击ok。

然后再点击run后就会出现一个新的选项

点击后就可以运行了。然后会弹出一个测试使用的idea窗口,就可以在里面操作右键的菜单,然后主题窗口的控制台就会输出打印的内容。

效果:

添加注释有时候会添加不进去,因为chatGPT不会给所有语句都写注释,

目前写的很简陋可以自己优化。


本文转载自: https://blog.csdn.net/loveisbunny/article/details/129121328
版权归原作者 秃头大魔王 所有, 如有侵权,请联系我们删除。

“使用GPT开发Idea自动写注释插件”的评论:

还没有评论