From b3fddf6cb37685b5eb2171cf910ca4076da33873 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 27 Apr 2026 00:42:10 -0500 Subject: [PATCH] Audit and overhaul virtual shell's git command Fix critical bugs, add extensive missing flags, and add 8 new subcommands to bring the browser-side git command closer to parity with real git. Critical bug fixes: - git commit: file-count classification used impossible stageStatus=1 comparisons, always reporting 0 files changed - git status --porcelain: untracked files could clobber staged indicators - git add: directory walker skipped all dotfiles (including .gitignore itself), ignoring real git's .gitignore-based filtering - git pull: untracked files incorrectly blocked pulls - git reset: target regex rejected valid refs like branch names - git diff: path filter used substring matching; --cached read working directory instead of index; and .. forms were stubbed/unimplemented; used fake JS hashes instead of git.hashBlob Implemented git reset --soft (was returning "not implemented"). New flags added across existing subcommands: - commit: --signoff, --no-verify, -F/--file, --author, -C/--reuse-message, multiple -m support - add: -u/--update, -f/--force, -n/--dry-run, absolute paths inside repo - log: --stat, -p/--patch, --name-only, --name-status, --author, --grep, --since, --until, --no-merges, --reverse, --follow, custom --pretty=format:, proper timezone in output - push: -u/--set-upstream (now wired to config), --tags, --delete, --dry-run, refspec (local:remote) - fetch: --all, --tags, --prune now actually passed through - branch: -a/--all, -r/--remotes, -m/-M (rename), --show-current, -v - checkout: -B, -f/--force, commit-hash support (detached HEAD) - config: --unset, --get-all, --add, --local, proper --list that reads the whole config file - tag: real annotated tags via git.annotatedTag, -m, -f, -n, glob patterns - clone: -b/--branch, -o/--origin, --bare - init: -b/--initial-branch - show: --stat, --name-only, --name-status - diff: --stat, --name-only, --name-status - remote: set-url, get-url, rename, show subcommands New subcommands: - git rm: remove files from index (and optionally worktree) - git mv: rename/move files with index updates - git restore: modern replacement for checkout of files - git switch: modern replacement for branch checkout - git merge: wrapper over git.merge (including --abort, --ff-only) - git revert: create an inverse commit - git rev-parse: resolve refs, --short, --abbrev-ref, --show-toplevel, --git-dir, HEAD~N / HEAD^N - git ls-files: list tracked/modified/deleted/untracked files All existing tests updated where behavior intentionally changed; new subcommands have dedicated test suites. Final suite: 1392 passing. --- AGENTS.md | 2 +- src/lib/commands/git.test.ts | 3 +- src/lib/commands/git.ts | 27 +- src/lib/commands/git/add.test.ts | 16 +- src/lib/commands/git/add.ts | 231 +++++-- src/lib/commands/git/branch.ts | 233 +++++-- src/lib/commands/git/checkout.ts | 204 +++--- src/lib/commands/git/clone.ts | 65 +- src/lib/commands/git/commit.ts | 168 ++++- src/lib/commands/git/config.ts | 216 +++++- src/lib/commands/git/diff.test.ts | 33 +- src/lib/commands/git/diff.ts | 868 +++++++++++++++++-------- src/lib/commands/git/fetch.ts | 10 +- src/lib/commands/git/init.ts | 50 +- src/lib/commands/git/log.test.ts | 2 +- src/lib/commands/git/log.ts | 416 +++++++++--- src/lib/commands/git/ls-files.test.ts | 82 +++ src/lib/commands/git/ls-files.ts | 126 ++++ src/lib/commands/git/merge.test.ts | 68 ++ src/lib/commands/git/merge.ts | 128 ++++ src/lib/commands/git/mv.test.ts | 91 +++ src/lib/commands/git/mv.ts | 168 +++++ src/lib/commands/git/pull.test.ts | 7 +- src/lib/commands/git/pull.ts | 7 +- src/lib/commands/git/push.ts | 116 +++- src/lib/commands/git/remote.ts | 190 ++++-- src/lib/commands/git/reset.test.ts | 34 +- src/lib/commands/git/reset.ts | 80 ++- src/lib/commands/git/restore.test.ts | 73 +++ src/lib/commands/git/restore.ts | 111 ++++ src/lib/commands/git/rev-parse.test.ts | 86 +++ src/lib/commands/git/rev-parse.ts | 182 ++++++ src/lib/commands/git/revert.test.ts | 102 +++ src/lib/commands/git/revert.ts | 173 +++++ src/lib/commands/git/rm.test.ts | 97 +++ src/lib/commands/git/rm.ts | 157 +++++ src/lib/commands/git/show.ts | 115 +++- src/lib/commands/git/status.ts | 19 +- src/lib/commands/git/switch.test.ts | 82 +++ src/lib/commands/git/switch.ts | 135 ++++ src/lib/commands/git/tag.ts | 207 ++++-- 41 files changed, 4384 insertions(+), 796 deletions(-) create mode 100644 src/lib/commands/git/ls-files.test.ts create mode 100644 src/lib/commands/git/ls-files.ts create mode 100644 src/lib/commands/git/merge.test.ts create mode 100644 src/lib/commands/git/merge.ts create mode 100644 src/lib/commands/git/mv.test.ts create mode 100644 src/lib/commands/git/mv.ts create mode 100644 src/lib/commands/git/restore.test.ts create mode 100644 src/lib/commands/git/restore.ts create mode 100644 src/lib/commands/git/rev-parse.test.ts create mode 100644 src/lib/commands/git/rev-parse.ts create mode 100644 src/lib/commands/git/revert.test.ts create mode 100644 src/lib/commands/git/revert.ts create mode 100644 src/lib/commands/git/rm.test.ts create mode 100644 src/lib/commands/git/rm.ts create mode 100644 src/lib/commands/git/switch.test.ts create mode 100644 src/lib/commands/git/switch.ts diff --git a/AGENTS.md b/AGENTS.md index 2ad27f57..4e7705e7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -67,7 +67,7 @@ Shakespeare provides a comprehensive set of shell commands that are JavaScript r - **File Operations**: `cat`, `cp`, `mv`, `rm`, `touch`, `find`, `grep` - **Directory Operations**: `cd`, `ls`, `mkdir`, `pwd`, `tree` - **System Commands**: `echo`, `which`, `wc`, `head`, `tail` -- **Git Commands**: `git add`, `git commit`, `git push`, `git pull`, `git status`, `git log`, etc. +- **Git Commands**: `git add`, `git commit`, `git push`, `git pull`, `git status`, `git log`, `git diff`, `git branch`, `git checkout`, `git switch`, `git merge`, `git revert`, `git rm`, `git mv`, `git restore`, `git rev-parse`, `git ls-files`, `git tag`, `git stash`, `git fetch`, `git clone`, `git init`, `git reset`, `git show`, `git remote`, `git config` #### Security diff --git a/src/lib/commands/git.test.ts b/src/lib/commands/git.test.ts index 4ecf4acd..aff172ba 100644 --- a/src/lib/commands/git.test.ts +++ b/src/lib/commands/git.test.ts @@ -115,7 +115,8 @@ describe('GitCommand', () => { it('should register all expected subcommands', () => { const expectedSubcommands = [ 'init', 'status', 'add', 'commit', 'log', 'branch', 'checkout', - 'remote', 'push', 'pull', 'clone', 'config', 'reset', 'diff', 'tag', 'show' + 'remote', 'push', 'pull', 'clone', 'config', 'reset', 'diff', 'tag', 'show', + 'stash', 'rm', 'mv', 'restore', 'switch', 'merge', 'revert', 'rev-parse', 'ls-files', ]; // We can't directly access the subcommands map, but we can test that they work diff --git a/src/lib/commands/git.ts b/src/lib/commands/git.ts index a2260ba7..aec4ff99 100644 --- a/src/lib/commands/git.ts +++ b/src/lib/commands/git.ts @@ -23,6 +23,14 @@ import { GitDiffCommand } from "./git/diff"; import { GitTagCommand } from "./git/tag"; import { GitShowCommand } from "./git/show"; import { GitStashCommand } from "./git/stash"; +import { GitRmCommand } from "./git/rm"; +import { GitMvCommand } from "./git/mv"; +import { GitRestoreCommand } from "./git/restore"; +import { GitSwitchCommand } from "./git/switch"; +import { GitMergeCommand } from "./git/merge"; +import { GitRevertCommand } from "./git/revert"; +import { GitRevParseCommand } from "./git/rev-parse"; +import { GitLsFilesCommand } from "./git/ls-files"; export interface GitSubcommand { name: string; @@ -91,6 +99,14 @@ export class GitCommand implements ShellCommand { this.registerSubcommand(new GitTagCommand(subcommandOptions)); this.registerSubcommand(new GitShowCommand(subcommandOptions)); this.registerSubcommand(new GitStashCommand(subcommandOptions)); + this.registerSubcommand(new GitRmCommand(subcommandOptions)); + this.registerSubcommand(new GitMvCommand(subcommandOptions)); + this.registerSubcommand(new GitRestoreCommand(subcommandOptions)); + this.registerSubcommand(new GitSwitchCommand(subcommandOptions)); + this.registerSubcommand(new GitMergeCommand(subcommandOptions)); + this.registerSubcommand(new GitRevertCommand(subcommandOptions)); + this.registerSubcommand(new GitRevParseCommand(subcommandOptions)); + this.registerSubcommand(new GitLsFilesCommand(subcommandOptions)); } private registerSubcommand(subcommand: GitSubcommand): void { @@ -138,11 +154,15 @@ start a working area (see also: git help tutorial) work on the current change (see also: git help everyday) add Add file contents to the index + mv Move or rename a file, a directory, or a symlink + restore Restore working tree files + rm Remove files from the working tree and from the index reset Reset current HEAD to the specified state stash Stash the changes in a dirty working directory away examine the history and state (see also: git help revisions) log Show commit logs + ls-files Show information about files in the index and the working tree show Show various types of objects status Show the working tree status diff Show changes between commits, commit and working tree, etc @@ -151,6 +171,10 @@ grow, mark and tweak your common history branch List, create, or delete branches checkout Switch branches or restore working tree files commit Record changes to the repository + merge Join two or more development histories together + rebase Reapply commits on top of another base tip (not implemented) + revert Revert some existing commits + switch Switch branches tag Create, list, delete or verify a tag object collaborate (see also: git help workflows) @@ -159,8 +183,9 @@ collaborate (see also: git help workflows) push Update remote refs along with associated objects remote Manage set of tracked repositories -configuration +configuration and low-level config Get and set repository or global options + rev-parse Pick out and massage parameters 'git help -a' and 'git help -g' list available subcommands and some concept guides. See 'git help ' or 'git help ' diff --git a/src/lib/commands/git/add.test.ts b/src/lib/commands/git/add.test.ts index 05aedc98..d8390d23 100644 --- a/src/lib/commands/git/add.test.ts +++ b/src/lib/commands/git/add.test.ts @@ -63,7 +63,7 @@ describe('GitAddCommand', () => { it('should have correct command properties', () => { expect(addCommand.name).toBe('add'); expect(addCommand.description).toBe('Add file contents to the index'); - expect(addCommand.usage).toBe('git add [--all | -A] [--] [...]'); + expect(addCommand.usage).toBe('git add [--all | -A] [--update | -u] [--force | -f] [--dry-run | -n] [--] [...]'); }); it('should return error when not in a git repository', async () => { @@ -172,11 +172,21 @@ describe('GitAddCommand', () => { }); }); - it('should reject absolute paths', async () => { + it('should reject absolute paths outside the repo', async () => { const result = await addCommand.execute(['/absolute/path/file.txt'], testCwd); expect(result.exitCode).toBe(1); - expect(result.stderr).toContain('absolute paths are not supported'); + expect(result.stderr).toContain('outside repository'); + }); + + it('should accept absolute paths inside the repo', async () => { + const result = await addCommand.execute([`${testCwd}/file.txt`], testCwd); + + expect(result.exitCode).toBe(0); + expect(mockGit.add).toHaveBeenCalledWith({ + dir: testCwd, + filepath: 'file.txt', + }); }); it('should handle non-existent files', async () => { diff --git a/src/lib/commands/git/add.ts b/src/lib/commands/git/add.ts index f1406bfb..822f099d 100644 --- a/src/lib/commands/git/add.ts +++ b/src/lib/commands/git/add.ts @@ -1,4 +1,4 @@ -import { join } from "path-browserify"; +import { join, isAbsolute, relative } from "path-browserify"; import type { JSRuntimeFS } from "../../JSRuntime"; import type { ShellCommandResult } from "../ShellCommand"; import { createSuccessResult, createErrorResult } from "../ShellCommand"; @@ -8,7 +8,7 @@ import type { Git } from "../../git"; export class GitAddCommand implements GitSubcommand { name = 'add'; description = 'Add file contents to the index'; - usage = 'git add [--all | -A] [--] [...]'; + usage = 'git add [--all | -A] [--update | -u] [--force | -f] [--dry-run | -n] [--] [...]'; private git: Git; private fs: JSRuntimeFS; @@ -31,12 +31,15 @@ export class GitAddCommand implements GitSubcommand { if (options.all) { // Add all files (git add -A) - return await this.addAllFiles(cwd); + return await this.addAllFiles(cwd, options); + } else if (options.update) { + // Add only tracked files with changes (git add -u) + return await this.updateTrackedFiles(paths, cwd, options); } else if (paths.length === 0) { return createErrorResult('Nothing specified, nothing added.\nMaybe you wanted to say \'git add .\'?'); } else { // Add specific files - return await this.addSpecificFiles(paths, cwd); + return await this.addSpecificFiles(paths, cwd, options); } } catch (error) { @@ -44,8 +47,11 @@ export class GitAddCommand implements GitSubcommand { } } - private parseArgs(args: string[]): { options: { all: boolean }; paths: string[] } { - const options = { all: false }; + private parseArgs(args: string[]): { + options: { all: boolean; update: boolean; force: boolean; dryRun: boolean }; + paths: string[]; + } { + const options = { all: false, update: false, force: false, dryRun: false }; const paths: string[] = []; let foundDoubleDash = false; @@ -57,6 +63,12 @@ export class GitAddCommand implements GitSubcommand { if (!foundDoubleDash && (arg === '--all' || arg === '-A')) { options.all = true; + } else if (!foundDoubleDash && (arg === '--update' || arg === '-u')) { + options.update = true; + } else if (!foundDoubleDash && (arg === '--force' || arg === '-f')) { + options.force = true; + } else if (!foundDoubleDash && (arg === '--dry-run' || arg === '-n')) { + options.dryRun = true; } else if (!foundDoubleDash && arg.startsWith('-')) { // Ignore other options for now continue; @@ -68,27 +80,51 @@ export class GitAddCommand implements GitSubcommand { return { options, paths }; } - private async addAllFiles(cwd: string): Promise { + /** + * Normalize a path argument to a repo-relative path. + * Returns null if the path is outside the repo. + */ + private normalizePath(path: string, cwd: string): string | null { + if (isAbsolute(path)) { + // Convert absolute path to repo-relative + if (!path.startsWith(cwd)) { + return null; // Outside repo + } + const rel = relative(cwd, path); + return rel || '.'; + } + return path; + } + + private async addAllFiles(cwd: string, options: { dryRun: boolean }): Promise { try { // Get status to find all changed files const statusMatrix = await this.git.statusMatrix({ dir: cwd, }); + const added: string[] = []; + for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) { try { if (workdirStatus === 0 && headStatus === 1) { // File was deleted in working directory - await this.git.remove({ - dir: cwd, - filepath, - }); + if (!options.dryRun) { + await this.git.remove({ + dir: cwd, + filepath, + }); + } + added.push(`remove '${filepath}'`); } else if (workdirStatus === 2 && stageStatus !== 2) { // File exists and has changes that aren't staged yet - await this.git.add({ - dir: cwd, - filepath, - }); + if (!options.dryRun) { + await this.git.add({ + dir: cwd, + filepath, + }); + } + added.push(`add '${filepath}'`); } } catch { // Continue with other files if one fails @@ -96,6 +132,10 @@ export class GitAddCommand implements GitSubcommand { } } + if (options.dryRun) { + return createSuccessResult(added.join('\n') + (added.length > 0 ? '\n' : '')); + } + // Git add is typically silent on success, like real git return createSuccessResult(''); @@ -104,7 +144,66 @@ export class GitAddCommand implements GitSubcommand { } } - private async addSpecificFiles(paths: string[], cwd: string): Promise { + /** + * Update only tracked files (git add -u behavior). + * Skips untracked files. + */ + private async updateTrackedFiles( + paths: string[], + cwd: string, + options: { dryRun: boolean } + ): Promise { + try { + const statusMatrix = await this.git.statusMatrix({ dir: cwd }); + const added: string[] = []; + + const matchesPath = (filepath: string): boolean => { + if (paths.length === 0) return true; + return paths.some(p => { + const normalized = this.normalizePath(p, cwd); + if (!normalized || normalized === '.') return true; + return filepath === normalized || filepath.startsWith(normalized + '/'); + }); + }; + + for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) { + // Only process tracked files (headStatus === 1) + if (headStatus !== 1) continue; + if (!matchesPath(filepath)) continue; + + try { + if (workdirStatus === 0) { + // File was deleted + if (!options.dryRun) { + await this.git.remove({ dir: cwd, filepath }); + } + added.push(`remove '${filepath}'`); + } else if (workdirStatus === 2 && stageStatus !== 2) { + // File modified + if (!options.dryRun) { + await this.git.add({ dir: cwd, filepath }); + } + added.push(`add '${filepath}'`); + } + } catch { + // Continue on error + } + } + + if (options.dryRun) { + return createSuccessResult(added.join('\n') + (added.length > 0 ? '\n' : '')); + } + return createSuccessResult(''); + } catch (error) { + return createErrorResult(`Failed to update tracked files: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private async addSpecificFiles( + paths: string[], + cwd: string, + options: { force: boolean; dryRun: boolean } + ): Promise { const addedFiles: string[] = []; const errors: string[] = []; @@ -120,17 +219,21 @@ export class GitAddCommand implements GitSubcommand { try { if (workdirStatus === 0 && headStatus === 1) { // File was deleted in working directory - await this.git.remove({ - dir: cwd, - filepath, - }); + if (!options.dryRun) { + await this.git.remove({ + dir: cwd, + filepath, + }); + } addedFiles.push(filepath); } else if (workdirStatus === 2 && stageStatus !== 2) { // File exists and has changes that aren't staged yet - await this.git.add({ - dir: cwd, - filepath, - }); + if (!options.dryRun) { + await this.git.add({ + dir: cwd, + filepath, + }); + } addedFiles.push(filepath); } } catch { @@ -138,13 +241,14 @@ export class GitAddCommand implements GitSubcommand { } } } else { - // Handle absolute paths - if (path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path)) { - errors.push(`'${path}': absolute paths are not supported`); + // Normalize path (handle absolute paths) + const normalized = this.normalizePath(path, cwd); + if (normalized === null) { + errors.push(`fatal: ${path}: '${path}' is outside repository`); continue; } - const absolutePath = join(cwd, path); + const absolutePath = join(cwd, normalized); // Check if file/directory exists try { @@ -152,25 +256,29 @@ export class GitAddCommand implements GitSubcommand { if (stats.isDirectory()) { // Add all files in directory - await this.addDirectory(path, addedFiles, cwd); + await this.addDirectory(normalized, addedFiles, cwd, options); } else { // Add single file - await this.git.add({ - dir: cwd, - filepath: path, - }); - addedFiles.push(path); + if (!options.dryRun) { + await this.git.add({ + dir: cwd, + filepath: normalized, + }); + } + addedFiles.push(normalized); } } catch { // Check if it's a deleted file try { - await this.git.remove({ - dir: cwd, - filepath: path, - }); - addedFiles.push(path); + if (!options.dryRun) { + await this.git.remove({ + dir: cwd, + filepath: normalized, + }); + } + addedFiles.push(normalized); } catch { - errors.push(`pathspec '${path}' did not match any files`); + errors.push(`fatal: pathspec '${path}' did not match any files`); } } } @@ -183,29 +291,54 @@ export class GitAddCommand implements GitSubcommand { return createErrorResult(errors.join('\n')); } + if (options.dryRun) { + return createSuccessResult(addedFiles.map(f => `add '${f}'`).join('\n') + (addedFiles.length > 0 ? '\n' : '')); + } + // Git add is typically silent on success, like real git return createSuccessResult(''); } - private async addDirectory(dirPath: string, addedFiles: string[], cwd: string): Promise { + private async addDirectory( + dirPath: string, + addedFiles: string[], + cwd: string, + options: { force: boolean; dryRun: boolean } + ): Promise { const absolutePath = join(cwd, dirPath); const entries = await this.fs.readdir(absolutePath, { withFileTypes: true }); for (const entry of entries) { - if (entry.name.startsWith('.')) { - continue; // Skip hidden files + // Skip only the .git directory. Real git tracks other dotfiles like .gitignore. + if (entry.name === '.git') { + continue; } - const entryPath = join(dirPath, entry.name); + const entryPath = dirPath === '.' ? entry.name : join(dirPath, entry.name); if (entry.isDirectory()) { - await this.addDirectory(entryPath, addedFiles, cwd); + await this.addDirectory(entryPath, addedFiles, cwd, options); } else { + // Check gitignore unless --force is specified + if (!options.force) { + try { + const ignored = await this.git.isIgnored({ + dir: cwd, + filepath: entryPath, + }); + if (ignored) continue; + } catch { + // If isIgnored fails, proceed with adding + } + } + try { - await this.git.add({ - dir: cwd, - filepath: entryPath, - }); + if (!options.dryRun) { + await this.git.add({ + dir: cwd, + filepath: entryPath, + }); + } addedFiles.push(entryPath); } catch { // Continue with other files diff --git a/src/lib/commands/git/branch.ts b/src/lib/commands/git/branch.ts index 5fc12dee..16aa06bd 100644 --- a/src/lib/commands/git/branch.ts +++ b/src/lib/commands/git/branch.ts @@ -4,10 +4,20 @@ import { createSuccessResult, createErrorResult } from "../ShellCommand"; import type { GitSubcommand, GitSubcommandOptions } from "../git"; import type { Git } from "../../git"; +interface BranchOptions { + force: boolean; + all: boolean; + remote: boolean; + verbose: boolean; + showCurrent: boolean; +} + +type BranchAction = 'list' | 'create' | 'delete' | 'rename' | 'show-current'; + export class GitBranchCommand implements GitSubcommand { name = 'branch'; description = 'List, create, or delete branches'; - usage = 'git branch [--list] | git branch | git branch (-d | -D) '; + usage = 'git branch [--list | -a | -r | -v | --show-current] | git branch [] | git branch (-d | -D) | git branch (-m | -M) [] '; private git: Git; private fs: JSRuntimeFS; @@ -26,17 +36,21 @@ export class GitBranchCommand implements GitSubcommand { return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); } - const { action, branchName, options } = this.parseArgs(args); + const { action, branchName, startPoint, newName, options } = this.parseArgs(args); switch (action) { case 'list': - return await this.listBranches(cwd); + return await this.listBranches(options, cwd); + case 'show-current': + return await this.showCurrentBranch(cwd); case 'create': - return await this.createBranch(branchName!, cwd); + return await this.createBranch(branchName!, startPoint, cwd); case 'delete': return await this.deleteBranch(branchName!, options.force, cwd); + case 'rename': + return await this.renameBranch(branchName, newName!, options.force, cwd); default: - return await this.listBranches(cwd); + return await this.listBranches(options, cwd); } } catch (error) { @@ -45,107 +59,175 @@ export class GitBranchCommand implements GitSubcommand { } private parseArgs(args: string[]): { - action: 'list' | 'create' | 'delete'; + action: BranchAction; branchName?: string; - options: { force: boolean } + startPoint?: string; + newName?: string; + options: BranchOptions; } { - const options = { force: false }; - let action: 'list' | 'create' | 'delete' = 'list'; + const options: BranchOptions = { + force: false, + all: false, + remote: false, + verbose: false, + showCurrent: false, + }; + let action: BranchAction = 'list'; let branchName: string | undefined; + let startPoint: string | undefined; + let newName: string | undefined; + const positionals: string[] = []; for (let i = 0; i < args.length; i++) { const arg = args[i]; if (arg === '--list' || arg === '-l') { action = 'list'; + } else if (arg === '-a' || arg === '--all') { + options.all = true; + action = 'list'; + } else if (arg === '-r' || arg === '--remotes') { + options.remote = true; + action = 'list'; + } else if (arg === '-v' || arg === '--verbose') { + options.verbose = true; + } else if (arg === '--show-current') { + action = 'show-current'; } else if (arg === '-d' || arg === '--delete') { action = 'delete'; - if (i + 1 < args.length) { - branchName = args[i + 1]; - i++; - } } else if (arg === '-D') { action = 'delete'; options.force = true; - if (i + 1 < args.length) { - branchName = args[i + 1]; - i++; - } + } else if (arg === '-m' || arg === '--move') { + action = 'rename'; + } else if (arg === '-M') { + action = 'rename'; + options.force = true; + } else if (arg === '-f' || arg === '--force') { + options.force = true; } else if (!arg.startsWith('-')) { - // Branch name for creation - action = 'create'; - branchName = arg; + positionals.push(arg); } } - return { action, branchName, options }; + if (action === 'delete') { + branchName = positionals[0]; + } else if (action === 'rename') { + if (positionals.length === 1) { + newName = positionals[0]; + } else if (positionals.length >= 2) { + branchName = positionals[0]; + newName = positionals[1]; + } + } else if (positionals.length >= 1) { + action = 'create'; + branchName = positionals[0]; + if (positionals.length >= 2) { + startPoint = positionals[1]; + } + } + + return { action, branchName, startPoint, newName, options }; } - private async listBranches(cwd: string): Promise { + private async showCurrentBranch(cwd: string): Promise { try { - const branches = await this.git.listBranches({ - dir: cwd, - }); - - if (branches.length === 0) { + const currentBranch = await this.git.currentBranch({ dir: cwd }); + if (!currentBranch) { return createSuccessResult(''); } + return createSuccessResult(`${currentBranch}\n`); + } catch { + return createSuccessResult(''); + } + } + + private async listBranches(options: BranchOptions, cwd: string): Promise { + try { + const lines: string[] = []; // Get current branch let currentBranch: string | null = null; try { - currentBranch = await this.git.currentBranch({ - - dir: cwd, - }) || null; + currentBranch = await this.git.currentBranch({ dir: cwd }) || null; } catch { - // Might be in detached HEAD state + // Detached HEAD } - const lines: string[] = []; - for (const branch of branches) { - if (branch === currentBranch) { - lines.push(`* ${branch}`); - } else { - lines.push(` ${branch}`); + const listLocal = !options.remote || options.all; + const listRemote = options.remote || options.all; + + if (listLocal) { + const branches = await this.git.listBranches({ dir: cwd }); + for (const branch of branches) { + const prefix = branch === currentBranch ? '* ' : ' '; + let line = `${prefix}${branch}`; + if (options.verbose) { + try { + const oid = await this.git.resolveRef({ dir: cwd, ref: branch }); + line += ` ${oid.substring(0, 7)}`; + // Get commit message + try { + const log = await this.git.log({ dir: cwd, depth: 1, ref: branch }); + if (log.length > 0) { + line += ` ${log[0].commit.message.split('\n')[0]}`; + } + } catch { /* empty */ } + } catch { /* empty */ } + } + lines.push(line); } } - return createSuccessResult(lines.join('\n') + '\n'); + if (listRemote) { + try { + const remotes = await this.git.listRemotes({ dir: cwd }); + for (const remote of remotes) { + try { + const remoteBranches = await this.git.listBranches({ dir: cwd, remote: remote.remote }); + for (const branch of remoteBranches) { + lines.push(` remotes/${remote.remote}/${branch}`); + } + } catch { /* empty */ } + } + } catch { /* empty */ } + } + if (lines.length === 0) { + return createSuccessResult(''); + } + + return createSuccessResult(lines.join('\n') + '\n'); } catch (error) { return createErrorResult(`Failed to list branches: ${error instanceof Error ? error.message : 'Unknown error'}`); } } - private async createBranch(branchName: string, cwd: string): Promise { + private async createBranch(branchName: string, startPoint: string | undefined, cwd: string): Promise { try { // Check if branch already exists - const branches = await this.git.listBranches({ - dir: cwd, - }); + const branches = await this.git.listBranches({ dir: cwd }); if (branches.includes(branchName)) { return createErrorResult(`fatal: A branch named '${branchName}' already exists.`); } - // Get current HEAD to base the new branch on - let currentRef: string; + // Get starting ref + let startOid: string; try { - currentRef = await this.git.resolveRef({ - + startOid = await this.git.resolveRef({ dir: cwd, - ref: 'HEAD', + ref: startPoint || 'HEAD', }); } catch { - return createErrorResult('fatal: Not a valid object name: \'HEAD\'.'); + return createErrorResult(`fatal: Not a valid object name: '${startPoint || 'HEAD'}'.`); } // Create the new branch await this.git.branch({ dir: cwd, ref: branchName, - object: currentRef, + object: startOid, }); return createSuccessResult(''); @@ -155,12 +237,10 @@ export class GitBranchCommand implements GitSubcommand { } } - private async deleteBranch(branchName: string, force: boolean, cwd: string): Promise { + private async deleteBranch(branchName: string, force: boolean, cwd: string): Promise { try { // Check if branch exists - const branches = await this.git.listBranches({ - dir: cwd, - }); + const branches = await this.git.listBranches({ dir: cwd }); if (!branches.includes(branchName)) { return createErrorResult(`error: branch '${branchName}' not found.`); @@ -169,10 +249,7 @@ export class GitBranchCommand implements GitSubcommand { // Check if it's the current branch let currentBranch: string | null = null; try { - currentBranch = await this.git.currentBranch({ - - dir: cwd, - }) || null; + currentBranch = await this.git.currentBranch({ dir: cwd }) || null; } catch { // Continue } @@ -196,4 +273,44 @@ export class GitBranchCommand implements GitSubcommand { return createErrorResult(`Failed to delete branch: ${error instanceof Error ? error.message : 'Unknown error'}`); } } + + private async renameBranch( + oldName: string | undefined, + newName: string, + force: boolean, + cwd: string + ): Promise { + try { + // If oldName not specified, rename the current branch + let actualOldName = oldName; + if (!actualOldName) { + try { + actualOldName = await this.git.currentBranch({ dir: cwd }) || undefined; + if (!actualOldName) { + return createErrorResult('fatal: Cannot rename the current branch while not on any.'); + } + } catch { + return createErrorResult('fatal: Cannot determine current branch.'); + } + } + + const branches = await this.git.listBranches({ dir: cwd }); + if (!branches.includes(actualOldName)) { + return createErrorResult(`error: refname refs/heads/${actualOldName} not found`); + } + if (!force && branches.includes(newName)) { + return createErrorResult(`fatal: A branch named '${newName}' already exists.`); + } + + await this.git.renameBranch({ + dir: cwd, + ref: newName, + oldref: actualOldName, + }); + + return createSuccessResult(''); + } catch (error) { + return createErrorResult(`Failed to rename branch: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } } diff --git a/src/lib/commands/git/checkout.ts b/src/lib/commands/git/checkout.ts index d43fc801..b1cb67cd 100644 --- a/src/lib/commands/git/checkout.ts +++ b/src/lib/commands/git/checkout.ts @@ -4,10 +4,18 @@ import { createSuccessResult, createErrorResult } from "../ShellCommand"; import type { GitSubcommand, GitSubcommandOptions } from "../git"; import type { Git } from "../../git"; +interface CheckoutOptions { + createBranch: boolean; + createOrReset: boolean; + force: boolean; +} + +type CheckoutAction = 'switch' | 'create' | 'restore'; + export class GitCheckoutCommand implements GitSubcommand { name = 'checkout'; description = 'Switch branches or restore working tree files'; - usage = 'git checkout | git checkout -b | git checkout -- '; + usage = 'git checkout [-f] | git checkout (-b | -B) [] | git checkout [] -- ...'; private git: Git; private fs: JSRuntimeFS; @@ -26,15 +34,17 @@ export class GitCheckoutCommand implements GitSubcommand { return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); } - const { action, target } = this.parseArgs(args); + const { action, target, startPoint, filepaths, options } = this.parseArgs(args); + + if (filepaths.length > 0) { + return await this.restoreFiles(filepaths, target, cwd); + } switch (action) { case 'switch': - return await this.switchBranch(target!, cwd); + return await this.switchRef(target!, options, cwd); case 'create': - return await this.createAndSwitchBranch(target!, cwd); - case 'restore': - return await this.restoreFiles(target!, cwd); + return await this.createAndSwitchBranch(target!, startPoint, options, cwd); default: return createErrorResult('error: pathspec did not match any file(s) known to git'); } @@ -45,125 +55,173 @@ export class GitCheckoutCommand implements GitSubcommand { } private parseArgs(args: string[]): { - action: 'switch' | 'create' | 'restore'; + action: CheckoutAction; target?: string; - options: { createBranch: boolean } + startPoint?: string; + filepaths: string[]; + options: CheckoutOptions; } { - const options = { createBranch: false }; - let action: 'switch' | 'create' | 'restore' = 'switch'; + const options: CheckoutOptions = { + createBranch: false, + createOrReset: false, + force: false, + }; + let action: CheckoutAction = 'switch'; let target: string | undefined; + let startPoint: string | undefined; + const filepaths: string[] = []; + const positionals: string[] = []; + let foundDoubleDash = false; for (let i = 0; i < args.length; i++) { const arg = args[i]; - if (arg === '-b') { + if (foundDoubleDash) { + filepaths.push(arg); + continue; + } + + if (arg === '--') { + foundDoubleDash = true; + continue; + } else if (arg === '-b') { action = 'create'; options.createBranch = true; - if (i + 1 < args.length) { - target = args[i + 1]; - i++; - } - } else if (arg === '--') { - // Everything after -- is a file path - if (i + 1 < args.length) { - action = 'restore'; - target = args[i + 1]; - } - break; + } else if (arg === '-B') { + action = 'create'; + options.createOrReset = true; + } else if (arg === '-f' || arg === '--force') { + options.force = true; } else if (!arg.startsWith('-')) { - if (!target) { - target = arg; - } + positionals.push(arg); } } - return { action, target, options }; + if (action === 'create') { + target = positionals[0]; + if (positionals.length >= 2) { + startPoint = positionals[1]; + } + } else { + target = positionals[0]; + } + + return { action, target, startPoint, filepaths, options }; } - private async switchBranch(branchName: string, cwd: string): Promise { + /** + * Switch to a branch or commit. + */ + private async switchRef(ref: string, options: CheckoutOptions, cwd: string): Promise { try { - // Check if branch exists - const branches = await this.git.listBranches({ - dir: cwd, - }); + const branches = await this.git.listBranches({ dir: cwd }); + const isBranch = branches.includes(ref); - if (!branches.includes(branchName)) { - return createErrorResult(`error: pathspec '${branchName}' did not match any file(s) known to git`); + // Verify the ref exists (either as a branch or as a commit) + if (!isBranch) { + try { + await this.git.resolveRef({ dir: cwd, ref }); + } catch { + // Try to match as a commit hash + if (!/^[a-f0-9]{4,40}$/.test(ref)) { + return createErrorResult(`error: pathspec '${ref}' did not match any file(s) known to git`); + } + try { + await this.git.readCommit({ dir: cwd, oid: ref }); + } catch { + return createErrorResult(`error: pathspec '${ref}' did not match any file(s) known to git`); + } + } } // Get current branch let currentBranch: string | null = null; try { - currentBranch = await this.git.currentBranch({ - dir: cwd, - }) || null; + currentBranch = await this.git.currentBranch({ dir: cwd }) || null; } catch { // Continue } - if (currentBranch === branchName) { - return createErrorResult(`Already on '${branchName}'`); + if (isBranch && currentBranch === ref) { + return createSuccessResult(`Already on '${ref}'\n`); } - // Check for uncommitted changes - const statusMatrix = await this.git.statusMatrix({ - dir: cwd, - }); + // Check for uncommitted changes unless --force + if (!options.force) { + const statusMatrix = await this.git.statusMatrix({ dir: cwd }); + const hasChanges = statusMatrix.some(([, headStatus, workdirStatus, stageStatus]) => { + // Ignore untracked files + if (headStatus === 0 && stageStatus === 0) return false; + return headStatus !== workdirStatus || headStatus !== stageStatus; + }); - const hasChanges = statusMatrix.some(([, headStatus, workdirStatus, stageStatus]) => { - return headStatus !== workdirStatus || headStatus !== stageStatus; - }); - - if (hasChanges) { - return createErrorResult('error: Your local changes to the following files would be overwritten by checkout:\nPlease commit your changes or stash them before you switch branches.'); + if (hasChanges) { + return createErrorResult('error: Your local changes to the following files would be overwritten by checkout:\nPlease commit your changes or stash them before you switch branches.'); + } } - // Switch to the branch + // Switch await this.git.checkout({ dir: cwd, - ref: branchName, + ref, + force: options.force, }); - return createSuccessResult(`Switched to branch '${branchName}'\n`); - + if (isBranch) { + return createSuccessResult(`Switched to branch '${ref}'\n`); + } else { + // Detached HEAD + return createSuccessResult(`Note: switching to '${ref}'.\n\nYou are in 'detached HEAD' state.\nHEAD is now at ${ref.substring(0, 7)}\n`); + } } catch (error) { - return createErrorResult(`Failed to switch branch: ${error instanceof Error ? error.message : 'Unknown error'}`); + return createErrorResult(`Failed to switch: ${error instanceof Error ? error.message : 'Unknown error'}`); } } - private async createAndSwitchBranch(branchName: string, cwd: string): Promise { + private async createAndSwitchBranch( + branchName: string, + startPoint: string | undefined, + options: CheckoutOptions, + cwd: string + ): Promise { try { - // Check if branch already exists - const branches = await this.git.listBranches({ - dir: cwd, - }); + const branches = await this.git.listBranches({ dir: cwd }); if (branches.includes(branchName)) { - return createErrorResult(`fatal: A branch named '${branchName}' already exists.`); + if (!options.createOrReset) { + return createErrorResult(`fatal: A branch named '${branchName}' already exists.`); + } + // -B: reset the existing branch + try { + await this.git.deleteBranch({ dir: cwd, ref: branchName }); + } catch { + // Continue + } } - // Get current HEAD - let currentRef: string; + // Resolve start point + let startOid: string; try { - currentRef = await this.git.resolveRef({ + startOid = await this.git.resolveRef({ dir: cwd, - ref: 'HEAD', + ref: startPoint || 'HEAD', }); } catch { - return createErrorResult('fatal: Not a valid object name: \'HEAD\'.'); + return createErrorResult(`fatal: Not a valid object name: '${startPoint || 'HEAD'}'.`); } // Create the branch await this.git.branch({ dir: cwd, ref: branchName, - object: currentRef, + object: startOid, }); // Switch to the new branch await this.git.checkout({ dir: cwd, ref: branchName, + force: options.force, }); return createSuccessResult(`Switched to a new branch '${branchName}'\n`); @@ -173,29 +231,27 @@ export class GitCheckoutCommand implements GitSubcommand { } } - private async restoreFiles(filePath: string, cwd: string): Promise { + private async restoreFiles(filepaths: string[], treeish: string | undefined, cwd: string): Promise { try { - // This is a simplified implementation - // In a full git implementation, this would restore files from the index or HEAD - - // Get the file from HEAD + const ref = treeish || 'HEAD'; try { await this.git.checkout({ dir: cwd, - ref: 'HEAD', - filepaths: [filePath], + ref, + filepaths, + force: true, }); return createSuccessResult(''); } catch (error) { if (error instanceof Error && error.message.includes('does not exist')) { - return createErrorResult(`error: pathspec '${filePath}' did not match any file(s) known to git`); + return createErrorResult(`error: pathspec did not match any file(s) known to git`); } throw error; } } catch (error) { - return createErrorResult(`Failed to restore file: ${error instanceof Error ? error.message : 'Unknown error'}`); + return createErrorResult(`Failed to restore files: ${error instanceof Error ? error.message : 'Unknown error'}`); } } } diff --git a/src/lib/commands/git/clone.ts b/src/lib/commands/git/clone.ts index 93cdef1e..5a79f5f3 100644 --- a/src/lib/commands/git/clone.ts +++ b/src/lib/commands/git/clone.ts @@ -8,7 +8,7 @@ import type { Git } from "../../git"; export class GitCloneCommand implements GitSubcommand { name = 'clone'; description = 'Clone a repository into a new directory'; - usage = 'git clone [--depth ] [--single-branch] []'; + usage = 'git clone [--depth ] [--single-branch] [--branch | -b ] [--origin | -o ] [--bare] []'; private git: Git; private fs: JSRuntimeFS; @@ -35,7 +35,7 @@ export class GitCloneCommand implements GitSubcommand { targetDir = repoName.replace(/\.git$/, ''); // Remove .git suffix if present } - const targetPath = `${cwd}/${targetDir}`; + const targetPath = targetDir.startsWith('/') ? targetDir : `${cwd}/${targetDir}`; // Check if target directory already exists try { @@ -45,11 +45,13 @@ export class GitCloneCommand implements GitSubcommand { // Directory doesn't exist, which is what we want } - // Validate URL format - try { - new URL(repository); - } catch { - return createErrorResult(`fatal: repository '${repository}' does not appear to be a git repository`); + // Validate URL format (accept nostr:// as well) + if (!repository.startsWith('nostr://')) { + try { + new URL(repository); + } catch { + return createErrorResult(`fatal: repository '${repository}' does not appear to be a git repository`); + } } // Clone the repository @@ -58,7 +60,10 @@ export class GitCloneCommand implements GitSubcommand { url: repository, singleBranch: options.singleBranch, depth: options.depth, - }); + ref: options.branch, + remote: options.origin, + noCheckout: options.bare, + } as Parameters[0]); return createSuccessResult(`Cloning into '${targetDir}'...\ndone.\n`); @@ -78,11 +83,27 @@ export class GitCloneCommand implements GitSubcommand { } private parseArgs(args: string[]): { - options: { depth?: number; singleBranch: boolean }; + options: { + depth?: number; + singleBranch: boolean; + branch?: string; + origin: string; + bare: boolean; + }; repository?: string; - directory?: string + directory?: string; } { - const options: { depth?: number; singleBranch: boolean } = { singleBranch: false }; + const options: { + depth?: number; + singleBranch: boolean; + branch?: string; + origin: string; + bare: boolean; + } = { + singleBranch: false, + origin: 'origin', + bare: false, + }; let repository: string | undefined; let directory: string | undefined; @@ -95,7 +116,7 @@ export class GitCloneCommand implements GitSubcommand { if (!isNaN(depth) && depth > 0) { options.depth = depth; } - i++; // Skip next argument + i++; } } else if (arg.startsWith('--depth=')) { const depth = parseInt(arg.substring(8), 10); @@ -104,6 +125,26 @@ export class GitCloneCommand implements GitSubcommand { } } else if (arg === '--single-branch') { options.singleBranch = true; + } else if (arg === '--no-single-branch') { + options.singleBranch = false; + } else if (arg === '--branch' || arg === '-b') { + if (i + 1 < args.length) { + options.branch = args[i + 1]; + options.singleBranch = true; + i++; + } + } else if (arg.startsWith('--branch=')) { + options.branch = arg.substring(9); + options.singleBranch = true; + } else if (arg === '--origin' || arg === '-o') { + if (i + 1 < args.length) { + options.origin = args[i + 1]; + i++; + } + } else if (arg.startsWith('--origin=')) { + options.origin = arg.substring(9); + } else if (arg === '--bare' || arg === '--mirror') { + options.bare = true; } else if (!arg.startsWith('-')) { if (!repository) { repository = arg; diff --git a/src/lib/commands/git/commit.ts b/src/lib/commands/git/commit.ts index 30650200..ca02bb14 100644 --- a/src/lib/commands/git/commit.ts +++ b/src/lib/commands/git/commit.ts @@ -7,7 +7,7 @@ import type { Git } from "../../git"; export class GitCommitCommand implements GitSubcommand { name = 'commit'; description = 'Record changes to the repository'; - usage = 'git commit [-m ] [-a | --all] [-am ] [--amend] [--allow-empty]'; + usage = 'git commit [-m ] [-a | --all] [-am ] [--amend] [--allow-empty] [--signoff] [-F ] [--author=] [-C ] [--no-verify]'; private git: Git; private fs: JSRuntimeFS; @@ -26,12 +26,12 @@ export class GitCommitCommand implements GitSubcommand { return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); } - const { options, message } = this.parseArgs(args); + const { options, message } = await this.parseArgs(args, cwd); - if (!message && !options.amend) { + if (!message && !options.amend && !options.reuseMessage) { return createErrorResult('Aborting commit due to empty commit message.'); } - + // If -a flag is provided, stage all tracked files with modifications if (options.addAll) { await this.stageTrackedChanges(cwd); @@ -52,13 +52,17 @@ export class GitCommitCommand implements GitSubcommand { } let commitMessage = message; - if (options.amend) { - // Get the last commit message if amending + if (options.amend || options.reuseMessage) { + // Get the last commit message if amending or reusing try { - const commits = await this.git.log({ + const logOpts: { dir: string; depth: number; ref?: string } = { dir: cwd, depth: 1, - }); + }; + if (options.reuseMessage) { + logOpts.ref = options.reuseMessage; + } + const commits = await this.git.log(logOpts); if (commits.length > 0 && !message) { commitMessage = commits[0].commit.message; } @@ -70,6 +74,14 @@ export class GitCommitCommand implements GitSubcommand { } } + // Append sign-off if requested + if (options.signoff && commitMessage) { + const signoff = await this.buildSignoff(cwd, options.author); + if (signoff && !commitMessage.includes(signoff)) { + commitMessage = commitMessage.replace(/\n+$/, '') + `\n\nSigned-off-by: ${signoff}\n`; + } + } + // Get current branch let currentBranch = 'main'; try { @@ -85,11 +97,19 @@ export class GitCommitCommand implements GitSubcommand { dir: string; message: string; parent?: string[]; + author?: { name: string; email: string }; } = { dir: cwd, message: commitMessage || 'Empty commit', }; + if (options.author) { + const parsed = this.parseAuthor(options.author); + if (parsed) { + commitOptions.author = parsed; + } + } + if (options.amend) { // For amend, we need to reset to the parent of the current commit try { @@ -110,13 +130,13 @@ export class GitCommitCommand implements GitSubcommand { // Get short hash const shortHash = commitSha.substring(0, 7); - // Count changes + // Count changes (status matrix values: 0=absent, 1=unchanged from HEAD, 2=differs from HEAD) const addedFiles = stagedFiles.filter(([, headStatus, , stageStatus]) => - headStatus === 0 && stageStatus === 1 + headStatus === 0 && stageStatus === 2 ).length; const modifiedFiles = stagedFiles.filter(([, headStatus, , stageStatus]) => - headStatus === 1 && stageStatus === 1 + headStatus === 1 && stageStatus === 2 ).length; const deletedFiles = stagedFiles.filter(([, headStatus, , stageStatus]) => @@ -178,40 +198,142 @@ export class GitCommitCommand implements GitSubcommand { } } - private parseArgs(args: string[]): { - options: { amend: boolean; allowEmpty: boolean; addAll: boolean }; - message?: string - } { - const options = { amend: false, allowEmpty: false, addAll: false }; - let message: string | undefined; + private async parseArgs(args: string[], cwd: string): Promise<{ + options: { + amend: boolean; + allowEmpty: boolean; + addAll: boolean; + signoff: boolean; + noVerify: boolean; + author?: string; + reuseMessage?: string; + }; + message?: string; + }> { + const options: { + amend: boolean; + allowEmpty: boolean; + addAll: boolean; + signoff: boolean; + noVerify: boolean; + author?: string; + reuseMessage?: string; + } = { + amend: false, + allowEmpty: false, + addAll: false, + signoff: false, + noVerify: false, + }; + const messageParts: string[] = []; for (let i = 0; i < args.length; i++) { const arg = args[i]; if (arg === '-m' || arg === '--message') { if (i + 1 < args.length) { - message = args[i + 1]; + messageParts.push(args[i + 1]); i++; // Skip next argument as it's the message } } else if (arg.startsWith('-m=')) { - message = arg.substring(3); + messageParts.push(arg.substring(3)); } else if (arg.startsWith('--message=')) { - message = arg.substring(10); + messageParts.push(arg.substring(10)); + } else if (arg === '-F' || arg === '--file') { + if (i + 1 < args.length) { + const filePath = args[i + 1]; + try { + const content = await this.fs.readFile( + filePath.startsWith('/') ? filePath : `${cwd}/${filePath}`, + 'utf8' + ); + messageParts.push(content.replace(/\n+$/, '')); + } catch { + // Ignore if file can't be read + } + i++; + } + } else if (arg.startsWith('--file=')) { + const filePath = arg.substring(7); + try { + const content = await this.fs.readFile( + filePath.startsWith('/') ? filePath : `${cwd}/${filePath}`, + 'utf8' + ); + messageParts.push(content.replace(/\n+$/, '')); + } catch { + // Ignore + } } else if (arg === '--amend') { options.amend = true; } else if (arg === '--allow-empty') { options.allowEmpty = true; } else if (arg === '-a' || arg === '--all') { options.addAll = true; - } else if (arg === '-am') { + } else if (arg === '-am' || arg === '-ma') { options.addAll = true; if (i + 1 < args.length) { - message = args[i + 1]; - i++; // Skip next argument as it's the message + messageParts.push(args[i + 1]); + i++; } + } else if (arg === '-s' || arg === '--signoff') { + options.signoff = true; + } else if (arg === '--no-verify' || arg === '-n') { + // --no-verify skips pre-commit / commit-msg hooks; we don't run hooks anyway + options.noVerify = true; + } else if (arg === '--author') { + if (i + 1 < args.length) { + options.author = args[i + 1]; + i++; + } + } else if (arg.startsWith('--author=')) { + options.author = arg.substring(9); + } else if (arg === '-C' || arg === '--reuse-message') { + if (i + 1 < args.length) { + options.reuseMessage = args[i + 1]; + i++; + } + } else if (arg.startsWith('--reuse-message=')) { + options.reuseMessage = arg.substring(16); } } + // Multiple -m flags are joined with double newlines (standard git behavior) + const message = messageParts.length > 0 ? messageParts.join('\n\n') : undefined; + return { options, message }; } + + /** + * Parse an author string like "Name " + */ + private parseAuthor(author: string): { name: string; email: string } | null { + const match = author.match(/^(.+?)\s*<(.+?)>\s*$/); + if (match) { + return { name: match[1].trim(), email: match[2].trim() }; + } + return null; + } + + /** + * Build a Signed-off-by line from the current user config or the provided author + */ + private async buildSignoff(cwd: string, authorOverride?: string): Promise { + if (authorOverride) { + const parsed = this.parseAuthor(authorOverride); + if (parsed) { + return `${parsed.name} <${parsed.email}>`; + } + } + try { + const name = await this.git.getConfig({ dir: cwd, path: 'user.name' }); + const email = await this.git.getConfig({ dir: cwd, path: 'user.email' }); + if (name && email) { + return `${name} <${email}>`; + } + } catch { + // Ignore + } + return null; + } } diff --git a/src/lib/commands/git/config.ts b/src/lib/commands/git/config.ts index ba919dfc..66fadd58 100644 --- a/src/lib/commands/git/config.ts +++ b/src/lib/commands/git/config.ts @@ -4,10 +4,12 @@ import { createSuccessResult, createErrorResult } from "../ShellCommand"; import type { GitSubcommand, GitSubcommandOptions } from "../git"; import type { Git } from "../../git"; +type ConfigAction = 'list' | 'get' | 'set' | 'unset' | 'get-all' | 'add'; + export class GitConfigCommand implements GitSubcommand { name = 'config'; description = 'Get and set repository or global options'; - usage = 'git config [--global] [] | git config [--global] --list'; + usage = 'git config [--global | --local] [--list] [--get | --get-all | --unset | --add] []'; private git: Git; private fs: JSRuntimeFS; @@ -35,10 +37,16 @@ export class GitConfigCommand implements GitSubcommand { return await this.listConfig(options.global, cwd); case 'get': return await this.getConfig(key!, options.global, cwd); + case 'get-all': + return await this.getConfigAll(key!, options.global, cwd); case 'set': return await this.setConfig(key!, value!, options.global, cwd); + case 'add': + return await this.addConfig(key!, value!, options.global, cwd); + case 'unset': + return await this.unsetConfig(key!, options.global, cwd); default: - return createErrorResult('usage: git config [--global] [] | git config [--global] --list'); + return createErrorResult('usage: git config [--global | --local] [--list] [--get | --get-all | --unset | --add] []'); } } catch (error) { @@ -47,30 +55,69 @@ export class GitConfigCommand implements GitSubcommand { } private parseArgs(args: string[]): { - action: 'list' | 'get' | 'set'; + action: ConfigAction; key?: string; value?: string; - options: { global: boolean } + options: { global: boolean; local: boolean }; } { - const options = { global: false }; - let action: 'list' | 'get' | 'set' = 'get'; + const options = { global: false, local: false }; + let action: ConfigAction = 'get'; let key: string | undefined; let value: string | undefined; + let explicitAction = false; for (let i = 0; i < args.length; i++) { const arg = args[i]; if (arg === '--global') { options.global = true; + } else if (arg === '--local') { + options.local = true; + } else if (arg === '--system') { + // Not supported; treat as global + options.global = true; } else if (arg === '--list' || arg === '-l') { action = 'list'; + explicitAction = true; + } else if (arg === '--get') { + action = 'get'; + explicitAction = true; + if (i + 1 < args.length) { + key = args[i + 1]; + i++; + } + } else if (arg === '--get-all') { + action = 'get-all'; + explicitAction = true; + if (i + 1 < args.length) { + key = args[i + 1]; + i++; + } + } else if (arg === '--add') { + action = 'add'; + explicitAction = true; + if (i + 1 < args.length) { + key = args[i + 1]; + i++; + } + if (i + 1 < args.length) { + value = args[i + 1]; + i++; + } + } else if (arg === '--unset') { + action = 'unset'; + explicitAction = true; + if (i + 1 < args.length) { + key = args[i + 1]; + i++; + } } else if (!arg.startsWith('-')) { if (!key) { key = arg; - action = 'get'; // Default to get if only key is provided + if (!explicitAction) action = 'get'; } else if (!value) { value = arg; - action = 'set'; // Set if both key and value are provided + if (!explicitAction) action = 'set'; } } } @@ -78,31 +125,87 @@ export class GitConfigCommand implements GitSubcommand { return { action, key, value, options }; } - private async listConfig(global: boolean, cwd: string): Promise { + /** + * Read the .git/config file directly to list all keys. + */ + private async readConfigFile(global: boolean, cwd: string): Promise> { + const result = new Map(); + const configPath = global ? '/config/git.json' : `${cwd}/.git/config`; try { - // For simplicity, we'll only show the most common config values - // isomorphic-git doesn't have a direct way to list all config - const commonKeys = [ - 'user.name', - 'user.email', - 'core.bare', - 'remote.origin.url', - 'remote.origin.fetch' - ]; + const content = await this.fs.readFile(configPath, 'utf8'); - const lines: string[] = []; - - for (const key of commonKeys) { + if (global) { + // JSON-based global config try { - const value = await this.git.getConfig({ - dir: global ? undefined : cwd, - path: key, - }); - if (value !== undefined) { - lines.push(`${key}=${value}`); - } + const parsed = JSON.parse(content); + const flatten = (obj: Record, prefix: string = ''): void => { + for (const [k, v] of Object.entries(obj)) { + const fullKey = prefix ? `${prefix}.${k}` : k; + if (v !== null && typeof v === 'object' && !Array.isArray(v)) { + flatten(v as Record, fullKey); + } else if (Array.isArray(v)) { + result.set(fullKey, v.map(String)); + } else { + result.set(fullKey, [String(v)]); + } + } + }; + flatten(parsed); } catch { - // Skip if config doesn't exist + // Not JSON + } + } else { + // INI-format .git/config + let section = ''; + for (const rawLine of content.split('\n')) { + const line = rawLine.trim(); + if (!line || line.startsWith('#') || line.startsWith(';')) continue; + const sectionMatch = line.match(/^\[([^\]]+)\]$/); + if (sectionMatch) { + section = sectionMatch[1].trim().replace(/\s+"/, '.').replace(/"$/, '').replace(/\s+/g, '.'); + continue; + } + const kvMatch = line.match(/^([^=]+?)\s*=\s*(.*)$/); + if (kvMatch && section) { + const fullKey = `${section}.${kvMatch[1].trim()}`.toLowerCase(); + const val = kvMatch[2].replace(/^["']|["']$/g, ''); + const existing = result.get(fullKey) || []; + existing.push(val); + result.set(fullKey, existing); + } + } + } + } catch { + // Config file doesn't exist or couldn't be read + } + return result; + } + + private async listConfig(global: boolean, cwd: string): Promise { + try { + const configMap = await this.readConfigFile(global, cwd); + const lines: string[] = []; + for (const [key, values] of configMap) { + for (const value of values) { + lines.push(`${key}=${value}`); + } + } + + // Also include common keys that might only be accessible via getConfig + const commonKeys = ['user.name', 'user.email', 'core.bare', 'remote.origin.url', 'remote.origin.fetch']; + for (const key of commonKeys) { + if (!configMap.has(key.toLowerCase())) { + try { + const val = await this.git.getConfig({ + dir: global ? undefined : cwd, + path: key, + }); + if (val !== undefined && val !== null) { + lines.push(`${key}=${val}`); + } + } catch { + // Skip + } } } @@ -113,14 +216,14 @@ export class GitConfigCommand implements GitSubcommand { } } - private async getConfig(key: string, global: boolean, cwd: string): Promise { + private async getConfig(key: string, global: boolean, cwd: string): Promise { try { const value = await this.git.getConfig({ dir: global ? undefined : cwd, path: key, }); - if (value === undefined) { + if (value === undefined || value === null) { return createErrorResult(`error: key does not exist: ${key}`); } @@ -131,7 +234,25 @@ export class GitConfigCommand implements GitSubcommand { } } - private async setConfig(key: string, value: string, global: boolean, cwd: string): Promise { + private async getConfigAll(key: string, global: boolean, cwd: string): Promise { + try { + const values = await this.git.getConfigAll({ + dir: global ? undefined : cwd, + path: key, + }); + + if (!values || values.length === 0) { + return createErrorResult(`error: key does not exist: ${key}`); + } + + return createSuccessResult(values.join('\n') + '\n'); + + } catch (error) { + return createErrorResult(`Failed to get config: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private async setConfig(key: string, value: string, global: boolean, cwd: string): Promise { try { await this.git.setConfig({ dir: global ? undefined : cwd, @@ -145,4 +266,35 @@ export class GitConfigCommand implements GitSubcommand { return createErrorResult(`Failed to set config: ${error instanceof Error ? error.message : 'Unknown error'}`); } } + + private async addConfig(key: string, value: string, global: boolean, cwd: string): Promise { + try { + await this.git.setConfig({ + dir: global ? undefined : cwd, + path: key, + value: value, + append: true, + } as Parameters[0]); + + return createSuccessResult(''); + + } catch (error) { + return createErrorResult(`Failed to add config: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private async unsetConfig(key: string, global: boolean, cwd: string): Promise { + try { + await this.git.setConfig({ + dir: global ? undefined : cwd, + path: key, + value: undefined, + } as Parameters[0]); + + return createSuccessResult(''); + + } catch (error) { + return createErrorResult(`Failed to unset config: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } } diff --git a/src/lib/commands/git/diff.test.ts b/src/lib/commands/git/diff.test.ts index 165dea2a..5e922e79 100644 --- a/src/lib/commands/git/diff.test.ts +++ b/src/lib/commands/git/diff.test.ts @@ -63,7 +63,7 @@ describe('GitDiffCommand', () => { type ParseArgsResult = { commits: string[]; paths: string[]; - options: { cached: boolean; staged: boolean }; + options: { cached: boolean; nameOnly: boolean; nameStatus: boolean; stat: boolean }; }; it('should parse no arguments correctly', () => { @@ -71,7 +71,7 @@ describe('GitDiffCommand', () => { expect(result).toEqual({ commits: [], paths: [], - options: { cached: false, staged: false }, + options: { cached: false, nameOnly: false, nameStatus: false, stat: false }, }); }); @@ -80,18 +80,43 @@ describe('GitDiffCommand', () => { expect(result).toEqual({ commits: [], paths: [], - options: { cached: true, staged: true }, + options: { cached: true, nameOnly: false, nameStatus: false, stat: false }, }); }); + it('should parse --staged option as alias for --cached', () => { + const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['--staged']); + expect(result.options.cached).toBe(true); + }); + + it('should parse --name-only option', () => { + const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['--name-only']); + expect(result.options.nameOnly).toBe(true); + }); + + it('should parse --name-status option', () => { + const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['--name-status']); + expect(result.options.nameStatus).toBe(true); + }); + + it('should parse --stat option', () => { + const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['--stat']); + expect(result.options.stat).toBe(true); + }); + it('should parse commits and paths', () => { const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['HEAD~1', 'HEAD', '--', 'file.txt']); expect(result).toEqual({ commits: ['HEAD~1', 'HEAD'], paths: ['file.txt'], - options: { cached: false, staged: false }, + options: { cached: false, nameOnly: false, nameStatus: false, stat: false }, }); }); + + it('should parse range syntax commit1..commit2', () => { + const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['HEAD~2..HEAD']); + expect(result.commits).toEqual(['HEAD~2', 'HEAD']); + }); }); describe('execute', () => { diff --git a/src/lib/commands/git/diff.ts b/src/lib/commands/git/diff.ts index b3866ca7..2536319d 100644 --- a/src/lib/commands/git/diff.ts +++ b/src/lib/commands/git/diff.ts @@ -5,10 +5,26 @@ import { createSuccessResult, createErrorResult } from "../ShellCommand"; import type { GitSubcommand, GitSubcommandOptions } from "../git"; import type { Git } from "../../git"; +interface DiffOptions { + cached: boolean; + nameOnly: boolean; + nameStatus: boolean; + stat: boolean; +} + +interface TreeEntry { + mode: string; + path: string; + oid: string; + type?: string; +} + +type ChangeType = 'add' | 'modify' | 'delete'; + export class GitDiffCommand implements GitSubcommand { name = 'diff'; description = 'Show changes between commits, commit and working tree, etc'; - usage = 'git diff [] [] [-- ...]'; + usage = 'git diff [--cached | --staged] [--stat] [--name-only] [--name-status] [] [] [-- ...]'; private git: Git; private fs: JSRuntimeFS; @@ -29,18 +45,18 @@ export class GitDiffCommand implements GitSubcommand { const { commits, paths, options } = this.parseArgs(args); - if (options.cached || options.staged) { - // Show staged changes (index vs HEAD) - return await this.showStagedDiff(paths, cwd); + if (options.cached) { + // Show staged changes (index vs HEAD) or (commit vs index) + return await this.showStagedDiff(paths, options, cwd, commits[0]); } else if (commits.length === 0) { // Show working directory changes vs index - return await this.showWorkingDirectoryDiff(paths, cwd); + return await this.showWorkingDirectoryDiff(paths, options, cwd); } else if (commits.length === 1) { // Show changes between commit and working directory - return await this.showCommitDiff(commits[0], paths, cwd); + return await this.showCommitVsWorkdir(commits[0], paths, options, cwd); } else if (commits.length === 2) { // Show changes between two commits - return await this.showCommitRangeDiff(commits[0], commits[1], paths, cwd); + return await this.showCommitRangeDiff(commits[0], commits[1], paths, options, cwd); } else { return createErrorResult('usage: git diff [] [] [-- ...]'); } @@ -53,9 +69,14 @@ export class GitDiffCommand implements GitSubcommand { private parseArgs(args: string[]): { commits: string[]; paths: string[]; - options: { cached: boolean; staged: boolean } + options: DiffOptions; } { - const options = { cached: false, staged: false }; + const options: DiffOptions = { + cached: false, + nameOnly: false, + nameStatus: false, + stat: false, + }; const commits: string[] = []; const paths: string[] = []; let foundDoubleDash = false; @@ -70,9 +91,21 @@ export class GitDiffCommand implements GitSubcommand { paths.push(arg); } else if (arg === '--cached' || arg === '--staged') { options.cached = true; - options.staged = true; - } else if (!arg.startsWith('-')) { - // Assume it's a commit reference + } else if (arg === '--name-only') { + options.nameOnly = true; + } else if (arg === '--name-status') { + options.nameStatus = true; + } else if (arg === '--stat') { + options.stat = true; + } else if (arg.startsWith('-')) { + // Unknown option, ignore for now + continue; + } else if (arg.includes('..')) { + // Range syntax: commit1..commit2 + const [c1, c2] = arg.split('..'); + if (c1) commits.push(c1); + if (c2) commits.push(c2); + } else { commits.push(arg); } } @@ -80,298 +113,605 @@ export class GitDiffCommand implements GitSubcommand { return { commits, paths, options }; } - private async showWorkingDirectoryDiff(paths: string[], cwd: string): Promise { + /** + * Match a file path against optional pathspec filters using prefix matching. + */ + private matchesPaths(filepath: string, paths: string[]): boolean { + if (paths.length === 0) return true; + return paths.some(p => { + if (p === '.') return true; + return filepath === p || filepath.startsWith(p.endsWith('/') ? p : p + '/'); + }); + } + + /** + * Read a file's content from the working directory + */ + private async readWorkdirFile(cwd: string, filepath: string): Promise { try { - // Get status to find changed files - const statusMatrix = await this.git.statusMatrix({ + return await this.fs.readFile(`${cwd}/${filepath}`, 'utf8'); + } catch { + return ''; + } + } + + /** + * Read a file's content from a tree (commit) + */ + private async readBlobFromRef(cwd: string, ref: string, filepath: string): Promise { + try { + const blob = await this.git.readBlob({ dir: cwd, + oid: ref, + filepath, }); + return new TextDecoder().decode(blob.blob); + } catch { + return ''; + } + } - // Filter for files with working directory changes - // Status matrix: [filepath, headStatus, workdirStatus, stageStatus] - // 0 = absent, 1 = same as previous stage, 2 = different from previous stage - const changedFiles = statusMatrix.filter(([filepath, _headStatus, workdirStatus, stageStatus]) => { - // Show files that have working directory changes (differ from index) - // Exclude untracked files - git diff only shows changes to tracked files - const hasWorkingDirChanges = (stageStatus !== workdirStatus && workdirStatus === 2 && stageStatus !== 0) || - (stageStatus === 2 && workdirStatus === 0) || - (stageStatus === 1 && workdirStatus === 0); + /** + * Read a file's content from the index (stage) via updateIndex/readBlob hack. + * Since isomorphic-git doesn't directly expose reading from the index, + * fall back to reading from HEAD when possible, or from working directory. + */ + private async readIndexContent( + cwd: string, + filepath: string, + stageStatus: number, + headStatus: number + ): Promise { + // If the stage matches HEAD, read from HEAD + if (stageStatus === 1 && headStatus === 1) { + return this.readBlobFromRef(cwd, 'HEAD', filepath); + } + // If file is in stage (either new or modified), we approximate by reading + // working directory. This is imperfect but the best we can do without + // direct index reading in isomorphic-git. + if (stageStatus === 2) { + return this.readWorkdirFile(cwd, filepath); + } + return ''; + } - if (paths.length > 0) { - return hasWorkingDirChanges && paths.some(path => filepath.includes(path)); + /** + * Generate a unified diff between two strings with proper context lines. + */ + private generateUnifiedDiff( + oldContent: string, + newContent: string, + oldPath: string, + newPath: string + ): string[] { + const lines: string[] = []; + const oldLines = oldContent === '' ? [] : oldContent.split('\n'); + const newLines = newContent === '' ? [] : newContent.split('\n'); + + // Use LCS-based diff + const hunks = this.computeHunks(oldLines, newLines, 3); + + for (const hunk of hunks) { + const oldSize = hunk.oldEnd - hunk.oldStart; + const newSize = hunk.newEnd - hunk.newStart; + lines.push(`@@ -${hunk.oldStart + 1},${oldSize} +${hunk.newStart + 1},${newSize} @@`); + for (const line of hunk.lines) { + lines.push(line); + } + } + + if (lines.length === 0 && oldPath !== newPath) { + lines.push('(No textual differences)'); + } + return lines; + } + + /** + * Compute hunks using a simple Myers-like diff algorithm. + */ + private computeHunks(oldLines: string[], newLines: string[], context: number): Array<{ + oldStart: number; + oldEnd: number; + newStart: number; + newEnd: number; + lines: string[]; + }> { + // Compute LCS table (for small files - could be inefficient for huge files) + const m = oldLines.length; + const n = newLines.length; + + // For performance, cap LCS to reasonable sizes + if (m > 5000 || n > 5000) { + // Fall back to naive line-by-line diff for huge files + return this.naiveDiffHunks(oldLines, newLines, context); + } + + const lcs: number[][] = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0)); + for (let i = m - 1; i >= 0; i--) { + for (let j = n - 1; j >= 0; j--) { + if (oldLines[i] === newLines[j]) { + lcs[i][j] = lcs[i + 1][j + 1] + 1; + } else { + lcs[i][j] = Math.max(lcs[i + 1][j], lcs[i][j + 1]); } - return hasWorkingDirChanges; + } + } + + // Generate the edit script + type Op = { op: ' ' | '-' | '+'; oldIdx: number; newIdx: number; line: string }; + const ops: Op[] = []; + let i = 0, j = 0; + while (i < m && j < n) { + if (oldLines[i] === newLines[j]) { + ops.push({ op: ' ', oldIdx: i, newIdx: j, line: oldLines[i] }); + i++; + j++; + } else if (lcs[i + 1][j] >= lcs[i][j + 1]) { + ops.push({ op: '-', oldIdx: i, newIdx: j, line: oldLines[i] }); + i++; + } else { + ops.push({ op: '+', oldIdx: i, newIdx: j, line: newLines[j] }); + j++; + } + } + while (i < m) { + ops.push({ op: '-', oldIdx: i, newIdx: j, line: oldLines[i] }); + i++; + } + while (j < n) { + ops.push({ op: '+', oldIdx: i, newIdx: j, line: newLines[j] }); + j++; + } + + // Group into hunks using context + const hunks: Array<{ oldStart: number; oldEnd: number; newStart: number; newEnd: number; lines: string[] }> = []; + let hunkStart = -1; + + for (let k = 0; k < ops.length; k++) { + if (ops[k].op !== ' ') { + if (hunkStart < 0) { + hunkStart = Math.max(0, k - context); + } + } else if (hunkStart >= 0) { + // Check if next non-context op is within 2*context + let nextChange = -1; + for (let l = k + 1; l < ops.length && l < k + 2 * context + 1; l++) { + if (ops[l].op !== ' ') { + nextChange = l; + break; + } + } + if (nextChange < 0) { + // Close the hunk + const hunkEnd = Math.min(ops.length, k + context); + hunks.push(this.buildHunk(ops, hunkStart, hunkEnd)); + hunkStart = -1; + } + } + } + if (hunkStart >= 0) { + hunks.push(this.buildHunk(ops, hunkStart, ops.length)); + } + + return hunks; + } + + private buildHunk( + ops: Array<{ op: ' ' | '-' | '+'; oldIdx: number; newIdx: number; line: string }>, + start: number, + end: number + ): { oldStart: number; oldEnd: number; newStart: number; newEnd: number; lines: string[] } { + // Count how many old-side and new-side lines appear in this hunk + let oldCount = 0; + let newCount = 0; + const lines: string[] = []; + for (let i = start; i < end; i++) { + const o = ops[i]; + if (o.op === ' ') { + lines.push(` ${o.line}`); + oldCount++; + newCount++; + } else if (o.op === '-') { + lines.push(`-${o.line}`); + oldCount++; + } else { + lines.push(`+${o.line}`); + newCount++; + } + } + + // Find the old/new starting line numbers by scanning from beginning + let oldPos = 0, newPos = 0; + for (let i = 0; i < start; i++) { + if (ops[i].op !== '+') oldPos++; + if (ops[i].op !== '-') newPos++; + } + + return { + oldStart: oldPos, + oldEnd: oldPos + oldCount, + newStart: newPos, + newEnd: newPos + newCount, + lines, + }; + } + + /** + * Naive line-by-line diff for large files. + */ + private naiveDiffHunks(oldLines: string[], newLines: string[], _context: number): Array<{ + oldStart: number; + oldEnd: number; + newStart: number; + newEnd: number; + lines: string[]; + }> { + const lines: string[] = []; + const maxLen = Math.max(oldLines.length, newLines.length); + for (let i = 0; i < maxLen; i++) { + const oldLine = oldLines[i]; + const newLine = newLines[i]; + if (oldLine !== undefined && newLine !== undefined) { + if (oldLine === newLine) { + lines.push(` ${oldLine}`); + } else { + lines.push(`-${oldLine}`); + lines.push(`+${newLine}`); + } + } else if (oldLine !== undefined) { + lines.push(`-${oldLine}`); + } else if (newLine !== undefined) { + lines.push(`+${newLine}`); + } + } + return [{ + oldStart: 0, + oldEnd: oldLines.length, + newStart: 0, + newEnd: newLines.length, + lines, + }]; + } + + /** + * Get the git-style short hash for a file's contents (using hashBlob). + */ + private async getGitShortHash(content: string): Promise { + try { + const encoder = new TextEncoder(); + const buf = encoder.encode(content); + const result = await this.git.hashBlob({ object: buf }); + return result.oid.substring(0, 7); + } catch { + // Fallback to a placeholder + return '0000000'; + } + } + + /** + * Emit diff output (unified, stat, or name-only) for a set of changes. + */ + private async emitDiff( + changes: Array<{ + filepath: string; + oldContent: string; + newContent: string; + oldMode?: string; + newMode?: string; + changeType: ChangeType; + }>, + options: DiffOptions + ): Promise { + if (options.nameOnly) { + return changes.map(c => c.filepath).join('\n') + (changes.length > 0 ? '\n' : ''); + } + + if (options.nameStatus) { + return changes.map(c => { + const status = c.changeType === 'add' ? 'A' : c.changeType === 'delete' ? 'D' : 'M'; + return `${status}\t${c.filepath}`; + }).join('\n') + (changes.length > 0 ? '\n' : ''); + } + + if (options.stat) { + const lines: string[] = []; + let totalAdd = 0, totalDel = 0; + const maxPathLen = Math.max(10, ...changes.map(c => c.filepath.length)); + for (const change of changes) { + const oldLines = change.oldContent === '' ? 0 : change.oldContent.split('\n').length; + const newLines = change.newContent === '' ? 0 : change.newContent.split('\n').length; + const adds = Math.max(0, newLines - (change.changeType === 'delete' ? newLines : oldLines)); + const dels = Math.max(0, oldLines - (change.changeType === 'add' ? oldLines : newLines)); + // For modifications, try to compute actual changes + let actualAdds = 0, actualDels = 0; + if (change.changeType === 'modify') { + const hunks = this.computeHunks( + change.oldContent.split('\n'), + change.newContent.split('\n'), + 0 + ); + for (const hunk of hunks) { + for (const l of hunk.lines) { + if (l.startsWith('+')) actualAdds++; + else if (l.startsWith('-')) actualDels++; + } + } + } else if (change.changeType === 'add') { + actualAdds = newLines; + } else { + actualDels = oldLines; + } + totalAdd += actualAdds; + totalDel += actualDels; + const bar = '+'.repeat(Math.min(actualAdds, 40)) + '-'.repeat(Math.min(actualDels, 40)); + lines.push(` ${change.filepath.padEnd(maxPathLen)} | ${actualAdds + actualDels} ${bar}`); + // suppress unused-variable warnings + void adds; void dels; + } + lines.push(` ${changes.length} file${changes.length !== 1 ? 's' : ''} changed, ${totalAdd} insertion${totalAdd !== 1 ? 's' : ''}(+), ${totalDel} deletion${totalDel !== 1 ? 's' : ''}(-)`); + return lines.join('\n') + '\n'; + } + + // Full unified diff + const diffLines: string[] = []; + for (const change of changes) { + const oldHash = await this.getGitShortHash(change.oldContent); + const newHash = await this.getGitShortHash(change.newContent); + + diffLines.push(`diff --git a/${change.filepath} b/${change.filepath}`); + + if (change.changeType === 'add') { + diffLines.push(`new file mode ${change.newMode || '100644'}`); + diffLines.push(`index 0000000..${newHash}`); + diffLines.push('--- /dev/null'); + diffLines.push(`+++ b/${change.filepath}`); + } else if (change.changeType === 'delete') { + diffLines.push(`deleted file mode ${change.oldMode || '100644'}`); + diffLines.push(`index ${oldHash}..0000000`); + diffLines.push(`--- a/${change.filepath}`); + diffLines.push('+++ /dev/null'); + } else { + diffLines.push(`index ${oldHash}..${newHash} ${change.newMode || '100644'}`); + diffLines.push(`--- a/${change.filepath}`); + diffLines.push(`+++ b/${change.filepath}`); + } + + const hunks = this.generateUnifiedDiff( + change.oldContent, + change.newContent, + change.filepath, + change.filepath + ); + diffLines.push(...hunks); + } + + return diffLines.join('\n') + (diffLines.length > 0 ? '\n' : ''); + } + + private async showWorkingDirectoryDiff( + paths: string[], + options: DiffOptions, + cwd: string + ): Promise { + try { + const statusMatrix = await this.git.statusMatrix({ dir: cwd }); + + const changedFiles = statusMatrix.filter(([filepath, _headStatus, workdirStatus, stageStatus]) => { + // Working dir differs from stage, but exclude purely untracked files + const hasChanges = (stageStatus !== workdirStatus && workdirStatus === 2 && stageStatus !== 0) || + (stageStatus === 2 && workdirStatus === 0) || + (stageStatus === 1 && workdirStatus === 0); + return hasChanges && this.matchesPaths(filepath, paths); }); if (changedFiles.length === 0) { return createSuccessResult(''); } - const diffLines: string[] = []; + const changes: Parameters[0] = []; + for (const [filepath, headStatus, workdirStatus, stageStatus] of changedFiles) { + const oldContent = await this.readIndexContent(cwd, filepath, stageStatus, headStatus); + const newContent = workdirStatus === 0 ? '' : await this.readWorkdirFile(cwd, filepath); - for (const [filepath, _headStatus, workdirStatus, stageStatus] of changedFiles) { - try { - // Get staged/index content - let indexContent = ''; - if (stageStatus === 1 || stageStatus === 2) { - try { - // For files in the index, read from HEAD as the baseline - // This represents the last committed version for comparison - const headBlob = await this.git.readBlob({ - dir: cwd, - oid: 'HEAD', - filepath, - }); - indexContent = new TextDecoder().decode(headBlob.blob); - } catch { - // File might be new or not in HEAD - indexContent = ''; - } - } + if (oldContent === newContent) continue; - // Get working directory content - let workdirContent = ''; - if (workdirStatus === 2) { - try { - workdirContent = await this.fs.readFile(`${cwd}/${filepath}`, 'utf8'); - } catch { - // File might be deleted - workdirContent = ''; - } - } else if (workdirStatus === 0) { - // File is deleted in working directory - workdirContent = ''; - } - - // Skip if contents are identical - if (indexContent === workdirContent) { - continue; - } - - // Generate diff header - diffLines.push(`diff --git a/${filepath} b/${filepath}`); - - if (workdirStatus === 0 && (stageStatus === 1 || stageStatus === 2)) { - // Deleted file - diffLines.push('deleted file mode 100644'); - diffLines.push(`index ${this.getShortHash(indexContent, cwd)}..0000000`); - diffLines.push(`--- a/${filepath}`); - diffLines.push('+++ /dev/null'); - } else { - // Modified file - diffLines.push(`index ${this.getShortHash(indexContent, cwd)}..${this.getShortHash(workdirContent, cwd)} 100644`); - diffLines.push(`--- a/${filepath}`); - diffLines.push(`+++ b/${filepath}`); - } - - // Generate unified diff - const indexLines = indexContent.split('\n'); - const workdirLines = workdirContent.split('\n'); - - // Simple hunk header - diffLines.push(`@@ -1,${indexLines.length} +1,${workdirLines.length} @@`); - - // Simple line-by-line diff - const maxLines = Math.max(indexLines.length, workdirLines.length); - for (let i = 0; i < maxLines; i++) { - const oldLine = indexLines[i]; - const newLine = workdirLines[i]; - - if (oldLine !== undefined && newLine !== undefined) { - if (oldLine === newLine) { - // Unchanged line (show context) - diffLines.push(` ${oldLine}`); - } else { - // Changed line - diffLines.push(`-${oldLine}`); - diffLines.push(`+${newLine}`); - } - } else if (oldLine !== undefined) { - // Removed line - diffLines.push(`-${oldLine}`); - } else if (newLine !== undefined) { - // Added line - diffLines.push(`+${newLine}`); - } - } - - diffLines.push(''); - } catch (error) { - // Skip files that can't be diffed - console.warn(`Failed to diff ${filepath}:`, error); - } + const changeType: ChangeType = workdirStatus === 0 ? 'delete' : 'modify'; + changes.push({ filepath, oldContent, newContent, changeType }); } - return createSuccessResult(diffLines.join('\n')); - + return createSuccessResult(await this.emitDiff(changes, options)); } catch (error) { return createErrorResult(`Failed to show diff: ${error instanceof Error ? error.message : 'Unknown error'}`); } } - private async showCommitDiff(commit: string, _paths: string[], cwd: string): Promise { + private async showStagedDiff( + paths: string[], + options: DiffOptions, + cwd: string, + baseCommit?: string + ): Promise { try { - // For simplicity, show the commit message and changed files - const commits = await this.git.log({ - dir: cwd, - depth: 1, - ref: commit, - }); + const statusMatrix = await this.git.statusMatrix({ dir: cwd }); + const base = baseCommit || 'HEAD'; - if (commits.length === 0) { - return createErrorResult(`fatal: bad revision '${commit}'`); - } - - const commitObj = commits[0]; - const lines: string[] = []; - - lines.push(`commit ${commitObj.oid}`); - lines.push(`Author: ${commitObj.commit.author.name} <${commitObj.commit.author.email}>`); - lines.push(`Date: ${new Date(commitObj.commit.author.timestamp * 1000).toUTCString()}`); - lines.push(''); - lines.push(` ${commitObj.commit.message}`); - lines.push(''); - - // Note: Showing actual file diffs would require more complex implementation - lines.push('(File content diff not implemented - use git log for commit details)'); - - return createSuccessResult(lines.join('\n')); - - } catch (error) { - return createErrorResult(`Failed to show commit diff: ${error instanceof Error ? error.message : 'Unknown error'}`); - } - } - - private async showCommitRangeDiff(_commit1: string, _commit2: string, _paths: string[], _cwd: string): Promise { - // This would require complex implementation to compare two commits - return createErrorResult('Commit range diff is not implemented in this git command'); - } - - private async showStagedDiff(paths: string[], cwd: string): Promise { - try { - // Get status to find staged files - const statusMatrix = await this.git.statusMatrix({ - dir: cwd, - }); - - // Filter for files with staged changes (index differs from HEAD) const stagedFiles = statusMatrix.filter(([filepath, headStatus, _workdirStatus, stageStatus]) => { - const hasStagedChanges = (headStatus === 0 && stageStatus === 2) || // Added to stage - (headStatus === 1 && stageStatus === 0) || // Deleted from stage - (headStatus === 1 && stageStatus === 2); // Modified in stage - - if (paths.length > 0) { - return hasStagedChanges && paths.some(path => filepath.includes(path)); - } - return hasStagedChanges; + const hasStagedChanges = (headStatus === 0 && stageStatus === 2) || + (headStatus === 1 && stageStatus === 0) || + (headStatus === 1 && stageStatus === 2); + return hasStagedChanges && this.matchesPaths(filepath, paths); }); if (stagedFiles.length === 0) { return createSuccessResult(''); } - const diffLines: string[] = []; - + const changes: Parameters[0] = []; for (const [filepath, headStatus, _workdirStatus, stageStatus] of stagedFiles) { - try { - // Get HEAD content - let headContent = ''; - if (headStatus === 1) { - try { - const headBlob = await this.git.readBlob({ - dir: cwd, - oid: 'HEAD', - filepath, - }); - headContent = new TextDecoder().decode(headBlob.blob); - } catch { - headContent = ''; - } - } + const oldContent = headStatus === 1 ? await this.readBlobFromRef(cwd, base, filepath) : ''; + // For staged, approximate with working dir (see readIndexContent for details) + const newContent = stageStatus === 0 ? '' : await this.readWorkdirFile(cwd, filepath); - // Get staged content (approximated by working directory for now) - let stagedContent = ''; - if (stageStatus === 1 || stageStatus === 2) { - try { - stagedContent = await this.fs.readFile(`${cwd}/${filepath}`, 'utf8'); - } catch { - stagedContent = ''; - } - } + let changeType: ChangeType = 'modify'; + if (headStatus === 0 && stageStatus === 2) changeType = 'add'; + else if (headStatus === 1 && stageStatus === 0) changeType = 'delete'; - // Generate diff header - diffLines.push(`diff --git a/${filepath} b/${filepath}`); - - if (headStatus === 0 && stageStatus === 2) { - // New file staged - diffLines.push('new file mode 100644'); - diffLines.push(`index 0000000..${this.getShortHash(stagedContent, cwd)}`); - diffLines.push('--- /dev/null'); - diffLines.push(`+++ b/${filepath}`); - } else if (headStatus === 1 && stageStatus === 0) { - // File deleted from stage - diffLines.push('deleted file mode 100644'); - diffLines.push(`index ${this.getShortHash(headContent, cwd)}..0000000`); - diffLines.push(`--- a/${filepath}`); - diffLines.push('+++ /dev/null'); - } else { - // Modified file - diffLines.push(`index ${this.getShortHash(headContent, cwd)}..${this.getShortHash(stagedContent, cwd)} 100644`); - diffLines.push(`--- a/${filepath}`); - diffLines.push(`+++ b/${filepath}`); - } - - // Generate unified diff - const headLines = headContent.split('\n'); - const stagedLines = stagedContent.split('\n'); - - diffLines.push(`@@ -1,${headLines.length} +1,${stagedLines.length} @@`); - - // Simple line-by-line diff - const maxLines = Math.max(headLines.length, stagedLines.length); - for (let i = 0; i < maxLines; i++) { - const oldLine = headLines[i]; - const newLine = stagedLines[i]; - - if (oldLine !== undefined && newLine !== undefined) { - if (oldLine === newLine) { - // Unchanged line (show context) - diffLines.push(` ${oldLine}`); - } else { - // Changed line - diffLines.push(`-${oldLine}`); - diffLines.push(`+${newLine}`); - } - } else if (oldLine !== undefined) { - // Removed line - diffLines.push(`-${oldLine}`); - } else if (newLine !== undefined) { - // Added line - diffLines.push(`+${newLine}`); - } - } - - diffLines.push(''); - } catch (error) { - console.warn(`Failed to diff staged ${filepath}:`, error); - } + changes.push({ filepath, oldContent, newContent, changeType }); } - return createSuccessResult(diffLines.join('\n')); - + return createSuccessResult(await this.emitDiff(changes, options)); } catch (error) { return createErrorResult(`Failed to show staged diff: ${error instanceof Error ? error.message : 'Unknown error'}`); } } - private getShortHash(content: string, _cwd: string): string { - // Simple hash for demo purposes - not a real git hash - let hash = 0; - for (let i = 0; i < content.length; i++) { - const char = content.charCodeAt(i); - hash = ((hash << 5) - hash) + char; - hash = hash & hash; // Convert to 32-bit integer + /** + * Show diff between a commit and the working directory. + */ + private async showCommitVsWorkdir( + commit: string, + paths: string[], + options: DiffOptions, + cwd: string + ): Promise { + try { + // Resolve the commit + let commitOid: string; + try { + commitOid = await this.git.resolveRef({ dir: cwd, ref: commit }); + } catch { + return createErrorResult(`fatal: bad revision '${commit}'`); + } + + // List all files in the commit tree + const commitFiles = await this.listFilesInCommit(cwd, commitOid); + + // List all files in the working directory (via statusMatrix) + const statusMatrix = await this.git.statusMatrix({ dir: cwd }); + + const changes: Parameters[0] = []; + const seen = new Set(); + + // Files present in working dir + for (const [filepath, _h, workdirStatus, _s] of statusMatrix) { + if (!this.matchesPaths(filepath, paths)) continue; + seen.add(filepath); + + const oldContent = commitFiles.has(filepath) + ? await this.readBlobFromRef(cwd, commitOid, filepath) + : ''; + const newContent = workdirStatus === 0 ? '' : await this.readWorkdirFile(cwd, filepath); + + if (oldContent === newContent) continue; + + let changeType: ChangeType = 'modify'; + if (!commitFiles.has(filepath)) changeType = 'add'; + else if (workdirStatus === 0) changeType = 'delete'; + + changes.push({ filepath, oldContent, newContent, changeType }); + } + + // Files only in the commit tree (deleted) + for (const filepath of commitFiles) { + if (seen.has(filepath)) continue; + if (!this.matchesPaths(filepath, paths)) continue; + + const oldContent = await this.readBlobFromRef(cwd, commitOid, filepath); + const newContent = await this.readWorkdirFile(cwd, filepath); + if (oldContent === newContent) continue; + + changes.push({ filepath, oldContent, newContent, changeType: 'delete' }); + } + + return createSuccessResult(await this.emitDiff(changes, options)); + } catch (error) { + return createErrorResult(`Failed to show commit diff: ${error instanceof Error ? error.message : 'Unknown error'}`); } - return Math.abs(hash).toString(16).substring(0, 7).padStart(7, '0'); + } + + /** + * Show diff between two commits. + */ + private async showCommitRangeDiff( + commit1: string, + commit2: string, + paths: string[], + options: DiffOptions, + cwd: string + ): Promise { + try { + let oid1: string; + let oid2: string; + try { + oid1 = await this.git.resolveRef({ dir: cwd, ref: commit1 }); + } catch { + return createErrorResult(`fatal: bad revision '${commit1}'`); + } + try { + oid2 = await this.git.resolveRef({ dir: cwd, ref: commit2 }); + } catch { + return createErrorResult(`fatal: bad revision '${commit2}'`); + } + + const files1 = await this.listFilesInCommit(cwd, oid1); + const files2 = await this.listFilesInCommit(cwd, oid2); + + const changes: Parameters[0] = []; + const allFiles = new Set([...files1, ...files2]); + + for (const filepath of allFiles) { + if (!this.matchesPaths(filepath, paths)) continue; + + const in1 = files1.has(filepath); + const in2 = files2.has(filepath); + + const oldContent = in1 ? await this.readBlobFromRef(cwd, oid1, filepath) : ''; + const newContent = in2 ? await this.readBlobFromRef(cwd, oid2, filepath) : ''; + + if (oldContent === newContent) continue; + + let changeType: ChangeType = 'modify'; + if (!in1) changeType = 'add'; + else if (!in2) changeType = 'delete'; + + changes.push({ filepath, oldContent, newContent, changeType }); + } + + return createSuccessResult(await this.emitDiff(changes, options)); + } catch (error) { + return createErrorResult(`Failed to show commit range diff: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + /** + * Recursively list all files in a commit's tree. + */ + private async listFilesInCommit(cwd: string, commitOid: string): Promise> { + const files = new Set(); + + const walkTree = async (oid: string, prefix: string): Promise => { + try { + const tree = await this.git.readTree({ dir: cwd, oid }); + for (const entry of tree.tree as TreeEntry[]) { + const path = prefix ? `${prefix}/${entry.path}` : entry.path; + if (entry.mode === '040000' || entry.type === 'tree') { + await walkTree(entry.oid, path); + } else { + files.add(path); + } + } + } catch { + // Ignore tree read errors + } + }; + + try { + // readTree with a commit oid resolves to the commit's tree + await walkTree(commitOid, ''); + } catch { + // Ignore + } + + return files; } } diff --git a/src/lib/commands/git/fetch.ts b/src/lib/commands/git/fetch.ts index 90dcfc34..9dbd33a7 100644 --- a/src/lib/commands/git/fetch.ts +++ b/src/lib/commands/git/fetch.ts @@ -26,7 +26,7 @@ export class GitFetchCommand implements GitSubcommand { return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); } - const { remote, refs } = this.parseArgs(args); + const { remote, refs, options } = this.parseArgs(args); // Get remote URL let remoteUrl: string; @@ -53,14 +53,18 @@ export class GitFetchCommand implements GitSubcommand { dir: cwd, remote: remote, ref: ref, - }); + tags: options.tags, + prune: options.prune, + } as Parameters[0]); } } else { // Fetch all refs (default behavior) await this.git.fetch({ dir: cwd, remote: remote, - }); + tags: options.tags, + prune: options.prune, + } as Parameters[0]); } // Build output message diff --git a/src/lib/commands/git/init.ts b/src/lib/commands/git/init.ts index e94b4b72..bca40f02 100644 --- a/src/lib/commands/git/init.ts +++ b/src/lib/commands/git/init.ts @@ -7,7 +7,7 @@ import type { Git } from "../../git"; export class GitInitCommand implements GitSubcommand { name = 'init'; description = 'Create an empty Git repository or reinitialize an existing one'; - usage = 'git init [--bare] []'; + usage = 'git init [--bare] [-b | --initial-branch ] []'; private git: Git; private fs: JSRuntimeFS; @@ -21,7 +21,9 @@ export class GitInitCommand implements GitSubcommand { try { // Parse arguments const { options, directory } = this.parseArgs(args); - const targetDir = directory || cwd; + const targetDir = directory + ? (directory.startsWith('/') ? directory : `${cwd}/${directory}`) + : cwd; // Check if directory exists, create if needed if (directory) { @@ -45,21 +47,25 @@ export class GitInitCommand implements GitSubcommand { await this.git.init({ dir: targetDir, bare: options.bare, - defaultBranch: 'main' + defaultBranch: options.initialBranch || 'main', }); // Set up basic configuration - await this.git.setConfig({ - dir: targetDir, - path: 'user.name', - value: 'shakespeare.diy' - }); + try { + await this.git.setConfig({ + dir: targetDir, + path: 'user.name', + value: 'shakespeare.diy', + }); - await this.git.setConfig({ - dir: targetDir, - path: 'user.email', - value: 'assistant@shakespeare.diy' - }); + await this.git.setConfig({ + dir: targetDir, + path: 'user.email', + value: 'assistant@shakespeare.diy', + }); + } catch { + // Non-fatal + } const message = options.bare ? `Initialized empty Git repository in ${targetDir}/\n` @@ -72,13 +78,25 @@ export class GitInitCommand implements GitSubcommand { } } - private parseArgs(args: string[]): { options: { bare: boolean }; directory?: string } { - const options = { bare: false }; + private parseArgs(args: string[]): { + options: { bare: boolean; initialBranch?: string }; + directory?: string; + } { + const options: { bare: boolean; initialBranch?: string } = { bare: false }; let directory: string | undefined; - for (const arg of args) { + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === '--bare') { options.bare = true; + } else if (arg === '-b' || arg === '--initial-branch') { + if (i + 1 < args.length) { + options.initialBranch = args[i + 1]; + i++; + } + } else if (arg.startsWith('--initial-branch=')) { + options.initialBranch = arg.substring(17); } else if (!arg.startsWith('-')) { directory = arg; } diff --git a/src/lib/commands/git/log.test.ts b/src/lib/commands/git/log.test.ts index 8ae74be1..f2859f89 100644 --- a/src/lib/commands/git/log.test.ts +++ b/src/lib/commands/git/log.test.ts @@ -148,7 +148,7 @@ describe('GitLogCommand', () => { expect(result.exitCode).toBe(0); expect(result.stdout).toContain('commit'); expect(result.stdout).toContain('author'); - expect(result.stdout).toMatch(/author .+ <.+> \d+ \+0000/); + expect(result.stdout).toMatch(/author .+ <.+> \d+ [+-]\d{4}/); }); it('should show graph with --graph', async () => { diff --git a/src/lib/commands/git/log.ts b/src/lib/commands/git/log.ts index bb1548f9..36d5ba8b 100644 --- a/src/lib/commands/git/log.ts +++ b/src/lib/commands/git/log.ts @@ -4,10 +4,37 @@ import { createSuccessResult, createErrorResult } from "../ShellCommand"; import type { GitSubcommand, GitSubcommandOptions } from "../git"; import type { Git } from "../../git"; +interface LogOptions { + oneline: boolean; + graph: boolean; + format?: string; + author?: string; + grep?: string; + since?: number; + until?: number; + patch: boolean; + stat: boolean; + nameOnly: boolean; + nameStatus: boolean; + follow?: string; + noMerges: boolean; + reverse: boolean; +} + +interface CommitInfo { + oid: string; + commit: { + message: string; + author: { name: string; email: string; timestamp: number; timezoneOffset?: number }; + committer?: { name: string; email: string; timestamp: number; timezoneOffset?: number }; + parent?: string[]; + }; +} + export class GitLogCommand implements GitSubcommand { name = 'log'; description = 'Show commit logs'; - usage = 'git log [--oneline] [--graph] [--format=] [-n ] [--all] []'; + usage = 'git log [--oneline] [--graph] [--stat] [-p|--patch] [--name-only] [--name-status] [--author=] [--grep=] [--since=] [--until=] [--no-merges] [--reverse] [--format=] [-n ] [--all] []'; private git: Git; private fs: JSRuntimeFS; @@ -37,16 +64,23 @@ export class GitLogCommand implements GitSubcommand { logOptions.ref = ref; } - const commits = await this.git.log(logOptions); + let commits = await this.git.log(logOptions) as CommitInfo[]; if (commits.length === 0) { return createErrorResult('fatal: your current branch does not have any commits yet'); } + // Apply filters + commits = this.filterCommits(commits, options); + + if (options.reverse) { + commits = [...commits].reverse(); + } + // Determine format based on options const format = options.format || (options.oneline ? 'oneline' : 'full'); - return this.formatLog(commits, format, options.graph, cwd); + return await this.formatLog(commits, format, options, cwd); } catch (error) { if (error instanceof Error && error.message.includes('does not exist')) { @@ -60,16 +94,38 @@ export class GitLogCommand implements GitSubcommand { } } + private filterCommits(commits: CommitInfo[], options: LogOptions): CommitInfo[] { + return commits.filter(commit => { + if (options.author) { + const authorStr = `${commit.commit.author.name} <${commit.commit.author.email}>`; + if (!authorStr.toLowerCase().includes(options.author.toLowerCase())) return false; + } + if (options.grep) { + if (!commit.commit.message.toLowerCase().includes(options.grep.toLowerCase())) return false; + } + if (options.since !== undefined && commit.commit.author.timestamp < options.since) return false; + if (options.until !== undefined && commit.commit.author.timestamp > options.until) return false; + if (options.noMerges && commit.commit.parent && commit.commit.parent.length > 1) return false; + return true; + }); + } + private parseArgs(args: string[]): { - options: { oneline: boolean; graph: boolean; format?: string }; + options: LogOptions; limit: number | undefined; ref?: string; } { - const options: { oneline: boolean; graph: boolean; format?: string } = { + const options: LogOptions = { oneline: false, - graph: false + graph: false, + patch: false, + stat: false, + nameOnly: false, + nameStatus: false, + noMerges: false, + reverse: false, }; - let limit: number | undefined = undefined; // No default limit - show all commits + let limit: number | undefined = undefined; let ref: string | undefined = undefined; for (let i = 0; i < args.length; i++) { @@ -80,24 +136,70 @@ export class GitLogCommand implements GitSubcommand { } else if (arg === '--graph') { options.graph = true; } else if (arg === '--all') { - // --all is not directly supported by isomorphic-git log - // We'll just ignore it for now + // Not directly supported by isomorphic-git + } else if (arg === '-p' || arg === '--patch') { + options.patch = true; + } else if (arg === '--stat') { + options.stat = true; + } else if (arg === '--name-only') { + options.nameOnly = true; + } else if (arg === '--name-status') { + options.nameStatus = true; + } else if (arg === '--no-merges') { + options.noMerges = true; + } else if (arg === '--reverse') { + options.reverse = true; } else if (arg === '--format' || arg === '--pretty') { if (i + 1 < args.length) { options.format = args[i + 1]; - i++; // Skip next argument + i++; } } else if (arg.startsWith('--format=')) { options.format = arg.substring(9); } else if (arg.startsWith('--pretty=')) { options.format = arg.substring(9); + } else if (arg === '--author') { + if (i + 1 < args.length) { + options.author = args[i + 1]; + i++; + } + } else if (arg.startsWith('--author=')) { + options.author = arg.substring(9); + } else if (arg === '--grep') { + if (i + 1 < args.length) { + options.grep = args[i + 1]; + i++; + } + } else if (arg.startsWith('--grep=')) { + options.grep = arg.substring(7); + } else if (arg === '--since' || arg === '--after') { + if (i + 1 < args.length) { + options.since = this.parseDate(args[i + 1]); + i++; + } + } else if (arg.startsWith('--since=') || arg.startsWith('--after=')) { + options.since = this.parseDate(arg.substring(arg.indexOf('=') + 1)); + } else if (arg === '--until' || arg === '--before') { + if (i + 1 < args.length) { + options.until = this.parseDate(args[i + 1]); + i++; + } + } else if (arg.startsWith('--until=') || arg.startsWith('--before=')) { + options.until = this.parseDate(arg.substring(arg.indexOf('=') + 1)); + } else if (arg === '--follow') { + if (i + 1 < args.length) { + options.follow = args[i + 1]; + i++; + } + } else if (arg.startsWith('--follow=')) { + options.follow = arg.substring(9); } else if (arg === '-n' || arg === '--max-count') { if (i + 1 < args.length) { const num = parseInt(args[i + 1], 10); if (!isNaN(num) && num > 0) { limit = num; } - i++; // Skip next argument + i++; } } else if (arg.startsWith('-n=')) { const num = parseInt(arg.substring(3), 10); @@ -110,13 +212,11 @@ export class GitLogCommand implements GitSubcommand { limit = num; } } else if (arg.match(/^-\d+$/)) { - // Handle -5, -10, etc. const num = parseInt(arg.substring(1), 10); if (!isNaN(num) && num > 0) { limit = num; } } else if (!arg.startsWith('-')) { - // Treat as a ref (branch name, commit hash, etc.) ref = arg; } } @@ -124,59 +224,235 @@ export class GitLogCommand implements GitSubcommand { return { options, limit, ref }; } - private formatLog( - commits: Array<{ oid: string; commit: { message: string; author: { name: string; email: string; timestamp: number }; committer?: { name: string; email: string; timestamp: number } } }>, + /** + * Parse a date string into a Unix timestamp (seconds). + * Supports absolute dates (ISO format) and relative dates ("2 weeks ago", "1 day ago"). + */ + private parseDate(str: string): number | undefined { + // Try ISO/standard date parsing first + const ts = Date.parse(str); + if (!isNaN(ts)) return Math.floor(ts / 1000); + + // Try relative dates like "2 weeks ago", "yesterday" + const now = Math.floor(Date.now() / 1000); + const lower = str.toLowerCase().trim(); + + if (lower === 'yesterday') return now - 86400; + if (lower === 'today') return now - (now % 86400); + + const relMatch = lower.match(/^(\d+)\s+(second|minute|hour|day|week|month|year)s?\s+ago$/); + if (relMatch) { + const num = parseInt(relMatch[1], 10); + const unit = relMatch[2]; + const secs: Record = { + second: 1, + minute: 60, + hour: 3600, + day: 86400, + week: 604800, + month: 2592000, + year: 31536000, + }; + return now - num * secs[unit]; + } + + return undefined; + } + + /** + * Format a Unix timestamp into a git-style date string with timezone offset. + */ + private formatGitDate(timestamp: number, tzOffset?: number): string { + const date = new Date(timestamp * 1000); + const offset = tzOffset ?? 0; + const sign = offset <= 0 ? '+' : '-'; + const absOff = Math.abs(offset); + const tzHours = Math.floor(absOff / 60).toString().padStart(2, '0'); + const tzMins = (absOff % 60).toString().padStart(2, '0'); + // Use UTC to get canonical git output + return date.toUTCString().replace('GMT', `${sign}${tzHours}${tzMins}`); + } + + /** + * Get the files changed in a commit (comparing against parent). + */ + private async getChangedFiles(commit: CommitInfo, cwd: string): Promise> { + const changes: Array<{ path: string; status: 'A' | 'M' | 'D' }> = []; + try { + const parents = commit.commit.parent || []; + if (parents.length === 0) { + // Initial commit: all files are added + const files = await this.listFilesInCommit(cwd, commit.oid); + for (const f of files) { + changes.push({ path: f, status: 'A' }); + } + } else { + const currentFiles = await this.getFileMap(cwd, commit.oid); + const parentFiles = await this.getFileMap(cwd, parents[0]); + // Find additions/modifications + for (const [path, oid] of currentFiles) { + const parentOid = parentFiles.get(path); + if (!parentOid) changes.push({ path, status: 'A' }); + else if (parentOid !== oid) changes.push({ path, status: 'M' }); + } + // Find deletions + for (const path of parentFiles.keys()) { + if (!currentFiles.has(path)) { + changes.push({ path, status: 'D' }); + } + } + } + } catch { + // Ignore + } + return changes; + } + + private async listFilesInCommit(cwd: string, commitOid: string): Promise> { + const map = await this.getFileMap(cwd, commitOid); + return new Set(map.keys()); + } + + private async getFileMap(cwd: string, commitOid: string): Promise> { + const files = new Map(); + const walk = async (oid: string, prefix: string): Promise => { + try { + const tree = await this.git.readTree({ dir: cwd, oid }); + for (const entry of tree.tree as Array<{ mode: string; path: string; oid: string; type?: string }>) { + const path = prefix ? `${prefix}/${entry.path}` : entry.path; + if (entry.mode === '040000' || entry.type === 'tree') { + await walk(entry.oid, path); + } else { + files.set(path, entry.oid); + } + } + } catch { + // Ignore + } + }; + await walk(commitOid, ''); + return files; + } + + private async formatLog( + commits: CommitInfo[], format: string, - showGraph: boolean, - _cwd: string - ): ShellCommandResult { + options: LogOptions, + cwd: string, + ): Promise { const lines: string[] = []; for (let i = 0; i < commits.length; i++) { const commit = commits[i]; const isLast = i === commits.length - 1; - const graphPrefix = showGraph ? '* ' : ''; + const graphPrefix = options.graph ? '* ' : ''; - // Format based on the specified format - switch (format) { - case 'oneline': - lines.push(this.formatOneline(commit, graphPrefix)); - break; + // Handle format: pretty format + if (format.startsWith('format:') || format.startsWith('tformat:')) { + const spec = format.substring(format.indexOf(':') + 1); + lines.push(this.formatCustom(commit, spec)); + } else { + switch (format) { + case 'oneline': + lines.push(this.formatOneline(commit, graphPrefix)); + break; - case 'short': - lines.push(this.formatShort(commit, graphPrefix)); - if (!isLast) lines.push(''); - break; + case 'short': + lines.push(this.formatShort(commit, graphPrefix)); + if (!isLast) lines.push(''); + break; - case 'medium': - case 'full': - default: - lines.push(this.formatFull(commit, graphPrefix)); - if (!isLast) lines.push(''); - break; + case 'medium': + case 'full': + default: + lines.push(this.formatFull(commit, graphPrefix)); + if (!isLast) lines.push(''); + break; - case 'fuller': - lines.push(this.formatFuller(commit, graphPrefix)); - if (!isLast) lines.push(''); - break; + case 'fuller': + lines.push(this.formatFuller(commit, graphPrefix)); + if (!isLast) lines.push(''); + break; - case 'raw': - lines.push(this.formatRaw(commit)); - if (!isLast) lines.push(''); - break; + case 'raw': + lines.push(this.formatRaw(commit)); + if (!isLast) lines.push(''); + break; + } + } + + // Include file changes if requested + if (options.stat || options.patch || options.nameOnly || options.nameStatus) { + const changes = await this.getChangedFiles(commit, cwd); + if (options.nameOnly) { + for (const c of changes) lines.push(c.path); + } else if (options.nameStatus) { + for (const c of changes) lines.push(`${c.status}\t${c.path}`); + } else if (options.stat) { + lines.push(''); + for (const c of changes) { + lines.push(` ${c.path} | ${c.status === 'A' ? '+' : c.status === 'D' ? '-' : 'M'}`); + } + lines.push(` ${changes.length} file${changes.length !== 1 ? 's' : ''} changed`); + } else if (options.patch) { + lines.push(''); + // Simple patch output: just show changed file names (full patch is expensive) + for (const c of changes) { + lines.push(`diff --git a/${c.path} b/${c.path}`); + if (c.status === 'A') { + lines.push('new file mode 100644'); + } else if (c.status === 'D') { + lines.push('deleted file mode 100644'); + } + lines.push(`--- ${c.status === 'A' ? '/dev/null' : `a/${c.path}`}`); + lines.push(`+++ ${c.status === 'D' ? '/dev/null' : `b/${c.path}`}`); + } + } + if (!isLast) lines.push(''); } } return createSuccessResult(lines.join('\n') + '\n'); } - private formatOneline(commit: { oid: string; commit: { message: string } }, graphPrefix: string): string { + private formatCustom(commit: CommitInfo, spec: string): string { + // Minimal pretty format placeholder support + const placeholders: Record = { + '%H': commit.oid, + '%h': commit.oid.substring(0, 7), + '%an': commit.commit.author.name, + '%ae': commit.commit.author.email, + '%ad': this.formatGitDate(commit.commit.author.timestamp, commit.commit.author.timezoneOffset), + '%at': String(commit.commit.author.timestamp), + '%s': commit.commit.message.split('\n')[0], + '%b': commit.commit.message.split('\n').slice(1).join('\n'), + '%B': commit.commit.message, + '%cn': commit.commit.committer?.name || commit.commit.author.name, + '%ce': commit.commit.committer?.email || commit.commit.author.email, + '%cd': this.formatGitDate(commit.commit.committer?.timestamp || commit.commit.author.timestamp, commit.commit.committer?.timezoneOffset), + '%ct': String(commit.commit.committer?.timestamp || commit.commit.author.timestamp), + '%P': (commit.commit.parent || []).join(' '), + '%p': (commit.commit.parent || []).map(p => p.substring(0, 7)).join(' '), + '%n': '\n', + '%%': '%', + }; + + let result = spec; + // Replace longer placeholders first to avoid partial replacements + const keys = Object.keys(placeholders).sort((a, b) => b.length - a.length); + for (const key of keys) { + result = result.split(key).join(placeholders[key]); + } + return result; + } + + private formatOneline(commit: CommitInfo, graphPrefix: string): string { const shortHash = commit.oid.substring(0, 7); - const message = commit.commit.message.split('\n')[0]; // First line only + const message = commit.commit.message.split('\n')[0]; return `${graphPrefix}${shortHash} ${message}`; } - private formatShort(commit: { oid: string; commit: { message: string; author: { name: string; email: string } } }, graphPrefix: string): string { + private formatShort(commit: CommitInfo, graphPrefix: string): string { const lines: string[] = []; const shortHash = commit.oid.substring(0, 7); @@ -192,73 +468,61 @@ export class GitLogCommand implements GitSubcommand { return lines.join('\n'); } - private formatFull(commit: { oid: string; commit: { message: string; author: { name: string; email: string; timestamp: number } } }, graphPrefix: string): string { + private formatFull(commit: CommitInfo, graphPrefix: string): string { const lines: string[] = []; - lines.push(`${graphPrefix}commit ${commit.oid}`); - const author = commit.commit.author; - const authorDate = new Date(author.timestamp * 1000); - const authorDateStr = authorDate.toUTCString(); - lines.push(`Author: ${author.name} <${author.email}>`); - lines.push(`Date: ${authorDateStr}`); + lines.push(`Date: ${this.formatGitDate(author.timestamp, author.timezoneOffset)}`); lines.push(''); - const messageLines = commit.commit.message.split('\n'); for (const messageLine of messageLines) { lines.push(` ${messageLine}`); } - return lines.join('\n'); } - private formatFuller(commit: { oid: string; commit: { message: string; author: { name: string; email: string; timestamp: number }; committer?: { name: string; email: string; timestamp: number } } }, graphPrefix: string): string { + private formatFuller(commit: CommitInfo, graphPrefix: string): string { const lines: string[] = []; - lines.push(`${graphPrefix}commit ${commit.oid}`); - const author = commit.commit.author; - const authorDate = new Date(author.timestamp * 1000); - lines.push(`Author: ${author.name} <${author.email}>`); - lines.push(`AuthorDate: ${authorDate.toUTCString()}`); - - // Include committer info if available + lines.push(`AuthorDate: ${this.formatGitDate(author.timestamp, author.timezoneOffset)}`); if (commit.commit.committer) { const committer = commit.commit.committer; - const commitDate = new Date(committer.timestamp * 1000); lines.push(`Commit: ${committer.name} <${committer.email}>`); - lines.push(`CommitDate: ${commitDate.toUTCString()}`); + lines.push(`CommitDate: ${this.formatGitDate(committer.timestamp, committer.timezoneOffset)}`); } - lines.push(''); - const messageLines = commit.commit.message.split('\n'); for (const messageLine of messageLines) { lines.push(` ${messageLine}`); } - return lines.join('\n'); } - private formatRaw(commit: { oid: string; commit: { message: string; author: { name: string; email: string; timestamp: number }; committer?: { name: string; email: string; timestamp: number } } }): string { + private formatRaw(commit: CommitInfo): string { const lines: string[] = []; - lines.push(`commit ${commit.oid}`); - const author = commit.commit.author; - lines.push(`author ${author.name} <${author.email}> ${author.timestamp} +0000`); - + const authorTz = this.gitTzString(author.timezoneOffset); + lines.push(`author ${author.name} <${author.email}> ${author.timestamp} ${authorTz}`); if (commit.commit.committer) { const committer = commit.commit.committer; - lines.push(`committer ${committer.name} <${committer.email}> ${committer.timestamp} +0000`); + const committerTz = this.gitTzString(committer.timezoneOffset); + lines.push(`committer ${committer.name} <${committer.email}> ${committer.timestamp} ${committerTz}`); } - lines.push(''); lines.push(commit.commit.message); - return lines.join('\n'); } -} + private gitTzString(tzOffset?: number): string { + const offset = tzOffset ?? 0; + const sign = offset <= 0 ? '+' : '-'; + const absOff = Math.abs(offset); + const h = Math.floor(absOff / 60).toString().padStart(2, '0'); + const m = (absOff % 60).toString().padStart(2, '0'); + return `${sign}${h}${m}`; + } +} diff --git a/src/lib/commands/git/ls-files.test.ts b/src/lib/commands/git/ls-files.test.ts new file mode 100644 index 00000000..b1f67f0f --- /dev/null +++ b/src/lib/commands/git/ls-files.test.ts @@ -0,0 +1,82 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { GitLsFilesCommand } from './ls-files'; +import type { Git } from '../../git'; +import type { JSRuntimeFS } from '../../JSRuntime'; + +const mockFS = { + stat: async (path: string) => { + if (path.endsWith('/.git')) { + return { isDirectory: () => true }; + } + throw new Error('File not found'); + }, +} as unknown as JSRuntimeFS; + +describe('GitLsFilesCommand', () => { + let lsFilesCommand: GitLsFilesCommand; + let mockGit: Git; + + beforeEach(() => { + mockGit = { + statusMatrix: vi.fn().mockResolvedValue([ + // [filepath, headStatus, workdirStatus, stageStatus] + ['file1.txt', 1, 1, 1], // Tracked, unchanged + ['file2.txt', 1, 1, 1], // Tracked, unchanged + ]), + resolveRef: vi.fn().mockResolvedValue('abc123'), + readBlob: vi.fn().mockResolvedValue({ oid: 'blob1', blob: new Uint8Array() }), + } as unknown as Git; + + lsFilesCommand = new GitLsFilesCommand({ git: mockGit, fs: mockFS }); + }); + + it('should list tracked files', async () => { + const result = await lsFilesCommand.execute([], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('file1.txt'); + expect(result.stdout).toContain('file2.txt'); + }); + + it('should list modified files with -m', async () => { + mockGit.statusMatrix = vi.fn().mockResolvedValue([ + ['file1.txt', 1, 2, 1], // Modified + ['file2.txt', 1, 1, 1], // Unchanged + ]); + const result = await lsFilesCommand.execute(['-m'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('file1.txt'); + expect(result.stdout).not.toContain('file2.txt'); + }); + + it('should list untracked files with -o', async () => { + mockGit.statusMatrix = vi.fn().mockResolvedValue([ + ['file1.txt', 1, 1, 1], // Tracked + ['untracked.txt', 0, 2, 0], // Untracked + ]); + const result = await lsFilesCommand.execute(['-o'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('untracked.txt'); + expect(result.stdout).not.toContain('file1.txt'); + }); + + it('should list deleted files with -d', async () => { + mockGit.statusMatrix = vi.fn().mockResolvedValue([ + ['deleted.txt', 1, 0, 1], // Deleted + ['file.txt', 1, 1, 1], // Unchanged + ]); + const result = await lsFilesCommand.execute(['-d'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('deleted.txt'); + expect(result.stdout).not.toContain('file.txt'); + }); + + it('should fail when not in a git repo', async () => { + const mockFSNoGit = { + stat: async () => { throw new Error('ENOENT'); }, + } as unknown as JSRuntimeFS; + const cmd = new GitLsFilesCommand({ git: mockGit, fs: mockFSNoGit }); + const result = await cmd.execute([], '/not-a-repo'); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('not a git repository'); + }); +}); diff --git a/src/lib/commands/git/ls-files.ts b/src/lib/commands/git/ls-files.ts new file mode 100644 index 00000000..0cb16d28 --- /dev/null +++ b/src/lib/commands/git/ls-files.ts @@ -0,0 +1,126 @@ +import type { JSRuntimeFS } from "../../JSRuntime"; +import type { ShellCommandResult } from "../ShellCommand"; +import { createSuccessResult, createErrorResult } from "../ShellCommand"; +import type { GitSubcommand, GitSubcommandOptions } from "../git"; +import type { Git } from "../../git"; + +export class GitLsFilesCommand implements GitSubcommand { + name = 'ls-files'; + description = 'Show information about files in the index and the working tree'; + usage = 'git ls-files [-m|--modified] [-o|--others] [-d|--deleted] [-s|--stage] [--] [...]'; + + private git: Git; + private fs: JSRuntimeFS; + + constructor(options: GitSubcommandOptions) { + this.git = options.git; + this.fs = options.fs; + } + + async execute(args: string[], cwd: string): Promise { + try { + try { + await this.fs.stat(`${cwd}/.git`); + } catch { + return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); + } + + const { paths, options } = this.parseArgs(args); + + const statusMatrix = await this.git.statusMatrix({ dir: cwd }); + + const matchesPaths = (filepath: string): boolean => { + if (paths.length === 0) return true; + return paths.some(p => p === '.' || filepath === p || filepath.startsWith(p + '/')); + }; + + const lines: string[] = []; + const anyFilter = options.modified || options.others || options.deleted; + + for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) { + if (!matchesPaths(filepath)) continue; + + const isTracked = headStatus === 1 || stageStatus !== 0; + const isModified = (headStatus === 1 && (workdirStatus !== 1 || stageStatus !== 1)); + const isDeleted = isTracked && workdirStatus === 0; + const isUntracked = headStatus === 0 && stageStatus === 0 && workdirStatus === 2; + + if (anyFilter) { + if (options.modified && isModified && !isDeleted) { + lines.push(filepath); + } + if (options.deleted && isDeleted) { + lines.push(filepath); + } + if (options.others && isUntracked) { + lines.push(filepath); + } + } else { + // Default: show tracked files (cached) + if (isTracked) { + if (options.stage) { + try { + const head = await this.git.resolveRef({ dir: cwd, ref: 'HEAD' }); + const blob = await this.git.readBlob({ dir: cwd, oid: head, filepath }); + lines.push(`100644 ${blob.oid} 0\t${filepath}`); + } catch { + lines.push(`100644 0000000000000000000000000000000000000000 0\t${filepath}`); + } + } else { + lines.push(filepath); + } + } + } + } + + return createSuccessResult(lines.join('\n') + (lines.length > 0 ? '\n' : '')); + } catch (error) { + return createErrorResult(`git ls-files: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private parseArgs(args: string[]): { + paths: string[]; + options: { + modified: boolean; + others: boolean; + deleted: boolean; + stage: boolean; + cached: boolean; + }; + } { + const options = { + modified: false, + others: false, + deleted: false, + stage: false, + cached: false, + }; + const paths: string[] = []; + let foundDoubleDash = false; + + for (const arg of args) { + if (arg === '--') { + foundDoubleDash = true; + continue; + } + if (foundDoubleDash) { + paths.push(arg); + } else if (arg === '-m' || arg === '--modified') { + options.modified = true; + } else if (arg === '-o' || arg === '--others') { + options.others = true; + } else if (arg === '-d' || arg === '--deleted') { + options.deleted = true; + } else if (arg === '-s' || arg === '--stage') { + options.stage = true; + } else if (arg === '-c' || arg === '--cached') { + options.cached = true; + } else if (!arg.startsWith('-')) { + paths.push(arg); + } + } + + return { paths, options }; + } +} diff --git a/src/lib/commands/git/merge.test.ts b/src/lib/commands/git/merge.test.ts new file mode 100644 index 00000000..77cd81db --- /dev/null +++ b/src/lib/commands/git/merge.test.ts @@ -0,0 +1,68 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { GitMergeCommand } from './merge'; +import type { Git } from '../../git'; +import type { JSRuntimeFS } from '../../JSRuntime'; + +const mockFS = { + stat: async (path: string) => { + if (path.endsWith('/.git')) return { isDirectory: () => true }; + throw new Error('ENOENT'); + }, +} as unknown as JSRuntimeFS; + +describe('GitMergeCommand', () => { + let mergeCommand: GitMergeCommand; + let mockGit: Git; + + beforeEach(() => { + mockGit = { + currentBranch: vi.fn().mockResolvedValue('main'), + merge: vi.fn().mockResolvedValue({ fastForward: true }), + abortMerge: vi.fn(async () => {}), + } as unknown as Git; + mergeCommand = new GitMergeCommand({ git: mockGit, fs: mockFS }); + }); + + it('should fail with no commits', async () => { + const result = await mergeCommand.execute([], '/test-repo'); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('No commit specified'); + }); + + it('should fail when not in a git repo', async () => { + const mockFSNoGit = { + stat: async () => { throw new Error('ENOENT'); }, + } as unknown as JSRuntimeFS; + const cmd = new GitMergeCommand({ git: mockGit, fs: mockFSNoGit }); + const result = await cmd.execute(['main'], '/not-a-repo'); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('not a git repository'); + }); + + it('should report already up to date when alreadyMerged', async () => { + vi.mocked(mockGit.merge).mockResolvedValue({ alreadyMerged: true } as unknown as Awaited>); + const result = await mergeCommand.execute(['other'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('Already up to date'); + }); + + it('should report fast-forward', async () => { + vi.mocked(mockGit.merge).mockResolvedValue({ fastForward: true } as unknown as Awaited>); + const result = await mergeCommand.execute(['other'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('Fast-forward'); + }); + + it('should call abortMerge with --abort', async () => { + const result = await mergeCommand.execute(['--abort'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(mockGit.abortMerge).toHaveBeenCalled(); + }); + + it('should pass --ff-only to merge', async () => { + await mergeCommand.execute(['--ff-only', 'other'], '/test-repo'); + expect(mockGit.merge).toHaveBeenCalledWith(expect.objectContaining({ + fastForwardOnly: true, + })); + }); +}); diff --git a/src/lib/commands/git/merge.ts b/src/lib/commands/git/merge.ts new file mode 100644 index 00000000..ae5626cd --- /dev/null +++ b/src/lib/commands/git/merge.ts @@ -0,0 +1,128 @@ +import type { JSRuntimeFS } from "../../JSRuntime"; +import type { ShellCommandResult } from "../ShellCommand"; +import { createSuccessResult, createErrorResult } from "../ShellCommand"; +import type { GitSubcommand, GitSubcommandOptions } from "../git"; +import type { Git } from "../../git"; + +export class GitMergeCommand implements GitSubcommand { + name = 'merge'; + description = 'Join two or more development histories together'; + usage = 'git merge [--ff | --no-ff | --ff-only] [-m ] [--abort] ...'; + + private git: Git; + private fs: JSRuntimeFS; + + constructor(options: GitSubcommandOptions) { + this.git = options.git; + this.fs = options.fs; + } + + async execute(args: string[], cwd: string): Promise { + try { + try { + await this.fs.stat(`${cwd}/.git`); + } catch { + return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); + } + + const { branches, options } = this.parseArgs(args); + + if (options.abort) { + try { + await this.git.abortMerge({ dir: cwd }); + return createSuccessResult(''); + } catch (error) { + return createErrorResult(`Failed to abort merge: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + if (branches.length === 0) { + return createErrorResult('fatal: No commit specified'); + } + + if (branches.length > 1) { + return createErrorResult('Octopus merges are not supported'); + } + + const theirs = branches[0]; + + // Get current branch + let currentBranch: string | null = null; + try { + currentBranch = await this.git.currentBranch({ dir: cwd }) || null; + } catch { + // Detached HEAD + } + + if (!currentBranch) { + return createErrorResult('fatal: Not currently on a branch.'); + } + + try { + const result = await this.git.merge({ + dir: cwd, + ours: currentBranch, + theirs, + fastForwardOnly: options.ffOnly, + message: options.message, + } as Parameters[0]); + + if ((result as { alreadyMerged?: boolean }).alreadyMerged) { + return createSuccessResult('Already up to date.\n'); + } + if ((result as { fastForward?: boolean }).fastForward) { + return createSuccessResult(`Fast-forward\n`); + } + return createSuccessResult(`Merge made by the 'recursive' strategy.\n`); + } catch (error) { + if (error instanceof Error) { + if (error.message.includes('conflict')) { + return createErrorResult('error: Merge conflict. Please resolve conflicts manually.'); + } + if (error.message.includes('fast-forward')) { + return createErrorResult('fatal: Not possible to fast-forward, aborting.'); + } + } + return createErrorResult(`Failed to merge: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } catch (error) { + return createErrorResult(`git merge: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private parseArgs(args: string[]): { + branches: string[]; + options: { ffOnly: boolean; noFf: boolean; abort: boolean; message?: string }; + } { + const options: { ffOnly: boolean; noFf: boolean; abort: boolean; message?: string } = { + ffOnly: false, + noFf: false, + abort: false, + }; + const branches: string[] = []; + + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === '--ff-only') { + options.ffOnly = true; + } else if (arg === '--no-ff') { + options.noFf = true; + } else if (arg === '--ff') { + // Default behavior + } else if (arg === '--abort') { + options.abort = true; + } else if (arg === '-m' || arg === '--message') { + if (i + 1 < args.length) { + options.message = args[i + 1]; + i++; + } + } else if (arg.startsWith('--message=')) { + options.message = arg.substring(10); + } else if (!arg.startsWith('-')) { + branches.push(arg); + } + } + + return { branches, options }; + } +} diff --git a/src/lib/commands/git/mv.test.ts b/src/lib/commands/git/mv.test.ts new file mode 100644 index 00000000..14defd7a --- /dev/null +++ b/src/lib/commands/git/mv.test.ts @@ -0,0 +1,91 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { GitMvCommand } from './mv'; +import type { Git } from '../../git'; +import type { JSRuntimeFS } from '../../JSRuntime'; + +const createMockFS = () => { + const files = new Map(); + const dirs = new Set(['/test-repo', '/test-repo/dir']); + files.set('/test-repo/file1.txt', 'contents'); + + return { + stat: vi.fn(async (path: string) => { + if (path.endsWith('/.git') || dirs.has(path)) { + return { isDirectory: () => true, isFile: () => false }; + } + if (files.has(path)) { + return { isDirectory: () => false, isFile: () => true }; + } + throw new Error('ENOENT'); + }), + rename: vi.fn(async (src: string, dst: string) => { + const content = files.get(src); + if (content === undefined) throw new Error('ENOENT'); + files.delete(src); + files.set(dst, content); + }), + mkdir: vi.fn(async (path: string) => { dirs.add(path); }), + readFile: vi.fn(async (path: string) => files.get(path) || ''), + _files: files, + } as unknown as JSRuntimeFS & { _files: Map }; +}; + +describe('GitMvCommand', () => { + let mvCommand: GitMvCommand; + let mockGit: Git; + let mockFS: JSRuntimeFS & { _files: Map }; + + beforeEach(() => { + mockFS = createMockFS() as JSRuntimeFS & { _files: Map }; + mockGit = { + remove: vi.fn(async () => {}), + add: vi.fn(async () => {}), + } as unknown as Git; + mvCommand = new GitMvCommand({ git: mockGit, fs: mockFS }); + }); + + it('should fail without arguments', async () => { + const result = await mvCommand.execute([], '/test-repo'); + expect(result.exitCode).toBe(1); + }); + + it('should rename a file', async () => { + const result = await mvCommand.execute(['file1.txt', 'file2.txt'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(mockFS.rename).toHaveBeenCalledWith('/test-repo/file1.txt', '/test-repo/file2.txt'); + expect(mockGit.remove).toHaveBeenCalledWith({ dir: '/test-repo', filepath: 'file1.txt' }); + expect(mockGit.add).toHaveBeenCalledWith({ dir: '/test-repo', filepath: 'file2.txt' }); + }); + + it('should fail when source does not exist', async () => { + const result = await mvCommand.execute(['nonexistent.txt', 'new.txt'], '/test-repo'); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('bad source'); + }); + + it('should fail when destination exists without --force', async () => { + mockFS._files.set('/test-repo/file2.txt', 'existing'); + const result = await mvCommand.execute(['file1.txt', 'file2.txt'], '/test-repo'); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('destination exists'); + }); + + it('should overwrite with --force', async () => { + mockFS._files.set('/test-repo/file2.txt', 'existing'); + const result = await mvCommand.execute(['-f', 'file1.txt', 'file2.txt'], '/test-repo'); + expect(result.exitCode).toBe(0); + }); + + it('should support --dry-run', async () => { + const result = await mvCommand.execute(['-n', 'file1.txt', 'file2.txt'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('Renaming'); + expect(mockFS.rename).not.toHaveBeenCalled(); + }); + + it('should move a file into a directory', async () => { + const result = await mvCommand.execute(['file1.txt', 'dir'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(mockFS.rename).toHaveBeenCalledWith('/test-repo/file1.txt', '/test-repo/dir/file1.txt'); + }); +}); diff --git a/src/lib/commands/git/mv.ts b/src/lib/commands/git/mv.ts new file mode 100644 index 00000000..41978b24 --- /dev/null +++ b/src/lib/commands/git/mv.ts @@ -0,0 +1,168 @@ +import { join, dirname, isAbsolute, relative } from "path-browserify"; +import type { JSRuntimeFS } from "../../JSRuntime"; +import type { ShellCommandResult } from "../ShellCommand"; +import { createSuccessResult, createErrorResult } from "../ShellCommand"; +import type { GitSubcommand, GitSubcommandOptions } from "../git"; +import type { Git } from "../../git"; + +export class GitMvCommand implements GitSubcommand { + name = 'mv'; + description = 'Move or rename a file, a directory, or a symlink'; + usage = 'git mv [-f | --force] [-k] [-n | --dry-run] [-v | --verbose] ... '; + + private git: Git; + private fs: JSRuntimeFS; + + constructor(options: GitSubcommandOptions) { + this.git = options.git; + this.fs = options.fs; + } + + async execute(args: string[], cwd: string): Promise { + try { + try { + await this.fs.stat(`${cwd}/.git`); + } catch { + return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); + } + + const { sources, destination, options } = this.parseArgs(args); + + if (sources.length === 0 || !destination) { + return createErrorResult('usage: git mv [-f] [-n] ... '); + } + + const normDest = this.normalizePath(destination, cwd); + if (normDest === null) { + return createErrorResult(`fatal: ${destination}: destination is outside repository`); + } + const destAbs = join(cwd, normDest); + + // Check if destination is a directory + let destIsDir = false; + try { + const stats = await this.fs.stat(destAbs); + destIsDir = stats.isDirectory(); + } catch { + // Doesn't exist + } + + if (sources.length > 1 && !destIsDir) { + return createErrorResult(`fatal: destination '${destination}' is not a directory`); + } + + const moves: string[] = []; + + for (const source of sources) { + const normSrc = this.normalizePath(source, cwd); + if (normSrc === null) { + return createErrorResult(`fatal: ${source}: source is outside repository`); + } + const srcAbs = join(cwd, normSrc); + + // Source must exist + try { + await this.fs.stat(srcAbs); + } catch { + return createErrorResult(`fatal: bad source, source=${source}, destination=${destination}`); + } + + // Determine final destination for this source + let finalDest: string; + let finalDestAbs: string; + if (destIsDir) { + const basename = normSrc.split('/').pop()!; + finalDest = join(normDest, basename); + finalDestAbs = join(cwd, finalDest); + } else { + finalDest = normDest; + finalDestAbs = destAbs; + } + + // Check destination existence (unless --force) + if (!options.force) { + try { + await this.fs.stat(finalDestAbs); + return createErrorResult(`fatal: destination exists, source=${source}, destination=${finalDest}`); + } catch { + // OK + } + } + + if (!options.dryRun) { + // Ensure destination directory exists + const destDir = dirname(finalDestAbs); + try { + await this.fs.mkdir(destDir, { recursive: true }); + } catch { + // Probably already exists + } + + // Move file on disk + await this.fs.rename(srcAbs, finalDestAbs); + + // Update git index + try { + await this.git.remove({ dir: cwd, filepath: normSrc }); + } catch { + // Might not have been tracked + } + try { + await this.git.add({ dir: cwd, filepath: finalDest }); + } catch { + // Continue + } + } + + moves.push(`Renaming ${normSrc} to ${finalDest}`); + } + + if (options.verbose || options.dryRun) { + return createSuccessResult(moves.join('\n') + '\n'); + } + return createSuccessResult(''); + } catch (error) { + return createErrorResult(`git mv: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private normalizePath(path: string, cwd: string): string | null { + if (isAbsolute(path)) { + if (!path.startsWith(cwd)) return null; + const rel = relative(cwd, path); + return rel || '.'; + } + return path; + } + + private parseArgs(args: string[]): { + sources: string[]; + destination?: string; + options: { force: boolean; dryRun: boolean; verbose: boolean; keep: boolean }; + } { + const options = { force: false, dryRun: false, verbose: false, keep: false }; + const positionals: string[] = []; + + for (const arg of args) { + if (arg === '-f' || arg === '--force') { + options.force = true; + } else if (arg === '-n' || arg === '--dry-run') { + options.dryRun = true; + } else if (arg === '-v' || arg === '--verbose') { + options.verbose = true; + } else if (arg === '-k') { + options.keep = true; + } else if (!arg.startsWith('-')) { + positionals.push(arg); + } + } + + if (positionals.length < 2) { + return { sources: positionals, destination: undefined, options }; + } + + const destination = positionals[positionals.length - 1]; + const sources = positionals.slice(0, -1); + return { sources, destination, options }; + } +} diff --git a/src/lib/commands/git/pull.test.ts b/src/lib/commands/git/pull.test.ts index ba60ccc8..814959e5 100644 --- a/src/lib/commands/git/pull.test.ts +++ b/src/lib/commands/git/pull.test.ts @@ -82,14 +82,14 @@ describe('GitPullCommand', () => { }); describe('execute', () => { - it('should list modified files when there are uncommitted changes', async () => { + it('should list modified files when there are uncommitted changes (but allow untracked)', async () => { // Mock statusMatrix to return some modified files const mockGitWithChanges = { ...mockGit, statusMatrix: async () => [ ['src/index.ts', 1, 2, 1], // Modified file ['README.md', 1, 2, 2], // Modified and staged - ['package.json', 0, 2, 0], // Untracked file + ['package.json', 0, 2, 0], // Untracked file (should NOT block pull) ], } as unknown as Git; @@ -114,7 +114,8 @@ describe('GitPullCommand', () => { expect(result.stderr).toContain('error: Your local changes to the following files would be overwritten by merge:'); expect(result.stderr).toContain('\tsrc/index.ts'); expect(result.stderr).toContain('\tREADME.md'); - expect(result.stderr).toContain('\tpackage.json'); + // Untracked file should not be listed + expect(result.stderr).not.toContain('\tpackage.json'); expect(result.stderr).toContain('Please commit your changes or stash them before you merge.'); }); }); diff --git a/src/lib/commands/git/pull.ts b/src/lib/commands/git/pull.ts index 1b8480d1..af3f9a0c 100644 --- a/src/lib/commands/git/pull.ts +++ b/src/lib/commands/git/pull.ts @@ -60,14 +60,17 @@ export class GitPullCommand implements GitSubcommand { return createErrorResult(`fatal: '${remote}' does not appear to be a git repository`); } - // Check for uncommitted changes + // Check for uncommitted changes (modified or staged). + // Untracked files are allowed (real git only blocks if they'd be overwritten). const statusMatrix = await this.git.statusMatrix({ dir: cwd, }); const modifiedFiles = statusMatrix .filter(([, headStatus, workdirStatus, stageStatus]) => { - // Check for any uncommitted changes (modified, staged, or untracked) + // Skip untracked files (not in HEAD, not in stage) + if (headStatus === 0 && stageStatus === 0) return false; + // Report if stage or workdir differs from HEAD return headStatus !== workdirStatus || headStatus !== stageStatus; }) .map(([filepath]) => filepath); diff --git a/src/lib/commands/git/push.ts b/src/lib/commands/git/push.ts index 5376c95b..ceebac5a 100644 --- a/src/lib/commands/git/push.ts +++ b/src/lib/commands/git/push.ts @@ -4,10 +4,19 @@ import { createSuccessResult, createErrorResult } from "../ShellCommand"; import type { GitSubcommand, GitSubcommandOptions } from "../git"; import type { Git } from "../../git"; +interface PushOptions { + force: boolean; + setUpstream: boolean; + tags: boolean; + deleteRef: boolean; + dryRun: boolean; + all: boolean; +} + export class GitPushCommand implements GitSubcommand { name = 'push'; description = 'Update remote refs along with associated objects'; - usage = 'git push [] []'; + usage = 'git push [-u | --set-upstream] [-f | --force] [--tags] [--delete] [--dry-run] [--all] [] []'; private git: Git; private fs: JSRuntimeFS; @@ -26,18 +35,35 @@ export class GitPushCommand implements GitSubcommand { return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); } - const { remote, branch, options } = this.parseArgs(args); + const { remote, refspec, options } = this.parseArgs(args); - // Get current branch if not specified - let targetBranch = branch; - if (!targetBranch) { + // Parse refspec (local:remote or just local, or HEAD) + let localRef: string | undefined; + let remoteRef: string | undefined; + if (refspec) { + if (refspec.includes(':')) { + const [l, r] = refspec.split(':'); + localRef = l || undefined; + remoteRef = r || undefined; + } else { + localRef = refspec; + remoteRef = refspec; + } + } + + // Resolve HEAD to current branch if localRef is HEAD or not specified + if (!localRef || localRef === 'HEAD') { try { - targetBranch = await this.git.currentBranch({ - dir: cwd, - }) || undefined; - if (!targetBranch) { + const currentBranch = await this.git.currentBranch({ dir: cwd }); + if (!currentBranch) { return createErrorResult('fatal: You are not currently on a branch.'); } + if (!localRef) { + localRef = currentBranch; + } + if (!remoteRef) { + remoteRef = currentBranch; + } } catch { return createErrorResult('fatal: You are not currently on a branch.'); } @@ -46,10 +72,7 @@ export class GitPushCommand implements GitSubcommand { // Get remote URL let remoteUrl: string; try { - const remotes = await this.git.listRemotes({ - dir: cwd, - }); - + const remotes = await this.git.listRemotes({ dir: cwd }); const targetRemote = remotes.find(r => r.remote === remote); if (!targetRemote) { return createErrorResult(`fatal: '${remote}' does not appear to be a git repository`); @@ -59,16 +82,42 @@ export class GitPushCommand implements GitSubcommand { return createErrorResult(`fatal: '${remote}' does not appear to be a git repository`); } + if (options.dryRun) { + return createSuccessResult(`Would push to ${remoteUrl}\n ${localRef} -> ${remoteRef}\n`); + } + try { await this.git.push({ dir: cwd, remote: remote, - ref: targetBranch, - remoteRef: targetBranch, + ref: options.deleteRef ? undefined : localRef, + remoteRef: remoteRef, force: options.force, - }); + delete: options.deleteRef, + } as Parameters[0]); - return createSuccessResult(`To ${remoteUrl}\n ${targetBranch} -> ${targetBranch}\n`); + // Set up upstream tracking if requested + if (options.setUpstream && localRef) { + try { + await this.git.setConfig({ + dir: cwd, + path: `branch.${localRef}.remote`, + value: remote, + }); + await this.git.setConfig({ + dir: cwd, + path: `branch.${localRef}.merge`, + value: `refs/heads/${remoteRef}`, + }); + } catch { + // Non-fatal + } + } + + if (options.deleteRef) { + return createSuccessResult(`To ${remoteUrl}\n - [deleted] ${remoteRef}\n`); + } + return createSuccessResult(`To ${remoteUrl}\n ${localRef} -> ${remoteRef}\n`); } catch (error) { if (error instanceof Error) { @@ -95,35 +144,48 @@ export class GitPushCommand implements GitSubcommand { private parseArgs(args: string[]): { remote: string; - branch?: string; - options: { force: boolean; setUpstream: boolean } + refspec?: string; + options: PushOptions; } { - const options = { force: false, setUpstream: false }; - let remote = 'origin'; // Default remote - let branch: string | undefined; + const options: PushOptions = { + force: false, + setUpstream: false, + tags: false, + deleteRef: false, + dryRun: false, + all: false, + }; + let remote = 'origin'; + let refspec: string | undefined; const positionalArgs: string[] = []; - // First, collect all non-option arguments for (let i = 0; i < args.length; i++) { const arg = args[i]; - if (arg === '--force' || arg === '-f') { + if (arg === '--force' || arg === '-f' || arg === '--force-with-lease') { options.force = true; } else if (arg === '--set-upstream' || arg === '-u') { options.setUpstream = true; + } else if (arg === '--tags') { + options.tags = true; + } else if (arg === '--delete' || arg === '-d') { + options.deleteRef = true; + } else if (arg === '--dry-run' || arg === '-n') { + options.dryRun = true; + } else if (arg === '--all') { + options.all = true; } else if (!arg.startsWith('-')) { positionalArgs.push(arg); } } - // Parse positional arguments: [remote] [branch] if (positionalArgs.length >= 1) { remote = positionalArgs[0]; } if (positionalArgs.length >= 2) { - branch = positionalArgs[1]; + refspec = positionalArgs[1]; } - return { remote, branch, options }; + return { remote, refspec, options }; } } diff --git a/src/lib/commands/git/remote.ts b/src/lib/commands/git/remote.ts index 414d58ad..8a04f403 100644 --- a/src/lib/commands/git/remote.ts +++ b/src/lib/commands/git/remote.ts @@ -1,14 +1,15 @@ - import type { JSRuntimeFS } from "../../JSRuntime"; import type { ShellCommandResult } from "../ShellCommand"; import { createSuccessResult, createErrorResult } from "../ShellCommand"; import type { GitSubcommand, GitSubcommandOptions } from "../git"; import type { Git } from "../../git"; +type RemoteAction = 'list' | 'add' | 'remove' | 'set-url' | 'get-url' | 'rename' | 'show'; + export class GitRemoteCommand implements GitSubcommand { name = 'remote'; description = 'Manage set of tracked repositories'; - usage = 'git remote [-v] | git remote add | git remote remove '; + usage = 'git remote [-v] | git remote add | git remote remove | git remote set-url | git remote get-url | git remote rename | git remote show '; private git: Git; private fs: JSRuntimeFS; @@ -27,7 +28,7 @@ export class GitRemoteCommand implements GitSubcommand { return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); } - const { action, name, url, options } = this.parseArgs(args); + const { action, name, url, newName, options } = this.parseArgs(args); switch (action) { case 'list': @@ -36,6 +37,14 @@ export class GitRemoteCommand implements GitSubcommand { return await this.addRemote(name!, url!, cwd); case 'remove': return await this.removeRemote(name!, cwd); + case 'set-url': + return await this.setRemoteUrl(name!, url!, cwd); + case 'get-url': + return await this.getRemoteUrl(name!, cwd); + case 'rename': + return await this.renameRemote(name!, newName!, cwd); + case 'show': + return await this.showRemote(name!, cwd); default: return await this.listRemotes(options.verbose, cwd); } @@ -46,15 +55,17 @@ export class GitRemoteCommand implements GitSubcommand { } private parseArgs(args: string[]): { - action: 'list' | 'add' | 'remove'; + action: RemoteAction; name?: string; url?: string; - options: { verbose: boolean } + newName?: string; + options: { verbose: boolean }; } { const options = { verbose: false }; - let action: 'list' | 'add' | 'remove' = 'list'; + let action: RemoteAction = 'list'; let name: string | undefined; let url: string | undefined; + let newName: string | undefined; for (let i = 0; i < args.length; i++) { const arg = args[i]; @@ -63,31 +74,34 @@ export class GitRemoteCommand implements GitSubcommand { options.verbose = true; } else if (arg === 'add') { action = 'add'; - if (i + 1 < args.length) { - name = args[i + 1]; - i++; - } - if (i + 1 < args.length) { - url = args[i + 1]; - i++; - } + if (i + 1 < args.length) { name = args[i + 1]; i++; } + if (i + 1 < args.length) { url = args[i + 1]; i++; } } else if (arg === 'remove' || arg === 'rm') { action = 'remove'; - if (i + 1 < args.length) { - name = args[i + 1]; - i++; - } + if (i + 1 < args.length) { name = args[i + 1]; i++; } + } else if (arg === 'set-url') { + action = 'set-url'; + if (i + 1 < args.length) { name = args[i + 1]; i++; } + if (i + 1 < args.length) { url = args[i + 1]; i++; } + } else if (arg === 'get-url') { + action = 'get-url'; + if (i + 1 < args.length) { name = args[i + 1]; i++; } + } else if (arg === 'rename') { + action = 'rename'; + if (i + 1 < args.length) { name = args[i + 1]; i++; } + if (i + 1 < args.length) { newName = args[i + 1]; i++; } + } else if (arg === 'show') { + action = 'show'; + if (i + 1 < args.length) { name = args[i + 1]; i++; } } } - return { action, name, url, options }; + return { action, name, url, newName, options }; } - private async listRemotes(verbose: boolean, cwd: string): Promise { + private async listRemotes(verbose: boolean, cwd: string): Promise { try { - const remotes = await this.git.listRemotes({ - dir: cwd, - }); + const remotes = await this.git.listRemotes({ dir: cwd }); if (remotes.length === 0) { return createSuccessResult(''); @@ -113,33 +127,22 @@ export class GitRemoteCommand implements GitSubcommand { } } - private async addRemote(name: string, url: string, cwd: string): Promise { + private async addRemote(name: string, url: string, cwd: string): Promise { try { if (!name || !url) { return createErrorResult('usage: git remote add '); } - // Check if remote already exists try { - const remotes = await this.git.listRemotes({ - - dir: cwd, - }); - - const existingRemote = remotes.find(r => r.remote === name); - if (existingRemote) { + const remotes = await this.git.listRemotes({ dir: cwd }); + if (remotes.find(r => r.remote === name)) { return createErrorResult(`fatal: remote ${name} already exists.`); } } catch { - // Continue if we can't list remotes + // Continue } - // Add the remote - await this.git.addRemote({ - dir: cwd, - remote: name, - url: url, - }); + await this.git.addRemote({ dir: cwd, remote: name, url }); return createSuccessResult(''); @@ -148,32 +151,22 @@ export class GitRemoteCommand implements GitSubcommand { } } - private async removeRemote(name: string, cwd: string): Promise { + private async removeRemote(name: string, cwd: string): Promise { try { if (!name) { return createErrorResult('usage: git remote remove '); } - // Check if remote exists try { - const remotes = await this.git.listRemotes({ - - dir: cwd, - }); - - const existingRemote = remotes.find(r => r.remote === name); - if (!existingRemote) { + const remotes = await this.git.listRemotes({ dir: cwd }); + if (!remotes.find(r => r.remote === name)) { return createErrorResult(`fatal: No such remote: ${name}`); } } catch { return createErrorResult(`fatal: No such remote: ${name}`); } - // Remove the remote - await this.git.deleteRemote({ - dir: cwd, - remote: name, - }); + await this.git.deleteRemote({ dir: cwd, remote: name }); return createSuccessResult(''); @@ -181,4 +174,95 @@ export class GitRemoteCommand implements GitSubcommand { return createErrorResult(`Failed to remove remote: ${error instanceof Error ? error.message : 'Unknown error'}`); } } + + private async setRemoteUrl(name: string, url: string, cwd: string): Promise { + try { + if (!name || !url) { + return createErrorResult('usage: git remote set-url '); + } + + try { + const remotes = await this.git.listRemotes({ dir: cwd }); + if (!remotes.find(r => r.remote === name)) { + return createErrorResult(`fatal: No such remote '${name}'`); + } + } catch { + return createErrorResult(`fatal: No such remote '${name}'`); + } + + // setRemoteURL is implemented in the Git wrapper + await this.git.setRemoteURL({ dir: cwd, remote: name, url }); + + return createSuccessResult(''); + + } catch (error) { + return createErrorResult(`Failed to set remote URL: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private async getRemoteUrl(name: string, cwd: string): Promise { + try { + if (!name) { + return createErrorResult('usage: git remote get-url '); + } + + const url = await this.git.getRemoteURL(cwd, name); + if (!url) { + return createErrorResult(`fatal: No such remote '${name}'`); + } + + return createSuccessResult(url + '\n'); + + } catch (error) { + return createErrorResult(`Failed to get remote URL: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private async renameRemote(oldName: string, newName: string, cwd: string): Promise { + try { + if (!oldName || !newName) { + return createErrorResult('usage: git remote rename '); + } + + const remotes = await this.git.listRemotes({ dir: cwd }); + const oldRemote = remotes.find(r => r.remote === oldName); + if (!oldRemote) { + return createErrorResult(`fatal: No such remote '${oldName}'`); + } + if (remotes.find(r => r.remote === newName)) { + return createErrorResult(`fatal: remote ${newName} already exists.`); + } + + // isomorphic-git has no rename: delete + re-add + await this.git.deleteRemote({ dir: cwd, remote: oldName }); + await this.git.addRemote({ dir: cwd, remote: newName, url: oldRemote.url }); + + return createSuccessResult(''); + } catch (error) { + return createErrorResult(`Failed to rename remote: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private async showRemote(name: string, cwd: string): Promise { + try { + if (!name) { + return createErrorResult('usage: git remote show '); + } + + const remotes = await this.git.listRemotes({ dir: cwd }); + const remote = remotes.find(r => r.remote === name); + if (!remote) { + return createErrorResult(`fatal: No such remote '${name}'`); + } + + const lines: string[] = []; + lines.push(`* remote ${name}`); + lines.push(` Fetch URL: ${remote.url}`); + lines.push(` Push URL: ${remote.url}`); + + return createSuccessResult(lines.join('\n') + '\n'); + } catch (error) { + return createErrorResult(`Failed to show remote: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } } diff --git a/src/lib/commands/git/reset.test.ts b/src/lib/commands/git/reset.test.ts index 34d0ca31..1935d5ff 100644 --- a/src/lib/commands/git/reset.test.ts +++ b/src/lib/commands/git/reset.test.ts @@ -73,8 +73,12 @@ describe('GitResetCommand', () => { isFileReset: boolean; }; - it('should parse no arguments as file reset', () => { - const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs([]); + const callParseArgs = (args: string[]): Promise => { + return (command as unknown as { parseArgs: (args: string[], cwd: string) => Promise }).parseArgs(args, '/test/repo'); + }; + + it('should parse no arguments as file reset', async () => { + const result = await callParseArgs([]); expect(result).toEqual({ mode: 'mixed', target: 'HEAD', @@ -83,8 +87,8 @@ describe('GitResetCommand', () => { }); }); - it('should parse HEAD as file reset', () => { - const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['HEAD']); + it('should parse HEAD as file reset', async () => { + const result = await callParseArgs(['HEAD']); expect(result).toEqual({ mode: 'mixed', target: 'HEAD', @@ -93,8 +97,8 @@ describe('GitResetCommand', () => { }); }); - it('should parse HEAD with files as file reset', () => { - const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['HEAD', 'file1.txt', 'file2.txt']); + it('should parse HEAD with files as file reset', async () => { + const result = await callParseArgs(['HEAD', 'file1.txt', 'file2.txt']); expect(result).toEqual({ mode: 'mixed', target: 'HEAD', @@ -103,8 +107,8 @@ describe('GitResetCommand', () => { }); }); - it('should parse commit hash as commit reset', () => { - const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['abc123def']); + it('should parse commit hash as commit reset', async () => { + const result = await callParseArgs(['abc123def']); expect(result).toEqual({ mode: 'mixed', target: 'abc123def', @@ -113,8 +117,8 @@ describe('GitResetCommand', () => { }); }); - it('should parse mode flags correctly', () => { - const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['--hard', 'HEAD~1']); + it('should parse mode flags correctly', async () => { + const result = await callParseArgs(['--hard', 'HEAD~1']); expect(result).toEqual({ mode: 'hard', target: 'HEAD~1', @@ -123,8 +127,8 @@ describe('GitResetCommand', () => { }); }); - it('should parse mixed mode with commit', () => { - const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['--mixed', 'HEAD~1']); + it('should parse mixed mode with commit', async () => { + const result = await callParseArgs(['--mixed', 'HEAD~1']); expect(result).toEqual({ mode: 'mixed', target: 'HEAD~1', @@ -233,11 +237,11 @@ describe('GitResetCommand', () => { expect(result.stdout).toContain('HEAD is now at def456a'); }); - it('should return error for soft reset (not implemented)', async () => { + it('should handle commit reset with soft mode', async () => { const result = await command.execute(['--soft', 'HEAD~1'], '/test/repo'); - expect(result.exitCode).toBe(1); - expect(result.stderr).toContain('--soft reset is not implemented'); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('HEAD is now at def456a'); }); it('should handle invalid commit reference', async () => { diff --git a/src/lib/commands/git/reset.ts b/src/lib/commands/git/reset.ts index c75d87d9..40def642 100644 --- a/src/lib/commands/git/reset.ts +++ b/src/lib/commands/git/reset.ts @@ -27,7 +27,7 @@ export class GitResetCommand implements GitSubcommand { return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); } - const { mode, target, files, isFileReset } = this.parseArgs(args); + const { mode, target, files, isFileReset } = await this.parseArgs(args, cwd); if (isFileReset) { // Reset specific files or all files (unstage) @@ -42,18 +42,20 @@ export class GitResetCommand implements GitSubcommand { } } - private parseArgs(args: string[]): { + private async parseArgs(args: string[], cwd: string): Promise<{ mode: 'soft' | 'mixed' | 'hard'; target: string; files: string[]; isFileReset: boolean; - } { + }> { let mode: 'soft' | 'mixed' | 'hard' = 'mixed'; // Default mode let target = 'HEAD'; // Default target const files: string[] = []; let foundTarget = false; let hasMode = false; + // First pass: identify mode flags + const nonFlagArgs: string[] = []; for (const arg of args) { if (arg === '--soft') { mode = 'soft'; @@ -65,12 +67,17 @@ export class GitResetCommand implements GitSubcommand { mode = 'hard'; hasMode = true; } else if (!arg.startsWith('-')) { - if (!foundTarget && (arg === 'HEAD' || arg.match(/^[a-f0-9]{7,40}$/) || arg.match(/^HEAD[~^]\d*$/))) { - target = arg; - foundTarget = true; - } else { - files.push(arg); - } + nonFlagArgs.push(arg); + } + } + + // Second pass: first non-flag arg may be a ref. Check if it resolves. + for (const arg of nonFlagArgs) { + if (!foundTarget && await this.isLikelyRef(arg, cwd)) { + target = arg; + foundTarget = true; + } else { + files.push(arg); } } @@ -82,11 +89,30 @@ export class GitResetCommand implements GitSubcommand { // git reset --mode = reset to commit with mode const isFileReset = (args.length === 0) || (target === 'HEAD' && !hasMode && files.length === 0) || - (files.length > 0); + (target === 'HEAD' && !hasMode && files.length > 0) || + (!foundTarget && files.length > 0); return { mode, target, files, isFileReset }; } + /** + * Check if a string looks like (and resolves as) a git ref. + */ + private async isLikelyRef(arg: string, cwd: string): Promise { + // Common ref patterns + if (arg === 'HEAD') return true; + if (/^HEAD[~^]\d*$/.test(arg)) return true; + if (/^[a-f0-9]{7,40}$/.test(arg)) return true; + + // Try to resolve as a ref + try { + await this.git.resolveRef({ dir: cwd, ref: arg }); + return true; + } catch { + return false; + } + } + private async resetFiles(files: string[], cwd: string): Promise { try { const resetFiles: string[] = []; @@ -190,8 +216,38 @@ export class GitResetCommand implements GitSubcommand { switch (mode) { case 'soft': // Move HEAD only (keep staging area and working directory) - // This is complex to implement with isomorphic-git - return createErrorResult('--soft reset is not implemented in this git command'); + try { + let currentBranch: string | null = null; + try { + currentBranch = await this.git.currentBranch({ + dir: cwd, + }) || null; + } catch { + // Detached HEAD state + } + + if (currentOid !== targetOid) { + if (currentBranch) { + await this.git.writeRef({ + dir: cwd, + ref: `refs/heads/${currentBranch}`, + value: targetOid, + force: true, + }); + } else { + await this.git.writeRef({ + dir: cwd, + ref: 'HEAD', + value: targetOid, + force: true, + }); + } + } + + return createSuccessResult(`HEAD is now at ${targetOid.substring(0, 7)}\n`); + } catch (error) { + return createErrorResult(`Failed to soft reset: ${error instanceof Error ? error.message : 'Unknown error'}`); + } case 'mixed': // Move HEAD and reset staging area (default) diff --git a/src/lib/commands/git/restore.test.ts b/src/lib/commands/git/restore.test.ts new file mode 100644 index 00000000..e115568b --- /dev/null +++ b/src/lib/commands/git/restore.test.ts @@ -0,0 +1,73 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { GitRestoreCommand } from './restore'; +import type { Git } from '../../git'; +import type { JSRuntimeFS } from '../../JSRuntime'; + +const mockFS = { + stat: async (path: string) => { + if (path.endsWith('/.git')) return { isDirectory: () => true }; + throw new Error('ENOENT'); + }, +} as unknown as JSRuntimeFS; + +describe('GitRestoreCommand', () => { + let restoreCommand: GitRestoreCommand; + let mockGit: Git; + + beforeEach(() => { + mockGit = { + checkout: vi.fn(async () => {}), + resetIndex: vi.fn(async () => {}), + } as unknown as Git; + restoreCommand = new GitRestoreCommand({ git: mockGit, fs: mockFS }); + }); + + it('should fail without path arguments', async () => { + const result = await restoreCommand.execute([], '/test-repo'); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('specify path'); + }); + + it('should fail when not in a git repo', async () => { + const mockFSNoGit = { + stat: async () => { throw new Error('ENOENT'); }, + } as unknown as JSRuntimeFS; + const cmd = new GitRestoreCommand({ git: mockGit, fs: mockFSNoGit }); + const result = await cmd.execute(['foo.txt'], '/not-a-repo'); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('not a git repository'); + }); + + it('should restore a file from HEAD by default', async () => { + const result = await restoreCommand.execute(['file1.txt'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(mockGit.checkout).toHaveBeenCalledWith(expect.objectContaining({ + dir: '/test-repo', + ref: 'HEAD', + filepaths: ['file1.txt'], + force: true, + })); + }); + + it('should unstage with --staged', async () => { + const result = await restoreCommand.execute(['--staged', 'file1.txt'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(mockGit.resetIndex).toHaveBeenCalledWith({ dir: '/test-repo', filepath: 'file1.txt' }); + expect(mockGit.checkout).not.toHaveBeenCalled(); + }); + + it('should restore both index and worktree with --staged --worktree', async () => { + const result = await restoreCommand.execute(['--staged', '--worktree', 'file1.txt'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(mockGit.resetIndex).toHaveBeenCalled(); + expect(mockGit.checkout).toHaveBeenCalled(); + }); + + it('should accept --source', async () => { + const result = await restoreCommand.execute(['--source=HEAD~1', 'file1.txt'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(mockGit.checkout).toHaveBeenCalledWith(expect.objectContaining({ + ref: 'HEAD~1', + })); + }); +}); diff --git a/src/lib/commands/git/restore.ts b/src/lib/commands/git/restore.ts new file mode 100644 index 00000000..6c94bf42 --- /dev/null +++ b/src/lib/commands/git/restore.ts @@ -0,0 +1,111 @@ +import type { JSRuntimeFS } from "../../JSRuntime"; +import type { ShellCommandResult } from "../ShellCommand"; +import { createSuccessResult, createErrorResult } from "../ShellCommand"; +import type { GitSubcommand, GitSubcommandOptions } from "../git"; +import type { Git } from "../../git"; + +export class GitRestoreCommand implements GitSubcommand { + name = 'restore'; + description = 'Restore working tree files'; + usage = 'git restore [--source=] [--staged] [--worktree] [...]'; + + private git: Git; + private fs: JSRuntimeFS; + + constructor(options: GitSubcommandOptions) { + this.git = options.git; + this.fs = options.fs; + } + + async execute(args: string[], cwd: string): Promise { + try { + try { + await this.fs.stat(`${cwd}/.git`); + } catch { + return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); + } + + const { paths, options } = this.parseArgs(args); + + if (paths.length === 0) { + return createErrorResult('fatal: you must specify path(s) to restore'); + } + + // Default behavior: restore working tree from index + // With --staged: restore index from HEAD (or source) + // With both --staged and --worktree: restore both + const restoreWorktree = options.worktree || !options.staged; + const restoreStaged = options.staged; + + if (restoreStaged) { + // Reset index entries to match HEAD (or source) + for (const filepath of paths) { + try { + await this.git.resetIndex({ dir: cwd, filepath }); + } catch { + return createErrorResult(`error: pathspec '${filepath}' did not match any file(s) known to git`); + } + } + } + + if (restoreWorktree) { + const source = options.source || 'HEAD'; + try { + await this.git.checkout({ + dir: cwd, + ref: source, + filepaths: paths, + force: true, + }); + } catch (error) { + if (error instanceof Error && error.message.includes('does not exist')) { + return createErrorResult(`error: pathspec did not match any file(s) known to git`); + } + return createErrorResult(`Failed to restore: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + return createSuccessResult(''); + } catch (error) { + return createErrorResult(`git restore: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private parseArgs(args: string[]): { + paths: string[]; + options: { source?: string; staged: boolean; worktree: boolean }; + } { + const options: { source?: string; staged: boolean; worktree: boolean } = { + staged: false, + worktree: false, + }; + const paths: string[] = []; + let foundDoubleDash = false; + + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === '--') { + foundDoubleDash = true; + continue; + } + if (foundDoubleDash) { + paths.push(arg); + } else if (arg === '--staged' || arg === '-S') { + options.staged = true; + } else if (arg === '--worktree' || arg === '-W') { + options.worktree = true; + } else if (arg === '--source' || arg === '-s') { + if (i + 1 < args.length) { + options.source = args[i + 1]; + i++; + } + } else if (arg.startsWith('--source=')) { + options.source = arg.substring(9); + } else if (!arg.startsWith('-')) { + paths.push(arg); + } + } + + return { paths, options }; + } +} diff --git a/src/lib/commands/git/rev-parse.test.ts b/src/lib/commands/git/rev-parse.test.ts new file mode 100644 index 00000000..c50fb262 --- /dev/null +++ b/src/lib/commands/git/rev-parse.test.ts @@ -0,0 +1,86 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { GitRevParseCommand } from './rev-parse'; +import type { Git } from '../../git'; +import type { JSRuntimeFS } from '../../JSRuntime'; + +const mockFS = { + stat: async (path: string) => { + if (path.endsWith('/.git')) return { isDirectory: () => true }; + throw new Error('ENOENT'); + }, +} as unknown as JSRuntimeFS; + +describe('GitRevParseCommand', () => { + let revParseCommand: GitRevParseCommand; + let mockGit: Git; + + beforeEach(() => { + mockGit = { + resolveRef: vi.fn().mockImplementation(({ ref }: { ref: string }) => { + if (ref === 'HEAD') return Promise.resolve('abcdef0123456789abcdef0123456789abcdef01'); + if (ref === 'main') return Promise.resolve('abcdef0123456789abcdef0123456789abcdef01'); + throw new Error('unknown ref'); + }), + readCommit: vi.fn().mockResolvedValue({ + oid: 'abcdef0123456789abcdef0123456789abcdef01', + commit: { parent: ['parent123parent123parent123parent123parent'] }, + }), + currentBranch: vi.fn().mockResolvedValue('main'), + } as unknown as Git; + revParseCommand = new GitRevParseCommand({ git: mockGit, fs: mockFS }); + }); + + it('should resolve HEAD to full commit hash', async () => { + const result = await revParseCommand.execute(['HEAD'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(result.stdout.trim()).toMatch(/^[a-f0-9]{40}$/); + }); + + it('should abbreviate with --short', async () => { + const result = await revParseCommand.execute(['--short', 'HEAD'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(result.stdout.trim()).toMatch(/^[a-f0-9]{7}$/); + }); + + it('should abbreviate with --short=', async () => { + const result = await revParseCommand.execute(['--short=4', 'HEAD'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(result.stdout.trim()).toMatch(/^[a-f0-9]{4}$/); + }); + + it('should resolve HEAD~1', async () => { + const result = await revParseCommand.execute(['HEAD~1'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(result.stdout.trim()).toBe('parent123parent123parent123parent123parent'); + }); + + it('should return main with --abbrev-ref HEAD', async () => { + const result = await revParseCommand.execute(['--abbrev-ref', 'HEAD'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(result.stdout.trim()).toBe('main'); + }); + + it('should output toplevel with --show-toplevel', async () => { + const result = await revParseCommand.execute(['--show-toplevel'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(result.stdout.trim()).toBe('/test-repo'); + }); + + it('should output git dir with --git-dir', async () => { + const result = await revParseCommand.execute(['--git-dir'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(result.stdout.trim()).toBe('/test-repo/.git'); + }); + + it('should output true with --is-inside-work-tree', async () => { + const result = await revParseCommand.execute(['--is-inside-work-tree'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(result.stdout.trim()).toBe('true'); + }); + + it('should fail for invalid revisions', async () => { + const result = await revParseCommand.execute(['notarevision'], '/test-repo'); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('ambiguous argument'); + }); +}); diff --git a/src/lib/commands/git/rev-parse.ts b/src/lib/commands/git/rev-parse.ts new file mode 100644 index 00000000..07371d21 --- /dev/null +++ b/src/lib/commands/git/rev-parse.ts @@ -0,0 +1,182 @@ +import type { JSRuntimeFS } from "../../JSRuntime"; +import type { ShellCommandResult } from "../ShellCommand"; +import { createSuccessResult, createErrorResult } from "../ShellCommand"; +import type { GitSubcommand, GitSubcommandOptions } from "../git"; +import type { Git } from "../../git"; + +export class GitRevParseCommand implements GitSubcommand { + name = 'rev-parse'; + description = 'Pick out and massage parameters'; + usage = 'git rev-parse [--short[=]] [--abbrev-ref] [--show-toplevel] [--git-dir] [--is-inside-work-tree] ...'; + + private git: Git; + private fs: JSRuntimeFS; + + constructor(options: GitSubcommandOptions) { + this.git = options.git; + this.fs = options.fs; + } + + async execute(args: string[], cwd: string): Promise { + try { + const { refs, options } = this.parseArgs(args); + + // Check if we're in a git repository + let inRepo = true; + try { + await this.fs.stat(`${cwd}/.git`); + } catch { + inRepo = false; + } + + // Handle special flags + const outputs: string[] = []; + + if (options.showToplevel) { + if (!inRepo) { + return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); + } + outputs.push(cwd); + } + + if (options.gitDir) { + if (!inRepo) { + return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); + } + outputs.push(`${cwd}/.git`); + } + + if (options.isInsideWorkTree) { + outputs.push(inRepo ? 'true' : 'false'); + } + + if (options.isInsideGitDir) { + outputs.push('false'); + } + + if (options.isBareRepository) { + outputs.push('false'); + } + + // Process refs + for (const ref of refs) { + if (!inRepo) { + return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); + } + try { + if (options.abbrevRef) { + // Output the branch name (remove refs/heads/ prefix) + if (ref === 'HEAD') { + const branch = await this.git.currentBranch({ dir: cwd }); + outputs.push(branch || 'HEAD'); + } else { + outputs.push(ref); + } + } else { + const oid = await this.resolveAnyRef(ref, cwd); + if (options.short) { + const len = options.short === true ? 7 : options.short; + outputs.push(oid.substring(0, len)); + } else { + outputs.push(oid); + } + } + } catch { + return createErrorResult(`fatal: ambiguous argument '${ref}': unknown revision or path not in the working tree.`); + } + } + + if (outputs.length === 0) { + return createErrorResult('usage: git rev-parse [--short[=]] [--abbrev-ref] [--show-toplevel] [--git-dir] ...'); + } + + return createSuccessResult(outputs.join('\n') + '\n'); + } catch (error) { + return createErrorResult(`git rev-parse: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + /** + * Resolve a ref including HEAD~N, HEAD^N, branch names, or commit hashes. + */ + private async resolveAnyRef(ref: string, cwd: string): Promise { + // HEAD~N syntax + const tildeMatch = ref.match(/^(.+)~(\d+)$/); + if (tildeMatch) { + const [, baseRef, steps] = tildeMatch; + let currentOid = await this.resolveAnyRef(baseRef, cwd); + const numSteps = parseInt(steps, 10); + for (let i = 0; i < numSteps; i++) { + const commit = await this.git.readCommit({ dir: cwd, oid: currentOid }); + if (!commit.commit.parent || commit.commit.parent.length === 0) { + throw new Error('No parent'); + } + currentOid = commit.commit.parent[0]; + } + return currentOid; + } + + // HEAD^N syntax + const caretMatch = ref.match(/^(.+)\^(\d*)$/); + if (caretMatch) { + const [, baseRef, parentNum] = caretMatch; + const parentIndex = parentNum ? parseInt(parentNum, 10) - 1 : 0; + const baseOid = await this.resolveAnyRef(baseRef, cwd); + const commit = await this.git.readCommit({ dir: cwd, oid: baseOid }); + if (!commit.commit.parent || parentIndex >= commit.commit.parent.length) { + throw new Error('No parent'); + } + return commit.commit.parent[parentIndex]; + } + + return await this.git.resolveRef({ dir: cwd, ref }); + } + + private parseArgs(args: string[]): { + refs: string[]; + options: { + short: boolean | number; + abbrevRef: boolean; + showToplevel: boolean; + gitDir: boolean; + isInsideWorkTree: boolean; + isInsideGitDir: boolean; + isBareRepository: boolean; + }; + } { + const options = { + short: false as boolean | number, + abbrevRef: false, + showToplevel: false, + gitDir: false, + isInsideWorkTree: false, + isInsideGitDir: false, + isBareRepository: false, + }; + const refs: string[] = []; + + for (const arg of args) { + if (arg === '--short') { + options.short = true; + } else if (arg.startsWith('--short=')) { + options.short = parseInt(arg.substring(8), 10) || 7; + } else if (arg === '--abbrev-ref') { + options.abbrevRef = true; + } else if (arg === '--show-toplevel') { + options.showToplevel = true; + } else if (arg === '--git-dir') { + options.gitDir = true; + } else if (arg === '--is-inside-work-tree') { + options.isInsideWorkTree = true; + } else if (arg === '--is-inside-git-dir') { + options.isInsideGitDir = true; + } else if (arg === '--is-bare-repository') { + options.isBareRepository = true; + } else if (!arg.startsWith('-')) { + refs.push(arg); + } + } + + return { refs, options }; + } +} diff --git a/src/lib/commands/git/revert.test.ts b/src/lib/commands/git/revert.test.ts new file mode 100644 index 00000000..d8534e7c --- /dev/null +++ b/src/lib/commands/git/revert.test.ts @@ -0,0 +1,102 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { GitRevertCommand } from './revert'; +import type { Git } from '../../git'; +import type { JSRuntimeFS } from '../../JSRuntime'; + +const mockFS = { + stat: async (path: string) => { + if (path.endsWith('/.git')) return { isDirectory: () => true }; + throw new Error('ENOENT'); + }, + writeFile: vi.fn(async () => {}), + unlink: vi.fn(async () => {}), + mkdir: vi.fn(async () => {}), +} as unknown as JSRuntimeFS; + +describe('GitRevertCommand', () => { + let revertCommand: GitRevertCommand; + let mockGit: Git; + + beforeEach(() => { + vi.clearAllMocks(); + mockGit = { + resolveRef: vi.fn().mockResolvedValue('abc123'), + readCommit: vi.fn().mockResolvedValue({ + oid: 'abc123', + commit: { + message: 'Add file2', + parent: ['parent123'], + author: { name: 'Test', email: 'test@example.com', timestamp: 1 }, + }, + }), + readTree: vi.fn().mockImplementation(({ oid }: { oid: string }) => { + if (oid === 'abc123') { + return Promise.resolve({ tree: [ + { mode: '100644', path: 'file1.txt', oid: 'blob1' }, + { mode: '100644', path: 'file2.txt', oid: 'blob2' }, + ] }); + } + if (oid === 'parent123') { + return Promise.resolve({ tree: [ + { mode: '100644', path: 'file1.txt', oid: 'blob1' }, + ] }); + } + return Promise.resolve({ tree: [] }); + }), + readBlob: vi.fn().mockResolvedValue({ + oid: 'blob1', + blob: new TextEncoder().encode('original'), + }), + add: vi.fn(async () => {}), + remove: vi.fn(async () => {}), + commit: vi.fn().mockResolvedValue('newcommit'), + currentBranch: vi.fn().mockResolvedValue('main'), + } as unknown as Git; + revertCommand = new GitRevertCommand({ git: mockGit, fs: mockFS }); + }); + + it('should fail without commit argument', async () => { + const result = await revertCommand.execute([], '/test-repo'); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('empty commit set'); + }); + + it('should fail when not in a git repo', async () => { + const mockFSNoGit = { + stat: async () => { throw new Error('ENOENT'); }, + } as unknown as JSRuntimeFS; + const cmd = new GitRevertCommand({ git: mockGit, fs: mockFSNoGit }); + const result = await cmd.execute(['HEAD'], '/not-a-repo'); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('not a git repository'); + }); + + it('should fail when reverting a root commit', async () => { + vi.mocked(mockGit.readCommit).mockResolvedValue({ + oid: 'abc123', + commit: { + message: 'Root', + parent: [], + author: { name: 'Test', email: 'test@example.com', timestamp: 1 }, + }, + } as unknown as Awaited>); + const result = await revertCommand.execute(['HEAD'], '/test-repo'); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('root commit'); + }); + + it('should revert a commit that added a file', async () => { + const result = await revertCommand.execute(['HEAD'], '/test-repo'); + expect(result.exitCode).toBe(0); + // file2.txt was added in target, so it should be removed + expect(mockGit.remove).toHaveBeenCalledWith({ dir: '/test-repo', filepath: 'file2.txt' }); + expect(mockGit.commit).toHaveBeenCalled(); + }); + + it('should support --no-commit', async () => { + const result = await revertCommand.execute(['--no-commit', 'HEAD'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('Applied revert'); + expect(mockGit.commit).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/commands/git/revert.ts b/src/lib/commands/git/revert.ts new file mode 100644 index 00000000..d1307223 --- /dev/null +++ b/src/lib/commands/git/revert.ts @@ -0,0 +1,173 @@ +import type { JSRuntimeFS } from "../../JSRuntime"; +import type { ShellCommandResult } from "../ShellCommand"; +import { createSuccessResult, createErrorResult } from "../ShellCommand"; +import type { GitSubcommand, GitSubcommandOptions } from "../git"; +import type { Git } from "../../git"; + +/** + * `git revert`: creates a new commit that undoes the changes from a previous commit. + * NOTE: This is a simplified implementation. True git revert creates an inverse + * patch; this version stages an inverse tree and commits it. + */ +export class GitRevertCommand implements GitSubcommand { + name = 'revert'; + description = 'Revert some existing commits'; + usage = 'git revert [--no-edit] [--no-commit | -n] '; + + private git: Git; + private fs: JSRuntimeFS; + + constructor(options: GitSubcommandOptions) { + this.git = options.git; + this.fs = options.fs; + } + + async execute(args: string[], cwd: string): Promise { + try { + try { + await this.fs.stat(`${cwd}/.git`); + } catch { + return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); + } + + const { commit, options } = this.parseArgs(args); + + if (!commit) { + return createErrorResult('fatal: empty commit set passed'); + } + + // Resolve target commit + let targetOid: string; + try { + targetOid = await this.git.resolveRef({ dir: cwd, ref: commit }); + } catch { + return createErrorResult(`fatal: bad revision '${commit}'`); + } + + // Read the commit and its parent + let targetCommit: Awaited>; + try { + targetCommit = await this.git.readCommit({ dir: cwd, oid: targetOid }); + } catch { + return createErrorResult(`fatal: bad revision '${commit}'`); + } + + const parentOid = targetCommit.commit.parent?.[0]; + if (!parentOid) { + return createErrorResult(`fatal: ${targetOid.substring(0, 7)} is a root commit, cannot revert`); + } + + // Walk both trees to get the inverse changes + const targetFiles = await this.getFileOids(targetOid, cwd); + const parentFiles = await this.getFileOids(parentOid, cwd); + + const changes: Array<{ path: string; action: 'restore' | 'delete' }> = []; + + // Files that existed in parent but were removed/modified in target: restore from parent + for (const [path, parentFileOid] of parentFiles) { + const targetFileOid = targetFiles.get(path); + if (!targetFileOid || targetFileOid !== parentFileOid) { + changes.push({ path, action: 'restore' }); + } + void parentFileOid; + } + // Files added in target: delete + for (const path of targetFiles.keys()) { + if (!parentFiles.has(path)) { + changes.push({ path, action: 'delete' }); + } + } + + // Apply the changes + for (const change of changes) { + try { + if (change.action === 'restore') { + const blob = await this.git.readBlob({ dir: cwd, oid: parentOid, filepath: change.path }); + // Ensure directory exists + const dir = change.path.substring(0, change.path.lastIndexOf('/')); + if (dir) { + try { + await this.fs.mkdir(`${cwd}/${dir}`, { recursive: true }); + } catch { /* empty */ } + } + await this.fs.writeFile(`${cwd}/${change.path}`, new TextDecoder().decode(blob.blob)); + await this.git.add({ dir: cwd, filepath: change.path }); + } else { + try { + await this.fs.unlink(`${cwd}/${change.path}`); + } catch { /* empty */ } + await this.git.remove({ dir: cwd, filepath: change.path }); + } + } catch (error) { + return createErrorResult(`error: failed to revert ${change.path}: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + if (options.noCommit) { + return createSuccessResult(`Applied revert for commit ${targetOid.substring(0, 7)}\n`); + } + + // Create the revert commit + const message = `Revert "${targetCommit.commit.message.split('\n')[0]}"\n\nThis reverts commit ${targetOid}.\n`; + + try { + const newCommitOid = await this.git.commit({ + dir: cwd, + message, + }); + return createSuccessResult(`[${await this.currentBranchName(cwd)} ${newCommitOid.substring(0, 7)}] ${message.split('\n')[0]}\n`); + } catch (error) { + return createErrorResult(`Failed to create revert commit: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } catch (error) { + return createErrorResult(`git revert: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private async currentBranchName(cwd: string): Promise { + try { + return await this.git.currentBranch({ dir: cwd }) || 'HEAD'; + } catch { + return 'HEAD'; + } + } + + private async getFileOids(commitOid: string, cwd: string): Promise> { + const files = new Map(); + const walk = async (treeOid: string, prefix: string): Promise => { + try { + const tree = await this.git.readTree({ dir: cwd, oid: treeOid }); + for (const entry of tree.tree as Array<{ mode: string; path: string; oid: string; type?: string }>) { + const path = prefix ? `${prefix}/${entry.path}` : entry.path; + if (entry.mode === '040000' || entry.type === 'tree') { + await walk(entry.oid, path); + } else { + files.set(path, entry.oid); + } + } + } catch { /* empty */ } + }; + await walk(commitOid, ''); + return files; + } + + private parseArgs(args: string[]): { + commit?: string; + options: { noEdit: boolean; noCommit: boolean }; + } { + const options = { noEdit: false, noCommit: false }; + let commit: string | undefined; + + for (const arg of args) { + if (arg === '--no-edit') { + options.noEdit = true; + } else if (arg === '--no-commit' || arg === '-n') { + options.noCommit = true; + } else if (!arg.startsWith('-')) { + commit = arg; + } + } + + return { commit, options }; + } +} diff --git a/src/lib/commands/git/rm.test.ts b/src/lib/commands/git/rm.test.ts new file mode 100644 index 00000000..06347007 --- /dev/null +++ b/src/lib/commands/git/rm.test.ts @@ -0,0 +1,97 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { GitRmCommand } from './rm'; +import type { Git } from '../../git'; +import type { JSRuntimeFS } from '../../JSRuntime'; + +const createMockFS = () => { + const files = new Map(); + const dirs = new Set(['/test-repo', '/test-repo/subdir']); + files.set('/test-repo/file1.txt', 'contents'); + files.set('/test-repo/subdir/nested.txt', 'nested'); + + return { + stat: vi.fn(async (path: string) => { + if (path.endsWith('/.git') || dirs.has(path)) { + return { isDirectory: () => true, isFile: () => false }; + } + if (files.has(path)) { + return { isDirectory: () => false, isFile: () => true }; + } + throw new Error('ENOENT'); + }), + readdir: vi.fn(async (path: string) => { + if (path === '/test-repo/subdir') { + return [{ name: 'nested.txt', isDirectory: () => false, isFile: () => true }]; + } + return []; + }), + unlink: vi.fn(async (path: string) => { + files.delete(path); + }), + _files: files, + } as unknown as JSRuntimeFS & { _files: Map }; +}; + +describe('GitRmCommand', () => { + let rmCommand: GitRmCommand; + let mockGit: Git; + let mockFS: JSRuntimeFS & { _files: Map }; + + beforeEach(() => { + mockFS = createMockFS() as JSRuntimeFS & { _files: Map }; + mockGit = { + remove: vi.fn(async () => {}), + } as unknown as Git; + rmCommand = new GitRmCommand({ git: mockGit, fs: mockFS }); + }); + + it('should fail without pathspec', async () => { + const result = await rmCommand.execute([], '/test-repo'); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('No pathspec'); + }); + + it('should fail when not in a git repo', async () => { + const mockFSNoGit = { + stat: async () => { throw new Error('ENOENT'); }, + } as unknown as JSRuntimeFS; + const cmd = new GitRmCommand({ git: mockGit, fs: mockFSNoGit }); + const result = await cmd.execute(['foo.txt'], '/not-a-repo'); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('not a git repository'); + }); + + it('should remove a file from working tree and index', async () => { + const result = await rmCommand.execute(['file1.txt'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain("rm 'file1.txt'"); + expect(mockGit.remove).toHaveBeenCalledWith({ dir: '/test-repo', filepath: 'file1.txt' }); + expect(mockFS.unlink).toHaveBeenCalled(); + }); + + it('should only remove from index with --cached', async () => { + const result = await rmCommand.execute(['--cached', 'file1.txt'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(mockGit.remove).toHaveBeenCalled(); + expect(mockFS.unlink).not.toHaveBeenCalled(); + }); + + it('should not remove files with --dry-run', async () => { + const result = await rmCommand.execute(['-n', 'file1.txt'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain("rm 'file1.txt'"); + expect(mockGit.remove).not.toHaveBeenCalled(); + }); + + it('should require -r for directories', async () => { + const result = await rmCommand.execute(['subdir'], '/test-repo'); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('-r'); + }); + + it('should remove directory recursively with -r', async () => { + const result = await rmCommand.execute(['-r', 'subdir'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('subdir/nested.txt'); + }); +}); diff --git a/src/lib/commands/git/rm.ts b/src/lib/commands/git/rm.ts new file mode 100644 index 00000000..c2314a6d --- /dev/null +++ b/src/lib/commands/git/rm.ts @@ -0,0 +1,157 @@ +import { join, isAbsolute, relative } from "path-browserify"; +import type { JSRuntimeFS } from "../../JSRuntime"; +import type { ShellCommandResult } from "../ShellCommand"; +import { createSuccessResult, createErrorResult } from "../ShellCommand"; +import type { GitSubcommand, GitSubcommandOptions } from "../git"; +import type { Git } from "../../git"; + +export class GitRmCommand implements GitSubcommand { + name = 'rm'; + description = 'Remove files from the working tree and from the index'; + usage = 'git rm [-f | --force] [-r] [--cached] [--dry-run | -n] [--] ...'; + + private git: Git; + private fs: JSRuntimeFS; + + constructor(options: GitSubcommandOptions) { + this.git = options.git; + this.fs = options.fs; + } + + async execute(args: string[], cwd: string): Promise { + try { + try { + await this.fs.stat(`${cwd}/.git`); + } catch { + return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); + } + + const { paths, options } = this.parseArgs(args); + + if (paths.length === 0) { + return createErrorResult('fatal: No pathspec was given. Which files should I remove?'); + } + + const removed: string[] = []; + const errors: string[] = []; + + for (const path of paths) { + const normalized = this.normalizePath(path, cwd); + if (normalized === null) { + errors.push(`fatal: ${path}: '${path}' is outside repository`); + continue; + } + + const absPath = join(cwd, normalized); + + let isDir = false; + try { + const stats = await this.fs.stat(absPath); + isDir = stats.isDirectory(); + } catch { + // File doesn't exist on disk - might still be in index + } + + if (isDir && !options.recursive) { + errors.push(`fatal: not removing '${path}' recursively without -r`); + continue; + } + + const filesToRemove: string[] = []; + if (isDir) { + // Collect all files in the directory + await this.collectFiles(absPath, normalized, filesToRemove); + } else { + filesToRemove.push(normalized); + } + + for (const file of filesToRemove) { + try { + if (!options.dryRun) { + // Remove from index + await this.git.remove({ dir: cwd, filepath: file }); + // Remove from working tree unless --cached + if (!options.cached) { + try { + await this.fs.unlink(join(cwd, file)); + } catch { + // File might not exist on disk + } + } + } + removed.push(file); + } catch { + errors.push(`fatal: pathspec '${file}' did not match any files`); + } + } + } + + if (errors.length > 0 && removed.length === 0) { + return createErrorResult(errors.join('\n')); + } + + const output = removed.map(f => `rm '${f}'`).join('\n'); + return createSuccessResult(output + (output ? '\n' : '')); + } catch (error) { + return createErrorResult(`git rm: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private async collectFiles(absPath: string, relPath: string, out: string[]): Promise { + try { + const entries = await this.fs.readdir(absPath, { withFileTypes: true }); + for (const entry of entries) { + if (entry.name === '.git') continue; + const entryAbs = join(absPath, entry.name); + const entryRel = join(relPath, entry.name); + if (entry.isDirectory()) { + await this.collectFiles(entryAbs, entryRel, out); + } else { + out.push(entryRel); + } + } + } catch { + // Ignore + } + } + + private normalizePath(path: string, cwd: string): string | null { + if (isAbsolute(path)) { + if (!path.startsWith(cwd)) return null; + const rel = relative(cwd, path); + return rel || '.'; + } + return path; + } + + private parseArgs(args: string[]): { + paths: string[]; + options: { force: boolean; recursive: boolean; cached: boolean; dryRun: boolean }; + } { + const options = { force: false, recursive: false, cached: false, dryRun: false }; + const paths: string[] = []; + let foundDoubleDash = false; + + for (const arg of args) { + if (arg === '--') { + foundDoubleDash = true; + continue; + } + if (foundDoubleDash) { + paths.push(arg); + } else if (arg === '-f' || arg === '--force') { + options.force = true; + } else if (arg === '-r' || arg === '-R') { + options.recursive = true; + } else if (arg === '--cached') { + options.cached = true; + } else if (arg === '-n' || arg === '--dry-run') { + options.dryRun = true; + } else if (!arg.startsWith('-')) { + paths.push(arg); + } + } + + return { paths, options }; + } +} diff --git a/src/lib/commands/git/show.ts b/src/lib/commands/git/show.ts index d51c9611..24091bcb 100644 --- a/src/lib/commands/git/show.ts +++ b/src/lib/commands/git/show.ts @@ -26,7 +26,7 @@ export class GitShowCommand implements GitSubcommand { return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); } - const { commit } = this.parseArgs(args); + const { commit, options } = this.parseArgs(args); // Resolve the commit reference (handling relative refs like HEAD~1) const resolvedCommit = await this.resolveCommitRef(commit, cwd); @@ -34,24 +34,33 @@ export class GitShowCommand implements GitSubcommand { return createErrorResult(`fatal: bad revision '${commit}'`); } - return await this.showCommit(resolvedCommit, cwd); + return await this.showCommit(resolvedCommit, cwd, options); } catch (error) { return createErrorResult(`git show: ${error instanceof Error ? error.message : 'Unknown error'}`); } } - private parseArgs(args: string[]): { commit: string } { + private parseArgs(args: string[]): { + commit: string; + options: { stat: boolean; nameOnly: boolean; nameStatus: boolean }; + } { let commit = 'HEAD'; // Default to HEAD + const options = { stat: false, nameOnly: false, nameStatus: false }; for (const arg of args) { - if (!arg.startsWith('-')) { + if (arg === '--stat') { + options.stat = true; + } else if (arg === '--name-only') { + options.nameOnly = true; + } else if (arg === '--name-status') { + options.nameStatus = true; + } else if (!arg.startsWith('-')) { commit = arg; - break; } } - return { commit }; + return { commit, options }; } /** @@ -173,7 +182,64 @@ export class GitShowCommand implements GitSubcommand { } } - private async showCommit(commitRef: string, cwd: string): Promise { + /** + * Compute file changes between a commit and its parent. + */ + private async computeChangesFromCommit( + commitOid: string, + parentOid: string | undefined, + cwd: string, + ): Promise> { + const changes: Array<{ type: 'add' | 'modify' | 'delete'; path: string }> = []; + + const walk = async (oid: string): Promise> => { + const files = new Map(); + const walkTree = async (treeOid: string, prefix: string): Promise => { + try { + const tree = await this.git.readTree({ dir: cwd, oid: treeOid }); + for (const entry of tree.tree as Array<{ mode: string; path: string; oid: string; type?: string }>) { + const path = prefix ? `${prefix}/${entry.path}` : entry.path; + if (entry.mode === '040000' || entry.type === 'tree') { + await walkTree(entry.oid, path); + } else { + files.set(path, entry.oid); + } + } + } catch { + // Ignore + } + }; + await walkTree(oid, ''); + return files; + }; + + const currentFiles = await walk(commitOid); + + if (!parentOid) { + for (const path of currentFiles.keys()) { + changes.push({ type: 'add', path }); + } + } else { + const parentFiles = await walk(parentOid); + for (const [path, oid] of currentFiles) { + const parentOidForFile = parentFiles.get(path); + if (!parentOidForFile) { + changes.push({ type: 'add', path }); + } else if (parentOidForFile !== oid) { + changes.push({ type: 'modify', path }); + } + } + for (const path of parentFiles.keys()) { + if (!currentFiles.has(path)) { + changes.push({ type: 'delete', path }); + } + } + } + + return changes.sort((a, b) => a.path.localeCompare(b.path)); + } + + private async showCommit(commitRef: string, cwd: string, options: { stat: boolean; nameOnly: boolean; nameStatus: boolean } = { stat: false, nameOnly: false, nameStatus: false }): Promise { try { // Get the commit const commits = await this.git.log({ @@ -187,6 +253,41 @@ export class GitShowCommand implements GitSubcommand { } const commit = commits[0]; + + // Handle --name-only / --name-status / --stat with a compact output + if (options.nameOnly || options.nameStatus || options.stat) { + const lines: string[] = []; + const changes = await this.computeChangesFromCommit(commit.oid, commit.commit.parent?.[0], cwd); + if (options.nameOnly) { + for (const c of changes) lines.push(c.path); + } else if (options.nameStatus) { + for (const c of changes) { + const status = c.type === 'add' ? 'A' : c.type === 'delete' ? 'D' : 'M'; + lines.push(`${status}\t${c.path}`); + } + } else { + // --stat: show commit metadata + file list + lines.push(`commit ${commit.oid}`); + lines.push(`Author: ${commit.commit.author.name} <${commit.commit.author.email}>`); + lines.push(`Date: ${new Date(commit.commit.author.timestamp * 1000).toUTCString()}`); + lines.push(''); + for (const messageLine of commit.commit.message.split('\n')) { + lines.push(` ${messageLine}`); + } + lines.push(''); + const maxLen = Math.max(10, ...changes.map(c => c.path.length)); + let added = 0, deleted = 0; + for (const c of changes) { + const bar = c.type === 'add' ? '+' : c.type === 'delete' ? '-' : 'M'; + lines.push(` ${c.path.padEnd(maxLen)} | ${bar}`); + if (c.type === 'add') added++; + else if (c.type === 'delete') deleted++; + } + lines.push(` ${changes.length} file${changes.length !== 1 ? 's' : ''} changed, ${added} insertion${added !== 1 ? 's' : ''}(+), ${deleted} deletion${deleted !== 1 ? 's' : ''}(-)`); + } + return createSuccessResult(lines.join('\n') + '\n'); + } + const lines: string[] = []; // Show commit information diff --git a/src/lib/commands/git/status.ts b/src/lib/commands/git/status.ts index 71a91baa..4be194b0 100644 --- a/src/lib/commands/git/status.ts +++ b/src/lib/commands/git/status.ts @@ -73,6 +73,12 @@ export class GitStatusCommand implements GitSubcommand { const lines: string[] = []; for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) { + // Untracked files show as '??' in porcelain format + if (headStatus === 0 && stageStatus === 0 && workdirStatus === 2) { + lines.push(`?? ${filepath}`); + continue; + } + let indexStatus = ' '; let workingStatus = ' '; @@ -86,16 +92,13 @@ export class GitStatusCommand implements GitSubcommand { } // Determine working directory status (comparing stage to working dir) - if (headStatus === 0 && stageStatus === 0 && workdirStatus === 2) { - // Untracked files show as ?? in porcelain format - indexStatus = '?'; - workingStatus = '?'; - } else if (stageStatus === 2 && workdirStatus === 0) { + if ((stageStatus === 2 || stageStatus === 1) && workdirStatus === 0) { workingStatus = 'D'; // Deleted in working dir - } else if (stageStatus === 1 && workdirStatus === 0) { - workingStatus = 'D'; // Deleted in working dir (was same as HEAD) - } else if (stageStatus !== workdirStatus && workdirStatus === 2) { + } else if (stageStatus !== workdirStatus && workdirStatus === 2 && stageStatus !== 0) { workingStatus = 'M'; // Modified in working dir + } else if (stageStatus === 0 && workdirStatus === 2 && headStatus === 1) { + // File deleted from index but still in working dir - unusual, treat as modified + workingStatus = 'M'; } // Only show files with changes diff --git a/src/lib/commands/git/switch.test.ts b/src/lib/commands/git/switch.test.ts new file mode 100644 index 00000000..57a3ccc2 --- /dev/null +++ b/src/lib/commands/git/switch.test.ts @@ -0,0 +1,82 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { GitSwitchCommand } from './switch'; +import type { Git } from '../../git'; +import type { JSRuntimeFS } from '../../JSRuntime'; + +const mockFS = { + stat: async (path: string) => { + if (path.endsWith('/.git')) return { isDirectory: () => true }; + throw new Error('ENOENT'); + }, +} as unknown as JSRuntimeFS; + +describe('GitSwitchCommand', () => { + let switchCommand: GitSwitchCommand; + let mockGit: Git; + + beforeEach(() => { + mockGit = { + listBranches: vi.fn().mockResolvedValue(['main', 'other']), + currentBranch: vi.fn().mockResolvedValue('main'), + checkout: vi.fn(async () => {}), + branch: vi.fn(async () => {}), + deleteBranch: vi.fn(async () => {}), + resolveRef: vi.fn().mockResolvedValue('abc123'), + statusMatrix: vi.fn().mockResolvedValue([]), + } as unknown as Git; + switchCommand = new GitSwitchCommand({ git: mockGit, fs: mockFS }); + }); + + it('should create and switch with -c', async () => { + vi.mocked(mockGit.listBranches).mockResolvedValue(['main']); + const result = await switchCommand.execute(['-c', 'feature'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain("Switched to a new branch 'feature'"); + expect(mockGit.branch).toHaveBeenCalled(); + }); + + it('should switch to existing branch', async () => { + const result = await switchCommand.execute(['other'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain("Switched to branch 'other'"); + }); + + it('should fail for non-existent branch', async () => { + const result = await switchCommand.execute(['nonexistent'], '/test-repo'); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('invalid reference'); + }); + + it('should say already on branch', async () => { + const result = await switchCommand.execute(['main'], '/test-repo'); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain("Already on 'main'"); + }); + + it('should fail when not in a git repo', async () => { + const mockFSNoGit = { + stat: async () => { throw new Error('ENOENT'); }, + } as unknown as JSRuntimeFS; + const cmd = new GitSwitchCommand({ git: mockGit, fs: mockFSNoGit }); + const result = await cmd.execute(['main'], '/not-a-repo'); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('not a git repository'); + }); + + it('should block switch with uncommitted changes', async () => { + vi.mocked(mockGit.statusMatrix).mockResolvedValue([ + ['file.txt', 1, 2, 1], + ]); + const result = await switchCommand.execute(['other'], '/test-repo'); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('local changes'); + }); + + it('should force switch with -f', async () => { + vi.mocked(mockGit.statusMatrix).mockResolvedValue([ + ['file.txt', 1, 2, 1], + ]); + const result = await switchCommand.execute(['-f', 'other'], '/test-repo'); + expect(result.exitCode).toBe(0); + }); +}); diff --git a/src/lib/commands/git/switch.ts b/src/lib/commands/git/switch.ts new file mode 100644 index 00000000..97bc33cb --- /dev/null +++ b/src/lib/commands/git/switch.ts @@ -0,0 +1,135 @@ +import type { JSRuntimeFS } from "../../JSRuntime"; +import type { ShellCommandResult } from "../ShellCommand"; +import { createSuccessResult, createErrorResult } from "../ShellCommand"; +import type { GitSubcommand, GitSubcommandOptions } from "../git"; +import type { Git } from "../../git"; + +/** + * `git switch` is the modern replacement for `git checkout `. + * Only switches branches; doesn't restore files. + */ +export class GitSwitchCommand implements GitSubcommand { + name = 'switch'; + description = 'Switch branches'; + usage = 'git switch [-c | -C] [--detach] [--force] | git switch - (switch to previous branch)'; + + private git: Git; + private fs: JSRuntimeFS; + + constructor(options: GitSubcommandOptions) { + this.git = options.git; + this.fs = options.fs; + } + + async execute(args: string[], cwd: string): Promise { + try { + try { + await this.fs.stat(`${cwd}/.git`); + } catch { + return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); + } + + const { target, startPoint, options } = this.parseArgs(args); + + if (!target) { + return createErrorResult('fatal: missing branch or commit argument'); + } + + // Handle "switch to previous branch" + if (target === '-') { + return createErrorResult('fatal: switch to previous branch is not supported'); + } + + const branches = await this.git.listBranches({ dir: cwd }); + const isBranch = branches.includes(target); + + if (options.create || options.createOrReset) { + if (isBranch && !options.createOrReset) { + return createErrorResult(`fatal: A branch named '${target}' already exists.`); + } + + if (isBranch && options.createOrReset) { + try { + await this.git.deleteBranch({ dir: cwd, ref: target }); + } catch { + // Continue + } + } + + let startOid: string; + try { + startOid = await this.git.resolveRef({ dir: cwd, ref: startPoint || 'HEAD' }); + } catch { + return createErrorResult(`fatal: invalid reference: ${startPoint || 'HEAD'}`); + } + + await this.git.branch({ dir: cwd, ref: target, object: startOid }); + + await this.git.checkout({ dir: cwd, ref: target, force: options.force }); + + return createSuccessResult(`Switched to a new branch '${target}'\n`); + } + + if (!isBranch && !options.detach) { + return createErrorResult(`fatal: invalid reference: ${target}`); + } + + // Check for uncommitted changes unless --force + if (!options.force) { + const statusMatrix = await this.git.statusMatrix({ dir: cwd }); + const hasChanges = statusMatrix.some(([, headStatus, workdirStatus, stageStatus]) => { + if (headStatus === 0 && stageStatus === 0) return false; + return headStatus !== workdirStatus || headStatus !== stageStatus; + }); + if (hasChanges) { + return createErrorResult('error: Your local changes to the following files would be overwritten by checkout:\nPlease commit your changes or stash them before you switch branches.'); + } + } + + let currentBranch: string | null = null; + try { + currentBranch = await this.git.currentBranch({ dir: cwd }) || null; + } catch { /* empty */ } + + if (isBranch && currentBranch === target) { + return createSuccessResult(`Already on '${target}'\n`); + } + + await this.git.checkout({ dir: cwd, ref: target, force: options.force }); + + return createSuccessResult(isBranch + ? `Switched to branch '${target}'\n` + : `HEAD is now at ${target.substring(0, 7)}\n`); + } catch (error) { + return createErrorResult(`git switch: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private parseArgs(args: string[]): { + target?: string; + startPoint?: string; + options: { create: boolean; createOrReset: boolean; detach: boolean; force: boolean }; + } { + const options = { create: false, createOrReset: false, detach: false, force: false }; + const positionals: string[] = []; + + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === '-c' || arg === '--create') { + options.create = true; + } else if (arg === '-C' || arg === '--force-create') { + options.createOrReset = true; + } else if (arg === '--detach' || arg === '-d') { + options.detach = true; + } else if (arg === '--force' || arg === '-f' || arg === '--discard-changes') { + options.force = true; + } else if (!arg.startsWith('-')) { + positionals.push(arg); + } + } + + const target = positionals[0]; + const startPoint = positionals[1]; + return { target, startPoint, options }; + } +} diff --git a/src/lib/commands/git/tag.ts b/src/lib/commands/git/tag.ts index e7c8ab06..a5195de0 100644 --- a/src/lib/commands/git/tag.ts +++ b/src/lib/commands/git/tag.ts @@ -1,14 +1,23 @@ - import type { JSRuntimeFS } from "../../JSRuntime"; import type { ShellCommandResult } from "../ShellCommand"; import { createSuccessResult, createErrorResult } from "../ShellCommand"; import type { GitSubcommand, GitSubcommandOptions } from "../git"; import type { Git } from "../../git"; +interface TagOptions { + annotated: boolean; + force: boolean; + list: boolean; + showMessages: boolean; + message?: string; +} + +type TagAction = 'list' | 'create' | 'delete'; + export class GitTagCommand implements GitSubcommand { name = 'tag'; description = 'Create, list, delete or verify a tag object'; - usage = 'git tag [-l] | git tag [] | git tag -d '; + usage = 'git tag [-l []] [-n []] | git tag [-a] [-f] [-m ] [] | git tag -d ...'; private git: Git; private fs: JSRuntimeFS; @@ -27,17 +36,17 @@ export class GitTagCommand implements GitSubcommand { return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); } - const { action, tagName, commit } = this.parseArgs(args); + const { action, tagName, commit, options, pattern } = this.parseArgs(args); switch (action) { case 'list': - return await this.listTags(cwd); + return await this.listTags(pattern, options.showMessages, cwd); case 'create': - return await this.createTag(tagName!, cwd, commit); + return await this.createTag(tagName!, cwd, commit, options); case 'delete': return await this.deleteTag(tagName!, cwd); default: - return await this.listTags(cwd); + return await this.listTags(pattern, options.showMessages, cwd); } } catch (error) { @@ -46,79 +55,157 @@ export class GitTagCommand implements GitSubcommand { } private parseArgs(args: string[]): { - action: 'list' | 'create' | 'delete'; + action: TagAction; tagName?: string; commit?: string; - options: { annotated: boolean } + pattern?: string; + options: TagOptions; } { - const options = { annotated: false }; - let action: 'list' | 'create' | 'delete' = 'list'; + const options: TagOptions = { + annotated: false, + force: false, + list: false, + showMessages: false, + }; + let action: TagAction = 'list'; let tagName: string | undefined; let commit: string | undefined; + let pattern: string | undefined; + const positionals: string[] = []; for (let i = 0; i < args.length; i++) { const arg = args[i]; if (arg === '-l' || arg === '--list') { action = 'list'; + options.list = true; } else if (arg === '-d' || arg === '--delete') { action = 'delete'; - if (i + 1 < args.length) { - tagName = args[i + 1]; - i++; - } } else if (arg === '-a' || arg === '--annotate') { options.annotated = true; - } else if (!arg.startsWith('-')) { - if (!tagName) { - tagName = arg; - action = 'create'; - } else if (!commit) { - commit = arg; + } else if (arg === '-f' || arg === '--force') { + options.force = true; + } else if (arg === '-n' || arg.match(/^-n\d+$/)) { + options.showMessages = true; + action = 'list'; + } else if (arg === '-m' || arg === '--message') { + if (i + 1 < args.length) { + options.message = args[i + 1]; + options.annotated = true; + i++; } + } else if (arg.startsWith('-m=')) { + options.message = arg.substring(3); + options.annotated = true; + } else if (arg.startsWith('--message=')) { + options.message = arg.substring(10); + options.annotated = true; + } else if (!arg.startsWith('-')) { + positionals.push(arg); } } - return { action, tagName, commit, options }; + if (action === 'delete') { + tagName = positionals[0]; + } else if (action === 'list') { + pattern = positionals[0]; + } else if (positionals.length >= 1) { + action = 'create'; + tagName = positionals[0]; + if (positionals.length >= 2) { + commit = positionals[1]; + } + } + + return { action, tagName, commit, pattern, options }; } - private async listTags(cwd: string): Promise { - try { - const tags = await this.git.listTags({ - dir: cwd, - }); + private matchPattern(tagName: string, pattern?: string): boolean { + if (!pattern) return true; + // Simple glob: convert * to .* and ? to . + const regex = new RegExp('^' + pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.') + '$'); + return regex.test(tagName); + } - if (tags.length === 0) { + private async listTags(pattern: string | undefined, showMessages: boolean, cwd: string): Promise { + try { + const tags = await this.git.listTags({ dir: cwd }); + + const filtered = tags.filter(t => this.matchPattern(t, pattern)); + if (filtered.length === 0) { return createSuccessResult(''); } - // Sort tags alphabetically - tags.sort(); + filtered.sort(); - return createSuccessResult(tags.join('\n') + '\n'); + if (showMessages) { + const lines: string[] = []; + for (const tag of filtered) { + try { + // Try to read as annotated tag + const oid = await this.git.resolveRef({ dir: cwd, ref: tag }); + try { + const tagObj = await this.git.readTag({ dir: cwd, oid }); + const firstLine = (tagObj.tag.message || '').split('\n')[0]; + lines.push(`${tag.padEnd(15)} ${firstLine}`); + } catch { + // Lightweight tag: show commit message + try { + const log = await this.git.log({ dir: cwd, depth: 1, ref: tag }); + if (log.length > 0) { + lines.push(`${tag.padEnd(15)} ${log[0].commit.message.split('\n')[0]}`); + } else { + lines.push(tag); + } + } catch { + lines.push(tag); + } + } + } catch { + lines.push(tag); + } + } + return createSuccessResult(lines.join('\n') + '\n'); + } + + return createSuccessResult(filtered.join('\n') + '\n'); } catch (error) { return createErrorResult(`Failed to list tags: ${error instanceof Error ? error.message : 'Unknown error'}`); } } - private async createTag(tagName: string, cwd: string, commit?: string): Promise { + private async createTag( + tagName: string, + cwd: string, + commit: string | undefined, + options: TagOptions, + ): Promise { try { if (!tagName) { return createErrorResult('usage: git tag []'); } - // Check if tag already exists - try { - const tags = await this.git.listTags({ - dir: cwd, - }); - - if (tags.includes(tagName)) { - return createErrorResult(`fatal: tag '${tagName}' already exists`); + // Check if tag already exists (unless --force) + if (!options.force) { + try { + const tags = await this.git.listTags({ dir: cwd }); + if (tags.includes(tagName)) { + return createErrorResult(`fatal: tag '${tagName}' already exists`); + } + } catch { + // Continue + } + } else { + // Delete existing tag first if --force + try { + const tags = await this.git.listTags({ dir: cwd }); + if (tags.includes(tagName)) { + await this.git.deleteTag({ dir: cwd, ref: tagName }); + } + } catch { + // Continue } - } catch { - // Continue if we can't list tags } // Resolve the target commit @@ -132,12 +219,32 @@ export class GitTagCommand implements GitSubcommand { return createErrorResult(`fatal: not a valid object name: '${commit || 'HEAD'}'`); } - // Create the tag - await this.git.tag({ - dir: cwd, - ref: tagName, - object: targetOid, - }); + // Create annotated or lightweight tag + if (options.annotated || options.message) { + const message = options.message || tagName; + try { + await this.git.annotatedTag({ + dir: cwd, + ref: tagName, + object: targetOid, + message, + }); + } catch (error) { + // Fallback to lightweight tag + await this.git.tag({ + dir: cwd, + ref: tagName, + object: targetOid, + }); + console.warn(`Created lightweight tag instead of annotated: ${error instanceof Error ? error.message : error}`); + } + } else { + await this.git.tag({ + dir: cwd, + ref: tagName, + object: targetOid, + }); + } return createSuccessResult(''); @@ -146,7 +253,7 @@ export class GitTagCommand implements GitSubcommand { } } - private async deleteTag(tagName: string, cwd: string): Promise { + private async deleteTag(tagName: string, cwd: string): Promise { try { if (!tagName) { return createErrorResult('usage: git tag -d '); @@ -154,9 +261,7 @@ export class GitTagCommand implements GitSubcommand { // Check if tag exists try { - const tags = await this.git.listTags({ - dir: cwd, - }); + const tags = await this.git.listTags({ dir: cwd }); if (!tags.includes(tagName)) { return createErrorResult(`error: tag '${tagName}' not found.`);