Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Epic/ai summary #757

Draft
wants to merge 14 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 119 additions & 0 deletions packages/analysis-engine/src/engine.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import "reflect-metadata";

import { container } from "tsyringe";

import { buildCommitDict } from "./commit.util";
import { buildCSMDict } from "./csm";
import getCommitRaws from "./parser";
import { PluginOctokit } from "./pluginOctokit";
import { buildStemDict } from "./stem";
import { getSummary } from "./summary";
import type { CommitNode } from "./types";

export type AnalysisEngineArgs = {
isDebugMode?: boolean;
gitLog: string;
owner: string;
repo: string;
baseBranchName: string;
auth?: string;
};

export class AnalysisEngine {
private static instance: AnalysisEngine | null = null;
private gitLog!: string;
private isDebugMode?: boolean;
private octokit!: PluginOctokit;
private baseBranchName!: string;
private nodes?: CommitNode[];
private isInitialized: boolean = false;

private constructor() {}

public static getInstance(): AnalysisEngine {
if (!AnalysisEngine.instance) {
AnalysisEngine.instance = new AnalysisEngine();
}
return AnalysisEngine.instance;
}

public initialize(args: AnalysisEngineArgs): void {
const { isDebugMode, gitLog, owner, repo, auth, baseBranchName } = args;
this.gitLog = gitLog;
this.baseBranchName = baseBranchName;
this.isDebugMode = isDebugMode;
container.register("OctokitOptions", {
useValue: {
owner,
repo,
options: {
auth,
},
},
});
this.octokit = container.resolve(PluginOctokit);
this.isInitialized = true;
}

private checkInitialization() {
if (!this.isInitialized) {
throw new Error("AnalysisEngine is not initialized. Call initialize() first.");
}
}

public async analyzeGit() {
this.checkInitialization();

if (!this.gitLog) {
throw new Error("AnalysisEngine is not initialized. Call initialize() first.");
}

let isPRSuccess = true;
if (this.isDebugMode) console.log("baseBranchName: ", this.baseBranchName);

const commitRaws = getCommitRaws(this.gitLog);
if (this.isDebugMode) console.log("commitRaws: ", commitRaws);

const commitDict = buildCommitDict(commitRaws);
if (this.isDebugMode) console.log("commitDict: ", commitDict);

const pullRequests = await this.octokit
.getPullRequests()
.catch((err) => {
console.error(err);
isPRSuccess = false;
return [];
})
.then((pullRequests) => {
console.log("success, pr = ", pullRequests);
return pullRequests;
});
if (this.isDebugMode) console.log("pullRequests: ", pullRequests);

const stemDict = buildStemDict(commitDict, this.baseBranchName);
if (this.isDebugMode) console.log("stemDict: ", stemDict);
const csmDict = buildCSMDict(commitDict, stemDict, this.baseBranchName, pullRequests);
if (this.isDebugMode) console.log("csmDict: ", csmDict);
this.nodes = stemDict.get(this.baseBranchName)?.nodes;

return {
isPRSuccess,
csmDict,
};
}

public updateArgs(args: AnalysisEngineArgs) {
if (container.isRegistered("OctokitOptions")) container.clearInstances();
this.initialize(args);
}

public async geminiCommitSummary() {
this.checkInitialization();
if (!this.nodes) {
throw new Error("No commits available. Run analyzeGit() first.");
}
return await getSummary(this.nodes.slice(-10).map(({ commit }) => commit));
}
}

export default AnalysisEngine;
96 changes: 2 additions & 94 deletions packages/analysis-engine/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,94 +1,2 @@
import "reflect-metadata";

import { container } from "tsyringe";

import { buildCommitDict } from "./commit.util";
import { buildCSMDict } from "./csm";
import getCommitRaws from "./parser";
import { PluginOctokit } from "./pluginOctokit";
import { buildStemDict } from "./stem";
import { getSummary } from "./summary";

type AnalysisEngineArgs = {
isDebugMode?: boolean;
gitLog: string;
owner: string;
repo: string;
baseBranchName: string;
auth?: string;
};

export class AnalysisEngine {
private gitLog!: string;

private isDebugMode?: boolean;

private octokit!: PluginOctokit;

private baseBranchName!: string;

constructor(args: AnalysisEngineArgs) {
this.insertArgs(args);
}

private insertArgs = (args: AnalysisEngineArgs) => {
const { isDebugMode, gitLog, owner, repo, auth, baseBranchName } = args;
this.gitLog = gitLog;
this.baseBranchName = baseBranchName;
this.isDebugMode = isDebugMode;
container.register("OctokitOptions", {
useValue: {
owner,
repo,
options: {
auth,
},
},
});
this.octokit = container.resolve(PluginOctokit);
};

public analyzeGit = async () => {
let isPRSuccess = true;
if (this.isDebugMode) console.log("baseBranchName: ", this.baseBranchName);

const commitRaws = getCommitRaws(this.gitLog);
if (this.isDebugMode) console.log("commitRaws: ", commitRaws);

const commitDict = buildCommitDict(commitRaws);
if (this.isDebugMode) console.log("commitDict: ", commitDict);

const pullRequests = await this.octokit
.getPullRequests()
.catch((err) => {
console.error(err);
isPRSuccess = false;
return [];
})
.then((pullRequests) => {
console.log("success, pr = ", pullRequests);
return pullRequests;
});
if (this.isDebugMode) console.log("pullRequests: ", pullRequests);

const stemDict = buildStemDict(commitDict, this.baseBranchName);
if (this.isDebugMode) console.log("stemDict: ", stemDict);
const csmDict = buildCSMDict(commitDict, stemDict, this.baseBranchName, pullRequests);
if (this.isDebugMode) console.log("csmDict: ", csmDict);
const nodes = stemDict.get(this.baseBranchName)?.nodes?.map(({commit}) => commit);
const geminiCommitSummary = await getSummary(nodes ? nodes?.slice(-10) : []);
if (this.isDebugMode) console.log("GeminiCommitSummary: ", geminiCommitSummary);

return {
isPRSuccess,
csmDict,
};
};

public updateArgs = (args: AnalysisEngineArgs) => {
if (container.isRegistered("OctokitOptions")) container.clearInstances();
this.insertArgs(args);
};
}

export default AnalysisEngine;
export type { AnalysisEngineArgs } from "./engine";
export { AnalysisEngine } from "./engine";
46 changes: 38 additions & 8 deletions packages/analysis-engine/src/summary.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
import type { CommitRaw } from "./types";
import type PluginOctokit from "./pluginOctokit";
import type { CommitRaw, StemDict } from "./types";

const apiKey = process.env.GEMENI_API_KEY || '';
const apiUrl = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key=";
const API_KEY = process.env.GEMENI_API_KEY || "";
const API_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key=";
const MERGE_BRANCH = "Merge branch";
const MERGE_PULL_REQUEST = "Merge pull request";

export async function getSummary(csmNodes: CommitRaw[]) {
const commitMessages = csmNodes.map((csmNode) => csmNode.message.split('\n')[0]).join(', ');
async function getSummary(csmNodes: CommitRaw[]) {
const commitMessages = csmNodes.map((csmNode) => csmNode.message.split("\n")[0]).join(", ");

console.log("commitMessages: ", commitMessages);
try {
const response = await fetch(apiUrl + apiKey, {
const response = await fetch(API_URL + API_KEY, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
contents: [{parts: [{text: `${prompt} \n${commitMessages}`}]}],
contents: [{ parts: [{ text: `${prompt} \n${commitMessages}` }] }],
}),
});

Expand All @@ -29,6 +33,32 @@ export async function getSummary(csmNodes: CommitRaw[]) {
}
}

function isNonMergeCommit(message: string) {
return !message.includes(MERGE_BRANCH) && !message.includes(MERGE_PULL_REQUEST);
}

export async function getLatestCommitSummary(stemDict: StemDict, baseBranchName: string) {
const nodes = stemDict
.get(baseBranchName)
?.nodes?.map(({ commit }) => commit)
.filter(({ message }) => isNonMergeCommit(message));

return await getSummary(nodes ? nodes?.slice(-10) : []);
}

export async function getCurrentUserCommitSummary(stemDict: StemDict, baseBranchName: string, octokit: PluginOctokit) {
const { data } = await octokit.rest.users.getAuthenticated();
const currentUserNodes = stemDict
.get(baseBranchName)
?.nodes?.filter(
({ commit: { author, message } }) =>
(author.name === data.login || author.name === data.name) && isNonMergeCommit(message)
)
?.map(({ commit }) => commit);

return await getSummary(currentUserNodes ? currentUserNodes?.slice(-10) : []);
}

const prompt = `Proceed with the task of summarising the contents of the commit message provided.

Procedure:
Expand All @@ -53,4 +83,4 @@ Output format:
- {prefix (if any)}:{commit summary3}
‘’

Commits:`
Commits:`;
21 changes: 20 additions & 1 deletion packages/vscode/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@
"visual analytics"
],
"activationEvents": [
"*"
"*",
"onView:githruSidebar"
],
"main": "./dist/extension.js",
"contributes": {
Expand Down Expand Up @@ -68,6 +69,24 @@
"description": "Insert your primary color."
}
}
},
"viewsContainers": {
"activitybar": [
{
"id": "githruSidebarView",
"title": "Githru Sidebar",
"icon": "images/logo.png"
}
]
},
"views": {
"githruSidebarView": [
{
"type": "webview",
"id": "githruSidebar",
"name": "Githru Sidebar"
}
]
}
},
"scripts": {
Expand Down
8 changes: 7 additions & 1 deletion packages/vscode/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { COMMAND_LAUNCH, COMMAND_LOGIN_WITH_GITHUB, COMMAND_RESET_GITHUB_AUTH }
import { Credentials } from "./credentials";
import { GithubTokenUndefinedError, WorkspacePathUndefinedError } from "./errors/ExtensionError";
import { deleteGithubToken, getGithubToken, setGithubToken } from "./setting-repository";
import { SidebarProvider } from "./sidebar";
import { mapClusterNodesFrom } from "./utils/csm.mapper";
import {
findGit,
Expand All @@ -25,6 +26,10 @@ function normalizeFsPath(fsPath: string) {
}

export async function activate(context: vscode.ExtensionContext) {
const provider = new SidebarProvider(context.extensionUri);

context.subscriptions.push(vscode.window.registerWebviewViewProvider("githruSidebar", provider));

const { subscriptions, extensionPath, secrets } = context;
const credentials = new Credentials();
let currentPanel: vscode.WebviewPanel | undefined = undefined;
Expand Down Expand Up @@ -82,7 +87,8 @@ export async function activate(context: vscode.ExtensionContext) {
const { owner, repo: initialRepo } = getRepo(gitConfig);
webLoader.setGlobalOwnerAndRepo(owner, initialRepo);
const repo = initialRepo[0];
const engine = new AnalysisEngine({
const engine = AnalysisEngine.getInstance();
engine.initialize({
isDebugMode: true,
gitLog,
owner,
Expand Down
Loading
Loading