-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextension.js
231 lines (195 loc) · 6.04 KB
/
extension.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
const vscode = require("vscode");
const axios = require("axios");
/**
* @param {vscode.ExtensionContext} context
*/
function activate(context) {
console.log("Coder Jr extension activated.");
let disposable = vscode.commands.registerCommand(
"coderjr.command",
async () => {
let apiKey = getApiKey();
if (!apiKey) {
let input = await openInputBoxForApiKey();
if (!input) {
const action = "How to get API KEY";
const action2 = "Get API Key";
let clickedAction = await vscode.window.showWarningMessage(
"Please enter you API Key", action, action2);
if (clickedAction === action) {
openLink(VIDEO_GUIDE_URL);
} else if (clickedAction === action2) {
openLink(GETTING_API_KEY_URL);
}
return;
}
apiKey = input;
storeApiKey(apiKey);
}
const comment = getComment();
if (!comment) {
return vscode.window.showWarningMessage(
"You should be in a position to comment."
);
} else if (comment.split(" ").length < 3) {
return vscode.window.showWarningMessage(
"You must use a minimum of three words."
);
}
let statusBarMsg = vscode.window.setStatusBarMessage("Searching...");
let response = await requestToOpenAi(comment, apiKey);
statusBarMsg.dispose();
if (response.status === "failed") {
vscode.window.setStatusBarMessage("Failed", 3000);
return vscode.window.showErrorMessage(response.msg);
}
let selection = await insertText(response);
selectText(selection);
}
);
context.subscriptions.push(disposable);
}
/**
* This makes http request to openAi with the query as prompt
*
* @param {String} query it is the prompt for openai chatGPT
* @param {String} apiKey the API Key of OpenAI
*
* @returns {Promise<Object>}
*/
async function requestToOpenAi(query, apiKey) {
let languageId = vscode.window.activeTextEditor.document.languageId;
const options = {
method: "POST",
url: "https://api.openai.com/v1/completions",
headers: {
Authorization: `Bearer ${apiKey}`,
"content-type": "application/json",
},
data: {
model: "text-davinci-003",
prompt: `${query} (${languageId})`,
temperature: 0.3,
max_tokens: 290,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
},
};
let response;
try {
response = await axios.default.request(options);
} catch (err) {
response = err.response;
storeApiKey(""); // Remove the invalid API Key.
return { status: "failed", msg: response.data.error.message };
}
if (response.status !== 200)
return { status: "failed", msg: response.statusText };
let text = response.data.choices[0].text;
return text.slice(2, text.length);
}
/**
* It inserts text after the comment and
* returns the selection of inserted text
*
* @param {string} text this will be inserted to the doc
* @returns {Promise<vscode.Selection>}
*/
async function insertText(text) {
let editor = vscode.window.activeTextEditor;
if (!editor) return;
let lineIndex = editor.selection.active.line;
let characterIndex = editor.document.lineAt(lineIndex).text.length;
let insertionPosition = new vscode.Position(lineIndex, characterIndex);
let edit = new vscode.WorkspaceEdit();
edit.insert(editor.document.uri, insertionPosition, `\n${text}`);
vscode.workspace.applyEdit(edit);
let startLine = lineIndex + 1;
let startPos = new vscode.Position(startLine, 0);
let endPos = getEndPosition(text, startLine);
return new Promise((resolve) => {
setTimeout(() => {
let selection = new vscode.Selection(startPos, endPos);
resolve(selection);
}, 10);
});
}
/**
* This Helper function helps to get end position of inserted line
*
* @param {String} text the insertion text
* @param {number} startLine the index of start line of insertion
* @returns {vscode.Position}
*/
function getEndPosition(text, startLine) {
let lines = text.split("\n");
let line = startLine + lines.length;
let endPos = new vscode.Position(line, 0);
return endPos;
}
/**
* Selects a range of text in the active text editor.
*
* @param {vscode.Selection} selection - The start position of the selection range.
*/
function selectText(selection) {
const textEditor = vscode.window.activeTextEditor;
textEditor.selection = selection;
}
/**
* It gives comment if the cursor is in a comment line
* Else it will return an empty string
*
* @returns {String}
*/
function getComment() {
let editor = vscode.window.activeTextEditor;
if (!editor) return "";
let lineIndex = editor.selection.active.line;
let lineText = editor.document.lineAt(lineIndex).text;
let comments, i = 0;
do {
comments = lineText.match(COMMENT_REGEX[i]);
} while (++i < COMMENT_REGEX.length && !comments);
if (!comments) return "";
let comment = comments[0].replace(/\/\/|\/\*|\*\/|#|<!--|-->/g, "");
return comment.trim();
}
async function openInputBoxForApiKey() {
let input = await vscode.window.showInputBox({
placeHolder: 'Enter your API Key of OpenAI'
});
return input;
}
async function storeApiKey(apiKey) {
let config = vscode.workspace.getConfiguration();
config.update('openAi.apiKey', apiKey, true);
}
function getApiKey() {
let config = vscode.workspace.getConfiguration();
let apiKey = config.get('openAi.apiKey');
return apiKey;
}
function openLink(link) {
var url = vscode.Uri.parse(link);
vscode.env.openExternal(url).then((success) => {
if (success) {
console.log(`Successfully opened ${url} in the browser`);
} else {
console.error(`Failed to open ${url} in the browser`);
}
});
}
function deactivate() { }
const VIDEO_GUIDE_URL = "http://www.youtube.com/watch?v=HHoCB_qZlks";
const GETTING_API_KEY_URL = "https://beta.openai.com/account/api-keys";
const COMMENT_REGEX = [
/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/gm, // /* */ , //
/#[^\n]*/g, // #
/<!--([\s\S]*?)-->/g // <!-- -->
];
module.exports = {
activate,
deactivate,
};