Skip to content

feat: add support for generating commit message #5828

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

Closed
wants to merge 17 commits into from
Closed
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
75 changes: 57 additions & 18 deletions core/commands/slash/built-in-legacy/commit.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,65 @@
import { SlashCommand } from "../../../index.js";
import {
IDE,
ILLM,
LLMFullCompletionOptions,
SlashCommand,
} from "../../../index.js";
import { renderChatMessage } from "../../../util/messageContent.js";

interface GenerateCommitMessageParams {
ide: IDE;
llm: ILLM;
includeUnstaged?: boolean;
diff?: string[];
signal: AbortSignal;
}

async function* _generateCommitMessage(
{ ide, llm, includeUnstaged, diff, signal }: GenerateCommitMessageParams,
options?: LLMFullCompletionOptions,
): AsyncGenerator<string> {
if (!diff) {
diff = await ide.getDiff(includeUnstaged ?? false);
}

if (diff.length === 0) {
yield "No changes detected. Make sure you are in a git repository with current changes.";
return;
}

const prompt = `${diff.join("\n")}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`;
for await (const chunk of llm.streamChat(
[{ role: "user", content: prompt }],
signal,
options,
)) {
yield renderChatMessage(chunk);
}
}

const CommitMessageCommand: SlashCommand = {
name: "commit",
description: "Generate a commit message for current changes",
run: async function* ({ ide, llm, params, abortController }) {
const includeUnstaged = params?.includeUnstaged ?? false;
const diff = await ide.getDiff(includeUnstaged);

if (diff.length === 0) {
yield "No changes detected. Make sure you are in a git repository with current changes.";
return;
}

const prompt = `${diff.join("\n")}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`;
for await (const chunk of llm.streamChat(
[{ role: "user", content: prompt }],
abortController.signal,
)) {
yield renderChatMessage(chunk);
}
},
run: ({ ide, llm, params, abortController, completionOptions }) =>
_generateCommitMessage(
{
ide,
llm,
includeUnstaged:
typeof params?.includeUnstaged === "boolean"
? params.includeUnstaged
: undefined,
signal: abortController.signal,
},
completionOptions,
),
};

export async function* generateCommitMessage(
params: GenerateCommitMessageParams,
options?: LLMFullCompletionOptions,
): AsyncGenerator<string> {
yield* _generateCommitMessage(params, { reasoning: false, ...options });
}

export default CommitMessageCommand;
46 changes: 46 additions & 0 deletions core/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache";
import { stringifyMcpPrompt } from "./commands/slash/mcpSlashCommand";
import { isLocalDefinitionFile } from "./config/loadLocalAssistants";
import { CodebaseRulesCache } from "./config/markdown/loadCodebaseRules";
import { generateCommitMessage } from "./commands/slash/built-in-legacy/commit";
import {
setupLocalConfig,
setupProviderConfig,
Expand Down Expand Up @@ -935,6 +936,51 @@ export class Core {
const isValid = setMdmLicenseKey(licenseKey);
return isValid;
});

on("generateCommitMessage", (msg) => {
return this.generateCommitMessageStream(msg);
});
}

private async *generateCommitMessageStream(
msg: Message<ToCoreProtocol["generateCommitMessage"][0]>,
): AsyncGenerator<string> {
const { config } = await this.configHandler.loadConfig();
if (!config) {
throw new Error("Failed to load config");
}

const { modelTitle, diff } = msg.data;

const llm =
config.modelsByRole.chat.find((m) => m.title === modelTitle) ??
config.selectedModelByRole.chat;

if (!llm) {
throw new Error("No model selected");
}

const abortController = this.addMessageAbortController(msg.messageId);

try {
for await (const content of generateCommitMessage({
ide: this.ide,
llm,
diff,
signal: abortController.signal,
})) {
yield content;
}
} catch (e) {
// Ignore this error as it may occur during manual reruns
if (e instanceof Error && !e.message.includes("operation was aborted")) {
console.log("Failed to generate commit message", e);
throw e;
}
} finally {
// Always clean up the abortController on success/failure.
this.abortById(msg.messageId);
}
}

private async handleToolCall(toolCall: ToolCall) {
Expand Down
8 changes: 8 additions & 0 deletions core/protocol/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,4 +261,12 @@ export type ToCoreFromIdeOrWebviewProtocol = {
"process/markAsBackgrounded": [{ toolCallId: string }, void];
"process/isBackgrounded": [{ toolCallId: string }, boolean];
"mdm/setLicenseKey": [{ licenseKey: string }, boolean];

generateCommitMessage: [
{
modelTitle?: string;
diff?: string[];
},
AsyncGenerator<string>,
];
};
2 changes: 2 additions & 0 deletions extensions/intellij/gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ pluginVersion=1.0.33
pluginSinceBuild=223
platformType=IC
platformVersion=2022.3.3
platformPlugins=org.jetbrains.plugins.terminal,Git4Idea
gradleVersion=8.3
kotlin.stdlib.default.dependency=false
org.gradle.configuration-cache=true
org.gradle.caching=true
Loading
Loading