diff --git a/src/lib/commands/git/show.test.ts b/src/lib/commands/git/show.test.ts new file mode 100644 index 00000000..68ea1cf5 --- /dev/null +++ b/src/lib/commands/git/show.test.ts @@ -0,0 +1,525 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { GitShowCommand } from './show'; +import type { Git } from '../../git'; +import type { JSRuntimeFS } from '../../JSRuntime'; + +describe('GitShowCommand', () => { + let showCommand: GitShowCommand; + let mockGit: Partial; + let mockFS: Partial; + const mockPwd = '/projects/test'; + + // Sample file contents for testing diffs + const oldFileContent = 'line 1\nline 2\nline 3\nline 4\nline 5\n'; + const modifiedFileContent = 'line 1\nmodified line 2\nline 3\nnew line\nline 5\n'; + const binaryFileContent = Buffer.from([0x00, 0x01, 0x02, 0x03]).toString(); + + beforeEach(() => { + // Mock the filesystem + mockFS = { + stat: vi.fn().mockResolvedValue({}), + }; + + // Mock Git methods with realistic behavior + mockGit = { + // Mock resolveRef to handle different references + resolveRef: vi.fn().mockImplementation(async ({ ref }) => { + switch (ref) { + case 'HEAD': + return 'merge-commit'; + case 'main': + return 'merge-commit'; + case 'branch': + return 'branch-commit'; + case 'initial-commit': + case 'simple-commit': + case 'merge-commit': + case 'branch-commit': + return ref; + default: + throw new Error(`Reference ${ref} does not exist`); + } + }), + + // Mock readCommit to return commit objects + readCommit: vi.fn().mockImplementation(async ({ oid }) => { + switch (oid) { + case 'initial-commit': + return { + oid: 'initial-commit', + commit: { + message: 'Initial commit', + parent: [], + tree: 'initial-tree', + author: { + name: 'Test User', + email: 'test@example.com', + timestamp: 1600000000, + timezoneOffset: 0, + }, + }, + }; + case 'simple-commit': + return { + oid: 'simple-commit', + commit: { + message: 'Simple changes', + parent: ['initial-commit'], + tree: 'simple-tree', + author: { + name: 'Test User', + email: 'test@example.com', + timestamp: 1600001000, + timezoneOffset: 0, + }, + }, + }; + case 'branch-commit': + return { + oid: 'branch-commit', + commit: { + message: 'Branch commit', + parent: ['initial-commit'], + tree: 'branch-tree', + author: { + name: 'Test User', + email: 'test@example.com', + timestamp: 1600001500, + timezoneOffset: 0, + }, + }, + }; + case 'merge-commit': + return { + oid: 'merge-commit', + commit: { + message: 'Merge branch', + parent: ['simple-commit', 'branch-commit'], + tree: 'merge-tree', + author: { + name: 'Test User', + email: 'test@example.com', + timestamp: 1600002000, + timezoneOffset: 0, + }, + }, + }; + default: + throw new Error(`Commit ${oid} not found`); + } + }), + + // Mock log to return commit history + log: vi.fn().mockImplementation(async ({ ref }) => { + switch (ref) { + case 'initial-commit': + return [{ + oid: 'initial-commit', + commit: { + message: 'Initial commit', + parent: [], + tree: 'initial-tree', + author: { + name: 'Test User', + email: 'test@example.com', + timestamp: 1600000000, + timezoneOffset: 0, + }, + }, + }]; + case 'simple-commit': + return [{ + oid: 'simple-commit', + commit: { + message: 'Simple changes', + parent: ['initial-commit'], + tree: 'simple-tree', + author: { + name: 'Test User', + email: 'test@example.com', + timestamp: 1600001000, + timezoneOffset: 0, + }, + }, + }]; + case 'branch-commit': + return [{ + oid: 'branch-commit', + commit: { + message: 'Branch commit', + parent: ['initial-commit'], + tree: 'branch-tree', + author: { + name: 'Test User', + email: 'test@example.com', + timestamp: 1600001500, + timezoneOffset: 0, + }, + }, + }]; + case 'merge-commit': + return [{ + oid: 'merge-commit', + commit: { + message: 'Merge branch', + parent: ['simple-commit', 'branch-commit'], + tree: 'merge-tree', + author: { + name: 'Test User', + email: 'test@example.com', + timestamp: 1600002000, + timezoneOffset: 0, + }, + }, + }]; + default: + return []; + } + }), + + // Mock readTree to return file trees + readTree: vi.fn().mockImplementation(async ({ oid }) => { + switch (oid) { + case 'initial-tree': + return { + tree: [ + { path: 'file1.txt', mode: '100644', oid: 'blob-initial-1' }, + { path: 'file2.txt', mode: '100644', oid: 'blob-initial-2' }, + ], + }; + case 'simple-tree': + return { + tree: [ + { path: 'file1.txt', mode: '100644', oid: 'blob-modified-1' }, + { path: 'file2.txt', mode: '100644', oid: 'blob-initial-2' }, + { path: 'file3.txt', mode: '100644', oid: 'blob-new-3' }, + ], + }; + case 'branch-tree': + return { + tree: [ + { path: 'file1.txt', mode: '100644', oid: 'blob-initial-1' }, + { path: 'file2.txt', mode: '100644', oid: 'blob-branch-2' }, + { path: 'binary.bin', mode: '100644', oid: 'blob-binary' }, + ], + }; + case 'merge-tree': + return { + tree: [ + { path: 'file1.txt', mode: '100644', oid: 'blob-modified-1' }, + { path: 'file2.txt', mode: '100644', oid: 'blob-branch-2' }, + { path: 'file3.txt', mode: '100644', oid: 'blob-new-3' }, + { path: 'binary.bin', mode: '100644', oid: 'blob-binary' }, + ], + }; + case 'initial-commit': + case 'simple-commit': + case 'branch-commit': + case 'merge-commit': + // Handle the case when oid is actually a commit hash + return { + tree: [ + { path: 'file1.txt', mode: '100644', oid: 'blob-modified-1' }, + { path: 'file2.txt', mode: '100644', oid: 'blob-initial-2' }, + ], + }; + default: + return { tree: [] }; + } + }), + + // Mock readBlob to return file contents + readBlob: vi.fn().mockImplementation(async ({ filepath, oid }) => { + // Return different content based on blob ID or filepath + if (filepath === 'file1.txt') { + if (oid.includes('initial') || oid === 'initial-commit') { + return { blob: new TextEncoder().encode(oldFileContent), oid: 'blob-initial-1' }; + } else { + return { blob: new TextEncoder().encode(modifiedFileContent), oid: 'blob-modified-1' }; + } + } else if (filepath === 'file2.txt') { + if (oid.includes('branch')) { + return { blob: new TextEncoder().encode('file 2 branch content'), oid: 'blob-branch-2' }; + } else { + return { blob: new TextEncoder().encode('file 2 content'), oid: 'blob-initial-2' }; + } + } else if (filepath === 'file3.txt') { + return { blob: new TextEncoder().encode('new file content'), oid: 'blob-new-3' }; + } else if (filepath === 'binary.bin') { + return { blob: new TextEncoder().encode(binaryFileContent), oid: 'blob-binary' }; + } + + // Default case + return { blob: new TextEncoder().encode('default content'), oid: 'default-blob' }; + }), + }; + + // Create the command instance with mocks + showCommand = new GitShowCommand({ + git: mockGit as Git, + fs: mockFS as JSRuntimeFS, + pwd: mockPwd, + }); + }); + + it('should show basic commit information', async () => { + const result = await showCommand.execute(['simple-commit']); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('commit simple-commit'); + expect(result.stdout).toContain('Author: Test User'); + expect(result.stdout).toContain('Simple changes'); + }); + + it('should handle initial commits properly', async () => { + const result = await showCommand.execute(['initial-commit']); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('Initial commit'); + + // The implementation should detect this is an initial commit + expect(result.stdout).toContain('initial commit'); + }); + + it('should resolve HEAD~1 correctly', async () => { + // First, check that the implementation correctly resolves HEAD~1 + const result = await showCommand.execute(['HEAD~1']); + + // Verify that resolveRef was called with HEAD + expect(mockGit.resolveRef).toHaveBeenCalledWith({ + dir: mockPwd, + ref: 'HEAD', + }); + + // Verify that readCommit was called with the resolved HEAD commit + expect(mockGit.readCommit).toHaveBeenCalledWith({ + dir: mockPwd, + oid: 'merge-commit', + }); + + // Check that the result contains the parent commit info + expect(result.stdout).toContain('Simple changes'); + }); + + it('should resolve HEAD^2 correctly', async () => { + const result = await showCommand.execute(['HEAD^2']); + + // Verify that resolveRef was called with HEAD + expect(mockGit.resolveRef).toHaveBeenCalledWith({ + dir: mockPwd, + ref: 'HEAD', + }); + + // Verify that readCommit was called with the resolved HEAD commit + expect(mockGit.readCommit).toHaveBeenCalledWith({ + dir: mockPwd, + oid: 'merge-commit', + }); + + // Check that the result contains the second parent commit info + expect(result.stdout).toContain('Branch commit'); + }); + + it('should show file changes between commits', async () => { + // This test verifies that the diff output includes file changes + // We need to ensure our mocks provide the necessary data for the diff algorithm + + // Reset the call counts + vi.clearAllMocks(); + + // Force the readTree mock to return different trees for parent and current commit + mockGit.readTree.mockImplementation(async ({ oid }) => { + if (oid === 'simple-commit' || oid === 'simple-tree') { + return { + tree: [ + { path: 'file1.txt', mode: '100644', oid: 'blob-modified-1' }, + { path: 'file3.txt', mode: '100644', oid: 'blob-new-3' }, + ], + }; + } else if (oid === 'initial-commit' || oid === 'initial-tree') { + return { + tree: [ + { path: 'file1.txt', mode: '100644', oid: 'blob-initial-1' }, + { path: 'file2.txt', mode: '100644', oid: 'blob-initial-2' }, + ], + }; + } + return { tree: [] }; + }); + + // Execute the command + const result = await showCommand.execute(['simple-commit']); + + // Check that the command output contains the commit message + expect(result.stdout).toContain('Simple changes'); + + // Verify that the necessary methods were called + expect(mockGit.readTree).toHaveBeenCalled(); + + // Check that the output mentions the files that were changed + expect(result.stdout).toContain('file1.txt'); + expect(result.stdout).toContain('file3.txt'); + + // Check for file status indicators + expect(result.stdout).toContain('added'); + expect(result.stdout).toContain('modified'); + }); + + it('should show line-by-line diffs with proper formatting', async () => { + // Reset the call counts + vi.clearAllMocks(); + + // Set up specific file content for diffing + const oldContent = 'line 1\nline 2\nline 3\nline 4\nline 5\n'; + const newContent = 'line 1\nmodified line 2\nline 3\nnew line\nline 5\n'; + + // Mock log to return a commit with a parent + mockGit.log.mockImplementation(async ({ ref }) => { + if (ref === 'diff-test-commit') { + return [{ + oid: 'diff-test-commit', + commit: { + message: 'Test diff formatting', + parent: ['diff-parent-commit'], + tree: 'diff-test-tree', + author: { + name: 'Test User', + email: 'test@example.com', + timestamp: 1600001000, + timezoneOffset: 0, + }, + }, + }]; + } + return []; + }); + + // Mock readCommit for the parent commit + mockGit.readCommit.mockImplementation(async ({ oid }) => { + if (oid === 'diff-test-commit') { + return { + oid: 'diff-test-commit', + commit: { + message: 'Test diff formatting', + parent: ['diff-parent-commit'], + tree: 'diff-test-tree', + author: { + name: 'Test User', + email: 'test@example.com', + timestamp: 1600001000, + timezoneOffset: 0, + }, + }, + }; + } else if (oid === 'diff-parent-commit') { + return { + oid: 'diff-parent-commit', + commit: { + message: 'Parent commit', + parent: [], + tree: 'diff-parent-tree', + author: { + name: 'Test User', + email: 'test@example.com', + timestamp: 1600000000, + timezoneOffset: 0, + }, + }, + }; + } + throw new Error(`Commit ${oid} not found`); + }); + + // Force the readTree mock to return trees with different content + mockGit.readTree.mockImplementation(async ({ oid }) => { + if (oid === 'diff-test-tree') { + return { + tree: [ + { path: 'diff-test.txt', mode: '100644', oid: 'blob-new' }, + ], + }; + } else if (oid === 'diff-parent-tree') { + return { + tree: [ + { path: 'diff-test.txt', mode: '100644', oid: 'blob-old' }, + ], + }; + } else if (oid === 'diff-parent-commit') { + return { + tree: [ + { path: 'diff-test.txt', mode: '100644', oid: 'blob-old' }, + ], + }; + } else if (oid === 'diff-test-commit') { + return { + tree: [ + { path: 'diff-test.txt', mode: '100644', oid: 'blob-new' }, + ], + }; + } + return { tree: [] }; + }); + + // Mock readBlob to return our test content + mockGit.readBlob.mockImplementation(async ({ filepath, oid }) => { + if (filepath === 'diff-test.txt') { + if (oid === 'blob-old' || oid === 'diff-parent-commit' || oid === 'diff-parent-tree') { + return { blob: new TextEncoder().encode(oldContent), oid: 'blob-old' }; + } else { + return { blob: new TextEncoder().encode(newContent), oid: 'blob-new' }; + } + } + return { blob: new TextEncoder().encode('default content'), oid: 'default-blob' }; + }); + + // Mock resolveRef to handle our test commit + mockGit.resolveRef.mockImplementation(async ({ ref }) => { + if (ref === 'diff-test-commit') { + return 'diff-test-commit'; + } + throw new Error(`Reference ${ref} does not exist`); + }); + + // Execute the command + const result = await showCommand.execute(['diff-test-commit']); + + // Debug output + console.log('Test output:', result.stdout); + + // Check for unified diff format with hunk headers + expect(result.stdout).toMatch(/@@ -\d+,\d+ \+\d+,\d+ @@/); + + // Check for context lines (unchanged lines) + expect(result.stdout).toContain(' line 1'); + expect(result.stdout).toContain(' line 3'); + expect(result.stdout).toContain(' line 5'); + + // Check for removed lines (with - prefix and red color) + expect(result.stdout).toContain('-line 2'); + expect(result.stdout).toContain('\x1b[31m'); // Red color + + // Check for added lines (with + prefix and green color) + expect(result.stdout).toContain('+modified line 2'); + expect(result.stdout).toContain('+new line'); + expect(result.stdout).toContain('\x1b[32m'); // Green color + + // Verify that readBlob was called to get file contents for diffing + expect(mockGit.readBlob).toHaveBeenCalled(); + }); + + it('should return an error for invalid references', async () => { + const result = await showCommand.execute(['non-existent-ref']); + + expect(result.exitCode).not.toBe(0); + expect(result.stderr).toContain('bad revision'); + }); + + it('should return an error when not in a git repository', async () => { + mockFS.stat = vi.fn().mockRejectedValue(new Error('Not a directory')); + + const result = await showCommand.execute([]); + + expect(result.exitCode).not.toBe(0); + expect(result.stderr).toContain('not a git repository'); + }); +}); \ No newline at end of file diff --git a/src/lib/commands/git/show.ts b/src/lib/commands/git/show.ts index d2dad343..dd61b5e2 100644 --- a/src/lib/commands/git/show.ts +++ b/src/lib/commands/git/show.ts @@ -1,4 +1,3 @@ - import type { JSRuntimeFS } from "../../JSRuntime"; import type { ShellCommandResult } from "../ShellCommand"; import { createSuccessResult, createErrorResult } from "../ShellCommand"; @@ -31,7 +30,13 @@ export class GitShowCommand implements GitSubcommand { const { commit } = this.parseArgs(args); - return await this.showCommit(commit); + // Resolve the commit reference (handling relative refs like HEAD~1) + const resolvedCommit = await this.resolveCommitRef(commit); + if (!resolvedCommit) { + return createErrorResult(`fatal: bad revision '${commit}'`); + } + + return await this.showCommit(resolvedCommit); } catch (error) { return createErrorResult(`git show: ${error instanceof Error ? error.message : 'Unknown error'}`); @@ -51,6 +56,125 @@ export class GitShowCommand implements GitSubcommand { return { commit }; } + /** + * Resolve a commit reference, handling special syntax like HEAD~N and HEAD^N + */ + private async resolveCommitRef(ref: string): Promise { + try { + // Handle HEAD~N syntax (ancestor) + const tildeMatch = ref.match(/^(.+)~(\d+)$/); + if (tildeMatch) { + const [, baseRef, steps] = tildeMatch; + const numSteps = parseInt(steps, 10); + + if (numSteps === 0) { + // ~0 is the commit itself + return this.resolveCommitRef(baseRef); + } + + // First resolve the base reference + const baseCommit = await this.resolveCommitRef(baseRef); + if (!baseCommit) { + throw new Error(`Could not resolve base reference: ${baseRef}`); + } + + // Walk back N steps in history + return this.walkBackNCommits(baseCommit, numSteps); + } + + // Handle HEAD^N syntax (Nth parent) + const caretMatch = ref.match(/^(.+)\^(\d*)$/); + if (caretMatch) { + const [, baseRef, parentNum] = caretMatch; + const parentIndex = parentNum ? parseInt(parentNum, 10) - 1 : 0; // Default to first parent + + // First resolve the base reference + const baseCommit = await this.resolveCommitRef(baseRef); + if (!baseCommit) { + throw new Error(`Could not resolve base reference: ${baseRef}`); + } + + // Get the specified parent + return this.getNthParent(baseCommit, parentIndex); + } + + // Handle simple reference (direct resolution) + try { + return await this.git.resolveRef({ + dir: this.pwd, + ref, + }); + } catch (error) { + if (error instanceof Error && error.message.includes('does not exist')) { + return null; + } + throw error; + } + } catch (error) { + console.error('Error resolving commit reference:', error); + return null; + } + } + + /** + * Walk back N commits from the given commit + */ + private async walkBackNCommits(startCommit: string, steps: number): Promise { + try { + let currentCommit = startCommit; + + for (let i = 0; i < steps; i++) { + // Get the commit object + const commit = await this.git.readCommit({ + dir: this.pwd, + oid: currentCommit, + }); + + // Check if the commit has parents + if (!commit.commit.parent || commit.commit.parent.length === 0) { + throw new Error(`Commit ${currentCommit.substring(0, 7)} has no parent, cannot go back further`); + } + + // Move to the first parent + currentCommit = commit.commit.parent[0]; + } + + return currentCommit; + } catch (error) { + console.error('Error walking back commits:', error); + return null; + } + } + + /** + * Get the Nth parent of the given commit + */ + private async getNthParent(commit: string, parentIndex: number): Promise { + try { + // Get the commit object + const commitObj = await this.git.readCommit({ + dir: this.pwd, + oid: commit, + }); + + // Check if the commit has parents + if (!commitObj.commit.parent || commitObj.commit.parent.length === 0) { + throw new Error(`Commit ${commit.substring(0, 7)} has no parents`); + } + + // Check if the requested parent index is valid + if (parentIndex < 0 || parentIndex >= commitObj.commit.parent.length) { + throw new Error(`Commit ${commit.substring(0, 7)} does not have a parent at index ${parentIndex + 1}`); + } + + // Return the specified parent + return commitObj.commit.parent[parentIndex]; + } catch (error) { + console.error('Error getting parent commit:', error); + return null; + } + } + private async showCommit(commitRef: string): Promise { try { // Get the commit @@ -88,25 +212,472 @@ export class GitShowCommand implements GitSubcommand { } lines.push(''); - // Try to show file changes (simplified) + // Show the actual diff between this commit and its parent try { - // Get the tree for this commit - const tree = await this.git.readTree({ + // If there's no parent, this is the first commit - show the entire tree + if (!commit.commit.parent || commit.commit.parent.length === 0) { + lines.push('(This is the initial commit)'); - dir: this.pwd, - oid: commit.oid, - }); + // Get the tree for this commit + const tree = await this.git.readTree({ + dir: this.pwd, + 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}`); + if (tree.tree.length > 0) { + lines.push(''); + lines.push('New files:'); + for (const entry of tree.tree) { + lines.push(`new file: ${entry.path}`); + } + } + } else { + // Get the parent commit to compare with + const parentCommit = commit.commit.parent[0]; + + // Get the trees for both commits + const parentTree = await this.git.readTree({ + dir: this.pwd, + oid: parentCommit, + }); + + const commitTree = await this.git.readTree({ + dir: this.pwd, + oid: commit.oid, + }); + + // Define types for tree entries + interface TreeEntry { + mode: string; + path: string; + oid: string; + type?: string; + } + + // Compare the trees manually + const parentFiles = new Map(); + const commitFiles = new Map(); + + // Populate the maps + for (const entry of parentTree.tree) { + parentFiles.set(entry.path, entry as TreeEntry); + } + + for (const entry of commitTree.tree) { + commitFiles.set(entry.path, entry as TreeEntry); + } + + type ChangeType = 'add' | 'modify' | 'delete'; + interface Change { + type: ChangeType; + path: string; + } + + const changes: Change[] = []; + + // Helper function to check if a path is a directory + const isDirectory = (entry: TreeEntry): boolean => { + return entry.mode === '040000'; + }; + + // Helper function to recursively list files in a directory + const listFilesInDirectory = async (oid: string, prefix: string = ''): Promise> => { + const result = new Map(); + try { + const tree = await this.git.readTree({ + dir: this.pwd, + oid, + }); + + for (const entry of tree.tree) { + const entryWithType = entry as TreeEntry; + const path = prefix ? `${prefix}/${entry.path}` : entry.path; + + if (isDirectory(entryWithType)) { + // Recursively list files in subdirectory + const subFiles = await listFilesInDirectory(entry.oid, path); + // Add all files from subdirectory to result + for (const [subPath, subEntry] of subFiles.entries()) { + result.set(subPath, subEntry); + } + } else { + // Add file to result + result.set(path, entryWithType); + } + } + } catch (error) { + console.error(`Error listing files in directory ${oid}:`, error); + } + return result; + }; + + // Expand directory entries to include all files within them + const expandDirectories = async (): Promise => { + // Process parent files + for (const [path, entry] of [...parentFiles.entries()]) { + if (isDirectory(entry)) { + // Remove the directory entry + parentFiles.delete(path); + // Add all files within the directory + const files = await listFilesInDirectory(entry.oid, path); + for (const [filePath, fileEntry] of files.entries()) { + parentFiles.set(filePath, fileEntry); + } + } + } + + // Process commit files + for (const [path, entry] of [...commitFiles.entries()]) { + if (isDirectory(entry)) { + // Remove the directory entry + commitFiles.delete(path); + // Add all files within the directory + const files = await listFilesInDirectory(entry.oid, path); + for (const [filePath, fileEntry] of files.entries()) { + commitFiles.set(filePath, fileEntry); + } + } + } + }; + + // Expand directories to get all files + await expandDirectories(); + + // Find added and modified files + for (const [path, entry] of commitFiles.entries()) { + const parentEntry = parentFiles.get(path); + if (!parentEntry) { + changes.push({ type: 'add', path }); + } else if (parentEntry.oid !== entry.oid) { + changes.push({ type: 'modify', path }); + } + } + + // Find deleted files + for (const path of parentFiles.keys()) { + if (!commitFiles.has(path)) { + changes.push({ type: 'delete', path }); + } + } + + // Sort changes by type and path + const filteredChanges = changes.sort((a, b) => { + if (a.type !== b.type) { + // Order: add, modify, delete + const typeOrder = { add: 0, modify: 1, delete: 2 }; + return typeOrder[a.type] - typeOrder[b.type]; + } + return a.path.localeCompare(b.path); + }); + + if (filteredChanges.length > 0) { + // Group changes by type + const added = filteredChanges.filter(c => c.type === 'add'); + const modified = filteredChanges.filter(c => c.type === 'modify'); + const deleted = filteredChanges.filter(c => c.type === 'delete'); + + lines.push(''); + + // Show summary + const changeDetails: string[] = []; + if (added.length > 0) changeDetails.push(`${added.length} file${added.length !== 1 ? 's' : ''} added`); + if (modified.length > 0) changeDetails.push(`${modified.length} file${modified.length !== 1 ? 's' : ''} modified`); + if (deleted.length > 0) changeDetails.push(`${deleted.length} file${deleted.length !== 1 ? 's' : ''} deleted`); + + lines.push(`\x1b[1mChanges: ${changeDetails.join(', ')}\x1b[0m`); // Bold summary line + lines.push(''); + + // List changed files + if (added.length > 0) { + lines.push('\x1b[1mAdded files:\x1b[0m'); + for (const change of added) { + lines.push(` \x1b[32mnew file: ${change.path}\x1b[0m`); // Green for new files + } + lines.push(''); + } + + if (modified.length > 0) { + lines.push('\x1b[1mModified files:\x1b[0m'); + for (const change of modified) { + lines.push(` \x1b[33mmodified: ${change.path}\x1b[0m`); // Yellow for modified files + } + lines.push(''); + } + + if (deleted.length > 0) { + lines.push('\x1b[1mDeleted files:\x1b[0m'); + for (const change of deleted) { + lines.push(` \x1b[31mdeleted: ${change.path}\x1b[0m`); // Red for deleted files + } + lines.push(''); + } + + // Show actual diffs for modified files (up to 3 files to avoid excessive output) + if (modified.length > 0) { + lines.push('Diffs:'); + lines.push(''); + + // We've already expanded directories, so all entries are files now + const filesToShow = modified.slice(0, 3); // Limit to 3 files + + if (filesToShow.length === 0) { + lines.push('(Only directory structure changes, no file content to show)'); + lines.push(''); + } + + for (const change of filesToShow) { + lines.push(`\x1b[1mdiff --git a/${change.path} b/${change.path}\x1b[0m`); // Bold + lines.push(`\x1b[1;31m--- a/${change.path}\x1b[0m`); // Bold red + lines.push(`\x1b[1;32m+++ b/${change.path}\x1b[0m`); // Bold green + + try { + // Get file content from parent commit + let parentContent = ''; + try { + const parentBlob = await this.git.readBlob({ + dir: this.pwd, + oid: parentCommit, + filepath: change.path, + }); + parentContent = new TextDecoder().decode(parentBlob.blob); + } catch (e) { + console.error(`Error reading parent blob for ${change.path}:`, e); + // File might not exist in parent + } + + // Get file content from current commit + let currentContent = ''; + try { + const currentBlob = await this.git.readBlob({ + dir: this.pwd, + oid: commit.oid, + filepath: change.path, + }); + currentContent = new TextDecoder().decode(currentBlob.blob); + } catch (e) { + console.error(`Error reading current blob for ${change.path}:`, e); + // File might not exist in current commit + } + + // Check if we have content to diff + if (parentContent === '' && currentContent === '') { + lines.push('(Unable to read file contents)'); + lines.push(''); + continue; + } + + // Generate a unified diff + const parentLines = parentContent.split('\n'); + const currentLines = currentContent.split('\n'); + + // Improved diff algorithm that generates unified diffs + const diffLines: string[] = []; + const contextSize = 3; // Number of context lines before and after changes + + // Find changed regions (hunks) + const hunks: Array<{ + startOld: number; + endOld: number; + startNew: number; + endNew: number; + }> = []; + + let oldIndex = 0; + let newIndex = 0; + let hunkStart: { old: number; new: number } | null = null; + + // Use a simple LCS-based diff algorithm to find matching lines + const matches: boolean[] = []; + for (let i = 0; i < parentLines.length; i++) { + matches[i] = false; + for (let j = 0; j < currentLines.length; j++) { + if (parentLines[i] === currentLines[j] && !matches[j]) { + matches[i] = true; + break; + } + } + } + + // Process the diff and identify hunks + while (oldIndex < parentLines.length || newIndex < currentLines.length) { + if (oldIndex < parentLines.length && newIndex < currentLines.length && parentLines[oldIndex] === currentLines[newIndex]) { + // Matching line + if (hunkStart) { + // End of a hunk + hunks.push({ + startOld: Math.max(0, hunkStart.old - contextSize), + endOld: Math.min(parentLines.length, oldIndex + contextSize), + startNew: Math.max(0, hunkStart.new - contextSize), + endNew: Math.min(currentLines.length, newIndex + contextSize) + }); + hunkStart = null; + } + oldIndex++; + newIndex++; + } else { + // Difference found + if (!hunkStart) { + hunkStart = { old: oldIndex, new: newIndex }; + } + + // Handle deletions and additions + if (oldIndex < parentLines.length && (!matches[oldIndex] || newIndex >= currentLines.length)) { + oldIndex++; + } else if (newIndex < currentLines.length) { + newIndex++; + } + } + } + + // Add the final hunk if there is one + if (hunkStart) { + hunks.push({ + startOld: Math.max(0, hunkStart.old - contextSize), + endOld: Math.min(parentLines.length, oldIndex + contextSize), + startNew: Math.max(0, hunkStart.new - contextSize), + endNew: Math.min(currentLines.length, newIndex + contextSize) + }); + } + + // Merge overlapping hunks + for (let i = 0; i < hunks.length - 1; i++) { + if (hunks[i].endOld >= hunks[i + 1].startOld - 2 * contextSize) { + hunks[i].endOld = hunks[i + 1].endOld; + hunks[i].endNew = hunks[i + 1].endNew; + hunks.splice(i + 1, 1); + i--; + } + } + + const foundDifference = hunks.length > 0; + + // Generate the diff output for each hunk + for (const hunk of hunks) { + const oldSize = hunk.endOld - hunk.startOld; + const newSize = hunk.endNew - hunk.startNew; + + // Add the hunk header with additional context + // Get a snippet of the surrounding code to provide context + const contextLine = hunk.startOld < parentLines.length ? parentLines[hunk.startOld] : hunk.startNew < currentLines.length ? currentLines[hunk.startNew] : ''; + + // Trim the context line to a reasonable length and remove leading whitespace + const trimmedContext = contextLine.trim().substring(0, 40) + (contextLine.length > 40 ? '...' : ''); + + // Add the hunk header with the context + diffLines.push(`\x1b[36m@@ -${hunk.startOld + 1},${oldSize} +${hunk.startNew + 1},${newSize} @@ \x1b[1;36m${trimmedContext}\x1b[0m`); + + // Process the hunk content with improved visual grouping + let oldLine = hunk.startOld; + let newLine = hunk.startNew; + + // Track consecutive additions/deletions for better visual grouping + let inAdditionBlock = false; + let inDeletionBlock = false; + + const addSeparator = () => { + if (inAdditionBlock || inDeletionBlock) { + diffLines.push(`\x1b[90m~\x1b[0m`); // Gray separator + inAdditionBlock = false; + inDeletionBlock = false; + } + }; + + while (oldLine < hunk.endOld || newLine < hunk.endNew) { + if (oldLine < hunk.endOld && newLine < hunk.endNew && parentLines[oldLine] === currentLines[newLine]) { + // Context line (unchanged) + addSeparator(); + diffLines.push(` ${parentLines[oldLine]}`); + oldLine++; + newLine++; + } else { + // Collect consecutive deletions + const deletions: string[] = []; + while (oldLine < hunk.endOld && (!matches[oldLine] || newLine >= hunk.endNew)) { + deletions.push(parentLines[oldLine]); + oldLine++; + } + + // Collect consecutive additions + const additions: string[] = []; + while (newLine < hunk.endNew && (oldLine >= hunk.endOld || parentLines[oldLine] !== currentLines[newLine])) { + additions.push(currentLines[newLine]); + newLine++; + } + + // If we have both deletions and additions, it might be a modification + if (deletions.length > 0 && additions.length > 0) { + addSeparator(); + + // Output deletions + for (const line of deletions) { + diffLines.push(`\x1b[31m-${line}\x1b[0m`); + } + + // Output additions + for (const line of additions) { + diffLines.push(`\x1b[32m+${line}\x1b[0m`); + } + } else { + // Handle pure deletions + if (deletions.length > 0) { + if (!inDeletionBlock && inAdditionBlock) { + addSeparator(); + } + inDeletionBlock = true; + + for (const line of deletions) { + diffLines.push(`\x1b[31m-${line}\x1b[0m`); + } + } + + // Handle pure additions + if (additions.length > 0) { + if (!inAdditionBlock && inDeletionBlock) { + addSeparator(); + } + inAdditionBlock = true; + + for (const line of additions) { + diffLines.push(`\x1b[32m+${line}\x1b[0m`); + } + } + } + } + } + } + + // Add the diff lines if we found changes + if (foundDifference && diffLines.length > 0) { + lines.push(...diffLines); + lines.push(''); + } else if (!foundDifference) { + lines.push('(No textual changes detected)'); + lines.push(''); + } else { + lines.push('(Binary files differ)'); + lines.push(''); + } + } catch (error) { + console.error(`Error generating diff for ${change.path}:`, error); + lines.push(`(Error generating diff: ${error instanceof Error ? error.message : 'Unknown error'})`); + lines.push(''); + } + } + + const remainingFiles = modified.length - filesToShow.length; + if (remainingFiles > 0) { + lines.push(`... and ${remainingFiles} more modified files`); + lines.push(''); + } + } + } else { + lines.push(''); + lines.push('No changes (empty commit)'); } } - } catch { - // If we can't read the tree, show a note - lines.push('(File details not available)'); + } catch (error) { + // If we can't generate the diff, show an error + lines.push(`(Error showing changes: ${error instanceof Error ? error.message : 'Unknown error'})`); } return createSuccessResult(lines.join('\n') + '\n');