From 0549083b240e0ba11b08f01b04ec6d3f89454a94 Mon Sep 17 00:00:00 2001 From: Maxime GUERIN <50274970+Natakout@users.noreply.github.com> Date: Tue, 21 Jul 2026 10:51:47 +0200 Subject: [PATCH] feat(cli): detect claude in VS Code extensions + detection order setting MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds the vscodeExtension detection source — the binary shipped with the official anthropic.claude-code extension. Resolved first through the vscode API (extensionUri), then by scanning extension directories: ~/.vscode-server, ~/.vscode and insiders/forks. Works both locally and in remote setups (SSH/WSL/devcontainer); when several versions are installed, the newest wins. The new claudeCommit.detectionOrder setting lets users define the order of sources (path, vscodeExtension, shellProfile, commonPaths) — first match wins, omitted sources are tried last. The cached path is invalidated when detectionOrder or cliPath changes. --- README.md | 25 ++++- package.json | 53 ++++++++--- src/cli/detection.ts | 212 +++++++++++++++++++++++++++++++++++-------- src/extension.ts | 14 ++- 4 files changed, 252 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index 7e1fc18..6f5466d 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,7 @@ The extension supports custom Claude API endpoints through environment variables This extension keeps it simple with optional settings: * `claudeCommit.cliPath`: Path to Claude CLI executable (leave empty for auto-detection) +* `claudeCommit.detectionOrder`: Order of the auto-detection sources (`path`, `vscodeExtension`, `shellProfile`, `commonPaths`) – first hit wins, defaults to `["path", "vscodeExtension", "shellProfile", "commonPaths"]` * `claudeCommit.apiKey`: Your Anthropic API key (only needed if using API method) * `claudeCommit.preferredMethod`: Choose AI backend (`auto`, `cli`, or `api`) – defaults to `auto` * `claudeCommit.model`: Claude model to use (`haiku`, `sonnet`, `opus`) – defaults to `haiku` @@ -109,7 +110,29 @@ This extension keeps it simple with optional settings: "claudeCommit.preferredMethod": "auto" } ``` -The extension will automatically search for Claude CLI in common locations. +The extension will automatically search for Claude CLI in common locations, including the binary bundled with the official **Claude Code VS Code extension** (`anthropic.claude-code`), e.g. `~/.vscode-server/extensions/anthropic.claude-code-/resources/native-binary/claude`. This works both locally and in remote sessions (Remote-SSH, WSL, dev containers). + +### Custom detection order +```json +{ + "claudeCommit.detectionOrder": [ + "vscodeExtension", + "path", + "commonPaths", + "shellProfile" + ] +} +``` +Sources are tried top to bottom and the first hit wins: + +| Source | Where it looks | +|---|---| +| `path` | `which claude` / `where claude` | +| `vscodeExtension` | binary shipped with the Claude Code VS Code extension (local and remote install dirs) | +| `shellProfile` | PATH after sourcing `~/.zshrc` / `~/.bashrc` (macOS/Linux) | +| `commonPaths` | npm global, `~/.local/bin`, Homebrew, nvm, … | + +Sources you omit are still tried last as a fallback, so detection never breaks. Setting `claudeCommit.cliPath` bypasses detection entirely. ### Manual CLI path (for NVM users or custom installations) ```json diff --git a/package.json b/package.json index 6715336..a148751 100644 --- a/package.json +++ b/package.json @@ -56,11 +56,38 @@ "description": "Path to Claude Code CLI executable (leave empty for auto-detection)", "order": 1 }, + "claudeCommit.detectionOrder": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "path", + "vscodeExtension", + "shellProfile", + "commonPaths" + ], + "enumDescriptions": [ + "Executable found on PATH (which/where claude)", + "Binary bundled with the official Claude Code VS Code extension (works locally and in Remote-SSH/WSL/devcontainers)", + "PATH after sourcing ~/.zshrc / ~/.bashrc (macOS/Linux only)", + "Common installation paths (npm global, ~/.local/bin, Homebrew, nvm, ...)" + ] + }, + "uniqueItems": true, + "default": [ + "path", + "vscodeExtension", + "shellProfile", + "commonPaths" + ], + "markdownDescription": "Order in which auto-detection looks for the Claude CLI. Sources are tried top to bottom and the first hit wins. Omitted sources are still tried last as a fallback. Ignored when `claudeCommit.cliPath` is set.", + "order": 2 + }, "claudeCommit.apiKey": { "type": "string", "default": "", "description": "Anthropic API key for Claude AI (optional if using Claude Code CLI)", - "order": 2 + "order": 3 }, "claudeCommit.preferredMethod": { "type": "string", @@ -71,7 +98,7 @@ ], "default": "auto", "description": "Preferred method for generating commits: auto (try CLI first, then API), cli (Claude Code CLI only), or api (Anthropic API only)", - "order": 3 + "order": 4 }, "claudeCommit.model": { "type": "string", @@ -87,7 +114,7 @@ "Claude Opus - Most capable" ], "description": "Claude model to use for commit generation", - "order": 4 + "order": 5 }, "claudeCommit.language": { "type": "string", @@ -105,13 +132,13 @@ "Chinese" ], "description": "Language for commit messages", - "order": 5 + "order": 6 }, "claudeCommit.multiLineCommit": { "type": "boolean", "default": false, "description": "Generate detailed multi-line commits with body and footer (conventional commits extended format)", - "order": 6 + "order": 7 }, "claudeCommit.diffSource": { "type": "string", @@ -127,19 +154,19 @@ "Use staged changes if available, otherwise use all changes" ], "description": "Which changes to use for generating commit messages", - "order": 7 + "order": 8 }, "claudeCommit.claudeCodeManaged": { "type": "boolean", "default": false, "markdownDescription": "Claude Code managed mode: Let Claude Code's haiku model generate commit messages with minimal intervention (only language hint provided). **Only works when preferredMethod is 'cli'**", - "order": 8 + "order": 9 }, "claudeCommit.keepCoAuthoredBy": { "type": "boolean", "default": false, "markdownDescription": "Keep Co-Authored-By signature in commit message. **Only works in Claude Code managed mode**", - "order": 9 + "order": 10 }, "claudeCommit.messageAutoCloseSeconds": { "type": "number", @@ -147,13 +174,13 @@ "minimum": 0, "maximum": 60, "description": "Auto-close timeout for the success message in seconds. Set to 0 to disable auto-close.", - "order": 10 + "order": 11 }, "claudeCommit.privacyMode": { "type": "boolean", "default": false, "markdownDescription": "Privacy mode: Restrict temporary prompt file permissions to owner-only (0600). When disabled, uses default permissions (0644). **Note: This option only takes effect on Linux/macOS. On Windows, file permissions are managed by the OS and this setting is ignored.**", - "order": 11 + "order": 12 }, "claudeCommit.commitStyle": { "type": "string", @@ -171,14 +198,14 @@ "Custom template using {diff} and {stats} variables" ], "markdownDescription": "Commit message style format. Choose 'custom' to use your own prompt template.", - "order": 12 + "order": 13 }, "claudeCommit.customPromptTemplate": { "type": "string", "default": "", "markdownDescription": "Custom prompt template. Use `{diff}` for diff content and `{stats}` for change statistics. Only used when commitStyle is set to 'custom'. Example: `Generate a commit message for:\n\n{stats}\n\n{diff}`", "editPresentation": "multilineText", - "order": 13 + "order": 14 }, "claudeCommit.commitTense": { "type": "string", @@ -192,7 +219,7 @@ "Past tense - 'added feature', 'fixed bug'" ], "markdownDescription": "Tense/mood for commit subjects. **Imperative** (default) follows the official Git convention - the subject reads as a command (e.g. 'add login button'). **Past tense** describes what was done (e.g. 'added login button').", - "order": 14 + "order": 15 } } } diff --git a/src/cli/detection.ts b/src/cli/detection.ts index cecbbda..a5286f3 100644 --- a/src/cli/detection.ts +++ b/src/cli/detection.ts @@ -11,6 +11,26 @@ const execAsync = promisify(exec); // Cache for found CLI path let cachedCliPath: string | null = null; +// Detection sources, in the order they can be configured by the user +export type DetectionSource = "path" | "vscodeExtension" | "shellProfile" | "commonPaths"; + +const DEFAULT_DETECTION_ORDER: DetectionSource[] = ["path", "vscodeExtension", "shellProfile", "commonPaths"]; + +const CLAUDE_EXTENSION_ID = "anthropic.claude-code"; + +function getDetectionOrder(config: vscode.WorkspaceConfiguration): DetectionSource[] { + const configured = config.get("detectionOrder"); + if (!Array.isArray(configured) || configured.length === 0) { + return DEFAULT_DETECTION_ORDER; + } + + const order = configured.filter((s): s is DetectionSource => DEFAULT_DETECTION_ORDER.includes(s as DetectionSource)); + + // Keep unlisted sources as a fallback tail so a partial list never disables detection + const missing = DEFAULT_DETECTION_ORDER.filter((s) => !order.includes(s)); + return [...order, ...missing]; +} + function getCommonCliPaths(): string[] { const home = os.homedir(); const paths: string[] = []; @@ -92,29 +112,101 @@ async function findCliWithGlob(pattern: string): Promise { return null; } -export async function findClaudeCliPath(): Promise { - // 1. Check user settings - const config = vscode.workspace.getConfiguration("claudeCommit"); - const userPath = config.get("cliPath"); +function getExtensionsDirs(): string[] { + const home = os.homedir(); + // Remote (`.vscode-server`) and local (`.vscode`) install roots, plus insiders + // and popular forks. Non-existent dirs are skipped silently. + return [ + ".vscode-server", + ".vscode-server-insiders", + ".vscode", + ".vscode-insiders", + ".cursor-server", + ".cursor", + ".windsurf-server", + ".windsurf", + ].map((dir) => path.join(home, dir, "extensions")); +} - if (userPath?.trim()) { - log(`Checking user-configured CLI path: ${userPath}`); - if (await fileExists(userPath)) { - log(`Found CLI at user-configured path: ${userPath}`); - return userPath; +function compareExtensionVersions(a: string, b: string): number { + // Sort newest first: anthropic.claude-code-2.1.216-linux-x64 + const parse = (name: string) => + (name.slice(CLAUDE_EXTENSION_ID.length + 1).match(/^\d+(\.\d+)*/)?.[0] ?? "0").split(".").map(Number); + + const va = parse(a); + const vb = parse(b); + for (let i = 0; i < Math.max(va.length, vb.length); i++) { + const diff = (vb[i] ?? 0) - (va[i] ?? 0); + if (diff !== 0) return diff; + } + return b.localeCompare(a); +} + +async function findCliInExtensionDir(extensionPath: string): Promise { + const binaryName = process.platform === "win32" ? "claude.exe" : "claude"; + const nativeBinaryDir = path.join(extensionPath, "resources", "native-binary"); + + // Layout used by the official extension: resources/native-binary/claude + const direct = path.join(nativeBinaryDir, binaryName); + if (await fileExists(direct)) return direct; + + // Tolerate a per-platform subdirectory: resources/native-binary//claude + try { + const entries = await fs.promises.readdir(nativeBinaryDir, { withFileTypes: true }); + for (const entry of entries) { + if (!entry.isDirectory()) continue; + const nested = path.join(nativeBinaryDir, entry.name, binaryName); + if (await fileExists(nested)) return nested; } - throw new Error(`Configured CLI path not found: ${userPath}`); + } catch { + // native-binary dir doesn't exist } - // 2. Check cache - if (cachedCliPath && (await fileExists(cachedCliPath))) { - log(`Using cached CLI path: ${cachedCliPath}`); - return cachedCliPath; + return null; +} + +/** + * Look for the CLI bundled with the official Claude Code VS Code extension. + * Works both locally and over Remote-SSH/WSL/devcontainers: the extension API + * is tried first (it knows where the current extension host installed it), + * with a scan of the well-known extension directories as fallback. + */ +async function findCliInVscodeExtensions(): Promise { + const installed = vscode.extensions.all.find((ext) => ext.id.toLowerCase() === CLAUDE_EXTENSION_ID); + + if (installed) { + const found = await findCliInExtensionDir(installed.extensionUri.fsPath); + if (found) { + log(`Found CLI in installed VS Code extension: ${found}`); + return found; + } + } + + for (const dir of getExtensionsDirs()) { + let entries: string[]; + try { + entries = await fs.promises.readdir(dir); + } catch { + continue; + } + + const candidates = entries + .filter((name) => name.toLowerCase().startsWith(`${CLAUDE_EXTENSION_ID}-`)) + .sort(compareExtensionVersions); + + for (const candidate of candidates) { + const found = await findCliInExtensionDir(path.join(dir, candidate)); + if (found) { + log(`Found CLI in VS Code extensions dir: ${found}`); + return found; + } + } } - log("Searching for Claude CLI..."); + return null; +} - // 3. Try which/where +async function findCliOnPath(): Promise { try { const cmd = process.platform === "win32" ? "where claude" : "which claude"; log(`Trying command: ${cmd}`); @@ -125,41 +217,82 @@ export async function findClaudeCliPath(): Promise { const foundPath = stdout.trim().split("\n")[0]; if (foundPath && (await fileExists(foundPath))) { log(`Found CLI via ${cmd}: ${foundPath}`); - cachedCliPath = foundPath; return foundPath; } } catch (err) { log(`which/where command failed: ${err instanceof Error ? err.message : String(err)}`); } + return null; +} - // 4. Try shell profile - if (process.platform !== "win32") { - try { - log("Trying shell profile sourcing..."); - const { stdout } = await execAsync( - "source ~/.zshrc 2>/dev/null || source ~/.bashrc 2>/dev/null || true; which claude", - { - shell: "/bin/bash", - } - ); - const foundPath = stdout.trim(); - if (foundPath && (await fileExists(foundPath))) { - log(`Found CLI via shell profile: ${foundPath}`); - cachedCliPath = foundPath; - return foundPath; +async function findCliViaShellProfile(): Promise { + if (process.platform === "win32") return null; + + try { + log("Trying shell profile sourcing..."); + const { stdout } = await execAsync( + "source ~/.zshrc 2>/dev/null || source ~/.bashrc 2>/dev/null || true; which claude", + { + shell: "/bin/bash", } - } catch (err) { - log(`Shell profile sourcing failed: ${err instanceof Error ? err.message : String(err)}`); + ); + const foundPath = stdout.trim(); + if (foundPath && (await fileExists(foundPath))) { + log(`Found CLI via shell profile: ${foundPath}`); + return foundPath; } + } catch (err) { + log(`Shell profile sourcing failed: ${err instanceof Error ? err.message : String(err)}`); } + return null; +} - // 5. Check common paths +async function findCliInCommonPaths(): Promise { log("Checking common installation paths..."); - const commonPaths = getCommonCliPaths(); - for (const p of commonPaths) { + for (const p of getCommonCliPaths()) { const found = await findCliWithGlob(p); if (found) { log(`Found CLI at common path: ${found}`); + return found; + } + } + return null; +} + +const DETECTORS: Record Promise> = { + path: findCliOnPath, + vscodeExtension: findCliInVscodeExtensions, + shellProfile: findCliViaShellProfile, + commonPaths: findCliInCommonPaths, +}; + +export async function findClaudeCliPath(): Promise { + // 1. Check user settings + const config = vscode.workspace.getConfiguration("claudeCommit"); + const userPath = config.get("cliPath"); + + if (userPath?.trim()) { + log(`Checking user-configured CLI path: ${userPath}`); + if (await fileExists(userPath)) { + log(`Found CLI at user-configured path: ${userPath}`); + return userPath; + } + throw new Error(`Configured CLI path not found: ${userPath}`); + } + + // 2. Check cache + if (cachedCliPath && (await fileExists(cachedCliPath))) { + log(`Using cached CLI path: ${cachedCliPath}`); + return cachedCliPath; + } + + // 3. Run the detection sources in the user-configured order + const order = getDetectionOrder(config); + log(`Searching for Claude CLI (order: ${order.join(" > ")})...`); + + for (const source of order) { + const found = await DETECTORS[source](); + if (found) { cachedCliPath = found; return found; } @@ -169,6 +302,11 @@ export async function findClaudeCliPath(): Promise { return null; } +// Exposed so callers can force a re-detection after settings change +export function clearCliPathCache(): void { + cachedCliPath = null; +} + export async function hasClaudeCodeCLI(): Promise { try { const cliPath = await findClaudeCliPath(); diff --git a/src/extension.ts b/src/extension.ts index add9235..af9920d 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -2,6 +2,7 @@ import * as vscode from "vscode"; import { generateCommitMessage, editCommitMessage } from "./generators/commit"; import type { GitRepository, GitAPI, Language } from "./types"; import { log, logError, showOutputChannel, disposeOutputChannel } from "./utils/logger"; +import { clearCliPathCache } from "./cli/detection"; /** * Show an information message that auto-closes after a specified timeout. @@ -244,7 +245,18 @@ export function activate(context: vscode.ExtensionContext): void { } ); - context.subscriptions.push(generateCommit, generateCommitWithCustomPrompt); + // Re-run detection when the user changes how the CLI should be located + const configWatcher = vscode.workspace.onDidChangeConfiguration((event) => { + if ( + event.affectsConfiguration("claudeCommit.detectionOrder") || + event.affectsConfiguration("claudeCommit.cliPath") + ) { + log("CLI detection settings changed, clearing cached CLI path"); + clearCliPathCache(); + } + }); + + context.subscriptions.push(generateCommit, generateCommitWithCustomPrompt, configWatcher); } async function handleCustomPrompt(repo: GitRepository): Promise {