import { spawn, spawnSync } from 'node:child_process' import { basename, dirname, isAbsolute, relative, resolve } from 'node:path' import { createHash } from 'node:crypto' import { type Stats, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, realpathSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs' import type { Branch, BranchSwitchRequest, BranchSwitchResponse, ChangedFileItem, ChangedFileState, CommitChangesResponse, Commit, FileContentType, FileSyncState, GeneratedLocalState, GitContext, GitIdentityUpdateResponse, GitUserIdentity, KeyDocumentItem, LocalPathClassification, LocalGitState, RemoteSyncResponse, RepoSyncState, RepoInfo, RepoRemoteContext, RepositoryStatusSummary, RepositoryStatusTone, TreeNode, ViewerPathType, } from '../types.js' import { validateSshPrivateKeyPath, } from './identity-settings.js' interface WorkingTreeChangeSummary { trackedPaths: string[] untrackedPaths: string[] } interface FileSyncAnalysis { changes: WorkingTreeChangeSummary repoSync: RepoSyncState localCommittedPaths: Set remoteCommittedPaths: Set } interface GitWorktreeEntry { path: string branchRef: string } let cachedAppVersion = '' function resolvePackageVersionFromCandidates(): string | null { const candidatePaths = [ new URL('../../package.json', import.meta.url), new URL('../package.json', import.meta.url), ] for (const packageJsonPath of candidatePaths) { try { const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as { version?: string } if (packageJson.version) { return packageJson.version } } catch { continue } } return null } export function getAppVersion(): string { if (cachedAppVersion) return cachedAppVersion cachedAppVersion = resolvePackageVersionFromCandidates() ?? '0.0.0' return cachedAppVersion } interface GitRunResult { status: number stdout: string stderr: string error?: Error } // Git output shared by every read inside one withGitOutputCache() call. The helpers in this module // are synchronous and freely re-run the same read-only command (a single sync-status check used to // run `git status` four times); the cache makes each distinct command run once per call. let activeGitOutputCache: Map | null = null function gitCacheKey(repoPath: string, args: string[]): string { return `${repoPath}\0${args.join('\0')}` } function runGit(repoPath: string, args: string[]): GitRunResult { const key = gitCacheKey(repoPath, args) const cached = activeGitOutputCache?.get(key) if (cached) return cached const result = spawnSync('git', args, { cwd: repoPath, encoding: 'utf-8' }) const captured: GitRunResult = { status: result.status ?? 1, stdout: result.stdout ?? '', stderr: result.stderr ?? '', error: result.error, } activeGitOutputCache?.set(key, captured) return captured } function runGitAsync(repoPath: string, args: string[]): Promise { return new Promise((resolvePromise) => { // GIT_OPTIONAL_LOCKS=0: a background `git status` must not take index.lock and make a git // command the user runs in the terminal at the same moment fail (VS Code does the same). const child = spawn('git', args, { cwd: repoPath, env: { ...process.env, GIT_OPTIONAL_LOCKS: '0' } }) const stdout: Buffer[] = [] const stderr: Buffer[] = [] child.stdout.on('data', (chunk: Buffer) => stdout.push(chunk)) child.stderr.on('data', (chunk: Buffer) => stderr.push(chunk)) child.on('error', (error) => resolvePromise({ status: 1, stdout: '', stderr: '', error })) child.on('close', (code) => { resolvePromise({ status: code ?? 1, stdout: Buffer.concat(stdout).toString('utf-8'), stderr: Buffer.concat(stderr).toString('utf-8'), }) }) }) } export async function getCurrentBranchAsync(repoPath: string): Promise { const result = await runGitAsync(repoPath, ['rev-parse', '--abbrev-ref', 'HEAD']) return result.status === 0 ? result.stdout.trim() : '' } /** * Runs `compute` with every read-only git command it issues memoized, after first running the * `prefetch` commands asynchronously. The server's event loop also carries terminal I/O, so the * expensive commands of a frequently-polled request (git status, ls-files) must not run through * spawnSync, which would freeze every open terminal for the command's full duration. `compute` * must be synchronous and must not modify the repository: the cache is only valid while nothing * else can run, and a write would make cached output stale. */ export async function withGitOutputCache(repoPath: string, prefetch: string[][], compute: () => T): Promise { const cache = new Map() const results = await Promise.all(prefetch.map((args) => runGitAsync(repoPath, args))) prefetch.forEach((args, index) => cache.set(gitCacheKey(repoPath, args), results[index])) const previous = activeGitOutputCache activeGitOutputCache = cache try { return compute() } finally { activeGitOutputCache = previous } } export function spawnGit(repoPath: string, ...args: string[]): string { const result = runGit(repoPath, args) /* v8 ignore next */ if (result.error) throw result.error /* v8 ignore next */ if (result.status !== 0) throw new Error(result.stderr.trim() || `git ${args[0]} failed`) return result.stdout.trim() } function runGitCapture(repoPath: string, ...args: string[]): { status: number; stdout: string; stderr: string } { const { status, stdout, stderr } = runGit(repoPath, args) return { status, stdout, stderr } } function readGitConfig(repoPath: string, scope: '--local' | '--global', key: string): string { const result = runGitCapture(repoPath, 'config', scope, key) return result.status === 0 ? result.stdout.trim() : '' } function writeGitConfig(repoPath: string, key: string, value: string): void { const result = runGitCapture(repoPath, 'config', '--local', key, value) if (result.status !== 0) { throw new Error(result.stderr.trim() || `Unable to update ${key}.`) } } function unsetGitConfig(repoPath: string, key: string): void { const result = runGitCapture(repoPath, 'config', '--local', '--unset', key) if (result.status !== 0 && result.status !== 5 && !result.stderr.includes('No such section') && !result.stderr.includes('No such key')) { /* v8 ignore next -- defensive for unexpected git config failures not reproducible through product flows */ throw new Error(result.stderr.trim() || `Unable to clear ${key}.`) } } function getConfiguredRemotes(repoPath: string): string[] { const result = runGitCapture(repoPath, 'remote') if (result.status !== 0 || !result.stdout) return [] return result.stdout .split('\n') .map((line) => line.trim()) .filter(Boolean) } function uniqueNormalizedPaths(paths: string[]): string[] { return [...new Set(paths.map((path) => normalizeRepoRelativePath(path)).filter(Boolean))] } function stripGitSuffix(value: string): string { return value.replace(/\.git$/i, '').replace(/\/+$/, '') } export function convertGitRemoteToWebUrl(fetchUrl: string): string { const trimmed = fetchUrl.trim() if (!trimmed || trimmed.startsWith('file://') || trimmed.startsWith('/')) return '' if (/^https?:\/\//i.test(trimmed)) { try { const parsed = new URL(trimmed) parsed.pathname = stripGitSuffix(parsed.pathname) parsed.search = '' parsed.hash = '' return parsed.toString().replace(/\/$/, '') } catch { return stripGitSuffix(trimmed) } } const sshUrlMatch = trimmed.match(/^ssh:\/\/[^@]+@([^/]+)\/(.+)$/i) if (sshUrlMatch) { const [, host, path] = sshUrlMatch return `https://${host}/${stripGitSuffix(path)}` } const scpStyleMatch = trimmed.match(/^[^@]+@([^:]+):(.+)$/) if (scpStyleMatch) { const [, host, path] = scpStyleMatch return `https://${host}/${stripGitSuffix(path)}` } return '' } export function getGitUserIdentity(repoPath: string): GitUserIdentity | null { const localName = readGitConfig(repoPath, '--local', 'user.name') const localEmail = readGitConfig(repoPath, '--local', 'user.email') const sshKeyPath = getRepoSshKeyPath(repoPath) if (!localName && !localEmail && !sshKeyPath) return null return { name: localName, email: localEmail, source: 'local', ...(sshKeyPath ? { sshKeyPath } : {}), } } export function getRepoSshKeyPath(repoPath: string): string { const sshCommand = readGitConfig(repoPath, '--local', 'core.sshCommand') if (!sshCommand) return '' const match = sshCommand.match(/(?:^|\s)-i\s+(?:"([^"]+)"|'([^']+)'|(\S+))/) return (match?.[1] ?? match?.[2] ?? match?.[3] ?? '').trim() } function formatSshCommandForKeyPath(sshKeyPath: string): string { const escaped = sshKeyPath.replaceAll('"', '\\"') return `ssh -i "${escaped}" -o IdentitiesOnly=yes` } export function setRepoGitIdentity(repoPath: string, name: string, email: string, sshKeyPath?: string): GitIdentityUpdateResponse { const trimmedName = name.trim() const trimmedEmail = email.trim() const normalizedSshKeyPath = sshKeyPath?.trim() const clearingUser = !trimmedName && !trimmedEmail if (!clearingUser && (!trimmedName || !trimmedEmail)) { throw new Error('Git name and email must both be set or both be cleared.') } if (!validateRepo(repoPath)) { throw new Error('No repository is currently open.') } if (normalizedSshKeyPath) { const validation = validateSshPrivateKeyPath(normalizedSshKeyPath) if (!validation.valid) { throw new Error(validation.message) } } if (clearingUser) { unsetGitConfig(repoPath, 'user.name') unsetGitConfig(repoPath, 'user.email') } else { writeGitConfig(repoPath, 'user.name', trimmedName) writeGitConfig(repoPath, 'user.email', trimmedEmail) } if (normalizedSshKeyPath !== undefined) { if (normalizedSshKeyPath) { writeGitConfig(repoPath, 'core.sshCommand', formatSshCommandForKeyPath(normalizedSshKeyPath)) } else { unsetGitConfig(repoPath, 'core.sshCommand') } } const user = getGitUserIdentity(repoPath) /* v8 ignore next 3 -- if local writes succeed, git must be able to read them back unless clearing */ if (!user && !clearingUser && normalizedSshKeyPath !== '') { throw new Error('GitLocal could not read the updated repository identity.') } return { ok: true, message: user ? 'Repository git identity updated.' : 'Repository git identity cleared.', user, } } export function getGitRemoteContext(repoPath: string): RepoRemoteContext | null { const remotes = getConfiguredRemotes(repoPath) if (remotes.length === 0) return null const currentBranch = getCurrentBranch(repoPath) const upstreamRemote = currentBranch && currentBranch !== 'HEAD' ? readGitConfig(repoPath, '--local', `branch.${currentBranch}.remote`) : '' const selectedRemote = (upstreamRemote && remotes.includes(upstreamRemote) ? upstreamRemote : '') || (remotes.includes('origin') ? 'origin' : '') || remotes[0] if (!selectedRemote) return null const selectionReason = selectedRemote === upstreamRemote ? 'upstream' : selectedRemote === 'origin' ? 'origin' : 'first-configured' const fetchUrl = readGitConfig(repoPath, '--local', `remote.${selectedRemote}.url`) if (!fetchUrl) return null return { name: selectedRemote, fetchUrl, webUrl: convertGitRemoteToWebUrl(fetchUrl), selectionReason, } } export function getGitContext(repoPath: string): GitContext { return { user: getGitUserIdentity(repoPath), remote: getGitRemoteContext(repoPath), } } function normalizePlatformPath(path: string): string { return resolve(path) } // Deliberately unguarded: a realpathSync failure here must propagate to the global onError // handler (src/server.ts) so classifyLocalPath's many callers (getInfo, treeHandler, etc.) see // a real failure rather than a classification that silently substitutes a fallback path. // realpathSync.native also returns the on-disk letter case on case-insensitive file systems // (macOS, Windows). `git rev-parse --show-toplevel` reports that case too, so a typed path in // another case (~/projects/app for ~/Projects/app) still compares equal to its repository root. function canonicalizeExistingPath(path: string): string { return normalizePlatformPath(realpathSync.native(path)) } function getContainingGitRoot(existingPath: string, isFile: boolean): string { const cwd = isFile ? dirname(existingPath) : existingPath try { const rootPath = spawnGit(cwd, 'rev-parse', '--show-toplevel') return rootPath ? canonicalizeExistingPath(rootPath) : '' } catch { return '' } } function isSamePath(left: string, right: string): boolean { return normalizePlatformPath(left) === normalizePlatformPath(right) } function isPathDescendant(parentPath: string, childPath: string): boolean { const rel = relative(parentPath, childPath) return Boolean(rel) && !rel.startsWith('..') && !isAbsolute(rel) } export function classifyLocalPath(inputPath: string): LocalPathClassification { const requestedPath = inputPath ? resolve(inputPath) : '' if (!requestedPath || !existsSync(requestedPath)) { return { inputPath, canonicalPath: requestedPath, exists: false, pathType: 'missing', gitState: 'outside-repository', openMode: 'blocked', message: requestedPath ? `Path does not exist: ${requestedPath}` : 'path is required', } } const stats = statSync(requestedPath) const pathType: LocalPathClassification['pathType'] = stats.isFile() ? 'file' : stats.isDirectory() ? 'directory' : 'unsupported' const canonicalPath = canonicalizeExistingPath(requestedPath) if (pathType === 'unsupported') { return { inputPath, canonicalPath, exists: true, pathType, gitState: 'outside-repository', openMode: 'blocked', message: `Not a folder or file: ${inputPath}`, } } const repositoryRootPath = getContainingGitRoot(canonicalPath, pathType === 'file') const gitState: LocalPathClassification['gitState'] = repositoryRootPath ? isSamePath(repositoryRootPath, canonicalPath) ? 'repository-root' : isPathDescendant(repositoryRootPath, canonicalPath) ? 'inside-repository' : 'outside-repository' : 'outside-repository' const openMode: LocalPathClassification['openMode'] = pathType === 'file' ? 'file' : gitState === 'repository-root' ? 'repository' : 'folder' return { inputPath, canonicalPath, exists: true, pathType, gitState, openMode, ...(repositoryRootPath ? { repositoryRootPath } : {}), } } export interface DirectOpenTarget { rootPath: string selectedPath: string selectedPathType: ViewerPathType isGitRepo: boolean } // The single rule for turning a directly-opened file's canonical path into a file-tree root // and a selection relative to that root: a file inside a git repository roots at the // repository and selects the file's path relative to it; a file outside any repository roots // at the file's own containing folder and selects just its name. Used by both the native // "open with" startup path and the runtime "open this file" API, so this determination is // made in exactly one place instead of two independently-computed copies of the same rule. export function resolveDirectOpenTarget(canonicalFilePath: string, repositoryRootPath?: string): DirectOpenTarget { const rootPath = repositoryRootPath ?? dirname(canonicalFilePath) const selectedPath = repositoryRootPath ? relative(rootPath, canonicalFilePath).split('\\').join('/') : basename(canonicalFilePath) return { rootPath, selectedPath, selectedPathType: 'file', isGitRepo: Boolean(repositoryRootPath), } } export interface DirectoryOpenTarget { rootPath: string selectedPath: string selectedPathType: ViewerPathType } // The rule for a directly-opened folder: a folder inside a git repository opens the repository // (so branch, sync and change state apply) with that folder selected; any other folder is its // own root. Shared by startup, the open API, and the parent-folder walk. export function resolveDirectoryOpenTarget(canonicalDirPath: string, gitState: LocalGitState, repositoryRootPath?: string): DirectoryOpenTarget { if (repositoryRootPath && gitState === 'inside-repository') { return { rootPath: repositoryRootPath, selectedPath: relative(repositoryRootPath, canonicalDirPath).split('\\').join('/'), selectedPathType: 'dir', } } return { rootPath: gitState === 'repository-root' && repositoryRootPath ? repositoryRootPath : canonicalDirPath, selectedPath: '', selectedPathType: 'none', } } export function validateRepo(repoPath: string): boolean { return classifyLocalPath(repoPath).gitState === 'repository-root' } export function getCurrentBranch(repoPath: string): string { try { return spawnGit(repoPath, 'rev-parse', '--abbrev-ref', 'HEAD') } catch { return '' } } // Handlers resolve a request branch the same way everywhere: honor an explicit branch for a // real repo, otherwise fall back to the current branch, and treat non-repos as branch-less. export function resolveCurrentBranch(repoPath: string, requestedBranch?: string | null): string { return validateRepo(repoPath) ? requestedBranch ?? getCurrentBranch(repoPath) : '' } export function hasCommits(repoPath: string): boolean { const result = spawnSync('git', ['rev-parse', '--verify', 'HEAD'], { cwd: repoPath, stdio: 'ignore', }) return result.status === 0 } // Deliberately does not catch readdirSync failures here (see listWorkingTreeDirectoryEntries): // this feeds RepoInfo.rootEntryCount for the non-git path, and swallowing a real read failure // to an empty/zero result would make it indistinguishable from a genuinely empty folder — the // exact "empty content on startup" bug. Let it propagate to the global onError handler instead. export function getBrowseableRootEntryCount(repoPath: string): number { return listWorkingTreeDirectoryEntries(repoPath) .filter((entry) => !entry.name.startsWith('.')) .length } // Unlike getBrowseableRootEntryCount above, returning 0 on failure here is intentionally safe: // this is only reached after other git operations (spawnGit, hasCommits) already implicitly // proved the path is accessible, making a readdirSync failure here a genuinely rare, near- // untestable edge case — not a template to copy for the non-git/general path. function getFastBrowseableRootEntryCount(repoPath: string): number { try { return readdirSync(repoPath, { withFileTypes: true }) .filter((entry) => entry.name !== '.git' && !entry.name.startsWith('.')) .length } catch { /* v8 ignore next -- directory readability can change between classification and counting */ return 0 } } export function getInfo(repoPath: string): RepoInfo { const version = getAppVersion() if (!repoPath) { return { name: '', path: '', currentBranch: '', isGitRepo: false, pickerMode: true, version, hasCommits: false, rootEntryCount: 0, gitContext: null, } } const classification = classifyLocalPath(repoPath) const isGitRepo = classification.gitState === 'repository-root' if (!isGitRepo) { return { name: basename(classification.canonicalPath || repoPath), path: classification.canonicalPath || repoPath, currentBranch: '', isGitRepo: false, pickerMode: false, version, hasCommits: false, rootEntryCount: getBrowseableRootEntryCount(classification.canonicalPath || repoPath), gitContext: null, } } let currentBranch = '' currentBranch = getCurrentBranch(classification.canonicalPath) return { name: basename(classification.canonicalPath), path: classification.canonicalPath, currentBranch, isGitRepo: true, pickerMode: false, version, hasCommits: hasCommits(classification.canonicalPath), rootEntryCount: getFastBrowseableRootEntryCount(classification.canonicalPath), gitContext: null, } } export function getBranches(repoPath: string): Branch[] { const currentBranch = getCurrentBranch(repoPath) const localResult = runGitCapture(repoPath, 'for-each-ref', '--format=%(refname:short)%00%(upstream:short)', 'refs/heads') const remoteResult = runGitCapture(repoPath, 'for-each-ref', '--format=%(refname:short)', 'refs/remotes') if (localResult.status !== 0 && remoteResult.status !== 0) return [] const branches: Branch[] = [] const localNames = new Set() for (const raw of localResult.stdout.split('\n').filter(Boolean)) { const [name, trackingRef = ''] = raw.split('\0') const remoteName = trackingRef.includes('/') ? trackingRef.split('/')[0] : undefined localNames.add(name) branches.push({ name, displayName: name, scope: 'local', remoteName, trackingRef: trackingRef || undefined, hasLocalCheckout: true, isCurrent: name === currentBranch, }) } for (const raw of remoteResult.stdout.split('\n').filter(Boolean)) { const ref = raw.trim() if (!ref || ref.endsWith('/HEAD')) continue const boundary = ref.indexOf('/') if (boundary < 0) continue const remoteName = ref.slice(0, boundary) const shortName = ref.slice(boundary + 1) if (!shortName || localNames.has(shortName)) continue branches.push({ name: shortName, displayName: `${shortName} (${remoteName})`, scope: 'remote', remoteName, trackingRef: ref, hasLocalCheckout: false, isCurrent: false, }) } return branches.sort((a, b) => { if (a.isCurrent !== b.isCurrent) return a.isCurrent ? -1 : 1 if ((a.scope ?? 'local') !== (b.scope ?? 'local')) return (a.scope ?? 'local') === 'local' ? -1 : 1 return (a.displayName ?? a.name).localeCompare(b.displayName ?? b.name) }) } export function getCommits(repoPath: string, branch: string, limit: number = 10): Commit[] { const max = Math.min(limit, 100) let output = '' try { output = spawnGit( repoPath, 'log', branch, `--max-count=${max}`, '--format=%H%x1f%an%x1f%aI%x1f%s', ) } catch { return [] } return output .split('\n') .filter(Boolean) .map((line) => { const [hash, author, date, ...msgParts] = line.split('\x1f') /* v8 ignore next 6 */ return { hash: hash ?? '', shortHash: (hash ?? '').slice(0, 7), author: author ?? '', date: date ?? '', message: msgParts.join('\x1f'), } }) } export function findReadme(repoPath: string, branch: string = 'HEAD', folderPath: string = ''): string { const normalizedFolder = normalizeRepoRelativePath(folderPath) if (isWorkingTreeBranch(repoPath, branch)) { const workingTreeReadme = listWorkingTreeDirectoryEntries(repoPath, normalizedFolder) .find((entry) => entry.type === 'file' && /^readme(\.\w+)?$/i.test(entry.name)) if (workingTreeReadme) { return workingTreeReadme.path } } const treeish = normalizedFolder ? `${branch}:${normalizedFolder}` : branch const result = runGitCapture(repoPath, 'ls-tree', '--name-only', treeish) if (result.status !== 0 || !result.stdout) { return '' } const readme = result.stdout .split('\n') .map((line) => line.trim()) .find((fileName) => /^readme(\.\w+)?$/i.test(fileName)) if (!readme) return '' return normalizedFolder ? `${normalizedFolder}/${readme}` : readme } export function isWorkingTreeBranch(repoPath: string, branch: string): boolean { if (!branch || branch === 'HEAD') return true return branch === getCurrentBranch(repoPath) } export function resolveRepoPath(repoPath: string, filePath: string): string { return resolve(repoPath, filePath) } export function normalizeRepoRelativePath(filePath: string): string { const normalized = filePath.replaceAll('\\', '/').trim() if (!normalized) return '' return normalized.replace(/^\.?\//, '').replace(/\/+/g, '/') } export function isPathInsideRepo(repoPath: string, filePath: string): boolean { const normalized = normalizeRepoRelativePath(filePath) if (!normalized) return false const resolvedPath = resolveRepoPath(repoPath, normalized) const rel = relative(repoPath, resolvedPath) return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel) } export function resolveSafeRepoPath(repoPath: string, filePath: string): string | null { if (!filePath) return repoPath if (!isPathInsideRepo(repoPath, filePath)) return null const fullPath = resolveRepoPath(repoPath, normalizeRepoRelativePath(filePath)) let existingAncestor = fullPath while (!existsSync(existingAncestor)) { const parent = dirname(existingAncestor) if (parent === existingAncestor) return null existingAncestor = parent } try { const canonicalRepoPath = realpathSync(repoPath) const canonicalAncestor = realpathSync(existingAncestor) const ancestorRelativePath = relative(canonicalRepoPath, canonicalAncestor) if (ancestorRelativePath.startsWith('..') || isAbsolute(ancestorRelativePath)) return null } catch { return null } return fullPath } // A cheaper resolution for read-only path classification: keeps resolveSafeRepoPath's lexical // `../`-escape guard (isPathInsideRepo, pure string comparison) but skips its per-segment // existsSync-walk + realpathSync symlink-escape re-check — the check that actually matters for // write operations (see writeWorkingTreeTextFile/createWorkingTreeFolder/deleteWorkingTreeFile, // which each re-resolve via the full resolveSafeRepoPath independently right before mutating // anything). getPathType is read-only classification only, so a symlinked ancestor at worst // changes what "type" gets reported for a path GitLocal never writes through this call — it // does not weaken the write-path containment guarantee, which is re-checked at write time // regardless of what any earlier getPathType call returned. function resolveClassificationPath(repoPath: string, filePath: string): string | null { if (!filePath) return repoPath if (!isPathInsideRepo(repoPath, filePath)) return null return resolveRepoPath(repoPath, normalizeRepoRelativePath(filePath)) } export function getPathType(repoPath: string, filePath: string): 'file' | 'dir' | 'missing' | 'none' { if (!filePath) return 'none' const fullPath = resolveClassificationPath(repoPath, filePath) if (!fullPath) return 'missing' if (!existsSync(fullPath)) return 'missing' const stats = statSync(fullPath) return stats.isDirectory() ? 'dir' : 'file' } export function validateRepoChildFolderName(name: string): string { const trimmed = name.trim() if (!trimmed) { throw new Error('Folder name is required.') } const normalized = trimmed.replaceAll('\\', '/') const reservedWindowsName = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i if ( normalized === '.' || normalized === '..' || normalized.includes('/') || normalized.includes('\0') || /[<>:"|?*]/.test(normalized) || normalized.endsWith('.') || reservedWindowsName.test(normalized) || isAbsolute(normalized) ) { throw new Error('Folder name must be one safe direct child name.') } return normalized } export function getRepoParentPath(filePath: string): string { const normalized = normalizeRepoRelativePath(filePath) if (!normalized || !normalized.includes('/')) return '' return normalized.slice(0, normalized.lastIndexOf('/')) } export function resolveWorkingTreeFolderParent(repoPath: string, parentPath: string): string { const normalizedParent = normalizeRepoRelativePath(parentPath) const fullParentPath = normalizedParent ? resolveSafeRepoPath(repoPath, normalizedParent) : repoPath if (!fullParentPath) { throw new Error('Parent folder must be inside the repository.') } if (!existsSync(fullParentPath) || !statSync(fullParentPath).isDirectory()) { throw new Error('Parent folder is no longer available.') } return normalizedParent } export function resolveWorkingTreeSubfolder(repoPath: string, folderPath: string): string { const normalizedPath = normalizeRepoRelativePath(folderPath) if (!normalizedPath) { throw new Error('Repository root cannot be deleted.') } const fullPath = resolveSafeRepoPath(repoPath, normalizedPath) if (!fullPath) { throw new Error('Folder must be inside the repository.') } if (!existsSync(fullPath) || !statSync(fullPath).isDirectory()) { throw new Error('The selected folder is no longer available.') } return normalizedPath } export function createWorkingTreeFolder(repoPath: string, parentPath: string, name: string): string { const normalizedParent = resolveWorkingTreeFolderParent(repoPath, parentPath) const childName = validateRepoChildFolderName(name) const targetPath = normalizedParent ? `${normalizedParent}/${childName}` : childName const fullTargetPath = resolveSafeRepoPath(repoPath, targetPath) /* v8 ignore next -- resolveWorkingTreeFolderParent already guarantees the target stays inside the root */ if (!fullTargetPath) { throw new Error('Folder must be created inside the opened folder.') } if (existsSync(fullTargetPath)) { throw new Error('That path already exists in the repository.') } mkdirSync(fullTargetPath) return targetPath } export interface FolderDeleteImpact { path: string name: string parentPath: string fileCount: number folderCount: number impactToken: string } export function countWorkingTreeFolderImpact(repoPath: string, folderPath: string): FolderDeleteImpact { const normalizedPath = resolveWorkingTreeSubfolder(repoPath, folderPath) const fullPath = resolveSafeRepoPath(repoPath, normalizedPath) /* v8 ignore next -- resolveWorkingTreeSubfolder already guarantees the target stays inside the root */ if (!fullPath) { throw new Error('Folder must be inside the opened folder.') } let fileCount = 0 let folderCount = 0 const impactHash = createHash('sha1') const visit = (dirPath: string): void => { const entries = readdirSync(dirPath, { withFileTypes: true }) .sort((left, right) => left.name.localeCompare(right.name)) for (const entry of entries) { const childPath = resolve(dirPath, entry.name) const childRelativePath = relative(fullPath, childPath).split('\\').join('/') if (entry.isDirectory()) { folderCount += 1 impactHash.update(`dir\0${childRelativePath}\0`) visit(childPath) continue } fileCount += 1 const stat = lstatSync(childPath) if (stat.isSymbolicLink()) { impactHash.update(`symlink\0${childRelativePath}\0${readlinkSync(childPath)}\0`) continue } impactHash.update(`file\0${childRelativePath}\0`) if (stat.isFile()) { impactHash.update(readFileSync(childPath)) } else { /* v8 ignore next -- filesystems used in tests expose entries here as regular files or symlinks */ impactHash.update(`${stat.mode}\0${stat.size}\0${stat.mtimeMs}`) } impactHash.update('\0') } } visit(fullPath) return { path: normalizedPath, name: basename(normalizedPath), parentPath: getRepoParentPath(normalizedPath), fileCount, folderCount, impactToken: impactHash.digest('hex'), } } export function deleteWorkingTreeFolder(repoPath: string, folderPath: string): FolderDeleteImpact { const impact = countWorkingTreeFolderImpact(repoPath, folderPath) const fullPath = resolveSafeRepoPath(repoPath, impact.path) /* v8 ignore next 3 -- countWorkingTreeFolderImpact already validates this path */ if (!fullPath) { throw new Error('Folder must be inside the repository.') } rmSync(fullPath, { recursive: true, force: false }) /* v8 ignore next 3 -- rmSync throws before returning if removal fails on supported platforms */ if (existsSync(fullPath)) { throw new Error('GitLocal could not remove the selected folder completely.') } return impact } export function nearestExistingRepoPath(repoPath: string, filePath: string): string { if (!filePath) return '' let current = resolveRepoPath(repoPath, normalizeRepoRelativePath(filePath)) while (current.startsWith(resolve(repoPath))) { if (existsSync(current)) { const rel = relative(repoPath, current) return rel === '' ? '' : rel.split('\\').join('/') } const parent = dirname(current) if (parent === current) break current = parent } /* v8 ignore next -- loop exits via parent traversal on normal absolute paths */ return '' } // Every path in the index, verbatim. `-z` matters: without it git C-quotes any path with non-ASCII // or special characters ("caf\303\251.md"), which then never matches the raw paths `git status -z` // reports. function listIndexedPaths(repoPath: string): string[] { const result = runGitCapture(repoPath, 'ls-files', '-z') if (result.status !== 0) return [] return result.stdout.split('\0').filter(Boolean) } function statTrackedFile(repoPath: string, filePath: string): Stats | null { try { const stats = statSync(resolveRepoPath(repoPath, filePath)) return stats.isDirectory() ? null : stats } catch { return null } } export function getTrackedWorkingTreeFiles(repoPath: string): string[] { return listIndexedPaths(repoPath) .filter((filePath) => statTrackedFile(repoPath, filePath) !== null) .sort() } export function getTrackedPathType(repoPath: string, filePath: string, trackedFiles?: string[]): 'file' | 'dir' | 'missing' | 'none' { if (!filePath) return 'none' const files = trackedFiles ?? getTrackedWorkingTreeFiles(repoPath) if (files.includes(filePath)) return 'file' return files.some((candidate) => candidate.startsWith(`${filePath}/`)) ? 'dir' : 'missing' } export function nearestExistingTrackedRepoPath(repoPath: string, filePath: string): string { if (!filePath) return '' let current = filePath while (current) { const currentType = getTrackedPathType(repoPath, current) if (currentType === 'file' || currentType === 'dir') { return current } const boundary = current.lastIndexOf('/') if (boundary < 0) break current = current.slice(0, boundary) } return '' } export function getWorkingTreeRevision(repoPath: string): string { const hash = createHash('sha1') hash.update(getCurrentBranch(repoPath)) // One stat per tracked file: this runs on every sync-status poll, on the event loop that also // carries terminal I/O. for (const relPath of listIndexedPaths(repoPath).sort()) { const stats = statTrackedFile(repoPath, relPath) if (!stats) continue hash.update(relPath) hash.update(String(stats.size)) hash.update(String(stats.mtimeMs)) } const changes = getWorkingTreeChanges(repoPath) hash.update(changes.trackedPaths.join('\0')) hash.update(changes.untrackedPaths.join('\0')) return hash.digest('hex') } export function getWorkingTreeChanges(repoPath: string): WorkingTreeChangeSummary { // Shares getWorkingTreeChangeDetails's NUL-delimited (`-z`) git status parsing rather than // its own newline/`' -> '`-splitting logic — the latter mis-parses a renamed, non-ASCII, or // quote-containing filename the same way getWorkingTreeChangeDetails used to before that was // fixed, silently corrupting this function's contribution to getWorkingTreeRevision's cache // key for any such filename. const trackedPaths: string[] = [] const untrackedPaths: string[] = [] for (const change of getWorkingTreeChangeDetails(repoPath)) { if (change.changeState === 'untracked') { untrackedPaths.push(change.path) } else { trackedPaths.push(change.path) } } return { trackedPaths: uniqueNormalizedPaths(trackedPaths), untrackedPaths: uniqueNormalizedPaths(untrackedPaths), } } function getCurrentUpstreamRef(repoPath: string): string { const result = runGitCapture(repoPath, 'rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}') return result.status === 0 ? result.stdout.trim() : '' } export function getRepoSyncState(repoPath: string): RepoSyncState { if (!validateRepo(repoPath)) { return { mode: 'unavailable', aheadCount: 0, behindCount: 0, hasUpstream: false, upstreamRef: '', remoteName: '', } } const upstreamRef = getCurrentUpstreamRef(repoPath) if (!upstreamRef) { return { mode: 'local-only', aheadCount: 0, behindCount: 0, hasUpstream: false, upstreamRef: '', remoteName: '', } } const remoteName = upstreamRef.includes('/') ? upstreamRef.split('/')[0] : '' const counts = runGitCapture(repoPath, 'rev-list', '--left-right', '--count', `HEAD...${upstreamRef}`) if (counts.status !== 0) { return { mode: 'unavailable', aheadCount: 0, behindCount: 0, hasUpstream: true, upstreamRef, remoteName, } } const [aheadRaw = '0', behindRaw = '0'] = counts.stdout.trim().split(/\s+/) const aheadCount = Number.parseInt(aheadRaw, 10) || 0 const behindCount = Number.parseInt(behindRaw, 10) || 0 const mode: RepoSyncState['mode'] = aheadCount > 0 && behindCount > 0 ? 'diverged' : aheadCount > 0 ? 'ahead' : behindCount > 0 ? 'behind' : 'up-to-date' return { mode, aheadCount, behindCount, hasUpstream: true, upstreamRef, remoteName, } } function listChangedPathsBetween(repoPath: string, fromRef: string, toRef: string): string[] { const result = runGitCapture(repoPath, 'log', '--format=', '--name-only', `${fromRef}..${toRef}`) if (result.status !== 0 || !result.stdout) return [] return uniqueNormalizedPaths(result.stdout.split('\n')) } function buildFileSyncAnalysis(repoPath: string): FileSyncAnalysis { const changes = getWorkingTreeChanges(repoPath) const repoSync = getRepoSyncState(repoPath) const localCommittedPaths = repoSync.hasUpstream ? new Set(listChangedPathsBetween(repoPath, repoSync.upstreamRef, 'HEAD')) : new Set() const remoteCommittedPaths = repoSync.hasUpstream ? new Set(listChangedPathsBetween(repoPath, 'HEAD', repoSync.upstreamRef)) : new Set() return { changes, repoSync, localCommittedPaths, remoteCommittedPaths, } } function classifyFileSyncState(path: string, analysis: FileSyncAnalysis): FileSyncState { const normalizedPath = normalizeRepoRelativePath(path) if (!normalizedPath) return 'clean' if ( analysis.changes.trackedPaths.includes(normalizedPath) || analysis.changes.untrackedPaths.includes(normalizedPath) ) { return 'local-uncommitted' } const localCommitted = analysis.localCommittedPaths.has(normalizedPath) const remoteCommitted = analysis.remoteCommittedPaths.has(normalizedPath) if (localCommitted && remoteCommitted) return 'diverged' if (localCommitted) return 'local-committed' if (remoteCommitted) return 'remote-committed' return 'clean' } export function applyFileSyncStates(repoPath: string, nodes: TreeNode[]): TreeNode[] { const analysis = buildFileSyncAnalysis(repoPath) return nodes.map((node) => node.type === 'file' ? { ...node, syncState: classifyFileSyncState(node.path, analysis), } : node, ) } export function getPathSyncState(repoPath: string, path: string): FileSyncState | 'none' { const normalizedPath = normalizeRepoRelativePath(path) if (!normalizedPath || getPathType(repoPath, normalizedPath) !== 'file') return 'none' return classifyFileSyncState(normalizedPath, buildFileSyncAnalysis(repoPath)) } export function getWorkingTreeSyncSummary(repoPath: string): { trackedChangeCount: number untrackedChangeCount: number repoSync: RepoSyncState } { const analysis = buildFileSyncAnalysis(repoPath) return { trackedChangeCount: analysis.changes.trackedPaths.length, untrackedChangeCount: analysis.changes.untrackedPaths.length, repoSync: analysis.repoSync, } } function isLikelyGeneratedPath(path: string): boolean { const normalized = normalizeRepoRelativePath(path) return /(^|\/)(node_modules|dist|build|coverage|\.vite|\.next|\.turbo|target|DerivedData)(\/|$)/.test(normalized) } function isTrackedRepoPath(repoPath: string, filePath: string, trackedFiles?: string[]): boolean { const normalized = normalizeRepoRelativePath(filePath) if (!normalized) return false if (trackedFiles) return trackedFiles.includes(normalized) const result = runGitCapture(repoPath, 'ls-files', '--error-unmatch', normalized) return result.status === 0 } export function classifyGeneratedLocalState(repoPath: string, filePath: string, trackedFiles?: string[]): GeneratedLocalState { const normalized = normalizeRepoRelativePath(filePath) if (!normalized || !validateRepo(repoPath)) return 'unknown' if (isTrackedRepoPath(repoPath, normalized, trackedFiles)) return 'tracked' const trackedType = getTrackedPathType(repoPath, normalized, trackedFiles) if (trackedType !== 'missing') return 'tracked' if (isIgnoredPath(repoPath, normalized)) return isLikelyGeneratedPath(normalized) ? 'generated' : 'ignored' return getPathType(repoPath, normalized) === 'missing' ? 'unknown' : 'local-only' } function parsePorcelainChangeState( record: string, sourcePath = '', ): { path: string; sourcePath: string; changeState: ChangedFileState } { const indexStatus = record[0] ?? ' ' const worktreeStatus = record[1] ?? ' ' const path = normalizeRepoRelativePath(record.slice(3)) if (record.startsWith('?? ')) { return { path, sourcePath: '', changeState: 'untracked' } } if (indexStatus === 'R' || worktreeStatus === 'R') { return { path, sourcePath: normalizeRepoRelativePath(sourcePath), changeState: 'renamed', } } if (indexStatus === 'D' || worktreeStatus === 'D') { return { path, sourcePath: '', changeState: 'deleted' } } if (indexStatus === 'A' || worktreeStatus === 'A') { return { path, sourcePath: '', changeState: 'added' } } return { path, sourcePath: '', changeState: 'modified' } } function getWorkingTreeChangeDetails(repoPath: string): Array<{ path: string sourcePath: string changeState: ChangedFileState }> { const result = runGitCapture(repoPath, 'status', '--porcelain=v1', '-z', '-uall') if (result.status !== 0 || !result.stdout) return [] const records = result.stdout.split('\0') const changes: Array<{ path: string; sourcePath: string; changeState: ChangedFileState }> = [] for (let index = 0; index < records.length; index += 1) { const record = records[index] if (!record) continue const renamedOrCopied = record[0] === 'R' || record[1] === 'R' || record[0] === 'C' || record[1] === 'C' const sourcePath = renamedOrCopied ? records[++index] ?? '' : '' const entry = parsePorcelainChangeState(record, sourcePath) if (entry.path) changes.push(entry) } return changes } function mapPathTypeForReview(pathType: ReturnType): ChangedFileItem['type'] { if (pathType === 'file') return 'file' if (pathType === 'dir') return 'folder' if (pathType === 'missing') return 'missing' /* v8 ignore next -- changed-file items are always concrete paths from git status */ return 'unknown' } function describeChangedFile(changeState: ChangedFileState, generatedLocalState: GeneratedLocalState): string { if (changeState === 'deleted') return 'Deleted locally' if (changeState === 'added') return 'Added locally' if (changeState === 'renamed') return 'Renamed locally' if (changeState === 'untracked') return generatedLocalState === 'generated' ? 'Generated local file' : 'Local-only file' return 'Modified locally' } // Same result as classifyGeneratedLocalState for every entry of a `git status` listing, with one // `git ls-files` and one batched `git check-ignore` for the whole listing. Calling // classifyGeneratedLocalState per entry spawned `ls-files` twice and stat'ed every tracked file for // each changed path, which took seconds on an ordinary repository with a few dozen local changes. function classifyChangedEntries( repoPath: string, entries: Array<{ path: string; changeState: ChangedFileState }>, ): Map { const paths = entries.map((entry) => entry.path) const states = new Map() if (!validateRepo(repoPath)) { for (const path of paths) states.set(path, 'unknown') return states } // `ls-files --error-unmatch ` (what classifyGeneratedLocalState asks) matches an indexed // file or any directory holding one, so both the entries and their ancestors count as tracked. const indexed = new Set() for (const line of listIndexedPaths(repoPath)) { const entry = normalizeRepoRelativePath(line) for (let boundary = entry.length; boundary > 0; boundary = entry.lastIndexOf('/', boundary - 1)) { const prefix = entry.slice(0, boundary) if (indexed.has(prefix)) break indexed.add(prefix) } } // git status never lists ignored untracked files, so only paths it reports for another reason // (a staged deletion of a file that is still on disk, say) can be ignored; for everything else // the check-ignore spawn would be wasted. const ignoreCandidates = entries .filter((entry) => entry.changeState !== 'untracked' && !indexed.has(normalizeRepoRelativePath(entry.path))) .map((entry) => entry.path) const ignored = getIgnoredPathSet(repoPath, ignoreCandidates) for (const path of paths) { const normalized = normalizeRepoRelativePath(path) if (!normalized) states.set(path, 'unknown') else if (indexed.has(normalized)) states.set(path, 'tracked') else if (ignored.has(normalized)) states.set(path, isLikelyGeneratedPath(normalized) ? 'generated' : 'ignored') else states.set(path, getPathType(repoPath, normalized) === 'missing' ? 'unknown' : 'local-only') } return states } export function buildChangedFileItems(repoPath: string, includeGeneratedLocal = false): ChangedFileItem[] { const changes = getWorkingTreeChangeDetails(repoPath) const generatedLocalStates = classifyChangedEntries(repoPath, changes) return changes .map((entry) => { const generatedLocalState = generatedLocalStates.get(entry.path) ?? 'unknown' const pathType = getPathType(repoPath, entry.path) const canOpen = pathType === 'file' || pathType === 'dir' return { path: entry.path, name: basename(entry.path), type: mapPathTypeForReview(pathType), changeState: entry.changeState, generatedLocalState, sourcePath: entry.sourcePath, canOpen, reviewHint: canOpen ? describeChangedFile(entry.changeState, generatedLocalState) : 'This path no longer exists. Open its parent folder to review context.', } satisfies ChangedFileItem }) .filter((item) => includeGeneratedLocal || item.generatedLocalState === 'tracked' || item.changeState === 'untracked') .sort((left, right) => left.path.localeCompare(right.path)) } export function summarizeChangedFiles(items: ChangedFileItem[]): { total: number modified: number added: number deleted: number renamed: number untracked: number remoteRelevant: number tracked: number } { const count = (state: ChangedFileState): number => items.filter((item) => item.changeState === state).length return { total: items.length, modified: count('modified'), added: count('added'), deleted: count('deleted'), renamed: count('renamed'), untracked: count('untracked'), remoteRelevant: items.filter((item) => item.changeState === 'local-committed' || item.changeState === 'remote-committed' || item.changeState === 'diverged').length, tracked: items.filter((item) => item.generatedLocalState === 'tracked').length, } } export function findKeyDocuments(repoPath: string): KeyDocumentItem[] { const candidates: Array> = [ { path: 'README.md', label: 'README', category: 'README', reason: 'Repository overview' }, { path: 'AGENTS.md', label: 'Agent instructions', category: 'agent-instructions', reason: 'Codex and agent guidance' }, { path: 'specs', label: 'Specs', category: 'specs', reason: 'Feature specifications' }, { path: 'docs', label: 'Docs', category: 'docs', reason: 'Project documentation' }, ] return candidates .map((candidate) => ({ ...candidate, available: getPathType(repoPath, candidate.path) !== 'missing', })) .filter((candidate) => candidate.available) } function toneForRepoSync(repoSync: RepoSyncState, localChangeCount: number): RepositoryStatusTone { if (repoSync.mode === 'diverged' || repoSync.mode === 'unavailable') return 'warning' if (repoSync.mode === 'behind') return 'warning' if (repoSync.mode === 'ahead' || localChangeCount > 0) return 'info' return 'neutral' } function describeRemoteSync(repoSync: RepoSyncState, branchLabel: string): string { if (repoSync.mode === 'local-only') return `${branchLabel} has no upstream remote configured.` if (repoSync.mode === 'unavailable') return `${branchLabel} remote status is unavailable locally.` if (repoSync.mode === 'ahead') return `${branchLabel} is ${repoSync.aheadCount} commit${repoSync.aheadCount === 1 ? '' : 's'} ahead of ${repoSync.upstreamRef}.` if (repoSync.mode === 'behind') return `${branchLabel} is ${repoSync.behindCount} commit${repoSync.behindCount === 1 ? '' : 's'} behind ${repoSync.upstreamRef}.` if (repoSync.mode === 'diverged') return `${branchLabel} and ${repoSync.upstreamRef} both have commits to review.` return `${branchLabel} is up to date with ${repoSync.upstreamRef || repoSync.remoteName || 'its remote'}.` } export function buildRepositoryStatusSummary(repoPath: string, branch = ''): RepositoryStatusSummary { const repoName = basename(repoPath) || 'Repository' const branchLabel = branch || getCurrentBranch(repoPath) || 'current branch' const syncSummary = getWorkingTreeSyncSummary(repoPath) const localChangeCount = syncSummary.trackedChangeCount + syncSummary.untrackedChangeCount const hasHistory = hasCommits(repoPath) const remoteDescription = describeRemoteSync(syncSummary.repoSync, branchLabel) const localDescription = !hasHistory ? ' It has no commits yet.' : localChangeCount > 0 ? ` It has ${localChangeCount} local ${localChangeCount === 1 ? 'change' : 'changes'} to review.` : ' It has no local changes.' return { repoName, branchLabel, remoteLabel: syncSummary.repoSync.remoteName || (syncSummary.repoSync.hasUpstream ? syncSummary.repoSync.upstreamRef : 'Local only'), syncState: syncSummary.repoSync.mode, syncDescription: `${remoteDescription}${localDescription}`, localChangeCount, untrackedChangeCount: syncSummary.untrackedChangeCount, statusTone: toneForRepoSync(syncSummary.repoSync, localChangeCount), detailBadges: [ { label: syncSummary.repoSync.mode, tone: toneForRepoSync(syncSummary.repoSync, localChangeCount) }, ...(localChangeCount > 0 ? [{ label: `${localChangeCount} local changes`, tone: 'info' as const }] : []), ], } } function resolveBranchSelection(repoPath: string, target: string): { localName: string checkoutRef: string trackingRef?: string createTrackingBranch: boolean } { const normalizedTarget = target.trim() const match = getBranches(repoPath).find((branch) => branch.name === normalizedTarget || branch.trackingRef === normalizedTarget || branch.displayName === normalizedTarget, ) if (!match) { return { localName: normalizedTarget, checkoutRef: normalizedTarget, createTrackingBranch: false, } } if (match.scope === 'remote' && match.trackingRef) { return { localName: match.name, checkoutRef: match.trackingRef, trackingRef: match.trackingRef, createTrackingBranch: true, } } return { localName: match.name, checkoutRef: match.name, trackingRef: match.trackingRef, createTrackingBranch: false, } } function getGitWorktreeEntries(repoPath: string): GitWorktreeEntry[] { const result = runGitCapture(repoPath, 'worktree', 'list', '--porcelain') if (result.status !== 0 || !result.stdout) return [] const entries: GitWorktreeEntry[] = [] let currentPath = '' let currentBranchRef = '' for (const line of result.stdout.split('\n')) { if (!line.trim()) { if (currentPath) { entries.push({ path: currentPath, branchRef: currentBranchRef, }) } currentPath = '' currentBranchRef = '' continue } if (line.startsWith('worktree ')) { currentPath = line.slice('worktree '.length).trim() continue } if (line.startsWith('branch ')) { currentBranchRef = line.slice('branch '.length).trim() } } /* v8 ignore next 6 -- git worktree porcelain normally terminates entries with a blank line */ if (currentPath) { entries.push({ path: currentPath, branchRef: currentBranchRef, }) } return entries } function getOtherWorktreePathForBranch(repoPath: string, branchName: string): string { const targetBranchRef = `refs/heads/${branchName}` const currentWorktreePath = resolve(repoPath) return getGitWorktreeEntries(repoPath) .find((entry) => entry.branchRef === targetBranchRef && resolve(entry.path) !== currentWorktreePath) ?.path ?? '' } function formatBranchInUseByWorktreeMessage(branchName: string, worktreePath: string): string { return `Branch ${branchName} is already checked out in another worktree at ${worktreePath}. Switch there or choose a different branch.` } function parseWorktreeInUseErrorPath(message: string): string { const match = message.match(/already used by worktree at '([^']+)'/) return match?.[1]?.trim() ?? '' } function discardTrackedChanges(repoPath: string): void { if (!hasCommits(repoPath)) return spawnGit(repoPath, 'reset', '--hard', 'HEAD') } function performBranchCheckout( repoPath: string, target: ReturnType, ): { currentBranch: string; createdTrackingBranch?: string } { if (target.createTrackingBranch && target.trackingRef) { spawnGit(repoPath, 'checkout', '-b', target.localName, '--track', target.trackingRef) return { currentBranch: target.localName, createdTrackingBranch: target.localName, } } spawnGit(repoPath, 'checkout', target.checkoutRef) return { currentBranch: getCurrentBranch(repoPath), } } export function switchBranch(repoPath: string, request: BranchSwitchRequest): BranchSwitchResponse { if (!validateRepo(repoPath)) { return { ok: false, status: 'blocked', message: 'No git repository is currently open.', } } const targetName = request.target.trim() if (!targetName) { return { ok: false, status: 'blocked', message: 'Select a branch before switching.', } } if (request.resolution === 'cancel') { return { ok: false, status: 'cancelled', message: 'Branch switch canceled.', currentBranch: getCurrentBranch(repoPath), } } const target = resolveBranchSelection(repoPath, targetName) const currentBranch = getCurrentBranch(repoPath) if (!target.createTrackingBranch && target.localName === currentBranch) { return { ok: true, status: 'switched', message: `Already on ${currentBranch}.`, currentBranch, } } const otherWorktreePath = getOtherWorktreePathForBranch(repoPath, target.localName) if (otherWorktreePath) { return { ok: false, status: 'blocked', message: formatBranchInUseByWorktreeMessage(target.localName, otherWorktreePath), currentBranch, } } const changes = getWorkingTreeChanges(repoPath) const summary: Pick = { trackedChangeCount: changes.trackedPaths.length, untrackedChangeCount: changes.untrackedPaths.length, blockingPaths: changes.trackedPaths, suggestedCommitMessage: `WIP before switching to ${target.localName}`, } if (request.resolution === 'preview' && changes.trackedPaths.length > 0) { return { ok: false, status: 'confirmation-required', message: 'This branch switch needs confirmation because your working tree has uncommitted changes.', currentBranch, ...summary, } } try { if (request.resolution === 'commit') { const commitMessage = request.commitMessage?.trim() if (!commitMessage) { return { ok: false, status: 'blocked', message: 'Enter a commit message before switching branches.', currentBranch, ...summary, } } spawnGit(repoPath, 'add', '-A') spawnGit(repoPath, 'commit', '-m', commitMessage) } if (request.resolution === 'discard') { discardTrackedChanges(repoPath) } const checkout = performBranchCheckout(repoPath, target) return { ok: true, status: 'switched', message: `Switched to ${checkout.currentBranch}.`, currentBranch: checkout.currentBranch, createdTrackingBranch: checkout.createdTrackingBranch, } } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Branch switch failed.' const worktreeInUsePath = parseWorktreeInUseErrorPath(errorMessage) return { ok: false, status: worktreeInUsePath ? 'blocked' : 'failed', message: worktreeInUsePath ? formatBranchInUseByWorktreeMessage(target.localName, worktreeInUsePath) : errorMessage, currentBranch, ...summary, } } } export function commitWorkingTreeChanges(repoPath: string, message: string): CommitChangesResponse { if (!validateRepo(repoPath)) { return { ok: false, status: 'blocked', message: 'No git repository is currently open.', } } const commitMessage = message.trim() if (!commitMessage) { return { ok: false, status: 'blocked', message: 'Enter a commit message before committing changes.', } } const changes = getWorkingTreeChanges(repoPath) if (changes.trackedPaths.length === 0 && changes.untrackedPaths.length === 0) { return { ok: false, status: 'blocked', message: 'There are no local changes to commit.', } } if (existsSync(resolve(repoPath, '.env'))) { const ignored = runGitCapture(repoPath, 'check-ignore', '-q', '.env').status === 0 const tracked = runGitCapture(repoPath, 'ls-files', '--error-unmatch', '.env').status === 0 if (!ignored || tracked) { return { ok: false, status: 'blocked', message: '.env is not safely ignored. GitLocal will not commit while .env could be included.', } } } try { spawnGit(repoPath, 'add', '-A') spawnGit(repoPath, 'commit', '-m', commitMessage) const commitHash = spawnGit(repoPath, 'rev-parse', 'HEAD') return { ok: true, status: 'committed', message: `Committed changes as ${commitHash.slice(0, 7)}.`, commitHash, shortHash: commitHash.slice(0, 7), } } catch (error) { return { ok: false, status: 'failed', message: error instanceof Error ? error.message : 'Commit failed.', } } } export function syncCurrentBranchWithRemote(repoPath: string): RemoteSyncResponse { if (!validateRepo(repoPath)) { return { ok: false, status: 'blocked', message: 'No git repository is currently open.', } } const currentBranch = getCurrentBranch(repoPath) if (!currentBranch || currentBranch === 'HEAD') { return { ok: false, status: 'blocked', message: 'Sync is only available on a named current branch.', } } const changes = getWorkingTreeChanges(repoPath) if (changes.trackedPaths.length > 0 || changes.untrackedPaths.length > 0) { return { ok: false, status: 'blocked', message: 'Commit or discard local changes before syncing with remote.', } } const initialSync = getRepoSyncState(repoPath) if (!initialSync.hasUpstream) { return { ok: false, status: 'blocked', message: 'This branch does not have an upstream remote to sync with.', } } const fetchResult = runGitCapture(repoPath, 'fetch', initialSync.remoteName || '--all', '--prune') if (fetchResult.status !== 0) { return { ok: false, status: 'failed', message: fetchResult.stderr.trim() || 'Remote sync failed while fetching.', } } const repoSync = getRepoSyncState(repoPath) if (repoSync.mode === 'diverged') { return { ok: false, status: 'blocked', message: 'Local and remote history diverged. Resolve it manually before syncing in GitLocal.', aheadCount: repoSync.aheadCount, behindCount: repoSync.behindCount, } } if (repoSync.mode === 'up-to-date') { return { ok: true, status: 'up-to-date', message: 'This branch is already up to date with its upstream.', aheadCount: 0, behindCount: 0, } } try { if (repoSync.mode === 'ahead') { spawnGit(repoPath, 'push') const refreshed = getRepoSyncState(repoPath) return { ok: true, status: 'pushed', message: `Pushed ${currentBranch} to ${repoSync.upstreamRef}.`, aheadCount: refreshed.aheadCount, behindCount: refreshed.behindCount, } } if (repoSync.mode === 'behind') { spawnGit(repoPath, 'pull', '--ff-only') const refreshed = getRepoSyncState(repoPath) return { ok: true, status: 'pulled', message: `Fast-forwarded ${currentBranch} from ${repoSync.upstreamRef}.`, aheadCount: refreshed.aheadCount, behindCount: refreshed.behindCount, } } return { ok: false, status: 'blocked', message: 'This branch is not in a syncable state.', aheadCount: repoSync.aheadCount, behindCount: repoSync.behindCount, } } catch (error) { return { ok: false, status: 'failed', message: error instanceof Error ? error.message : 'Remote sync failed.', aheadCount: repoSync.aheadCount, behindCount: repoSync.behindCount, } } } export function readWorkingTreeFile(repoPath: string, filePath: string): Buffer | null { const fullPath = resolveSafeRepoPath(repoPath, filePath) if (!fullPath) return null if (!existsSync(fullPath)) return null const stats = statSync(fullPath) if (stats.isDirectory()) return null return readFileSync(fullPath) } export function isIgnoredPath(repoPath: string, filePath: string): boolean { if (!validateRepo(repoPath)) return false const normalized = normalizeRepoRelativePath(filePath) if (!normalized) return false const result = spawnSync('git', ['check-ignore', '-q', normalized], { cwd: repoPath }) return result.status === 0 } function getIgnoredPathSet(repoPath: string, paths: string[]): Set { const normalizedPaths = uniqueNormalizedPaths(paths) if (normalizedPaths.length === 0) return new Set() // `-z` on both ends: without it git C-quotes output paths with non-ASCII or special characters. const result = spawnSync('git', ['check-ignore', '-z', '--stdin'], { cwd: repoPath, input: normalizedPaths.join('\0'), encoding: 'utf-8', }) if (result.status !== 0 || !result.stdout) return new Set() return new Set(result.stdout.split('\0').filter(Boolean)) } export function getEditableState(repoPath: string, filePath: string, branch: string): { editable: boolean; revisionToken: string | null } { if (!isWorkingTreeBranch(repoPath, branch)) { return { editable: false, revisionToken: null } } const pathType = getPathType(repoPath, filePath) if (pathType !== 'file') { return { editable: false, revisionToken: null } } const { type } = detectFileType(filePath) return { editable: isInlineEditableType(type), revisionToken: getFileRevisionToken(repoPath, filePath), } } export function isInlineEditableType(type: FileContentType): boolean { return type === 'markdown' || type === 'text' || type === 'html' } export function getFileRevisionToken(repoPath: string, filePath: string): string | null { const rawBytes = readWorkingTreeFile(repoPath, filePath) if (!rawBytes) return null const hash = createHash('sha1') hash.update(normalizeRepoRelativePath(filePath)) hash.update(rawBytes) return hash.digest('hex') } export function writeWorkingTreeTextFile(repoPath: string, filePath: string, content: string): void { const fullPath = resolveSafeRepoPath(repoPath, filePath) if (!fullPath) { throw new Error('Path must stay inside the opened repository.') } mkdirSync(dirname(fullPath), { recursive: true }) writeFileSync(fullPath, content, 'utf-8') } export function deleteWorkingTreeFile(repoPath: string, filePath: string): void { const fullPath = resolveSafeRepoPath(repoPath, filePath) if (!fullPath) { throw new Error('Path must stay inside the opened repository.') } unlinkSync(fullPath) } function validateChildFolderName(name: string): string { const trimmed = name.trim() if (!trimmed) { throw new Error('A folder name is required.') } if (trimmed === '.' || trimmed === '..' || /[\\/]/.test(trimmed)) { throw new Error('Folder names cannot contain path separators.') } return trimmed } export function createChildFolder(parentPath: string, name: string): string { const normalizedName = validateChildFolderName(name) if (!existsSync(parentPath) || !statSync(parentPath).isDirectory()) { throw new Error('The selected parent folder is not available.') } const createdPath = resolve(parentPath, normalizedName) /* v8 ignore next -- validateChildFolderName prevents separators, so this is purely defensive */ if (dirname(createdPath) !== resolve(parentPath)) { throw new Error('The new folder must stay inside the selected parent.') } if (existsSync(createdPath)) { throw new Error('A file or folder with that name already exists.') } mkdirSync(createdPath, { recursive: false }) return createdPath } export function initializeGitRepository(path: string): string { if (!existsSync(path) || !statSync(path).isDirectory()) { throw new Error('The selected folder is not available.') } if (validateRepo(path)) { throw new Error('This folder is already a git repository.') } const result = runGitCapture(path, 'init') if (result.status !== 0) { throw new Error(result.stderr || 'git init failed.') } return path } export function cloneRepositoryInto(parentPath: string, name: string, repositoryUrl: string): string { const normalizedName = validateChildFolderName(name) const trimmedUrl = repositoryUrl.trim() if (!trimmedUrl) { throw new Error('A repository URL is required.') } if (!existsSync(parentPath) || !statSync(parentPath).isDirectory()) { throw new Error('The selected parent folder is not available.') } const targetPath = resolve(parentPath, normalizedName) /* v8 ignore next -- validateChildFolderName prevents separators, so this is purely defensive */ if (dirname(targetPath) !== resolve(parentPath)) { throw new Error('The clone target must stay inside the selected parent.') } if (existsSync(targetPath)) { throw new Error('A file or folder with that name already exists.') } const result = runGitCapture(parentPath, 'clone', trimmedUrl, normalizedName) if (result.status !== 0) { throw new Error(result.stderr || 'git clone failed.') } return targetPath } // The readdirSync call below is deliberately unguarded — do not wrap it in a try/catch that // returns [] on failure. This feeds both /api/tree directly and getBrowseableRootEntryCount's // RepoInfo.rootEntryCount; swallowing a real read failure to an empty array would make it // indistinguishable from a genuinely empty folder (the exact bug this function must not // reintroduce). Let it propagate to the global onError handler (src/server.ts) instead. export function listWorkingTreeDirectoryEntries(repoPath: string, subpath: string = ''): TreeNode[] { const normalized = normalizeRepoRelativePath(subpath) const dirPath = normalized ? resolveSafeRepoPath(repoPath, normalized) : repoPath const isGitRepo = validateRepo(repoPath) if (!dirPath || !existsSync(dirPath) || !statSync(dirPath).isDirectory()) { return [] } const directoryEntries = readdirSync(dirPath, { withFileTypes: true }) .filter((entry) => !isGitRepo || entry.name !== '.git') const ignoredPaths = isGitRepo ? getIgnoredPathSet(repoPath, directoryEntries.map((entry) => normalized ? `${normalized}/${entry.name}` : entry.name)) : new Set() return directoryEntries .map((entry) => { const path = normalized ? `${normalized}/${entry.name}` : entry.name return { name: entry.name, path, type: entry.isDirectory() ? 'dir' as const : 'file' as const, localOnly: isGitRepo ? ignoredPaths.has(path) : true, } }) .sort((a, b) => { if (a.type !== b.type) return a.type === 'dir' ? -1 : 1 return a.name.localeCompare(b.name) }) } export function detectFileType(filename: string): { type: FileContentType; language: string } { /* v8 ignore next */ const ext = filename.split('.').pop()?.toLowerCase() ?? '' if (ext === 'svg') return { type: 'svg', language: 'xml' } if (ext === 'csv') return { type: 'csv', language: '' } const imageExts = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'ico', 'bmp', 'tiff']) if (imageExts.has(ext)) return { type: 'image', language: '' } const markdownExts = new Set(['md', 'markdown', 'mdx', 'mdown']) if (markdownExts.has(ext)) return { type: 'markdown', language: '' } // json gets its own FileContentType (unlike langMap entries below, which only affect highlighting) if (ext === 'json') return { type: 'json', language: 'json' } // HTML is previewed as a rendered, sandboxed page and stays editable as text (#117). if (ext === 'html' || ext === 'htm') return { type: 'html', language: 'html' } const langMap: Record = { ts: 'typescript', tsx: 'typescript', js: 'javascript', jsx: 'javascript', mjs: 'javascript', cjs: 'javascript', py: 'python', go: 'go', rs: 'rust', java: 'java', kt: 'kotlin', swift: 'swift', c: 'c', cpp: 'cpp', h: 'c', hpp: 'cpp', cs: 'csharp', rb: 'ruby', php: 'php', sh: 'bash', bash: 'bash', zsh: 'bash', yaml: 'yaml', yml: 'yaml', toml: 'toml', xml: 'xml', css: 'css', scss: 'scss', sql: 'sql', graphql: 'graphql', proto: 'protobuf', tf: 'hcl', r: 'r', lua: 'lua', ex: 'elixir', exs: 'elixir', hs: 'haskell', clj: 'clojure', scala: 'scala', dart: 'dart', vue: 'html', svelte: 'html', dockerfile: 'dockerfile', } if (ext in langMap) return { type: 'text', language: langMap[ext] } if (ext === 'pdf') return { type: 'pdf', language: '' } if (ext === 'xlsx' || ext === 'xls') return { type: 'excel', language: '' } if (ext === 'pptx') return { type: 'pptx', language: '' } // Word documents and templates share one OOXML format; macro-enabled ones are previewed too, // since the preview only reads the document and never runs anything in it. if (ext === 'docx' || ext === 'docm' || ext === 'dotx' || ext === 'dotm') return { type: 'docx', language: '' } const binaryExts = new Set([ 'exe', 'dll', 'so', 'dylib', 'bin', 'obj', 'o', 'a', 'zip', 'tar', 'gz', 'bz2', 'xz', '7z', 'rar', 'doc', 'ppt', 'mp3', 'mp4', 'wav', 'mov', 'avi', 'mkv', 'ttf', 'woff', 'woff2', 'eot', 'pyc', 'class', 'jar', 'war', ]) if (binaryExts.has(ext)) return { type: 'binary', language: '' } // Fallback: treat as text with no language hint return { type: 'text', language: '' } }