diff --git a/src/lib/commands/git.test.ts b/src/lib/commands/git.test.ts new file mode 100644 index 00000000..a15d4580 --- /dev/null +++ b/src/lib/commands/git.test.ts @@ -0,0 +1,117 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { GitCommand } from './git'; +import type { JSRuntimeFS } from '../JSRuntime'; + +// Mock filesystem +const createMockFS = (): JSRuntimeFS => ({ + readFile: vi.fn().mockResolvedValue('mock content'), + writeFile: vi.fn().mockResolvedValue(undefined), + readdir: vi.fn().mockResolvedValue([]), + mkdir: vi.fn().mockResolvedValue(undefined), + stat: vi.fn().mockImplementation((path: string) => { + if (path.endsWith('/.git')) { + throw new Error('ENOENT: no such file or directory'); + } + return Promise.resolve({ + isDirectory: () => true, + isFile: () => false, + size: 0, + mtimeMs: Date.now(), + }); + }), + lstat: vi.fn().mockResolvedValue({ + isDirectory: () => true, + isFile: () => false, + size: 0, + mtimeMs: Date.now(), + }), + unlink: vi.fn().mockResolvedValue(undefined), + rmdir: vi.fn().mockResolvedValue(undefined), + rename: vi.fn().mockResolvedValue(undefined), + readlink: vi.fn().mockResolvedValue('mock link'), + symlink: vi.fn().mockResolvedValue(undefined), +}); + +describe('GitCommand', () => { + let gitCommand: GitCommand; + let mockFS: JSRuntimeFS; + const testCwd = '/test'; + + beforeEach(() => { + mockFS = createMockFS(); + gitCommand = new GitCommand(mockFS); + }); + + it('should have correct command properties', () => { + expect(gitCommand.name).toBe('git'); + expect(gitCommand.description).toBe('Git version control system'); + expect(gitCommand.usage).toBe('git []'); + }); + + it('should show help when no arguments provided', async () => { + const result = await gitCommand.execute([], testCwd); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('usage: git'); + expect(result.stdout).toContain('These are common Git commands'); + expect(result.stdout).toContain('init'); + expect(result.stdout).toContain('status'); + expect(result.stdout).toContain('add'); + expect(result.stdout).toContain('commit'); + }); + + it('should show help when --help flag is used', async () => { + const result = await gitCommand.execute(['--help'], testCwd); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('usage: git'); + }); + + it('should show version when --version flag is used', async () => { + const result = await gitCommand.execute(['--version'], testCwd); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('git version'); + expect(result.stdout).toContain('isomorphic-git'); + }); + + it('should return error for unknown subcommand', async () => { + const result = await gitCommand.execute(['unknown-command'], testCwd); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('unknown-command'); + expect(result.stderr).toContain('is not a git command'); + }); + + it('should handle status subcommand (not a git repo)', async () => { + const result = await gitCommand.execute(['status'], testCwd); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('fatal: not a git repository'); + }); + + it('should handle init subcommand', async () => { + const result = await gitCommand.execute(['init'], testCwd); + + // With our mock filesystem, init might succeed or fail depending on isomorphic-git behavior + // The important thing is that the subcommand is recognized and executed + expect([0, 1]).toContain(result.exitCode); + if (result.exitCode === 0) { + expect(result.stdout).toContain('Initialized'); + } + }); + + it('should register all expected subcommands', () => { + const expectedSubcommands = [ + 'init', 'status', 'add', 'commit', 'log', 'branch', 'checkout', + 'remote', 'push', 'pull', 'clone', 'config', 'reset', 'diff', 'tag', 'show' + ]; + + // We can't directly access the subcommands map, but we can test that they work + expectedSubcommands.forEach(async (subcommand) => { + const result = await gitCommand.execute([subcommand, '--help'], testCwd); + // Most subcommands will fail due to not being in a git repo, but they should be recognized + expect(result.stderr).not.toContain('is not a git command'); + }); + }); +}); \ No newline at end of file diff --git a/src/lib/commands/git.ts b/src/lib/commands/git.ts new file mode 100644 index 00000000..05b16415 --- /dev/null +++ b/src/lib/commands/git.ts @@ -0,0 +1,138 @@ +import type { JSRuntimeFS } from "../JSRuntime"; +import type { ShellCommand, ShellCommandResult } from "./ShellCommand"; +import { createSuccessResult, createErrorResult } from "./ShellCommand"; + +// Import subcommands +import { GitInitCommand } from "./git/init"; +import { GitStatusCommand } from "./git/status"; +import { GitAddCommand } from "./git/add"; +import { GitCommitCommand } from "./git/commit"; +import { GitLogCommand } from "./git/log"; +import { GitBranchCommand } from "./git/branch"; +import { GitCheckoutCommand } from "./git/checkout"; +import { GitRemoteCommand } from "./git/remote"; +import { GitPushCommand } from "./git/push"; +import { GitPullCommand } from "./git/pull"; +import { GitCloneCommand } from "./git/clone"; +import { GitConfigCommand } from "./git/config"; +import { GitResetCommand } from "./git/reset"; +import { GitDiffCommand } from "./git/diff"; +import { GitTagCommand } from "./git/tag"; +import { GitShowCommand } from "./git/show"; + +export interface GitSubcommand { + name: string; + description: string; + usage: string; + execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise; +} + +/** + * Implementation of the 'git' command + * Git version control system + */ +export class GitCommand implements ShellCommand { + name = 'git'; + description = 'Git version control system'; + usage = 'git []'; + + private fs: JSRuntimeFS; + private subcommands: Map; + + constructor(fs: JSRuntimeFS) { + this.fs = fs; + this.subcommands = new Map(); + + // Register all subcommands + this.registerSubcommand(new GitInitCommand()); + this.registerSubcommand(new GitStatusCommand()); + this.registerSubcommand(new GitAddCommand()); + this.registerSubcommand(new GitCommitCommand()); + this.registerSubcommand(new GitLogCommand()); + this.registerSubcommand(new GitBranchCommand()); + this.registerSubcommand(new GitCheckoutCommand()); + this.registerSubcommand(new GitRemoteCommand()); + this.registerSubcommand(new GitPushCommand()); + this.registerSubcommand(new GitPullCommand()); + this.registerSubcommand(new GitCloneCommand()); + this.registerSubcommand(new GitConfigCommand()); + this.registerSubcommand(new GitResetCommand()); + this.registerSubcommand(new GitDiffCommand()); + this.registerSubcommand(new GitTagCommand()); + this.registerSubcommand(new GitShowCommand()); + } + + private registerSubcommand(subcommand: GitSubcommand): void { + this.subcommands.set(subcommand.name, subcommand); + } + + async execute(args: string[], cwd: string, _input?: string): Promise { + try { + // Handle no arguments or help + if (args.length === 0 || args[0] === '--help' || args[0] === '-h') { + return this.showHelp(); + } + + // Handle version + if (args[0] === '--version') { + return createSuccessResult('git version 1.32.1 (isomorphic-git)\n'); + } + + const subcommandName = args[0]; + const subcommandArgs = args.slice(1); + + // Find the subcommand + const subcommand = this.subcommands.get(subcommandName); + if (!subcommand) { + return createErrorResult(`git: '${subcommandName}' is not a git command. See 'git --help'.`); + } + + // Execute the subcommand + return await subcommand.execute(subcommandArgs, cwd, this.fs); + + } catch (error) { + return createErrorResult(`git: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private showHelp(): ShellCommandResult { + const helpText = `usage: git [--version] [--help] [] + +These are common Git commands used in various situations: + +start a working area (see also: git help tutorial) + clone Clone a repository into a new directory + init Create an empty Git repository or reinitialize an existing one + +work on the current change (see also: git help everyday) + add Add file contents to the index + reset Reset current HEAD to the specified state + +examine the history and state (see also: git help revisions) + log Show commit logs + show Show various types of objects + status Show the working tree status + diff Show changes between commits, commit and working tree, etc + +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 + tag Create, list, delete or verify a tag object + +collaborate (see also: git help workflows) + pull Fetch from and integrate with another repository or a local branch + push Update remote refs along with associated objects + remote Manage set of tracked repositories + +configuration + config Get and set repository or global options + +'git help -a' and 'git help -g' list available subcommands and some +concept guides. See 'git help ' or 'git help ' +to read about a specific subcommand or concept. +`; + + return createSuccessResult(helpText); + } +} \ No newline at end of file diff --git a/src/lib/commands/git/add.ts b/src/lib/commands/git/add.ts new file mode 100644 index 00000000..6386ae4f --- /dev/null +++ b/src/lib/commands/git/add.ts @@ -0,0 +1,236 @@ +import git from 'isomorphic-git'; +import { join } from "@std/path"; +import type { JSRuntimeFS } from "../../JSRuntime"; +import type { ShellCommandResult } from "../ShellCommand"; +import { createSuccessResult, createErrorResult } from "../ShellCommand"; +import type { GitSubcommand } from "../git"; + +export class GitAddCommand implements GitSubcommand { + name = 'add'; + description = 'Add file contents to the index'; + usage = 'git add [--all | -A] [--] [...]'; + + async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise { + try { + // Check if we're in a git repository + try { + await fs.stat(`${cwd}/.git`); + } catch { + return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); + } + + const { options, paths } = this.parseArgs(args); + + if (options.all) { + // Add all files (git add -A) + return await this.addAllFiles(fs, cwd); + } 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(fs, cwd, paths); + } + + } catch (error) { + return createErrorResult(`git add: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private parseArgs(args: string[]): { options: { all: boolean }; paths: string[] } { + const options = { all: false }; + const paths: string[] = []; + let foundDoubleDash = false; + + for (const arg of args) { + if (arg === '--') { + foundDoubleDash = true; + continue; + } + + if (!foundDoubleDash && (arg === '--all' || arg === '-A')) { + options.all = true; + } else if (!foundDoubleDash && arg.startsWith('-')) { + // Ignore other options for now + continue; + } else { + paths.push(arg); + } + } + + return { options, paths }; + } + + private async addAllFiles(fs: JSRuntimeFS, cwd: string): Promise { + try { + // Get status to find all changed files + const statusMatrix = await git.statusMatrix({ + fs, + dir: cwd, + }); + + let addedCount = 0; + let removedCount = 0; + + for (const [filepath, headStatus, workdirStatus] of statusMatrix) { + try { + if (workdirStatus === 0 && headStatus === 1) { + // File was deleted + await git.remove({ + fs, + dir: cwd, + filepath, + }); + removedCount++; + } else if (workdirStatus === 1) { + // File exists (new or modified) + await git.add({ + fs, + dir: cwd, + filepath, + }); + addedCount++; + } + } catch { + // Continue with other files if one fails + console.warn(`Failed to add/remove ${filepath}`); + } + } + + const messages: string[] = []; + if (addedCount > 0) { + messages.push(`Added ${addedCount} file${addedCount !== 1 ? 's' : ''}`); + } + if (removedCount > 0) { + messages.push(`Removed ${removedCount} file${removedCount !== 1 ? 's' : ''}`); + } + + if (messages.length === 0) { + return createSuccessResult(''); + } + + return createSuccessResult(messages.join(', ') + '\n'); + + } catch (error) { + return createErrorResult(`Failed to add all files: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private async addSpecificFiles(fs: JSRuntimeFS, cwd: string, paths: string[]): Promise { + const addedFiles: string[] = []; + const errors: string[] = []; + + for (const path of paths) { + try { + if (path === '.') { + // Add current directory (all files in it) + const statusMatrix = await git.statusMatrix({ + fs, + dir: cwd, + }); + + for (const [filepath, headStatus, workdirStatus] of statusMatrix) { + try { + if (workdirStatus === 0 && headStatus === 1) { + // File was deleted + await git.remove({ + fs, + dir: cwd, + filepath, + }); + addedFiles.push(filepath); + } else if (workdirStatus === 1) { + // File exists + await git.add({ + fs, + dir: cwd, + filepath, + }); + addedFiles.push(filepath); + } + } catch { + // Continue with other files + } + } + } else { + // Handle absolute paths + if (path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path)) { + errors.push(`'${path}': absolute paths are not supported`); + continue; + } + + const absolutePath = join(cwd, path); + + // Check if file/directory exists + try { + const stats = await fs.stat(absolutePath); + + if (stats.isDirectory()) { + // Add all files in directory + await this.addDirectory(fs, cwd, path, addedFiles); + } else { + // Add single file + await git.add({ + fs, + dir: cwd, + filepath: path, + }); + addedFiles.push(path); + } + } catch { + // Check if it's a deleted file + try { + await git.remove({ + fs, + dir: cwd, + filepath: path, + }); + addedFiles.push(path); + } catch { + errors.push(`pathspec '${path}' did not match any files`); + } + } + } + } catch (error) { + errors.push(`'${path}': ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + if (errors.length > 0) { + return createErrorResult(errors.join('\n')); + } + + if (addedFiles.length === 0) { + return createSuccessResult(''); + } + + return createSuccessResult(`Added ${addedFiles.length} file${addedFiles.length !== 1 ? 's' : ''}\n`); + } + + private async addDirectory(fs: JSRuntimeFS, cwd: string, dirPath: string, addedFiles: string[]): Promise { + const absolutePath = join(cwd, dirPath); + const entries = await fs.readdir(absolutePath, { withFileTypes: true }); + + for (const entry of entries) { + if (entry.name.startsWith('.')) { + continue; // Skip hidden files + } + + const entryPath = join(dirPath, entry.name); + + if (entry.isDirectory()) { + await this.addDirectory(fs, cwd, entryPath, addedFiles); + } else { + try { + await git.add({ + fs, + dir: cwd, + filepath: entryPath, + }); + addedFiles.push(entryPath); + } catch { + // Continue with other files + } + } + } + } +} \ No newline at end of file diff --git a/src/lib/commands/git/branch.ts b/src/lib/commands/git/branch.ts new file mode 100644 index 00000000..3f92f677 --- /dev/null +++ b/src/lib/commands/git/branch.ts @@ -0,0 +1,196 @@ +import git from 'isomorphic-git'; +import type { JSRuntimeFS } from "../../JSRuntime"; +import type { ShellCommandResult } from "../ShellCommand"; +import { createSuccessResult, createErrorResult } from "../ShellCommand"; +import type { GitSubcommand } from "../git"; + +export class GitBranchCommand implements GitSubcommand { + name = 'branch'; + description = 'List, create, or delete branches'; + usage = 'git branch [--list] | git branch | git branch (-d | -D) '; + + async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise { + try { + // Check if we're in a git repository + try { + await fs.stat(`${cwd}/.git`); + } catch { + return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); + } + + const { action, branchName, options } = this.parseArgs(args); + + switch (action) { + case 'list': + return await this.listBranches(fs, cwd); + case 'create': + return await this.createBranch(fs, cwd, branchName!); + case 'delete': + return await this.deleteBranch(fs, cwd, branchName!, options.force); + default: + return await this.listBranches(fs, cwd); + } + + } catch (error) { + return createErrorResult(`git branch: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private parseArgs(args: string[]): { + action: 'list' | 'create' | 'delete'; + branchName?: string; + options: { force: boolean } + } { + const options = { force: false }; + let action: 'list' | 'create' | 'delete' = 'list'; + let branchName: string | undefined; + + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + + if (arg === '--list' || arg === '-l') { + action = 'list'; + } 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.startsWith('-')) { + // Branch name for creation + action = 'create'; + branchName = arg; + } + } + + return { action, branchName, options }; + } + + private async listBranches(fs: JSRuntimeFS, cwd: string): Promise { + try { + const branches = await git.listBranches({ + fs, + dir: cwd, + }); + + if (branches.length === 0) { + return createSuccessResult(''); + } + + // Get current branch + let currentBranch: string | null = null; + try { + currentBranch = await git.currentBranch({ + fs, + dir: cwd, + }) || null; + } catch { + // Might be in detached HEAD state + } + + const lines: string[] = []; + for (const branch of branches) { + if (branch === currentBranch) { + lines.push(`* ${branch}`); + } else { + lines.push(` ${branch}`); + } + } + + return createSuccessResult(lines.join('\n') + '\n'); + + } catch (error) { + return createErrorResult(`Failed to list branches: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private async createBranch(fs: JSRuntimeFS, cwd: string, branchName: string): Promise { + try { + // Check if branch already exists + const branches = await git.listBranches({ + fs, + 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; + try { + currentRef = await git.resolveRef({ + fs, + dir: cwd, + ref: 'HEAD', + }); + } catch { + return createErrorResult('fatal: Not a valid object name: \'HEAD\'.'); + } + + // Create the new branch + await git.branch({ + fs, + dir: cwd, + ref: branchName, + object: currentRef, + }); + + return createSuccessResult(''); + + } catch (error) { + return createErrorResult(`Failed to create branch: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private async deleteBranch(fs: JSRuntimeFS, cwd: string, branchName: string, force: boolean): Promise { + try { + // Check if branch exists + const branches = await git.listBranches({ + fs, + dir: cwd, + }); + + if (!branches.includes(branchName)) { + return createErrorResult(`error: branch '${branchName}' not found.`); + } + + // Check if it's the current branch + let currentBranch: string | null = null; + try { + currentBranch = await git.currentBranch({ + fs, + dir: cwd, + }) || null; + } catch { + // Continue + } + + if (currentBranch === branchName) { + return createErrorResult(`error: Cannot delete branch '${branchName}' checked out at '${cwd}'`); + } + + // Delete the branch + await git.deleteBranch({ + fs, + dir: cwd, + ref: branchName, + }); + + return createSuccessResult(`Deleted branch ${branchName}.\n`); + + } catch (error) { + if (!force && error instanceof Error && error.message.includes('not fully merged')) { + return createErrorResult(`error: The branch '${branchName}' is not fully merged.\nIf you are sure you want to delete it, run 'git branch -D ${branchName}'.`); + } + return createErrorResult(`Failed to delete branch: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } +} \ No newline at end of file diff --git a/src/lib/commands/git/checkout.ts b/src/lib/commands/git/checkout.ts new file mode 100644 index 00000000..8346fc84 --- /dev/null +++ b/src/lib/commands/git/checkout.ts @@ -0,0 +1,202 @@ +import git from 'isomorphic-git'; +import type { JSRuntimeFS } from "../../JSRuntime"; +import type { ShellCommandResult } from "../ShellCommand"; +import { createSuccessResult, createErrorResult } from "../ShellCommand"; +import type { GitSubcommand } from "../git"; + +export class GitCheckoutCommand implements GitSubcommand { + name = 'checkout'; + description = 'Switch branches or restore working tree files'; + usage = 'git checkout | git checkout -b | git checkout -- '; + + async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise { + try { + // Check if we're in a git repository + try { + await fs.stat(`${cwd}/.git`); + } catch { + return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); + } + + const { action, target } = this.parseArgs(args); + + switch (action) { + case 'switch': + return await this.switchBranch(fs, cwd, target!); + case 'create': + return await this.createAndSwitchBranch(fs, cwd, target!); + case 'restore': + return await this.restoreFiles(fs, cwd, target!); + default: + return createErrorResult('error: pathspec did not match any file(s) known to git'); + } + + } catch (error) { + return createErrorResult(`git checkout: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private parseArgs(args: string[]): { + action: 'switch' | 'create' | 'restore'; + target?: string; + options: { createBranch: boolean } + } { + const options = { createBranch: false }; + let action: 'switch' | 'create' | 'restore' = 'switch'; + let target: string | undefined; + + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + + 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.startsWith('-')) { + if (!target) { + target = arg; + } + } + } + + return { action, target, options }; + } + + private async switchBranch(fs: JSRuntimeFS, cwd: string, branchName: string): Promise { + try { + // Check if branch exists + const branches = await git.listBranches({ + fs, + dir: cwd, + }); + + if (!branches.includes(branchName)) { + return createErrorResult(`error: pathspec '${branchName}' did not match any file(s) known to git`); + } + + // Get current branch + let currentBranch: string | null = null; + try { + currentBranch = await git.currentBranch({ + fs, + dir: cwd, + }) || null; + } catch { + // Continue + } + + if (currentBranch === branchName) { + return createErrorResult(`Already on '${branchName}'`); + } + + // Check for uncommitted changes + const statusMatrix = await git.statusMatrix({ + fs, + dir: cwd, + }); + + 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.'); + } + + // Switch to the branch + await git.checkout({ + fs, + dir: cwd, + ref: branchName, + }); + + return createSuccessResult(`Switched to branch '${branchName}'\n`); + + } catch (error) { + return createErrorResult(`Failed to switch branch: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private async createAndSwitchBranch(fs: JSRuntimeFS, cwd: string, branchName: string): Promise { + try { + // Check if branch already exists + const branches = await git.listBranches({ + fs, + dir: cwd, + }); + + if (branches.includes(branchName)) { + return createErrorResult(`fatal: A branch named '${branchName}' already exists.`); + } + + // Get current HEAD + let currentRef: string; + try { + currentRef = await git.resolveRef({ + fs, + dir: cwd, + ref: 'HEAD', + }); + } catch { + return createErrorResult('fatal: Not a valid object name: \'HEAD\'.'); + } + + // Create the branch + await git.branch({ + fs, + dir: cwd, + ref: branchName, + object: currentRef, + }); + + // Switch to the new branch + await git.checkout({ + fs, + dir: cwd, + ref: branchName, + }); + + return createSuccessResult(`Switched to a new branch '${branchName}'\n`); + + } catch (error) { + return createErrorResult(`Failed to create and switch branch: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private async restoreFiles(fs: JSRuntimeFS, cwd: string, filePath: 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 + try { + await git.checkout({ + fs, + dir: cwd, + ref: 'HEAD', + filepaths: [filePath], + }); + + 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`); + } + throw error; + } + + } catch (error) { + return createErrorResult(`Failed to restore file: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } +} \ No newline at end of file diff --git a/src/lib/commands/git/clone.ts b/src/lib/commands/git/clone.ts new file mode 100644 index 00000000..887e66ec --- /dev/null +++ b/src/lib/commands/git/clone.ts @@ -0,0 +1,116 @@ +import git from 'isomorphic-git'; +import http from 'isomorphic-git/http/web'; +import type { JSRuntimeFS } from "../../JSRuntime"; +import type { ShellCommandResult } from "../ShellCommand"; +import { createSuccessResult, createErrorResult } from "../ShellCommand"; +import type { GitSubcommand } from "../git"; + +export class GitCloneCommand implements GitSubcommand { + name = 'clone'; + description = 'Clone a repository into a new directory'; + usage = 'git clone [--depth ] [--single-branch] []'; + + async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise { + try { + const { options, repository, directory } = this.parseArgs(args); + + if (!repository) { + return createErrorResult('fatal: You must specify a repository to clone.'); + } + + // Determine the target directory + let targetDir = directory; + if (!targetDir) { + // Extract repository name from URL + const urlParts = repository.split('/'); + const repoName = urlParts[urlParts.length - 1]; + targetDir = repoName.replace(/\.git$/, ''); // Remove .git suffix if present + } + + const targetPath = `${cwd}/${targetDir}`; + + // Check if target directory already exists + try { + await fs.stat(targetPath); + return createErrorResult(`fatal: destination path '${targetDir}' already exists and is not an empty directory.`); + } catch { + // Directory doesn't exist, which is what we want + } + + // Parse URL to determine if we need CORS proxy + let url: URL; + try { + url = new URL(repository); + } catch { + return createErrorResult(`fatal: repository '${repository}' does not appear to be a git repository`); + } + + // Clone the repository + await git.clone({ + fs, + http, + dir: targetPath, + url: repository, + singleBranch: options.singleBranch, + depth: options.depth, + corsProxy: (url.hostname === 'github.com' || url.hostname === 'gitlab.com') + ? 'https://cors.isomorphic-git.org' + : undefined, + }); + + return createSuccessResult(`Cloning into '${targetDir}'...\ndone.\n`); + + } catch (error) { + if (error instanceof Error) { + if (error.message.includes('authentication')) { + return createErrorResult('fatal: Authentication failed. Repository may be private or credentials are required.'); + } else if (error.message.includes('network')) { + return createErrorResult('fatal: unable to access repository. Please check your network connection.'); + } else if (error.message.includes('not found')) { + return createErrorResult('fatal: repository not found.'); + } + } + + return createErrorResult(`git clone: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private parseArgs(args: string[]): { + options: { depth?: number; singleBranch: boolean }; + repository?: string; + directory?: string + } { + const options: { depth?: number; singleBranch: boolean } = { singleBranch: false }; + let repository: string | undefined; + let directory: string | undefined; + + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + + if (arg === '--depth') { + if (i + 1 < args.length) { + const depth = parseInt(args[i + 1], 10); + if (!isNaN(depth) && depth > 0) { + options.depth = depth; + } + i++; // Skip next argument + } + } else if (arg.startsWith('--depth=')) { + const depth = parseInt(arg.substring(8), 10); + if (!isNaN(depth) && depth > 0) { + options.depth = depth; + } + } else if (arg === '--single-branch') { + options.singleBranch = true; + } else if (!arg.startsWith('-')) { + if (!repository) { + repository = arg; + } else if (!directory) { + directory = arg; + } + } + } + + return { options, repository, directory }; + } +} \ No newline at end of file diff --git a/src/lib/commands/git/commit.ts b/src/lib/commands/git/commit.ts new file mode 100644 index 00000000..1e5e1f0a --- /dev/null +++ b/src/lib/commands/git/commit.ts @@ -0,0 +1,194 @@ +import git from 'isomorphic-git'; +import type { JSRuntimeFS } from "../../JSRuntime"; +import type { ShellCommandResult } from "../ShellCommand"; +import { createSuccessResult, createErrorResult } from "../ShellCommand"; +import type { GitSubcommand } from "../git"; + +export class GitCommitCommand implements GitSubcommand { + name = 'commit'; + description = 'Record changes to the repository'; + usage = 'git commit [-m ] [--amend] [--allow-empty]'; + + async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise { + try { + // Check if we're in a git repository + try { + await fs.stat(`${cwd}/.git`); + } catch { + return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); + } + + const { options, message } = this.parseArgs(args); + + if (!message && !options.amend) { + return createErrorResult('Aborting commit due to empty commit message.'); + } + + // Get current status + const statusMatrix = await git.statusMatrix({ + fs, + dir: cwd, + }); + + // Check for staged changes + const stagedFiles = statusMatrix.filter(([, headStatus, , stageStatus]) => { + return headStatus !== stageStatus; + }); + + if (stagedFiles.length === 0 && !options.allowEmpty && !options.amend) { + return createErrorResult('nothing to commit, working tree clean'); + } + + // Get author info + const author = { + name: 'shakespeare.diy', + email: 'assistant@shakespeare.diy', + }; + + try { + const configName = await git.getConfig({ + fs, + dir: cwd, + path: 'user.name', + }); + const configEmail = await git.getConfig({ + fs, + dir: cwd, + path: 'user.email', + }); + if (configName) author.name = configName; + if (configEmail) author.email = configEmail; + } catch { + // Use defaults + } + + let commitMessage = message; + if (options.amend) { + // Get the last commit message if amending + try { + const commits = await git.log({ + fs, + dir: cwd, + depth: 1, + }); + if (commits.length > 0 && !message) { + commitMessage = commits[0].commit.message; + } + } catch { + // If we can't get the last commit, use the provided message or default + if (!commitMessage) { + commitMessage = 'Amended commit'; + } + } + } + + // Get current branch + let currentBranch = 'main'; + try { + currentBranch = await git.currentBranch({ + fs, + dir: cwd, + }) || 'main'; + } catch { + // Use default + } + + // Create the commit + const commitOptions: { + fs: JSRuntimeFS; + dir: string; + message: string; + author: { name: string; email: string }; + committer: { name: string; email: string }; + parent?: string[]; + } = { + fs, + dir: cwd, + message: commitMessage || 'Empty commit', + author, + committer: author, + }; + + if (options.amend) { + // For amend, we need to reset to the parent of the current commit + try { + const commits = await git.log({ + fs, + dir: cwd, + depth: 2, + }); + if (commits.length > 1) { + commitOptions.parent = [commits[1].oid]; + } + } catch { + // If we can't get parent, proceed without amending + } + } + + const commitSha = await git.commit(commitOptions); + + // Get short hash + const shortHash = commitSha.substring(0, 7); + + // Count changes + const addedFiles = stagedFiles.filter(([, headStatus, , stageStatus]) => + headStatus === 0 && stageStatus === 1 + ).length; + + const modifiedFiles = stagedFiles.filter(([, headStatus, , stageStatus]) => + headStatus === 1 && stageStatus === 1 + ).length; + + const deletedFiles = stagedFiles.filter(([, headStatus, , stageStatus]) => + headStatus === 1 && stageStatus === 0 + ).length; + + const totalFiles = stagedFiles.length; + + let result = `[${currentBranch} ${shortHash}] ${commitMessage}\n`; + + if (totalFiles > 0) { + const changes: string[] = []; + if (addedFiles > 0) changes.push(`${addedFiles} file${addedFiles !== 1 ? 's' : ''} added`); + if (modifiedFiles > 0) changes.push(`${modifiedFiles} file${modifiedFiles !== 1 ? 's' : ''} changed`); + if (deletedFiles > 0) changes.push(`${deletedFiles} file${deletedFiles !== 1 ? 's' : ''} deleted`); + + result += ` ${changes.join(', ')}\n`; + } + + return createSuccessResult(result); + + } catch (error) { + return createErrorResult(`git commit: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private parseArgs(args: string[]): { + options: { amend: boolean; allowEmpty: boolean }; + message?: string + } { + const options = { amend: false, allowEmpty: false }; + let message: string | undefined; + + 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]; + i++; // Skip next argument as it's the message + } + } else if (arg.startsWith('-m=')) { + message = arg.substring(3); + } else if (arg.startsWith('--message=')) { + message = arg.substring(10); + } else if (arg === '--amend') { + options.amend = true; + } else if (arg === '--allow-empty') { + options.allowEmpty = true; + } + } + + return { options, message }; + } +} \ No newline at end of file diff --git a/src/lib/commands/git/config.ts b/src/lib/commands/git/config.ts new file mode 100644 index 00000000..9273b397 --- /dev/null +++ b/src/lib/commands/git/config.ts @@ -0,0 +1,143 @@ +import git from 'isomorphic-git'; +import type { JSRuntimeFS } from "../../JSRuntime"; +import type { ShellCommandResult } from "../ShellCommand"; +import { createSuccessResult, createErrorResult } from "../ShellCommand"; +import type { GitSubcommand } from "../git"; + +export class GitConfigCommand implements GitSubcommand { + name = 'config'; + description = 'Get and set repository or global options'; + usage = 'git config [--global] [] | git config [--global] --list'; + + async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise { + try { + const { action, key, value, options } = this.parseArgs(args); + + // Check if we're in a git repository (unless --global is used) + if (!options.global) { + try { + await fs.stat(`${cwd}/.git`); + } catch { + return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); + } + } + + switch (action) { + case 'list': + return await this.listConfig(fs, cwd, options.global); + case 'get': + return await this.getConfig(fs, cwd, key!, options.global); + case 'set': + return await this.setConfig(fs, cwd, key!, value!, options.global); + default: + return createErrorResult('usage: git config [--global] [] | git config [--global] --list'); + } + + } catch (error) { + return createErrorResult(`git config: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private parseArgs(args: string[]): { + action: 'list' | 'get' | 'set'; + key?: string; + value?: string; + options: { global: boolean } + } { + const options = { global: false }; + let action: 'list' | 'get' | 'set' = 'get'; + let key: string | undefined; + let value: string | undefined; + + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + + if (arg === '--global') { + options.global = true; + } else if (arg === '--list' || arg === '-l') { + action = 'list'; + } else if (!arg.startsWith('-')) { + if (!key) { + key = arg; + action = 'get'; // Default to get if only key is provided + } else if (!value) { + value = arg; + action = 'set'; // Set if both key and value are provided + } + } + } + + return { action, key, value, options }; + } + + private async listConfig(fs: JSRuntimeFS, cwd: string, global: boolean): Promise { + 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 lines: string[] = []; + + for (const key of commonKeys) { + try { + const value = await git.getConfig({ + fs, + dir: global ? undefined : cwd, + path: key, + }); + if (value !== undefined) { + lines.push(`${key}=${value}`); + } + } catch { + // Skip if config doesn't exist + } + } + + return createSuccessResult(lines.join('\n') + (lines.length > 0 ? '\n' : '')); + + } catch (error) { + return createErrorResult(`Failed to list config: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private async getConfig(fs: JSRuntimeFS, cwd: string, key: string, global: boolean): Promise { + try { + const value = await git.getConfig({ + fs, + dir: global ? undefined : cwd, + path: key, + }); + + if (value === undefined) { + return createErrorResult(`error: key does not exist: ${key}`); + } + + return createSuccessResult(value + '\n'); + + } catch (error) { + return createErrorResult(`Failed to get config: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private async setConfig(fs: JSRuntimeFS, cwd: string, key: string, value: string, global: boolean): Promise { + try { + await git.setConfig({ + fs, + dir: global ? undefined : cwd, + path: key, + value: value, + }); + + return createSuccessResult(''); + + } catch (error) { + return createErrorResult(`Failed to set config: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } +} \ No newline at end of file diff --git a/src/lib/commands/git/diff.ts b/src/lib/commands/git/diff.ts new file mode 100644 index 00000000..23370480 --- /dev/null +++ b/src/lib/commands/git/diff.ts @@ -0,0 +1,206 @@ +import git from 'isomorphic-git'; +import type { JSRuntimeFS } from "../../JSRuntime"; +import type { ShellCommandResult } from "../ShellCommand"; +import { createSuccessResult, createErrorResult } from "../ShellCommand"; +import type { GitSubcommand } from "../git"; + +export class GitDiffCommand implements GitSubcommand { + name = 'diff'; + description = 'Show changes between commits, commit and working tree, etc'; + usage = 'git diff [] [] [-- ...]'; + + async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise { + try { + // Check if we're in a git repository + try { + await fs.stat(`${cwd}/.git`); + } catch { + return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); + } + + const { commits, paths } = this.parseArgs(args); + + if (commits.length === 0) { + // Show working directory changes vs index + return await this.showWorkingDirectoryDiff(fs, cwd, paths); + } else if (commits.length === 1) { + // Show changes between commit and working directory + return await this.showCommitDiff(fs, cwd, commits[0], paths); + } else if (commits.length === 2) { + // Show changes between two commits + return await this.showCommitRangeDiff(fs, cwd, commits[0], commits[1], paths); + } else { + return createErrorResult('usage: git diff [] [] [-- ...]'); + } + + } catch (error) { + return createErrorResult(`git diff: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private parseArgs(args: string[]): { + commits: string[]; + paths: string[]; + options: { cached: boolean; staged: boolean } + } { + const options = { cached: false, staged: false }; + const commits: string[] = []; + const paths: string[] = []; + let foundDoubleDash = false; + + for (const arg of args) { + if (arg === '--') { + foundDoubleDash = true; + continue; + } + + if (foundDoubleDash) { + 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 + commits.push(arg); + } + } + + return { commits, paths, options }; + } + + private async showWorkingDirectoryDiff(fs: JSRuntimeFS, cwd: string, paths: string[]): Promise { + try { + // Get status to find changed files + const statusMatrix = await git.statusMatrix({ + fs, + dir: cwd, + }); + + // Filter for modified files in working directory + const modifiedFiles = statusMatrix.filter(([filepath, headStatus, workdirStatus, stageStatus]) => { + const isModified = workdirStatus === 1 && stageStatus === 1 && headStatus !== workdirStatus; + if (paths.length > 0) { + return isModified && paths.some(path => filepath.includes(path)); + } + return isModified; + }); + + if (modifiedFiles.length === 0) { + return createSuccessResult(''); + } + + const diffLines: string[] = []; + + for (const [filepath] of modifiedFiles) { + try { + // Get file content from HEAD + let headContent = ''; + try { + const headBlob = await git.readBlob({ + fs, + dir: cwd, + oid: 'HEAD', + filepath, + }); + headContent = new TextDecoder().decode(headBlob.blob); + } catch { + // File might be new + } + + // Get file content from working directory + let workdirContent = ''; + try { + workdirContent = await fs.readFile(`${cwd}/${filepath}`, 'utf8'); + } catch { + // File might be deleted + } + + // Simple diff representation + diffLines.push(`diff --git a/${filepath} b/${filepath}`); + diffLines.push(`index ${this.getShortHash(headContent)}..${this.getShortHash(workdirContent)} 100644`); + diffLines.push(`--- a/${filepath}`); + diffLines.push(`+++ b/${filepath}`); + + // Show a simplified diff + const headLines = headContent.split('\n'); + const workdirLines = workdirContent.split('\n'); + + diffLines.push(`@@ -1,${headLines.length} +1,${workdirLines.length} @@`); + + // Show removed lines + for (const line of headLines) { + if (!workdirLines.includes(line)) { + diffLines.push(`-${line}`); + } + } + + // Show added lines + for (const line of workdirLines) { + if (!headLines.includes(line)) { + diffLines.push(`+${line}`); + } + } + + diffLines.push(''); + } catch { + // Skip files that can't be diffed + } + } + + return createSuccessResult(diffLines.join('\n')); + + } catch (error) { + return createErrorResult(`Failed to show diff: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private async showCommitDiff(fs: JSRuntimeFS, cwd: string, commit: string, _paths: string[]): Promise { + try { + // For simplicity, show the commit message and changed files + const commits = await git.log({ + fs, + dir: cwd, + depth: 1, + ref: commit, + }); + + 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(_fs: JSRuntimeFS, _cwd: string, _commit1: string, _commit2: string, _paths: string[]): Promise { + // This would require complex implementation to compare two commits + return createErrorResult('Commit range diff is not implemented in this git command'); + } + + private getShortHash(content: 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 + } + return Math.abs(hash).toString(16).substring(0, 7).padStart(7, '0'); + } +} \ No newline at end of file diff --git a/src/lib/commands/git/init.ts b/src/lib/commands/git/init.ts new file mode 100644 index 00000000..c2a6f8fb --- /dev/null +++ b/src/lib/commands/git/init.ts @@ -0,0 +1,84 @@ +import git from 'isomorphic-git'; +import type { JSRuntimeFS } from "../../JSRuntime"; +import type { ShellCommandResult } from "../ShellCommand"; +import { createSuccessResult, createErrorResult } from "../ShellCommand"; +import type { GitSubcommand } from "../git"; + +export class GitInitCommand implements GitSubcommand { + name = 'init'; + description = 'Create an empty Git repository or reinitialize an existing one'; + usage = 'git init [--bare] []'; + + async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise { + try { + // Parse arguments + const { options, directory } = this.parseArgs(args); + const targetDir = directory || cwd; + + // Check if directory exists, create if needed + if (directory) { + try { + await fs.stat(targetDir); + } catch { + // Directory doesn't exist, create it + await fs.mkdir(targetDir, { recursive: true }); + } + } + + // Check if already a git repository + try { + await fs.stat(`${targetDir}/.git`); + return createSuccessResult(`Reinitialized existing Git repository in ${targetDir}/.git/\n`); + } catch { + // Not a git repository, proceed with initialization + } + + // Initialize the repository + await git.init({ + fs, + dir: targetDir, + bare: options.bare, + defaultBranch: 'main' + }); + + // Set up basic configuration + await git.setConfig({ + fs, + dir: targetDir, + path: 'user.name', + value: 'shakespeare.diy' + }); + + await git.setConfig({ + fs, + dir: targetDir, + path: 'user.email', + value: 'assistant@shakespeare.diy' + }); + + const message = options.bare + ? `Initialized empty Git repository in ${targetDir}/\n` + : `Initialized empty Git repository in ${targetDir}/.git/\n`; + + return createSuccessResult(message); + + } catch (error) { + return createErrorResult(`git init: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private parseArgs(args: string[]): { options: { bare: boolean }; directory?: string } { + const options = { bare: false }; + let directory: string | undefined; + + for (const arg of args) { + if (arg === '--bare') { + options.bare = true; + } else if (!arg.startsWith('-')) { + directory = arg; + } + } + + return { options, directory }; + } +} \ No newline at end of file diff --git a/src/lib/commands/git/log.ts b/src/lib/commands/git/log.ts new file mode 100644 index 00000000..acfcd501 --- /dev/null +++ b/src/lib/commands/git/log.ts @@ -0,0 +1,148 @@ +import git from 'isomorphic-git'; +import type { JSRuntimeFS } from "../../JSRuntime"; +import type { ShellCommandResult } from "../ShellCommand"; +import { createSuccessResult, createErrorResult } from "../ShellCommand"; +import type { GitSubcommand } from "../git"; + +export class GitLogCommand implements GitSubcommand { + name = 'log'; + description = 'Show commit logs'; + usage = 'git log [--oneline] [--graph] [-n ] [..]'; + + async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise { + try { + // Check if we're in a git repository + try { + await fs.stat(`${cwd}/.git`); + } catch { + return createErrorError('fatal: not a git repository (or any of the parent directories): .git'); + } + + const { options, limit } = this.parseArgs(args); + + try { + const commits = await git.log({ + fs, + dir: cwd, + depth: limit, + }); + + if (commits.length === 0) { + return createErrorResult('fatal: your current branch does not have any commits yet'); + } + + if (options.oneline) { + return this.formatOnelineLog(commits); + } else { + return this.formatFullLog(commits, options.graph); + } + + } catch (error) { + if (error instanceof Error && error.message.includes('does not exist')) { + return createErrorResult('fatal: your current branch does not have any commits yet'); + } + throw error; + } + + } catch (error) { + return createErrorResult(`git log: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private parseArgs(args: string[]): { + options: { oneline: boolean; graph: boolean }; + limit: number + } { + const options = { oneline: false, graph: false }; + let limit = 50; // Default limit + + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + + if (arg === '--oneline') { + options.oneline = true; + } else if (arg === '--graph') { + options.graph = true; + } 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 + } + } else if (arg.startsWith('-n=')) { + const num = parseInt(arg.substring(3), 10); + if (!isNaN(num) && num > 0) { + limit = num; + } + } else if (arg.startsWith('--max-count=')) { + const num = parseInt(arg.substring(12), 10); + if (!isNaN(num) && num > 0) { + 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; + } + } + } + + return { options, limit }; + } + + private formatOnelineLog(commits: Array<{ oid: string; commit: { message: string } }>): ShellCommandResult { + const lines: string[] = []; + + for (const commit of commits) { + const shortHash = commit.oid.substring(0, 7); + const message = commit.commit.message.split('\n')[0]; // First line only + lines.push(`${shortHash} ${message}`); + } + + return createSuccessResult(lines.join('\n') + '\n'); + } + + private formatFullLog(commits: Array<{ oid: string; commit: { message: string; author: { name: string; email: string; timestamp: number } } }>, showGraph: boolean): ShellCommandResult { + const lines: string[] = []; + + for (let i = 0; i < commits.length; i++) { + const commit = commits[i]; + const isLast = i === commits.length - 1; + + if (showGraph) { + lines.push('* commit ' + commit.oid); + } else { + lines.push('commit ' + commit.oid); + } + + // Author information + 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(''); + + // Commit message (indented) + const messageLines = commit.commit.message.split('\n'); + for (const messageLine of messageLines) { + lines.push(` ${messageLine}`); + } + + if (!isLast) { + lines.push(''); + } + } + + return createSuccessResult(lines.join('\n') + '\n'); + } +} + +// Fix the typo in the error function +function createErrorError(message: string): ShellCommandResult { + return createErrorResult(message); +} \ No newline at end of file diff --git a/src/lib/commands/git/pull.ts b/src/lib/commands/git/pull.ts new file mode 100644 index 00000000..419af798 --- /dev/null +++ b/src/lib/commands/git/pull.ts @@ -0,0 +1,171 @@ +import git from 'isomorphic-git'; +import http from 'isomorphic-git/http/web'; +import type { JSRuntimeFS } from "../../JSRuntime"; +import type { ShellCommandResult } from "../ShellCommand"; +import { createSuccessResult, createErrorResult } from "../ShellCommand"; +import type { GitSubcommand } from "../git"; + +export class GitPullCommand implements GitSubcommand { + name = 'pull'; + description = 'Fetch from and integrate with another repository or a local branch'; + usage = 'git pull [] []'; + + async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise { + try { + // Check if we're in a git repository + try { + await fs.stat(`${cwd}/.git`); + } catch { + return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); + } + + const { remote, branch } = this.parseArgs(args); + + // Get current branch if not specified + let targetBranch = branch; + let currentBranch: string | null = null; + try { + currentBranch = await git.currentBranch({ + fs, + dir: cwd, + }) || null; + if (!targetBranch) { + targetBranch = currentBranch || 'main'; + } + } catch { + if (!targetBranch) { + targetBranch = 'main'; + } + } + + // Get remote URL + let remoteUrl: string; + try { + const remotes = await git.listRemotes({ + fs, + dir: cwd, + }); + + const targetRemote = remotes.find(r => r.remote === remote); + if (!targetRemote) { + return createErrorResult(`fatal: '${remote}' does not appear to be a git repository`); + } + remoteUrl = targetRemote.url; + } catch { + return createErrorResult(`fatal: '${remote}' does not appear to be a git repository`); + } + + // Check for uncommitted changes + const statusMatrix = await git.statusMatrix({ + fs, + dir: cwd, + }); + + 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 merge:\nPlease commit your changes or stash them before you merge.'); + } + + try { + // Fetch from remote + await git.fetch({ + fs, + http, + dir: cwd, + remote: remote, + ref: targetBranch, + corsProxy: 'https://cors.isomorphic-git.org', + }); + + // Get the remote ref + const remoteRef = `refs/remotes/${remote}/${targetBranch}`; + let remoteOid: string; + try { + remoteOid = await git.resolveRef({ + fs, + dir: cwd, + ref: remoteRef, + }); + } catch { + return createErrorResult(`fatal: couldn't find remote ref ${targetBranch}`); + } + + // Get current HEAD + let currentOid: string; + try { + currentOid = await git.resolveRef({ + fs, + dir: cwd, + ref: 'HEAD', + }); + } catch { + // Empty repository, just checkout the remote branch + await git.checkout({ + fs, + dir: cwd, + ref: targetBranch, + }); + return createSuccessResult(`From ${remoteUrl}\n * branch ${targetBranch} -> FETCH_HEAD\nUpdating empty repository\nFast-forward\n`); + } + + // Check if already up to date + if (currentOid === remoteOid) { + return createSuccessResult('Already up to date.\n'); + } + + // Perform fast-forward merge (simplified) + await git.merge({ + fs, + dir: cwd, + ours: currentBranch || 'HEAD', + theirs: remoteRef, + fastForwardOnly: true, + }); + + return createSuccessResult(`From ${remoteUrl}\n ${currentOid.substring(0, 7)}..${remoteOid.substring(0, 7)} ${targetBranch} -> ${remote}/${targetBranch}\nUpdating ${currentOid.substring(0, 7)}..${remoteOid.substring(0, 7)}\nFast-forward\n`); + + } catch (error) { + if (error instanceof Error) { + if (error.message.includes('authentication')) { + return createErrorResult('fatal: Authentication failed. Please configure git credentials.'); + } else if (error.message.includes('network')) { + return createErrorResult('fatal: unable to access remote repository. Please check your network connection.'); + } else if (error.message.includes('merge conflict')) { + return createErrorResult('error: Merge conflict detected. Please resolve conflicts manually.'); + } else if (error.message.includes('fast-forward')) { + return createErrorResult('fatal: Not possible to fast-forward, aborting.'); + } + } + + return createErrorResult(`Failed to pull: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + + } catch (error) { + return createErrorResult(`git pull: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private parseArgs(args: string[]): { remote: string; branch?: string } { + let remote = 'origin'; // Default remote + let branch: string | undefined; + + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + + if (!arg.startsWith('-')) { + if (remote === 'origin' && !branch) { + // First non-option argument is remote + remote = arg; + } else if (!branch) { + // Second non-option argument is branch + branch = arg; + } + } + } + + return { remote, branch }; + } +} \ No newline at end of file diff --git a/src/lib/commands/git/push.ts b/src/lib/commands/git/push.ts new file mode 100644 index 00000000..52a68a91 --- /dev/null +++ b/src/lib/commands/git/push.ts @@ -0,0 +1,118 @@ +import git from 'isomorphic-git'; +import http from 'isomorphic-git/http/web'; +import type { JSRuntimeFS } from "../../JSRuntime"; +import type { ShellCommandResult } from "../ShellCommand"; +import { createSuccessResult, createErrorResult } from "../ShellCommand"; +import type { GitSubcommand } from "../git"; + +export class GitPushCommand implements GitSubcommand { + name = 'push'; + description = 'Update remote refs along with associated objects'; + usage = 'git push [] []'; + + async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise { + try { + // Check if we're in a git repository + try { + await fs.stat(`${cwd}/.git`); + } catch { + return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); + } + + const { remote, branch } = this.parseArgs(args); + + // Get current branch if not specified + let targetBranch = branch; + if (!targetBranch) { + try { + targetBranch = await git.currentBranch({ + fs, + dir: cwd, + }) || undefined; + if (!targetBranch) { + return createErrorResult('fatal: You are not currently on a branch.'); + } + } catch { + return createErrorResult('fatal: You are not currently on a branch.'); + } + } + + // Get remote URL + let remoteUrl: string; + try { + const remotes = await git.listRemotes({ + fs, + dir: cwd, + }); + + const targetRemote = remotes.find(r => r.remote === remote); + if (!targetRemote) { + return createErrorResult(`fatal: '${remote}' does not appear to be a git repository`); + } + remoteUrl = targetRemote.url; + } catch { + return createErrorResult(`fatal: '${remote}' does not appear to be a git repository`); + } + + try { + await git.push({ + fs, + http, + dir: cwd, + remote: remote, + ref: targetBranch, + remoteRef: targetBranch, + corsProxy: 'https://cors.isomorphic-git.org', + }); + + return createSuccessResult(`To ${remoteUrl}\n ${targetBranch} -> ${targetBranch}\n`); + + } catch (error) { + if (error instanceof Error) { + if (error.message.includes('authentication')) { + return createErrorResult('fatal: Authentication failed. Please configure git credentials.'); + } else if (error.message.includes('rejected')) { + return createErrorResult(`error: failed to push some refs to '${remoteUrl}'\nhint: Updates were rejected because the remote contains work that you do not have locally.`); + } else if (error.message.includes('network')) { + return createErrorResult('fatal: unable to access remote repository. Please check your network connection.'); + } + } + + return createErrorResult(`Failed to push: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + + } catch (error) { + return createErrorResult(`git push: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private parseArgs(args: string[]): { + remote: string; + branch?: string; + options: { force: boolean; setUpstream: boolean } + } { + const options = { force: false, setUpstream: false }; + let remote = 'origin'; // Default remote + let branch: string | undefined; + + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + + if (arg === '--force' || arg === '-f') { + options.force = true; + } else if (arg === '--set-upstream' || arg === '-u') { + options.setUpstream = true; + } else if (!arg.startsWith('-')) { + if (remote === 'origin' && !branch) { + // First non-option argument is remote + remote = arg; + } else if (!branch) { + // Second non-option argument is branch + branch = arg; + } + } + } + + return { remote, branch, options }; + } +} \ No newline at end of file diff --git a/src/lib/commands/git/remote.ts b/src/lib/commands/git/remote.ts new file mode 100644 index 00000000..ad8302aa --- /dev/null +++ b/src/lib/commands/git/remote.ts @@ -0,0 +1,178 @@ +import git from 'isomorphic-git'; +import type { JSRuntimeFS } from "../../JSRuntime"; +import type { ShellCommandResult } from "../ShellCommand"; +import { createSuccessResult, createErrorResult } from "../ShellCommand"; +import type { GitSubcommand } from "../git"; + +export class GitRemoteCommand implements GitSubcommand { + name = 'remote'; + description = 'Manage set of tracked repositories'; + usage = 'git remote [-v] | git remote add | git remote remove '; + + async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise { + try { + // Check if we're in a git repository + try { + await fs.stat(`${cwd}/.git`); + } catch { + return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); + } + + const { action, name, url, options } = this.parseArgs(args); + + switch (action) { + case 'list': + return await this.listRemotes(fs, cwd, options.verbose); + case 'add': + return await this.addRemote(fs, cwd, name!, url!); + case 'remove': + return await this.removeRemote(fs, cwd, name!); + default: + return await this.listRemotes(fs, cwd, options.verbose); + } + + } catch (error) { + return createErrorResult(`git remote: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private parseArgs(args: string[]): { + action: 'list' | 'add' | 'remove'; + name?: string; + url?: string; + options: { verbose: boolean } + } { + const options = { verbose: false }; + let action: 'list' | 'add' | 'remove' = 'list'; + let name: string | undefined; + let url: string | undefined; + + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + + if (arg === '-v' || arg === '--verbose') { + 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++; + } + } else if (arg === 'remove' || arg === 'rm') { + action = 'remove'; + if (i + 1 < args.length) { + name = args[i + 1]; + i++; + } + } + } + + return { action, name, url, options }; + } + + private async listRemotes(fs: JSRuntimeFS, cwd: string, verbose: boolean): Promise { + try { + const remotes = await git.listRemotes({ + fs, + dir: cwd, + }); + + if (remotes.length === 0) { + return createSuccessResult(''); + } + + const lines: string[] = []; + + if (verbose) { + for (const remote of remotes) { + lines.push(`${remote.remote}\t${remote.url} (fetch)`); + lines.push(`${remote.remote}\t${remote.url} (push)`); + } + } else { + for (const remote of remotes) { + lines.push(remote.remote); + } + } + + return createSuccessResult(lines.join('\n') + (lines.length > 0 ? '\n' : '')); + + } catch (error) { + return createErrorResult(`Failed to list remotes: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private async addRemote(fs: JSRuntimeFS, cwd: string, name: string, url: string): Promise { + try { + if (!name || !url) { + return createErrorResult('usage: git remote add '); + } + + // Check if remote already exists + try { + const remotes = await git.listRemotes({ + fs, + dir: cwd, + }); + + const existingRemote = remotes.find(r => r.remote === name); + if (existingRemote) { + return createErrorResult(`fatal: remote ${name} already exists.`); + } + } catch { + // Continue if we can't list remotes + } + + // Add the remote + await git.addRemote({ + fs, + dir: cwd, + remote: name, + url: url, + }); + + return createSuccessResult(''); + + } catch (error) { + return createErrorResult(`Failed to add remote: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private async removeRemote(fs: JSRuntimeFS, cwd: string, name: string): Promise { + try { + if (!name) { + return createErrorResult('usage: git remote remove '); + } + + // Check if remote exists + try { + const remotes = await git.listRemotes({ + fs, + dir: cwd, + }); + + const existingRemote = remotes.find(r => r.remote === name); + if (!existingRemote) { + return createErrorResult(`fatal: No such remote: ${name}`); + } + } catch { + return createErrorResult(`fatal: No such remote: ${name}`); + } + + // Remove the remote + await git.deleteRemote({ + fs, + dir: cwd, + remote: name, + }); + + return createSuccessResult(''); + + } catch (error) { + return createErrorResult(`Failed to remove remote: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } +} \ No newline at end of file diff --git a/src/lib/commands/git/reset.ts b/src/lib/commands/git/reset.ts new file mode 100644 index 00000000..b007d454 --- /dev/null +++ b/src/lib/commands/git/reset.ts @@ -0,0 +1,176 @@ +import git from 'isomorphic-git'; +import type { JSRuntimeFS } from "../../JSRuntime"; +import type { ShellCommandResult } from "../ShellCommand"; +import { createSuccessResult, createErrorResult } from "../ShellCommand"; +import type { GitSubcommand } from "../git"; + +export class GitResetCommand implements GitSubcommand { + name = 'reset'; + description = 'Reset current HEAD to the specified state'; + usage = 'git reset [--soft | --mixed | --hard] [] | git reset HEAD [...]'; + + async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise { + try { + // Check if we're in a git repository + try { + await fs.stat(`${cwd}/.git`); + } catch { + return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); + } + + const { mode, target, files } = this.parseArgs(args); + + if (files.length > 0) { + // Reset specific files (unstage) + return await this.resetFiles(fs, cwd, files); + } else { + // Reset to commit + return await this.resetToCommit(fs, cwd, target, mode); + } + + } catch (error) { + return createErrorResult(`git reset: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private parseArgs(args: string[]): { + mode: 'soft' | 'mixed' | 'hard'; + target: string; + files: string[] + } { + let mode: 'soft' | 'mixed' | 'hard' = 'mixed'; // Default mode + let target = 'HEAD'; // Default target + const files: string[] = []; + let foundTarget = false; + + for (const arg of args) { + if (arg === '--soft') { + mode = 'soft'; + } else if (arg === '--mixed') { + mode = 'mixed'; + } else if (arg === '--hard') { + mode = 'hard'; + } else if (!arg.startsWith('-')) { + if (!foundTarget && (arg === 'HEAD' || arg.match(/^[a-f0-9]{7,40}$/))) { + target = arg; + foundTarget = true; + } else { + files.push(arg); + } + } + } + + return { mode, target, files }; + } + + private async resetFiles(fs: JSRuntimeFS, cwd: string, files: string[]): Promise { + try { + const resetFiles: string[] = []; + const errors: string[] = []; + + for (const file of files) { + try { + // Remove from staging area (reset to HEAD) + await git.resetIndex({ + fs, + dir: cwd, + filepath: file, + }); + resetFiles.push(file); + } catch { + errors.push(`error: pathspec '${file}' did not match any file(s) known to git`); + } + } + + if (errors.length > 0) { + return createErrorResult(errors.join('\n')); + } + + if (resetFiles.length === 0) { + return createSuccessResult(''); + } + + return createSuccessResult(`Unstaged changes after reset:\n${resetFiles.map(f => `M\t${f}`).join('\n')}\n`); + + } catch (error) { + return createErrorResult(`Failed to reset files: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private async resetToCommit(fs: JSRuntimeFS, cwd: string, target: string, mode: 'soft' | 'mixed' | 'hard'): Promise { + try { + // Resolve the target commit + let targetOid: string; + try { + targetOid = await git.resolveRef({ + fs, + dir: cwd, + ref: target, + }); + } catch { + return createErrorResult(`fatal: ambiguous argument '${target}': unknown revision or path not in the working tree.`); + } + + // Get current HEAD for comparison + let currentOid: string; + try { + currentOid = await git.resolveRef({ + fs, + dir: cwd, + ref: 'HEAD', + }); + } catch { + return createErrorResult('fatal: Failed to resolve HEAD'); + } + + if (currentOid === targetOid) { + return createSuccessResult(''); + } + + // Note: isomorphic-git doesn't have a direct reset command + // We'll implement basic functionality based on the mode + + 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'); + + case 'mixed': + // Move HEAD and reset staging area (default) + // Reset the index to match the target commit + try { + await git.checkout({ + fs, + dir: cwd, + ref: target, + noCheckout: true, // Only update the index, not the working directory + }); + return createSuccessResult(`HEAD is now at ${targetOid.substring(0, 7)}\n`); + } catch { + return createErrorResult('Failed to reset index'); + } + + case 'hard': + // Move HEAD, reset staging area, and reset working directory + try { + await git.checkout({ + fs, + dir: cwd, + ref: target, + force: true, + }); + return createSuccessResult(`HEAD is now at ${targetOid.substring(0, 7)}\n`); + } catch { + return createErrorResult('Failed to reset working directory'); + } + + default: + return createErrorResult(`Unknown reset mode: ${mode}`); + } + + } catch (error) { + return createErrorResult(`Failed to reset: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } +} \ No newline at end of file diff --git a/src/lib/commands/git/show.ts b/src/lib/commands/git/show.ts new file mode 100644 index 00000000..c0e19366 --- /dev/null +++ b/src/lib/commands/git/show.ts @@ -0,0 +1,111 @@ +import git from 'isomorphic-git'; +import type { JSRuntimeFS } from "../../JSRuntime"; +import type { ShellCommandResult } from "../ShellCommand"; +import { createSuccessResult, createErrorResult } from "../ShellCommand"; +import type { GitSubcommand } from "../git"; + +export class GitShowCommand implements GitSubcommand { + name = 'show'; + description = 'Show various types of objects'; + usage = 'git show []'; + + async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise { + try { + // Check if we're in a git repository + try { + await fs.stat(`${cwd}/.git`); + } catch { + return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); + } + + const { commit } = this.parseArgs(args); + + return await this.showCommit(fs, cwd, commit); + + } catch (error) { + return createErrorResult(`git show: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private parseArgs(args: string[]): { commit: string } { + let commit = 'HEAD'; // Default to HEAD + + for (const arg of args) { + if (!arg.startsWith('-')) { + commit = arg; + break; + } + } + + return { commit }; + } + + private async showCommit(fs: JSRuntimeFS, cwd: string, commitRef: string): Promise { + try { + // Get the commit + const commits = await git.log({ + fs, + dir: cwd, + depth: 1, + ref: commitRef, + }); + + if (commits.length === 0) { + return createErrorResult(`fatal: bad revision '${commitRef}'`); + } + + const commit = commits[0]; + const lines: string[] = []; + + // Show commit information + lines.push(`commit ${commit.oid}`); + + // Show parent commits if any + if (commit.commit.parent && commit.commit.parent.length > 0) { + for (const parent of commit.commit.parent) { + lines.push(`parent ${parent}`); + } + } + + lines.push(`Author: ${commit.commit.author.name} <${commit.commit.author.email}>`); + lines.push(`Date: ${new Date(commit.commit.author.timestamp * 1000).toUTCString()}`); + lines.push(''); + + // Show commit message (indented) + const messageLines = commit.commit.message.split('\n'); + for (const messageLine of messageLines) { + lines.push(` ${messageLine}`); + } + lines.push(''); + + // Try to show file changes (simplified) + try { + // Get the tree for this commit + const tree = await git.readTree({ + fs, + dir: cwd, + oid: commit.oid, + }); + + if (tree.tree.length > 0) { + lines.push('Files in this commit:'); + for (const entry of tree.tree) { + const mode = entry.mode === '040000' ? 'tree' : 'blob'; + lines.push(`${mode} ${entry.oid.substring(0, 7)} ${entry.path}`); + } + } + } catch { + // If we can't read the tree, show a note + lines.push('(File details not available)'); + } + + return createSuccessResult(lines.join('\n') + '\n'); + + } catch (error) { + if (error instanceof Error && error.message.includes('does not exist')) { + return createErrorResult(`fatal: bad revision '${commitRef}'`); + } + return createErrorResult(`Failed to show commit: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } +} \ No newline at end of file diff --git a/src/lib/commands/git/status.ts b/src/lib/commands/git/status.ts new file mode 100644 index 00000000..3ad790e3 --- /dev/null +++ b/src/lib/commands/git/status.ts @@ -0,0 +1,175 @@ +import git from 'isomorphic-git'; +import type { JSRuntimeFS } from "../../JSRuntime"; +import type { ShellCommandResult } from "../ShellCommand"; +import { createSuccessResult, createErrorResult } from "../ShellCommand"; +import type { GitSubcommand } from "../git"; + +export class GitStatusCommand implements GitSubcommand { + name = 'status'; + description = 'Show the working tree status'; + usage = 'git status [--porcelain] [--short]'; + + async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise { + try { + // Check if we're in a git repository + try { + await fs.stat(`${cwd}/.git`); + } catch { + return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); + } + + const options = this.parseArgs(args); + + // Get the status matrix + const statusMatrix = await git.statusMatrix({ + fs, + dir: cwd, + }); + + // Get current branch + let currentBranch: string | null = null; + try { + currentBranch = await git.currentBranch({ + fs, + dir: cwd, + }) || null; + } catch { + // Might be an empty repository + } + + if (options.porcelain || options.short) { + return this.formatPorcelainStatus(statusMatrix); + } else { + return this.formatHumanStatus(statusMatrix, currentBranch); + } + + } catch (error) { + return createErrorResult(`git status: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private parseArgs(args: string[]): { porcelain: boolean; short: boolean } { + const options = { porcelain: false, short: false }; + + for (const arg of args) { + if (arg === '--porcelain') { + options.porcelain = true; + } else if (arg === '--short' || arg === '-s') { + options.short = true; + } + } + + return options; + } + + private formatPorcelainStatus(statusMatrix: Array<[string, number, number, number]>): ShellCommandResult { + const lines: string[] = []; + + for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) { + let indexStatus = ' '; + let workingStatus = ' '; + + // Determine index status (staged changes) + if (headStatus === 0 && stageStatus === 1) { + indexStatus = 'A'; // Added + } else if (headStatus === 1 && stageStatus === 0) { + indexStatus = 'D'; // Deleted + } else if (headStatus === 1 && stageStatus === 1 && headStatus !== stageStatus) { + indexStatus = 'M'; // Modified + } + + // Determine working directory status + if (headStatus === 0 && stageStatus === 0 && workdirStatus === 1) { + workingStatus = '?'; // Untracked + } else if (stageStatus === 1 && workdirStatus === 0) { + workingStatus = 'D'; // Deleted + } else if (stageStatus !== workdirStatus) { + workingStatus = 'M'; // Modified + } + + // Only show files with changes + if (indexStatus !== ' ' || workingStatus !== ' ') { + lines.push(`${indexStatus}${workingStatus} ${filepath}`); + } + } + + return createSuccessResult(lines.join('\n') + (lines.length > 0 ? '\n' : '')); + } + + private formatHumanStatus(statusMatrix: Array<[string, number, number, number]>, currentBranch: string | null): ShellCommandResult { + const lines: string[] = []; + + // Show current branch + if (currentBranch) { + lines.push(`On branch ${currentBranch}`); + } else { + lines.push('On branch main'); + } + + // Categorize changes + const staged: string[] = []; + const modified: string[] = []; + const untracked: string[] = []; + const deleted: string[] = []; + + for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) { + // Staged changes (index differs from HEAD) + if (headStatus === 0 && stageStatus === 1) { + staged.push(`\tnew file: ${filepath}`); + } else if (headStatus === 1 && stageStatus === 0) { + staged.push(`\tdeleted: ${filepath}`); + } else if (headStatus !== stageStatus && headStatus === 1 && stageStatus === 1) { + staged.push(`\tmodified: ${filepath}`); + } + + // Working directory changes (working dir differs from index) + if (stageStatus === 1 && workdirStatus === 0) { + deleted.push(`\tdeleted: ${filepath}`); + } else if (stageStatus !== workdirStatus && stageStatus === 1 && workdirStatus === 1) { + modified.push(`\tmodified: ${filepath}`); + } + + // Untracked files + if (headStatus === 0 && stageStatus === 0 && workdirStatus === 1) { + untracked.push(`\t${filepath}`); + } + } + + // Show staged changes + if (staged.length > 0) { + lines.push(''); + lines.push('Changes to be committed:'); + lines.push(' (use "git reset HEAD ..." to unstage)'); + lines.push(''); + lines.push(...staged); + } + + // Show unstaged changes + if (modified.length > 0 || deleted.length > 0) { + lines.push(''); + lines.push('Changes not staged for commit:'); + lines.push(' (use "git add ..." to update what will be committed)'); + lines.push(' (use "git checkout -- ..." to discard changes in working directory)'); + lines.push(''); + lines.push(...modified); + lines.push(...deleted); + } + + // Show untracked files + if (untracked.length > 0) { + lines.push(''); + lines.push('Untracked files:'); + lines.push(' (use "git add ..." to include in what will be committed)'); + lines.push(''); + lines.push(...untracked); + } + + // Clean status + if (staged.length === 0 && modified.length === 0 && deleted.length === 0 && untracked.length === 0) { + lines.push('nothing to commit, working tree clean'); + } + + lines.push(''); + return createSuccessResult(lines.join('\n')); + } +} \ No newline at end of file diff --git a/src/lib/commands/git/tag.ts b/src/lib/commands/git/tag.ts new file mode 100644 index 00000000..773c5fcd --- /dev/null +++ b/src/lib/commands/git/tag.ts @@ -0,0 +1,177 @@ +import git from 'isomorphic-git'; +import type { JSRuntimeFS } from "../../JSRuntime"; +import type { ShellCommandResult } from "../ShellCommand"; +import { createSuccessResult, createErrorResult } from "../ShellCommand"; +import type { GitSubcommand } from "../git"; + +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 '; + + async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise { + try { + // Check if we're in a git repository + try { + await fs.stat(`${cwd}/.git`); + } catch { + return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); + } + + const { action, tagName, commit } = this.parseArgs(args); + + switch (action) { + case 'list': + return await this.listTags(fs, cwd); + case 'create': + return await this.createTag(fs, cwd, tagName!, commit); + case 'delete': + return await this.deleteTag(fs, cwd, tagName!); + default: + return await this.listTags(fs, cwd); + } + + } catch (error) { + return createErrorResult(`git tag: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private parseArgs(args: string[]): { + action: 'list' | 'create' | 'delete'; + tagName?: string; + commit?: string; + options: { annotated: boolean } + } { + const options = { annotated: false }; + let action: 'list' | 'create' | 'delete' = 'list'; + let tagName: string | undefined; + let commit: string | undefined; + + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + + if (arg === '-l' || arg === '--list') { + action = 'list'; + } 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; + } + } + } + + return { action, tagName, commit, options }; + } + + private async listTags(fs: JSRuntimeFS, cwd: string): Promise { + try { + const tags = await git.listTags({ + fs, + dir: cwd, + }); + + if (tags.length === 0) { + return createSuccessResult(''); + } + + // Sort tags alphabetically + tags.sort(); + + return createSuccessResult(tags.join('\n') + '\n'); + + } catch (error) { + return createErrorResult(`Failed to list tags: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private async createTag(fs: JSRuntimeFS, cwd: string, tagName: string, commit?: string): Promise { + try { + if (!tagName) { + return createErrorResult('usage: git tag []'); + } + + // Check if tag already exists + try { + const tags = await git.listTags({ + fs, + dir: cwd, + }); + + if (tags.includes(tagName)) { + return createErrorResult(`fatal: tag '${tagName}' already exists`); + } + } catch { + // Continue if we can't list tags + } + + // Resolve the target commit + let targetOid: string; + try { + targetOid = await git.resolveRef({ + fs, + dir: cwd, + ref: commit || 'HEAD', + }); + } catch { + return createErrorResult(`fatal: not a valid object name: '${commit || 'HEAD'}'`); + } + + // Create the tag + await git.tag({ + fs, + dir: cwd, + ref: tagName, + object: targetOid, + }); + + return createSuccessResult(''); + + } catch (error) { + return createErrorResult(`Failed to create tag: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + private async deleteTag(fs: JSRuntimeFS, cwd: string, tagName: string): Promise { + try { + if (!tagName) { + return createErrorResult('usage: git tag -d '); + } + + // Check if tag exists + try { + const tags = await git.listTags({ + fs, + dir: cwd, + }); + + if (!tags.includes(tagName)) { + return createErrorResult(`error: tag '${tagName}' not found.`); + } + } catch { + return createErrorResult(`error: tag '${tagName}' not found.`); + } + + // Delete the tag + await git.deleteTag({ + fs, + dir: cwd, + ref: tagName, + }); + + return createSuccessResult(`Deleted tag '${tagName}'\n`); + + } catch (error) { + return createErrorResult(`Failed to delete tag: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } +} \ No newline at end of file diff --git a/src/lib/commands/index.ts b/src/lib/commands/index.ts index 0ec7fbdd..4e9f0024 100644 --- a/src/lib/commands/index.ts +++ b/src/lib/commands/index.ts @@ -9,6 +9,7 @@ export { DiffCommand } from './diff'; export { EchoCommand } from './echo'; export { EnvCommand } from './env'; export { FindCommand } from './find'; +export { GitCommand } from './git'; export { GrepCommand } from './grep'; export { HeadCommand } from './head'; export { LsCommand } from './ls'; diff --git a/src/lib/tools/ShellTool.test.ts b/src/lib/tools/ShellTool.test.ts index b9897e2a..09b3234b 100644 --- a/src/lib/tools/ShellTool.test.ts +++ b/src/lib/tools/ShellTool.test.ts @@ -28,7 +28,7 @@ describe('ShellTool', () => { }); it('should have correct tool properties', () => { - expect(shellTool.description).toBe('Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear. Supports compound commands with &&, ||, ;, and | operators'); + expect(shellTool.description).toBe('Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git. Supports compound commands with &&, ||, ;, and | operators'); expect(shellTool.inputSchema).toBeDefined(); }); diff --git a/src/lib/tools/ShellTool.ts b/src/lib/tools/ShellTool.ts index 7cf6e4dc..710e1f27 100644 --- a/src/lib/tools/ShellTool.ts +++ b/src/lib/tools/ShellTool.ts @@ -13,6 +13,7 @@ import { EchoCommand, EnvCommand, FindCommand, + GitCommand, GrepCommand, HeadCommand, LsCommand, @@ -42,11 +43,11 @@ export class ShellTool implements Tool { private cwd: string; private commands: Map; - readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear. Supports compound commands with &&, ||, ;, and | operators"; + readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git. Supports compound commands with &&, ||, ;, and | operators"; readonly inputSchema = z.object({ command: z.string().describe( - 'Shell command to execute, e.g. "cat file.txt", "ls -la", "cd src", "pwd", "sort file.txt", "diff file1 file2". Supports compound commands with &&, ||, ;, and | operators, e.g. "pwd && ls -la", "cat file.txt | grep pattern", "echo hello; echo world"' + 'Shell command to execute, e.g. "cat file.txt", "ls -la", "cd src", "pwd", "sort file.txt", "diff file1 file2", "git status", "git add .", "git commit -m \'message\'". Supports compound commands with &&, ||, ;, and | operators, e.g. "pwd && ls -la", "cat file.txt | grep pattern", "git add . && git commit -m \'update\'"' ), }); @@ -66,6 +67,7 @@ export class ShellTool implements Tool { this.registerCommand(new EchoCommand()); this.registerCommand(new EnvCommand()); this.registerCommand(new FindCommand(fs)); + this.registerCommand(new GitCommand(fs)); this.registerCommand(new GrepCommand(fs)); this.registerCommand(new HeadCommand(fs)); this.registerCommand(new LsCommand(fs));