diff --git a/.changeset/rude-jeans-impress.md b/.changeset/rude-jeans-impress.md new file mode 100644 index 00000000..d88337e8 --- /dev/null +++ b/.changeset/rude-jeans-impress.md @@ -0,0 +1,5 @@ +--- +"claude-dev": minor +--- + +Add ability to generate commit message via cline diff --git a/package.json b/package.json index dd38581a..e946778c 100644 --- a/package.json +++ b/package.json @@ -118,6 +118,12 @@ "command": "cline.focusChatInput", "title": "Jump to Chat Input", "category": "Cline" + }, + { + "command": "cline.generateGitCommitMessage", + "title": "✨ Generate Commit Message with Cline", + "category": "Cline", + "icon": "$(robot)" } ], "keybindings": [ @@ -128,6 +134,10 @@ "win": "ctrl+'", "linux": "ctrl+'", "when": "editorHasSelection" + }, + { + "command": "cline.generateGitCommitMessage", + "when": "scmProvider == git" } ], "menus": { @@ -207,6 +217,19 @@ "command": "cline.addTerminalOutputToChat", "group": "navigation" } + ], + "scm/title": [ + { + "command": "cline.generateGitCommitMessage", + "group": "navigation", + "when": "scmProvider == git" + } + ], + "commandPalette": [ + { + "command": "cline.generateGitCommitMessage", + "when": "scmProvider == git" + } ] }, "configuration": { diff --git a/src/core/controller/index.ts b/src/core/controller/index.ts index 7df6e222..873a55aa 100644 --- a/src/core/controller/index.ts +++ b/src/core/controller/index.ts @@ -30,7 +30,8 @@ import { McpDownloadResponse, McpMarketplaceCatalog, McpServer } from "@shared/m import { TelemetrySetting } from "@shared/TelemetrySetting" import { ClineCheckpointRestore, WebviewMessage } from "@shared/WebviewMessage" import { fileExistsAtPath } from "@utils/fs" -import { searchCommits } from "@utils/git" +import { searchCommits, getWorkingState } from "@utils/git" +import { extractCommitMessage } from "@integrations/git/commit-message-generator" import { getWorkspacePath } from "@utils/path" import { getTotalTasksSize } from "@utils/storage" import { openMention } from "../mentions" @@ -1813,6 +1814,109 @@ Here is the project's README to help you get started:\n\n${mcpDetails.readmeCont } } + // Git commit message generation + + async generateGitCommitMessage() { + try { + // Check if there's a workspace folder open + const cwd = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath + if (!cwd) { + vscode.window.showErrorMessage("No workspace folder open") + return + } + + // Get the git diff + const gitDiff = await getWorkingState(cwd) + if (gitDiff === "No changes in working directory") { + vscode.window.showInformationMessage("No changes in workspace for commit message") + return + } + + // Show a progress notification + await vscode.window.withProgress( + { + location: vscode.ProgressLocation.Notification, + title: "Generating commit message...", + cancellable: false, + }, + async (progress, token) => { + try { + // Format the git diff into a prompt + const prompt = `Based on the following git diff, generate a concise and descriptive commit message: + +${gitDiff.length > 5000 ? gitDiff.substring(0, 5000) + "\n\n[Diff truncated due to size]" : gitDiff} + +The commit message should: +1. Start with a short summary (50-72 characters) +2. Use the imperative mood (e.g., "Add feature" not "Added feature") +3. Describe what was changed and why +4. Be clear and descriptive + +Commit message:` + + // Get the current API configuration + const { apiConfiguration } = await getAllExtensionState(this.context) + + // Build the API handler + const apiHandler = buildApiHandler(apiConfiguration) + + // Create a system prompt + const systemPrompt = + "You are a helpful assistant that generates concise and descriptive git commit messages based on git diffs." + + // Create a message for the API + const messages = [ + { + role: "user" as const, + content: prompt, + }, + ] + + // Call the API directly + const stream = apiHandler.createMessage(systemPrompt, messages) + + // Collect the response + let response = "" + for await (const chunk of stream) { + if (chunk.type === "text") { + response += chunk.text + } + } + + // Extract the commit message + const commitMessage = extractCommitMessage(response) + + // Apply the commit message to the Git input box + if (commitMessage) { + // Get the Git extension API + const gitExtension = vscode.extensions.getExtension("vscode.git")?.exports + if (gitExtension) { + const api = gitExtension.getAPI(1) + if (api && api.repositories.length > 0) { + const repo = api.repositories[0] + repo.inputBox.value = commitMessage + vscode.window.showInformationMessage("Commit message generated and applied") + } else { + vscode.window.showErrorMessage("No Git repositories found") + } + } else { + vscode.window.showErrorMessage("Git extension not found") + } + } else { + vscode.window.showErrorMessage("Failed to generate commit message") + } + } catch (innerError) { + const innerErrorMessage = innerError instanceof Error ? innerError.message : String(innerError) + vscode.window.showErrorMessage(`Failed to generate commit message: ${innerErrorMessage}`) + } + }, + ) + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error) + vscode.window.showErrorMessage(`Failed to generate commit message: ${errorMessage}`) + } + } + // dev async resetState() { diff --git a/src/extension.ts b/src/extension.ts index 867479ec..5d0b47c7 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -10,6 +10,7 @@ import { DIFF_VIEW_URI_SCHEME } from "./integrations/editor/DiffViewProvider" import assert from "node:assert" import { posthogClientProvider } from "./services/posthog/PostHogClientProvider" import { WebviewProvider } from "./core/webview" +import { Controller } from "./core/controller" import { ErrorService } from "./services/error/ErrorService" import { initializeTestMode, cleanupTestMode } from "./services/test/TestMode" import { telemetryService } from "./services/posthog/telemetry/TelemetryService" @@ -423,6 +424,26 @@ export function activate(context: vscode.ExtensionContext) { }), ) + // Register the generateGitCommitMessage command handler + context.subscriptions.push( + vscode.commands.registerCommand("cline.generateGitCommitMessage", async () => { + // Get the controller from any instance, without activating the view + const controller = WebviewProvider.getAllInstances()[0]?.controller + + if (controller) { + // Call the controller method to generate commit message + await controller.generateGitCommitMessage() + } else { + // Create a temporary controller just for this operation + const outputChannel = vscode.window.createOutputChannel("Cline Commit Generator") + const tempController = new Controller(context, outputChannel, () => Promise.resolve(true)) + + await tempController.generateGitCommitMessage() + outputChannel.dispose() + } + }), + ) + return createClineAPI(outputChannel, sidebarWebview.controller) } diff --git a/src/integrations/git/commit-message-generator.ts b/src/integrations/git/commit-message-generator.ts new file mode 100644 index 00000000..eb0887b6 --- /dev/null +++ b/src/integrations/git/commit-message-generator.ts @@ -0,0 +1,134 @@ +import * as vscode from "vscode" +import { getWorkingState } from "@utils/git" + +/** + * Formats the git diff into a prompt for the AI + * @param gitDiff The git diff to format + * @returns A formatted prompt for the AI + */ +function formatGitDiffPrompt(gitDiff: string): string { + // Limit the diff size to avoid token limits + const maxDiffLength = 5000 + let truncatedDiff = gitDiff + + if (gitDiff.length > maxDiffLength) { + truncatedDiff = gitDiff.substring(0, maxDiffLength) + "\n\n[Diff truncated due to size]" + } + + return `Based on the following git diff, generate a concise and descriptive commit message: + +${truncatedDiff} + +The commit message should: +1. Start with a short summary (50-72 characters) +2. Use the imperative mood (e.g., "Add feature" not "Added feature") +3. Describe what was changed and why +4. Be clear and descriptive + +Commit message:` +} + +/** + * Extracts the commit message from the AI response + * @param aiResponse The response from the AI + * @returns The extracted commit message + */ +export function extractCommitMessage(aiResponse: string): string { + // Remove any markdown formatting or extra text + let message = aiResponse.trim() + + // Remove markdown code blocks if present + if (message.startsWith("```") && message.endsWith("```")) { + message = message.substring(3, message.length - 3).trim() + + // Remove language identifier if present (e.g., ```git) + const firstLineBreak = message.indexOf("\n") + if (firstLineBreak > 0 && firstLineBreak < 20) { + // Reasonable length for a language identifier + message = message.substring(firstLineBreak).trim() + } + } + + return message +} + +/** + * Copies the generated commit message to the clipboard + * @param message The commit message to copy + */ +export async function copyCommitMessageToClipboard(message: string): Promise { + await vscode.env.clipboard.writeText(message) + vscode.window.showInformationMessage("Commit message copied to clipboard") +} + +/** + * Shows a dialog with options to apply the generated commit message + * @param message The generated commit message + */ +export async function showCommitMessageOptions(message: string): Promise { + const copyAction = "Copy to Clipboard" + const applyAction = "Apply to Git Input" + const editAction = "Edit Message" + + const selectedAction = await vscode.window.showInformationMessage( + "Commit message generated", + { modal: false, detail: message }, + copyAction, + applyAction, + editAction, + ) + + // Handle user dismissing the dialog (selectedAction is undefined) + if (!selectedAction) { + return + } + + switch (selectedAction) { + case copyAction: + await copyCommitMessageToClipboard(message) + break + case applyAction: + await applyCommitMessageToGitInput(message) + break + case editAction: + await editCommitMessage(message) + break + } +} + +/** + * Applies the commit message to the Git input box in the Source Control view + * @param message The commit message to apply + */ +async function applyCommitMessageToGitInput(message: string): Promise { + // Set the SCM input box value + const gitExtension = vscode.extensions.getExtension("vscode.git")?.exports + if (gitExtension) { + const api = gitExtension.getAPI(1) + if (api && api.repositories.length > 0) { + const repo = api.repositories[0] + repo.inputBox.value = message + vscode.window.showInformationMessage("Commit message applied to Git input") + } else { + vscode.window.showErrorMessage("No Git repositories found") + await copyCommitMessageToClipboard(message) + } + } else { + vscode.window.showErrorMessage("Git extension not found") + await copyCommitMessageToClipboard(message) + } +} + +/** + * Opens the commit message in an editor for further editing + * @param message The commit message to edit + */ +async function editCommitMessage(message: string): Promise { + const document = await vscode.workspace.openTextDocument({ + content: message, + language: "markdown", + }) + + await vscode.window.showTextDocument(document) + vscode.window.showInformationMessage("Edit the commit message and copy when ready") +}