Skip to content

Commit

Permalink
add more code
Browse files Browse the repository at this point in the history
  • Loading branch information
decyjphr authored and sclachar committed Feb 16, 2025
1 parent 0a7f341 commit c642d4e
Show file tree
Hide file tree
Showing 2 changed files with 133 additions and 87 deletions.
21 changes: 20 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,26 @@
"description": "Focus on a program..."
}
]
}
},
{
"id": "legacynavigator.demo",
"name": "navigator",
"description": "Provide various commands that helps developers to migrate legacy code",
"commands": [
{
"name": "demystify",
"description": "Provides natural language explanation of the code to different personas"
},
{
"name": "structure",
"description": "Provides a graph representation of the code"
},
{
"name": "transform",
"description": "Transform snippets of legacy the code to a modern implementation"
}
]
}
],
"commands": [
{
Expand Down
199 changes: 113 additions & 86 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { DigPrompt, PromptProps } from './dig';
import { GoalsPrompt } from './goals';
import { TriggersPrompt } from './triggers';
import { FocusPrompt } from './focus';
import * as fs from 'fs';
import * as path from 'path';

const CODEARCHEO_NAMES_COMMAND_ID = 'codearcheo.namesInEditor';
const CODEARCHEO_AST_COMMAND_ID = 'codearcheo.astInEditor';
Expand All @@ -22,43 +24,6 @@ export function activate(context: vscode.ExtensionContext) {

// Define a Codearcheo chat handler.
const handler: vscode.ChatRequestHandler = async (request: vscode.ChatRequest, context: vscode.ChatContext, stream: vscode.ChatResponseStream, token: vscode.CancellationToken): Promise<ICodearcheoChatResult> => {
// To talk to an LLM in your subcommand handler implementation, your
// extension can use VS Code's `requestChatAccess` API to access the Copilot API.
// The GitHub Copilot Chat extension implements this provider.
// if (request.command === 'funny') {
// stream.progress('Coming up with something funny...');
// const topic = getTopic(context.history);
// try {
// // To get a list of all available models, do not pass any selector to the selectChatModels.
// const [model] = await vscode.lm.selectChatModels(MODEL_SELECTOR);
// if (model) {
// const messages = [
// vscode.LanguageModelChatMessage.User('You are a cat! Your job is to explain computer science concepts in the funny manner of a cat. Always start your response by stating what concept you are explaining. Always include code samples.'),
// vscode.LanguageModelChatMessage.User(topic)
// ];

// const chatResponse = await model.sendRequest(messages, {}, token);
// for await (const fragment of chatResponse.text) {
// stream.markdown(fragment);
// }
// }
// } catch(err) {
// handleError(logger, err, stream);
// }

// stream.button({
// command: CODEARCHEO_AST_COMMAND_ID,
// title: vscode.l10n.t('Lets get the AST')
// });

// // stream.button({
// // command: CODEARCHEO_NAMES_COMMAND_ID,
// // title: vscode.l10n.t('Lets find some labels')
// // });

// logger.logUsage('request', { kind: 'funny'});
// return { metadata: { command: 'funny' } };
// } else
if (request.command === 'goals') {
stream.progress('Getting the goals...');
await processCommandRequest(GoalsPrompt, request, token, stream, logger);
Expand Down Expand Up @@ -110,6 +75,102 @@ export function activate(context: vscode.ExtensionContext) {
}
};


vscode.chat.createChatParticipant("legacynavigator.demo", async (request, context, response, token) => {
const query = request.prompt;
const chatModel = await vscode.lm.selectChatModels({family: 'gpt-4o'});


if (request.command === 'demystify') {
let documentText = '';
let editor = vscode.window.activeTextEditor;
if (editor) {
let document = editor.document;
// Get the document text
documentText = document.getText();
}

const promptFilePath = '../src/prompts/explain.md';
const pathToPrompt = path.resolve(__dirname, promptFilePath);
const prompt = fs.readFileSync(pathToPrompt, 'utf-8');

const messages = [vscode.LanguageModelChatMessage.User(prompt),
vscode.LanguageModelChatMessage.User(`${query} ${documentText}`)];

const chatRequest = await chatModel[0].sendRequest(messages, undefined, token);
for await (const message of chatRequest.text) {
response.markdown(message);
}

}
else if (request.command === 'structure') {
const promptFilePath = '../src/prompts/graph.md';
const pathToPrompt = path.resolve(__dirname, promptFilePath);
const prompt = fs.readFileSync(pathToPrompt, 'utf-8');

const srcFilePath = '../../../codeql/legacy-mars-global-climate-model/code/Makefile';
const pathToSrc= path.resolve(__dirname, srcFilePath);
const srcFiles = extractSrcFiles(pathToSrc);

let documentText = '';
let editor = vscode.window.activeTextEditor;
if (editor) {
let document = editor.document;
// Get the document text
documentText = document.getText();
}

// prompt = `Analyze the following file contents and determine how each file is linked to the others:\n${prompt}`;
const messages = [
vscode.LanguageModelChatMessage.User(prompt + "\n" + `The following files are used in this repository:\n${srcFiles.join('\n')}` + "\n" + "You should suggest a mermaid diagram that begins with ```mermaid and ends with ```" + "\n"),
vscode.LanguageModelChatMessage.User(`${query} ${documentText}`)
];

const chatRequest = await chatModel[0].sendRequest(messages, undefined, token);
for await (const message of chatRequest.text) {
response.markdown(message);
}


}else if (request.command === 'transform') {
let promptFilePath = '../src/prompts/dependencies.md';
let pathToPrompt = path.resolve(__dirname, promptFilePath);

//dependencies
const prompt = fs.readFileSync(pathToPrompt, 'utf-8');

promptFilePath = '../src/prompts/features.md';
pathToPrompt = path.resolve(__dirname, promptFilePath);

//functionality
const prompt2 = fs.readFileSync(pathToPrompt, 'utf-8');

promptFilePath = '../src/prompts/transform.md';
pathToPrompt = path.resolve(__dirname, promptFilePath);
// transform
const prompt3 = fs.readFileSync(pathToPrompt, 'utf-8');

let documentText = '';
let editor = vscode.window.activeTextEditor;
if (editor) {
let document = editor.document;
// Get the document text
documentText = document.getText();
}

const messages = [vscode.LanguageModelChatMessage.User(prompt + "\n" + prompt2 + "\n" + prompt3),
vscode.LanguageModelChatMessage.User(`${query} ${documentText}`)];

const chatRequest = await chatModel[0].sendRequest(messages, undefined, token);
for await (const message of chatRequest.text) {
response.markdown(message);
}

}

});


// Chat participants appear as top-level options in the chat input
// when you type `@`, and can contribute sub-commands in the chat input
// that appear when you type `/`.
Expand Down Expand Up @@ -208,55 +269,6 @@ export function activate(context: vscode.ExtensionContext) {

await vscode.commands.executeCommand('codeQL.viewAst', textEditor.document.uri);


// let chatResponse: vscode.LanguageModelChatResponse | undefined;
// try {
// const [model] = await vscode.lm.selectChatModels(MODEL_SELECTOR);
// if (!model) {
// console.log('Model not found. Please make sure the GitHub Copilot Chat extension is installed and enabled.');
// return;
// }

// const messages = [
// vscode.LanguageModelChatMessage.User(`You are a cat! Think carefully and step by step like a cat would.
// Your job is to replace all variable names in the following code with funny cat variable names. Be creative. IMPORTANT respond just with code. Do not use markdown!`),
// vscode.LanguageModelChatMessage.User(text)
// ];
// chatResponse = await model.sendRequest(messages, {}, new vscode.CancellationTokenSource().token);

// } catch (err) {
// if (err instanceof vscode.LanguageModelError) {
// console.log(err.message, err.code, err.cause);
// } else {
// throw err;
// }
// return;
// }

// // Clear the editor content before inserting new content
// await textEditor.edit(edit => {
// const start = new vscode.Position(0, 0);
// const end = new vscode.Position(textEditor.document.lineCount - 1, textEditor.document.lineAt(textEditor.document.lineCount - 1).text.length);
// edit.delete(new vscode.Range(start, end));
// });

// // Stream the code into the editor as it is coming in from the Language Model
// try {
// for await (const fragment of chatResponse.text) {
// await textEditor.edit(edit => {
// const lastLine = textEditor.document.lineAt(textEditor.document.lineCount - 1);
// const position = new vscode.Position(lastLine.lineNumber, lastLine.text.length);
// edit.insert(position, fragment);
// });
// }
// } catch (err) {
// // async response stream may fail, e.g network interruption or server side error
// await textEditor.edit(edit => {
// const lastLine = textEditor.document.lineAt(textEditor.document.lineCount - 1);
// const position = new vscode.Position(lastLine.lineNumber, lastLine.text.length);
// edit.insert(position, (<Error>err).message);
// });
// }
}),
);
}
Expand Down Expand Up @@ -319,4 +331,19 @@ function getTopic(history: ReadonlyArray<vscode.ChatRequestTurn | vscode.ChatRes
return topicsNoRepetition[Math.floor(Math.random() * topicsNoRepetition.length)] || 'I have taught you everything I know. Meow!';
}

function extractSrcFiles(makefilePath: string): string[] {
const content = fs.readFileSync(makefilePath, 'utf-8');
const srcMatch = content.match(/SRC\s*=\s*([\s\S]*?)(?=\n\S|$)/);

if (srcMatch) {
const srcFiles = srcMatch[1]
.split(/\\?\s+/)
.map(file => path.resolve(path.dirname(makefilePath), file.trim()))
.filter(file => file.length > 0);
return srcFiles.splice(0, srcFiles.length-1);
} else {
return [];
}
}

export function deactivate() { }

0 comments on commit c642d4e

Please sign in to comment.