mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Merge remote-tracking branch 'origin/main' into capacitor
This commit is contained in:
10 files changed
+2617
-21
No files matched your search
@@ -6,6 +6,7 @@ import { cn } from '@/lib/utils';
|
||||
import { ShellTool } from '@/lib/tools/ShellTool';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { ansiToHtml, containsAnsiCodes } from '@/lib/ansiToHtml';
|
||||
|
||||
interface TerminalProps {
|
||||
projectId: string;
|
||||
@@ -152,7 +153,9 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
||||
|
||||
const copyToClipboard = useCallback(async (content: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(content);
|
||||
// Strip ANSI codes when copying to clipboard
|
||||
const cleanContent = content.replace(/\u001b\[(?:\d+;)*\d+m/g, '');
|
||||
await navigator.clipboard.writeText(cleanContent);
|
||||
} catch (error) {
|
||||
console.error('Failed to copy to clipboard:', error);
|
||||
}
|
||||
@@ -187,7 +190,9 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
||||
${' '}
|
||||
</span>
|
||||
) : null}
|
||||
{line.content}
|
||||
{containsAnsiCodes(line.content)
|
||||
? <span dangerouslySetInnerHTML={{ __html: ansiToHtml(line.content) }} />
|
||||
: line.content}
|
||||
</pre>
|
||||
<Button
|
||||
variant="ghost"
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Terminal } from './Terminal';
|
||||
|
||||
/**
|
||||
* A test component to verify ANSI color code rendering in the terminal
|
||||
*/
|
||||
export function TerminalTest() {
|
||||
return (
|
||||
<div className="h-[500px] w-full">
|
||||
<Terminal projectId="test" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* Utility to convert ANSI color codes to HTML spans with appropriate CSS classes
|
||||
*/
|
||||
|
||||
// ANSI color code mapping to Tailwind CSS classes
|
||||
const colorMap: Record<string, string> = {
|
||||
'30': 'text-black',
|
||||
'31': 'text-red-500',
|
||||
'32': 'text-green-500',
|
||||
'33': 'text-yellow-500',
|
||||
'34': 'text-blue-500',
|
||||
'35': 'text-purple-500',
|
||||
'36': 'text-cyan-500',
|
||||
'37': 'text-gray-200',
|
||||
'90': 'text-gray-400',
|
||||
'91': 'text-red-400',
|
||||
'92': 'text-green-400',
|
||||
'93': 'text-yellow-400',
|
||||
'94': 'text-blue-400',
|
||||
'95': 'text-purple-400',
|
||||
'96': 'text-cyan-400',
|
||||
'97': 'text-white',
|
||||
};
|
||||
|
||||
// Background color mapping
|
||||
const bgColorMap: Record<string, string> = {
|
||||
'40': 'bg-black',
|
||||
'41': 'bg-red-500',
|
||||
'42': 'bg-green-500',
|
||||
'43': 'bg-yellow-500',
|
||||
'44': 'bg-blue-500',
|
||||
'45': 'bg-purple-500',
|
||||
'46': 'bg-cyan-500',
|
||||
'47': 'bg-gray-200',
|
||||
};
|
||||
|
||||
// Style mapping
|
||||
const styleMap: Record<string, string> = {
|
||||
'1': 'font-bold',
|
||||
'2': 'opacity-75',
|
||||
'3': 'italic',
|
||||
'4': 'underline',
|
||||
'9': 'line-through',
|
||||
};
|
||||
|
||||
/**
|
||||
* Convert ANSI escape sequences to HTML with appropriate CSS classes
|
||||
*/
|
||||
export function ansiToHtml(text: string): string {
|
||||
// Regular expression to match ANSI escape sequences
|
||||
const ansiRegex = /\u001b\[((?:\d+;)*\d+)m/g;
|
||||
|
||||
// Initialize result and current style classes
|
||||
let result = '';
|
||||
let currentClasses: string[] = [];
|
||||
|
||||
// Find all matches and their positions
|
||||
const matches: Array<{index: number, length: number, codes: string}> = [];
|
||||
let match;
|
||||
|
||||
while ((match = ansiRegex.exec(text)) !== null) {
|
||||
matches.push({
|
||||
index: match.index,
|
||||
length: match[0].length,
|
||||
codes: match[1]
|
||||
});
|
||||
}
|
||||
|
||||
// If no ANSI codes found, return the original text
|
||||
if (matches.length === 0) {
|
||||
return text;
|
||||
}
|
||||
|
||||
// Process the text with ANSI codes
|
||||
let lastIndex = 0;
|
||||
|
||||
for (const match of matches) {
|
||||
// Add text before this match with current styling
|
||||
if (match.index > lastIndex) {
|
||||
const textSegment = text.substring(lastIndex, match.index);
|
||||
if (currentClasses.length > 0) {
|
||||
result += `<span class="${currentClasses.join(' ')}">${textSegment}</span>`;
|
||||
} else {
|
||||
result += textSegment;
|
||||
}
|
||||
}
|
||||
|
||||
// Update current classes based on ANSI codes
|
||||
const codes = match.codes.split(';');
|
||||
|
||||
for (const code of codes) {
|
||||
if (code === '0') {
|
||||
// Reset all styles
|
||||
currentClasses = [];
|
||||
} else if (colorMap[code]) {
|
||||
// Remove any existing text color classes
|
||||
currentClasses = currentClasses.filter(cls => !Object.values(colorMap).includes(cls));
|
||||
// Add the new text color
|
||||
currentClasses.push(colorMap[code]);
|
||||
} else if (bgColorMap[code]) {
|
||||
// Remove any existing background color classes
|
||||
currentClasses = currentClasses.filter(cls => !Object.values(bgColorMap).includes(cls));
|
||||
// Add the new background color
|
||||
currentClasses.push(bgColorMap[code]);
|
||||
} else if (styleMap[code]) {
|
||||
// Add style if it doesn't exist yet
|
||||
if (!currentClasses.includes(styleMap[code])) {
|
||||
currentClasses.push(styleMap[code]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update lastIndex to after this match
|
||||
lastIndex = match.index + match.length;
|
||||
}
|
||||
|
||||
// Add any remaining text
|
||||
if (lastIndex < text.length) {
|
||||
const textSegment = text.substring(lastIndex);
|
||||
if (currentClasses.length > 0) {
|
||||
result += `<span class="${currentClasses.join(' ')}">${textSegment}</span>`;
|
||||
} else {
|
||||
result += textSegment;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a string contains ANSI escape sequences
|
||||
*/
|
||||
export function containsAnsiCodes(text: string): boolean {
|
||||
return /\u001b\[(?:\d+;)*\d+m/.test(text);
|
||||
}
|
||||
@@ -21,6 +21,7 @@ import { GitResetCommand } from "./git/reset";
|
||||
import { GitDiffCommand } from "./git/diff";
|
||||
import { GitTagCommand } from "./git/tag";
|
||||
import { GitShowCommand } from "./git/show";
|
||||
import { GitStashCommand } from "./git/stash";
|
||||
|
||||
export interface GitSubcommand {
|
||||
name: string;
|
||||
@@ -85,6 +86,7 @@ export class GitCommand implements ShellCommand {
|
||||
this.registerSubcommand(new GitDiffCommand(subcommandOptions));
|
||||
this.registerSubcommand(new GitTagCommand(subcommandOptions));
|
||||
this.registerSubcommand(new GitShowCommand(subcommandOptions));
|
||||
this.registerSubcommand(new GitStashCommand(subcommandOptions));
|
||||
}
|
||||
|
||||
private registerSubcommand(subcommand: GitSubcommand): void {
|
||||
@@ -132,6 +134,7 @@ start a working area (see also: git help tutorial)
|
||||
work on the current change (see also: git help everyday)
|
||||
add Add file contents to the index
|
||||
reset Reset current HEAD to the specified state
|
||||
stash Stash the changes in a dirty working directory away
|
||||
|
||||
examine the history and state (see also: git help revisions)
|
||||
log Show commit logs
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { GitCommitCommand } from './commit';
|
||||
import type { Git } from '../../git';
|
||||
import type { JSRuntimeFS } from '../../JSRuntime';
|
||||
|
||||
describe('GitCommitCommand', () => {
|
||||
let commitCommand: GitCommitCommand;
|
||||
let mockGit: Partial<Git>;
|
||||
let mockFS: Partial<JSRuntimeFS>;
|
||||
const mockPwd = '/projects/test';
|
||||
|
||||
beforeEach(() => {
|
||||
// Mock the filesystem
|
||||
mockFS = {
|
||||
stat: vi.fn().mockResolvedValue({}),
|
||||
};
|
||||
|
||||
// Mock Git methods
|
||||
mockGit = {
|
||||
statusMatrix: vi.fn().mockResolvedValue([
|
||||
// filepath, HEAD status, workdir status, stage status
|
||||
['file1.txt', 1, 2, 1], // modified in workdir
|
||||
['file2.txt', 1, 1, 2], // modified in index
|
||||
['file3.txt', 0, 2, 2], // new file
|
||||
['file4.txt', 1, 0, 1], // deleted file
|
||||
]),
|
||||
|
||||
currentBranch: vi.fn().mockResolvedValue('main'),
|
||||
|
||||
resolveRef: vi.fn().mockResolvedValue('headcommit'),
|
||||
|
||||
log: vi.fn().mockResolvedValue([
|
||||
{
|
||||
oid: 'headcommit',
|
||||
commit: {
|
||||
message: 'Previous commit',
|
||||
parent: ['parentcommit'],
|
||||
tree: 'tree1',
|
||||
author: {
|
||||
name: 'Test User',
|
||||
email: '[email protected]',
|
||||
timestamp: 1600000000,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
oid: 'parentcommit',
|
||||
commit: {
|
||||
message: 'Parent commit',
|
||||
parent: [],
|
||||
tree: 'tree2',
|
||||
author: {
|
||||
name: 'Test User',
|
||||
email: '[email protected]',
|
||||
timestamp: 1599000000,
|
||||
},
|
||||
},
|
||||
},
|
||||
]),
|
||||
|
||||
getConfig: vi.fn().mockImplementation(({ path }) => {
|
||||
if (path === 'user.name') return Promise.resolve('Test User');
|
||||
if (path === 'user.email') return Promise.resolve('[email protected]');
|
||||
return Promise.resolve(null);
|
||||
}),
|
||||
|
||||
commit: vi.fn().mockResolvedValue('newcommit'),
|
||||
|
||||
add: vi.fn().mockResolvedValue(undefined),
|
||||
|
||||
remove: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
|
||||
// Create the command instance with mocks
|
||||
commitCommand = new GitCommitCommand({
|
||||
git: mockGit as Git,
|
||||
fs: mockFS as JSRuntimeFS,
|
||||
pwd: mockPwd,
|
||||
});
|
||||
});
|
||||
|
||||
it('should commit with a message', async () => {
|
||||
const result = await commitCommand.execute(['-m', 'Test commit']);
|
||||
|
||||
expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({
|
||||
dir: mockPwd,
|
||||
message: 'Test commit',
|
||||
}));
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Test commit');
|
||||
});
|
||||
|
||||
it('should fail without a message', async () => {
|
||||
const result = await commitCommand.execute([]);
|
||||
|
||||
expect(mockGit.commit).not.toHaveBeenCalled();
|
||||
|
||||
expect(result.exitCode).not.toBe(0);
|
||||
expect(result.stderr).toContain('Aborting commit due to empty commit message');
|
||||
});
|
||||
|
||||
it('should handle --amend flag', async () => {
|
||||
const result = await commitCommand.execute(['--amend', '-m', 'Amended commit']);
|
||||
|
||||
expect(mockGit.log).toHaveBeenCalledWith({
|
||||
dir: mockPwd,
|
||||
depth: 2,
|
||||
});
|
||||
|
||||
expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({
|
||||
dir: mockPwd,
|
||||
message: 'Amended commit',
|
||||
parent: ['parentcommit'],
|
||||
}));
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Amended commit');
|
||||
});
|
||||
|
||||
it('should handle --amend flag without message', async () => {
|
||||
const result = await commitCommand.execute(['--amend']);
|
||||
|
||||
expect(mockGit.log).toHaveBeenCalledWith({
|
||||
dir: mockPwd,
|
||||
depth: 1,
|
||||
});
|
||||
|
||||
expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({
|
||||
dir: mockPwd,
|
||||
message: 'Previous commit',
|
||||
}));
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
});
|
||||
|
||||
it('should handle -a flag to stage all tracked modified files', async () => {
|
||||
const result = await commitCommand.execute(['-a', '-m', 'Commit with auto-stage']);
|
||||
|
||||
// Should call add for the modified tracked file
|
||||
expect(mockGit.add).toHaveBeenCalledWith({
|
||||
dir: mockPwd,
|
||||
filepath: 'file1.txt',
|
||||
});
|
||||
|
||||
// Should not call add for already staged files
|
||||
expect(mockGit.add).not.toHaveBeenCalledWith({
|
||||
dir: mockPwd,
|
||||
filepath: 'file2.txt',
|
||||
});
|
||||
|
||||
// Should call remove for deleted files
|
||||
expect(mockGit.remove).toHaveBeenCalledWith({
|
||||
dir: mockPwd,
|
||||
filepath: 'file4.txt',
|
||||
});
|
||||
|
||||
expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({
|
||||
dir: mockPwd,
|
||||
message: 'Commit with auto-stage',
|
||||
}));
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Commit with auto-stage');
|
||||
});
|
||||
|
||||
it('should handle -am flag for combined auto-stage and message', async () => {
|
||||
const result = await commitCommand.execute(['-am', 'Combined flag commit']);
|
||||
|
||||
// Should call add for the modified tracked file
|
||||
expect(mockGit.add).toHaveBeenCalledWith({
|
||||
dir: mockPwd,
|
||||
filepath: 'file1.txt',
|
||||
});
|
||||
|
||||
// Should call remove for deleted files
|
||||
expect(mockGit.remove).toHaveBeenCalledWith({
|
||||
dir: mockPwd,
|
||||
filepath: 'file4.txt',
|
||||
});
|
||||
|
||||
expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({
|
||||
dir: mockPwd,
|
||||
message: 'Combined flag commit',
|
||||
}));
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Combined flag commit');
|
||||
});
|
||||
|
||||
it('should handle --allow-empty flag', async () => {
|
||||
// Mock empty status
|
||||
mockGit.statusMatrix = vi.fn().mockResolvedValue([]);
|
||||
|
||||
const result = await commitCommand.execute(['--allow-empty', '-m', 'Empty commit']);
|
||||
|
||||
expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({
|
||||
dir: mockPwd,
|
||||
message: 'Empty commit',
|
||||
}));
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Empty commit');
|
||||
});
|
||||
|
||||
it('should fail if there are no staged changes', async () => {
|
||||
// Mock status with only unstaged changes
|
||||
mockGit.statusMatrix = vi.fn().mockResolvedValue([
|
||||
['file1.txt', 1, 2, 1], // modified in workdir only
|
||||
]);
|
||||
|
||||
const result = await commitCommand.execute(['-m', 'Should fail']);
|
||||
|
||||
expect(mockGit.commit).not.toHaveBeenCalled();
|
||||
|
||||
expect(result.exitCode).not.toBe(0);
|
||||
expect(result.stderr).toContain('nothing to commit');
|
||||
});
|
||||
|
||||
it('should handle not being in a git repository', async () => {
|
||||
mockFS.stat = vi.fn().mockRejectedValue(new Error('Not a directory'));
|
||||
|
||||
const result = await commitCommand.execute(['-m', 'Test commit']);
|
||||
|
||||
expect(mockGit.commit).not.toHaveBeenCalled();
|
||||
|
||||
expect(result.exitCode).not.toBe(0);
|
||||
expect(result.stderr).toContain('not a git repository');
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,7 @@ import type { Git } from "../../git";
|
||||
export class GitCommitCommand implements GitSubcommand {
|
||||
name = 'commit';
|
||||
description = 'Record changes to the repository';
|
||||
usage = 'git commit [-m <msg>] [--amend] [--allow-empty]';
|
||||
usage = 'git commit [-m <msg>] [-a | --all] [-am <msg>] [--amend] [--allow-empty]';
|
||||
|
||||
private git: Git;
|
||||
private fs: JSRuntimeFS;
|
||||
@@ -33,6 +33,11 @@ export class GitCommitCommand implements GitSubcommand {
|
||||
if (!message && !options.amend) {
|
||||
return createErrorResult('Aborting commit due to empty commit message.');
|
||||
}
|
||||
|
||||
// If -a flag is provided, stage all tracked files with modifications
|
||||
if (options.addAll) {
|
||||
await this.stageTrackedChanges();
|
||||
}
|
||||
|
||||
// Get current status
|
||||
const statusMatrix = await this.git.statusMatrix({
|
||||
@@ -169,11 +174,46 @@ export class GitCommitCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stage all tracked files with modifications
|
||||
* This is used when the -a flag is provided
|
||||
*/
|
||||
private async stageTrackedChanges(): Promise<void> {
|
||||
try {
|
||||
// Get the status matrix
|
||||
const statusMatrix = await this.git.statusMatrix({
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
// Process each file based on its status
|
||||
for (const [filepath, headStatus, workdirStatus] of statusMatrix) {
|
||||
// Only process tracked files (headStatus === 1) with changes
|
||||
if (headStatus === 1 && workdirStatus !== headStatus) {
|
||||
if (workdirStatus === 0) {
|
||||
// File was deleted, use remove
|
||||
await this.git.remove({
|
||||
dir: this.pwd,
|
||||
filepath,
|
||||
});
|
||||
} else {
|
||||
// File was modified, use add
|
||||
await this.git.add({
|
||||
dir: this.pwd,
|
||||
filepath,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to stage tracked changes: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
private parseArgs(args: string[]): {
|
||||
options: { amend: boolean; allowEmpty: boolean };
|
||||
options: { amend: boolean; allowEmpty: boolean; addAll: boolean };
|
||||
message?: string
|
||||
} {
|
||||
const options = { amend: false, allowEmpty: false };
|
||||
const options = { amend: false, allowEmpty: false, addAll: false };
|
||||
let message: string | undefined;
|
||||
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
@@ -192,6 +232,14 @@ export class GitCommitCommand implements GitSubcommand {
|
||||
options.amend = true;
|
||||
} else if (arg === '--allow-empty') {
|
||||
options.allowEmpty = true;
|
||||
} else if (arg === '-a' || arg === '--all') {
|
||||
options.addAll = true;
|
||||
} else if (arg === '-am') {
|
||||
options.addAll = true;
|
||||
if (i + 1 < args.length) {
|
||||
message = args[i + 1];
|
||||
i++; // Skip next argument as it's the message
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,613 @@
|
||||
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<Git>;
|
||||
let mockFS: Partial<JSRuntimeFS>;
|
||||
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: '[email protected]',
|
||||
timestamp: 1600000000,
|
||||
timezoneOffset: 0,
|
||||
},
|
||||
committer: {
|
||||
name: 'Test User',
|
||||
email: '[email protected]',
|
||||
timestamp: 1600000000,
|
||||
timezoneOffset: 0,
|
||||
},
|
||||
},
|
||||
payload: '',
|
||||
};
|
||||
case 'simple-commit':
|
||||
return {
|
||||
oid: 'simple-commit',
|
||||
commit: {
|
||||
message: 'Simple changes',
|
||||
parent: ['initial-commit'],
|
||||
tree: 'simple-tree',
|
||||
author: {
|
||||
name: 'Test User',
|
||||
email: '[email protected]',
|
||||
timestamp: 1600001000,
|
||||
timezoneOffset: 0,
|
||||
},
|
||||
committer: {
|
||||
name: 'Test User',
|
||||
email: '[email protected]',
|
||||
timestamp: 1600001000,
|
||||
timezoneOffset: 0,
|
||||
},
|
||||
},
|
||||
payload: '',
|
||||
};
|
||||
case 'branch-commit':
|
||||
return {
|
||||
oid: 'branch-commit',
|
||||
commit: {
|
||||
message: 'Branch commit',
|
||||
parent: ['initial-commit'],
|
||||
tree: 'branch-tree',
|
||||
author: {
|
||||
name: 'Test User',
|
||||
email: '[email protected]',
|
||||
timestamp: 1600001500,
|
||||
timezoneOffset: 0,
|
||||
},
|
||||
committer: {
|
||||
name: 'Test User',
|
||||
email: '[email protected]',
|
||||
timestamp: 1600001500,
|
||||
timezoneOffset: 0,
|
||||
},
|
||||
},
|
||||
payload: '',
|
||||
};
|
||||
case 'merge-commit':
|
||||
return {
|
||||
oid: 'merge-commit',
|
||||
commit: {
|
||||
message: 'Merge branch',
|
||||
parent: ['simple-commit', 'branch-commit'],
|
||||
tree: 'merge-tree',
|
||||
author: {
|
||||
name: 'Test User',
|
||||
email: '[email protected]',
|
||||
timestamp: 1600002000,
|
||||
timezoneOffset: 0,
|
||||
},
|
||||
committer: {
|
||||
name: 'Test User',
|
||||
email: '[email protected]',
|
||||
timestamp: 1600002000,
|
||||
timezoneOffset: 0,
|
||||
},
|
||||
},
|
||||
payload: '',
|
||||
};
|
||||
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: '[email protected]',
|
||||
timestamp: 1600000000,
|
||||
timezoneOffset: 0,
|
||||
},
|
||||
committer: {
|
||||
name: 'Test User',
|
||||
email: '[email protected]',
|
||||
timestamp: 1600000000,
|
||||
timezoneOffset: 0,
|
||||
},
|
||||
},
|
||||
payload: '',
|
||||
}];
|
||||
case 'simple-commit':
|
||||
return [{
|
||||
oid: 'simple-commit',
|
||||
commit: {
|
||||
message: 'Simple changes',
|
||||
parent: ['initial-commit'],
|
||||
tree: 'simple-tree',
|
||||
author: {
|
||||
name: 'Test User',
|
||||
email: '[email protected]',
|
||||
timestamp: 1600001000,
|
||||
timezoneOffset: 0,
|
||||
},
|
||||
committer: {
|
||||
name: 'Test User',
|
||||
email: '[email protected]',
|
||||
timestamp: 1600001000,
|
||||
timezoneOffset: 0,
|
||||
},
|
||||
},
|
||||
payload: '',
|
||||
}];
|
||||
case 'branch-commit':
|
||||
return [{
|
||||
oid: 'branch-commit',
|
||||
commit: {
|
||||
message: 'Branch commit',
|
||||
parent: ['initial-commit'],
|
||||
tree: 'branch-tree',
|
||||
author: {
|
||||
name: 'Test User',
|
||||
email: '[email protected]',
|
||||
timestamp: 1600001500,
|
||||
timezoneOffset: 0,
|
||||
},
|
||||
committer: {
|
||||
name: 'Test User',
|
||||
email: '[email protected]',
|
||||
timestamp: 1600001500,
|
||||
timezoneOffset: 0,
|
||||
},
|
||||
},
|
||||
payload: '',
|
||||
}];
|
||||
case 'merge-commit':
|
||||
return [{
|
||||
oid: 'merge-commit',
|
||||
commit: {
|
||||
message: 'Merge branch',
|
||||
parent: ['simple-commit', 'branch-commit'],
|
||||
tree: 'merge-tree',
|
||||
author: {
|
||||
name: 'Test User',
|
||||
email: '[email protected]',
|
||||
timestamp: 1600002000,
|
||||
timezoneOffset: 0,
|
||||
},
|
||||
committer: {
|
||||
name: 'Test User',
|
||||
email: '[email protected]',
|
||||
timestamp: 1600002000,
|
||||
timezoneOffset: 0,
|
||||
},
|
||||
},
|
||||
payload: '',
|
||||
}];
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}),
|
||||
|
||||
// Mock readTree to return file trees
|
||||
readTree: vi.fn().mockImplementation(async ({ oid }) => {
|
||||
switch (oid) {
|
||||
case 'initial-tree':
|
||||
return {
|
||||
oid,
|
||||
tree: [
|
||||
{ path: 'file1.txt', mode: '100644', type: 'blob', oid: 'blob-initial-1' },
|
||||
{ path: 'file2.txt', mode: '100644', type: 'blob', oid: 'blob-initial-2' },
|
||||
],
|
||||
};
|
||||
case 'simple-tree':
|
||||
return {
|
||||
oid,
|
||||
tree: [
|
||||
{ path: 'file1.txt', mode: '100644', type: 'blob', oid: 'blob-modified-1' },
|
||||
{ path: 'file2.txt', mode: '100644', type: 'blob', oid: 'blob-initial-2' },
|
||||
{ path: 'file3.txt', mode: '100644', type: 'blob', oid: 'blob-new-3' },
|
||||
],
|
||||
};
|
||||
case 'branch-tree':
|
||||
return {
|
||||
oid,
|
||||
tree: [
|
||||
{ path: 'file1.txt', mode: '100644', type: 'blob', oid: 'blob-initial-1' },
|
||||
{ path: 'file2.txt', mode: '100644', type: 'blob', oid: 'blob-branch-2' },
|
||||
{ path: 'binary.bin', mode: '100644', type: 'blob', oid: 'blob-binary' },
|
||||
],
|
||||
};
|
||||
case 'merge-tree':
|
||||
return {
|
||||
oid,
|
||||
tree: [
|
||||
{ path: 'file1.txt', mode: '100644', type: 'blob', oid: 'blob-modified-1' },
|
||||
{ path: 'file2.txt', mode: '100644', type: 'blob', oid: 'blob-branch-2' },
|
||||
{ path: 'file3.txt', mode: '100644', type: 'blob', oid: 'blob-new-3' },
|
||||
{ path: 'binary.bin', mode: '100644', type: 'blob', 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 {
|
||||
oid,
|
||||
tree: [
|
||||
{ path: 'file1.txt', mode: '100644', type: 'blob', oid: 'blob-modified-1' },
|
||||
{ path: 'file2.txt', mode: '100644', type: 'blob', oid: 'blob-initial-2' },
|
||||
],
|
||||
};
|
||||
default:
|
||||
return { oid, 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
|
||||
vi.mocked(mockGit.readTree!).mockImplementation(async ({ oid }) => {
|
||||
if (oid === 'simple-commit' || oid === 'simple-tree') {
|
||||
return {
|
||||
oid,
|
||||
tree: [
|
||||
{ path: 'file1.txt', mode: '100644', type: 'blob', oid: 'blob-modified-1' },
|
||||
{ path: 'file3.txt', mode: '100644', type: 'blob', oid: 'blob-new-3' },
|
||||
],
|
||||
};
|
||||
} else if (oid === 'initial-commit' || oid === 'initial-tree') {
|
||||
return {
|
||||
oid,
|
||||
tree: [
|
||||
{ path: 'file1.txt', mode: '100644', type: 'blob', oid: 'blob-initial-1' },
|
||||
{ path: 'file2.txt', mode: '100644', type: 'blob', oid: 'blob-initial-2' },
|
||||
],
|
||||
};
|
||||
}
|
||||
return { oid, 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
|
||||
vi.mocked(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: '[email protected]',
|
||||
timestamp: 1600001000,
|
||||
timezoneOffset: 0,
|
||||
},
|
||||
committer: {
|
||||
name: 'Test User',
|
||||
email: '[email protected]',
|
||||
timestamp: 1600001000,
|
||||
timezoneOffset: 0,
|
||||
},
|
||||
},
|
||||
payload: '',
|
||||
}];
|
||||
}
|
||||
return [];
|
||||
});
|
||||
|
||||
// Mock readCommit for the parent commit
|
||||
vi.mocked(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: '[email protected]',
|
||||
timestamp: 1600001000,
|
||||
timezoneOffset: 0,
|
||||
},
|
||||
committer: {
|
||||
name: 'Test User',
|
||||
email: '[email protected]',
|
||||
timestamp: 1600001000,
|
||||
timezoneOffset: 0,
|
||||
},
|
||||
},
|
||||
payload: '',
|
||||
};
|
||||
} 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: '[email protected]',
|
||||
timestamp: 1600000000,
|
||||
timezoneOffset: 0,
|
||||
},
|
||||
committer: {
|
||||
name: 'Test User',
|
||||
email: '[email protected]',
|
||||
timestamp: 1600000000,
|
||||
timezoneOffset: 0,
|
||||
},
|
||||
},
|
||||
payload: '',
|
||||
};
|
||||
}
|
||||
throw new Error(`Commit ${oid} not found`);
|
||||
});
|
||||
|
||||
// Force the readTree mock to return trees with different content
|
||||
vi.mocked(mockGit.readTree!).mockImplementation(async ({ oid }) => {
|
||||
if (oid === 'diff-test-tree') {
|
||||
return {
|
||||
oid,
|
||||
tree: [
|
||||
{ path: 'diff-test.txt', mode: '100644', type: 'blob', oid: 'blob-new' },
|
||||
],
|
||||
};
|
||||
} else if (oid === 'diff-parent-tree') {
|
||||
return {
|
||||
oid,
|
||||
tree: [
|
||||
{ path: 'diff-test.txt', mode: '100644', type: 'blob', oid: 'blob-old' },
|
||||
],
|
||||
};
|
||||
} else if (oid === 'diff-parent-commit') {
|
||||
return {
|
||||
oid,
|
||||
tree: [
|
||||
{ path: 'diff-test.txt', mode: '100644', type: 'blob', oid: 'blob-old' },
|
||||
],
|
||||
};
|
||||
} else if (oid === 'diff-test-commit') {
|
||||
return {
|
||||
oid,
|
||||
tree: [
|
||||
{ path: 'diff-test.txt', mode: '100644', type: 'blob', oid: 'blob-new' },
|
||||
],
|
||||
};
|
||||
}
|
||||
return { oid, tree: [] };
|
||||
});
|
||||
|
||||
// Mock readBlob to return our test content
|
||||
vi.mocked(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
|
||||
vi.mocked(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');
|
||||
});
|
||||
});
|
||||
+587
-16
@@ -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<string | null> {
|
||||
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<string | null> {
|
||||
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<string | null> {
|
||||
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<ShellCommandResult> {
|
||||
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<string, TreeEntry>();
|
||||
const commitFiles = new Map<string, TreeEntry>();
|
||||
|
||||
// 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<Map<string, TreeEntry>> => {
|
||||
const result = new Map<string, TreeEntry>();
|
||||
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<void> => {
|
||||
// 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');
|
||||
|
||||
@@ -0,0 +1,530 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { GitStashCommand } from './stash';
|
||||
import type { JSRuntimeFS } from '../../JSRuntime';
|
||||
import type { Git } from '../../git';
|
||||
|
||||
// Mock filesystem
|
||||
const createMockFS = (): JSRuntimeFS => ({
|
||||
readFile: vi.fn().mockImplementation((path: string) => {
|
||||
if (path.includes('shakespeare_stash.json')) {
|
||||
return Promise.reject(new Error('ENOENT'));
|
||||
}
|
||||
return Promise.resolve('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')) {
|
||||
return Promise.resolve({
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
size: 0,
|
||||
mtimeMs: Date.now(),
|
||||
});
|
||||
}
|
||||
return Promise.resolve({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
size: 100,
|
||||
mtimeMs: Date.now(),
|
||||
});
|
||||
}),
|
||||
lstat: vi.fn().mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
size: 100,
|
||||
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),
|
||||
});
|
||||
|
||||
// Mock Git
|
||||
const createMockGit = (): Git => ({
|
||||
statusMatrix: vi.fn(),
|
||||
currentBranch: vi.fn().mockResolvedValue('main'),
|
||||
add: vi.fn(),
|
||||
checkout: vi.fn(),
|
||||
resetIndex: vi.fn(),
|
||||
readBlob: vi.fn().mockResolvedValue({ blob: new Uint8Array() }),
|
||||
} as unknown as Git);
|
||||
|
||||
describe('GitStashCommand', () => {
|
||||
let stashCommand: GitStashCommand;
|
||||
let mockFS: JSRuntimeFS;
|
||||
let mockGit: Git;
|
||||
const testCwd = '/test';
|
||||
|
||||
beforeEach(() => {
|
||||
mockFS = createMockFS();
|
||||
mockGit = createMockGit();
|
||||
stashCommand = new GitStashCommand({
|
||||
git: mockGit,
|
||||
fs: mockFS,
|
||||
pwd: testCwd,
|
||||
});
|
||||
});
|
||||
|
||||
it('should have correct command properties', () => {
|
||||
expect(stashCommand.name).toBe('stash');
|
||||
expect(stashCommand.description).toBe('Stash the changes in a dirty working directory away');
|
||||
expect(stashCommand.usage).toBe('git stash [push | list | apply | pop | drop | clear | show] [<options>]');
|
||||
});
|
||||
|
||||
it('should return error when not in a git repository', async () => {
|
||||
vi.mocked(mockFS.stat).mockRejectedValueOnce(new Error('ENOENT'));
|
||||
|
||||
const result = await stashCommand.execute(['push']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('fatal: not a git repository');
|
||||
});
|
||||
|
||||
it('should show help with --help flag', async () => {
|
||||
const result = await stashCommand.execute(['--help']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('git stash list');
|
||||
expect(result.stdout).toContain('git stash push');
|
||||
expect(result.stdout).toContain('pop | apply');
|
||||
});
|
||||
|
||||
describe('stash push', () => {
|
||||
it('should return error when no changes to stash', async () => {
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['unchanged.txt', 1, 1, 1], // No changes
|
||||
]);
|
||||
|
||||
const result = await stashCommand.execute(['push']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('No local changes to save');
|
||||
});
|
||||
|
||||
it('should stash modified files', async () => {
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['modified.txt', 1, 2, 2], // Staged modified file
|
||||
]);
|
||||
vi.mocked(mockFS.readFile).mockImplementation((path: string) => {
|
||||
if (path.includes('modified.txt')) {
|
||||
return Promise.resolve('modified content');
|
||||
}
|
||||
if (path.includes('shakespeare_stash.json')) {
|
||||
return Promise.reject(new Error('ENOENT'));
|
||||
}
|
||||
return Promise.resolve('');
|
||||
});
|
||||
|
||||
const result = await stashCommand.execute(['push']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Saved working directory and index state');
|
||||
expect(mockFS.writeFile).toHaveBeenCalled();
|
||||
expect(mockGit.checkout).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepaths: ['modified.txt'],
|
||||
force: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('should stash with custom message', async () => {
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['modified.txt', 1, 2, 2],
|
||||
]);
|
||||
vi.mocked(mockFS.readFile).mockImplementation((path: string) => {
|
||||
if (path.includes('modified.txt')) {
|
||||
return Promise.resolve('content');
|
||||
}
|
||||
if (path.includes('shakespeare_stash.json')) {
|
||||
return Promise.reject(new Error('ENOENT'));
|
||||
}
|
||||
return Promise.resolve('');
|
||||
});
|
||||
|
||||
const result = await stashCommand.execute(['push', '-m', 'my custom message']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('my custom message');
|
||||
});
|
||||
|
||||
it('should include untracked files with -u flag', async () => {
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['untracked.txt', 0, 2, 0], // Untracked file
|
||||
]);
|
||||
vi.mocked(mockFS.readFile).mockImplementation((path: string) => {
|
||||
if (path.includes('untracked.txt')) {
|
||||
return Promise.resolve('untracked content');
|
||||
}
|
||||
if (path.includes('shakespeare_stash.json')) {
|
||||
return Promise.reject(new Error('ENOENT'));
|
||||
}
|
||||
return Promise.resolve('');
|
||||
});
|
||||
|
||||
const result = await stashCommand.execute(['push', '-u']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Saved working directory');
|
||||
expect(mockFS.unlink).toHaveBeenCalledWith(expect.stringContaining('untracked.txt'));
|
||||
});
|
||||
|
||||
it('should handle deleted files', async () => {
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['deleted.txt', 1, 0, 1], // Deleted file
|
||||
]);
|
||||
vi.mocked(mockFS.readFile).mockImplementation((path: string) => {
|
||||
if (path.includes('shakespeare_stash.json')) {
|
||||
return Promise.reject(new Error('ENOENT'));
|
||||
}
|
||||
return Promise.resolve('');
|
||||
});
|
||||
|
||||
const result = await stashCommand.execute(['push']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(mockGit.checkout).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepaths: ['deleted.txt'],
|
||||
force: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('should clear staging area after stash', async () => {
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['staged.txt', 1, 2, 2], // Staged file
|
||||
]);
|
||||
vi.mocked(mockFS.readFile).mockImplementation((path: string) => {
|
||||
if (path.includes('staged.txt')) {
|
||||
return Promise.resolve('staged content');
|
||||
}
|
||||
if (path.includes('shakespeare_stash.json')) {
|
||||
return Promise.reject(new Error('ENOENT'));
|
||||
}
|
||||
return Promise.resolve('');
|
||||
});
|
||||
|
||||
const result = await stashCommand.execute(['push']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(mockGit.resetIndex).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'staged.txt',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('stash list', () => {
|
||||
it('should return empty when no stashes', async () => {
|
||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('ENOENT'));
|
||||
|
||||
const result = await stashCommand.execute(['list']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
|
||||
it('should list all stashes', async () => {
|
||||
const mockStashes = [
|
||||
{ message: 'first stash', branch: 'main', timestamp: Date.now(), files: [], stagedFiles: [] },
|
||||
{ message: 'second stash', branch: 'main', timestamp: Date.now(), files: [], stagedFiles: [] },
|
||||
];
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||
|
||||
const result = await stashCommand.execute(['list']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('stash@{0}: first stash');
|
||||
expect(result.stdout).toContain('stash@{1}: second stash');
|
||||
});
|
||||
});
|
||||
|
||||
describe('stash show', () => {
|
||||
it('should return error when no stashes', async () => {
|
||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('ENOENT'));
|
||||
|
||||
const result = await stashCommand.execute(['show']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('No stash entries found');
|
||||
});
|
||||
|
||||
it('should show files in most recent stash', async () => {
|
||||
const mockStashes = [
|
||||
{
|
||||
message: 'test stash',
|
||||
branch: 'main',
|
||||
timestamp: Date.now(),
|
||||
files: [
|
||||
{ filepath: 'modified.txt', content: 'content', status: 'modified' },
|
||||
{ filepath: 'added.txt', content: 'content', status: 'added' },
|
||||
],
|
||||
stagedFiles: [],
|
||||
},
|
||||
];
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||
|
||||
const result = await stashCommand.execute(['show']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('M\tmodified.txt');
|
||||
expect(result.stdout).toContain('A\tadded.txt');
|
||||
});
|
||||
|
||||
it('should show specific stash by index', async () => {
|
||||
const mockStashes = [
|
||||
{
|
||||
message: 'stash 0',
|
||||
branch: 'main',
|
||||
timestamp: Date.now(),
|
||||
files: [{ filepath: 'file0.txt', content: '', status: 'modified' }],
|
||||
stagedFiles: [],
|
||||
},
|
||||
{
|
||||
message: 'stash 1',
|
||||
branch: 'main',
|
||||
timestamp: Date.now(),
|
||||
files: [{ filepath: 'file1.txt', content: '', status: 'modified' }],
|
||||
stagedFiles: [],
|
||||
},
|
||||
];
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||
|
||||
const result = await stashCommand.execute(['show', 'stash@{1}']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('file1.txt');
|
||||
expect(result.stdout).not.toContain('file0.txt');
|
||||
});
|
||||
});
|
||||
|
||||
describe('stash apply', () => {
|
||||
it('should return error when no stashes', async () => {
|
||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('ENOENT'));
|
||||
|
||||
const result = await stashCommand.execute(['apply']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('No stash entries found');
|
||||
});
|
||||
|
||||
it('should apply most recent stash', async () => {
|
||||
const mockStashes = [
|
||||
{
|
||||
message: 'test stash',
|
||||
branch: 'main',
|
||||
timestamp: Date.now(),
|
||||
files: [
|
||||
{ filepath: 'modified.txt', content: 'stashed content', status: 'modified' },
|
||||
],
|
||||
stagedFiles: ['modified.txt'],
|
||||
},
|
||||
];
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||
|
||||
const result = await stashCommand.execute(['apply']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('test stash');
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
expect.stringContaining('modified.txt'),
|
||||
'stashed content'
|
||||
);
|
||||
expect(mockGit.add).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'modified.txt',
|
||||
});
|
||||
});
|
||||
|
||||
it('should apply specific stash by index', async () => {
|
||||
const mockStashes = [
|
||||
{
|
||||
message: 'stash 0',
|
||||
branch: 'main',
|
||||
timestamp: Date.now(),
|
||||
files: [{ filepath: 'file0.txt', content: 'content0', status: 'modified' }],
|
||||
stagedFiles: [],
|
||||
},
|
||||
{
|
||||
message: 'stash 1',
|
||||
branch: 'main',
|
||||
timestamp: Date.now(),
|
||||
files: [{ filepath: 'file1.txt', content: 'content1', status: 'modified' }],
|
||||
stagedFiles: [],
|
||||
},
|
||||
];
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||
|
||||
const result = await stashCommand.execute(['apply', 'stash@{1}']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
expect.stringContaining('file1.txt'),
|
||||
'content1'
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle deleted files in stash', async () => {
|
||||
const mockStashes = [
|
||||
{
|
||||
message: 'deleted file',
|
||||
branch: 'main',
|
||||
timestamp: Date.now(),
|
||||
files: [{ filepath: 'deleted.txt', content: '', status: 'deleted' }],
|
||||
stagedFiles: [],
|
||||
},
|
||||
];
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||
|
||||
const result = await stashCommand.execute(['apply']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(mockFS.unlink).toHaveBeenCalledWith(expect.stringContaining('deleted.txt'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('stash pop', () => {
|
||||
it('should apply and drop stash', async () => {
|
||||
const mockStashes = [
|
||||
{
|
||||
message: 'test stash',
|
||||
branch: 'main',
|
||||
timestamp: Date.now(),
|
||||
files: [{ filepath: 'file.txt', content: 'content', status: 'modified' }],
|
||||
stagedFiles: [],
|
||||
},
|
||||
];
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||
|
||||
const result = await stashCommand.execute(['pop']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
expect.stringContaining('file.txt'),
|
||||
'content'
|
||||
);
|
||||
// Should also write the stash file with empty array (dropped)
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
expect.stringContaining('shakespeare_stash.json'),
|
||||
expect.stringContaining('[]')
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('stash drop', () => {
|
||||
it('should return error when no stashes', async () => {
|
||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('ENOENT'));
|
||||
|
||||
const result = await stashCommand.execute(['drop']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('No stash entries found');
|
||||
});
|
||||
|
||||
it('should drop most recent stash', async () => {
|
||||
const mockStashes = [
|
||||
{ message: 'stash 0', branch: 'main', timestamp: Date.now(), files: [], stagedFiles: [] },
|
||||
{ message: 'stash 1', branch: 'main', timestamp: Date.now(), files: [], stagedFiles: [] },
|
||||
];
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||
|
||||
const result = await stashCommand.execute(['drop']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Dropped stash@{0}');
|
||||
// Should write remaining stash
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
expect.stringContaining('shakespeare_stash.json'),
|
||||
expect.stringMatching(/stash 1/)
|
||||
);
|
||||
});
|
||||
|
||||
it('should drop specific stash by index', async () => {
|
||||
const mockStashes = [
|
||||
{ message: 'stash 0', branch: 'main', timestamp: Date.now(), files: [], stagedFiles: [] },
|
||||
{ message: 'stash 1', branch: 'main', timestamp: Date.now(), files: [], stagedFiles: [] },
|
||||
];
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||
|
||||
const result = await stashCommand.execute(['drop', 'stash@{1}']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Dropped stash@{1}');
|
||||
});
|
||||
|
||||
it('should return error for invalid stash index', async () => {
|
||||
const mockStashes = [
|
||||
{ message: 'stash 0', branch: 'main', timestamp: Date.now(), files: [], stagedFiles: [] },
|
||||
];
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||
|
||||
const result = await stashCommand.execute(['drop', 'stash@{5}']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('is not a valid reference');
|
||||
});
|
||||
});
|
||||
|
||||
describe('stash clear', () => {
|
||||
it('should clear all stashes', async () => {
|
||||
const mockStashes = [
|
||||
{ message: 'stash 0', branch: 'main', timestamp: Date.now(), files: [], stagedFiles: [] },
|
||||
{ message: 'stash 1', branch: 'main', timestamp: Date.now(), files: [], stagedFiles: [] },
|
||||
];
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||
|
||||
const result = await stashCommand.execute(['clear']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
expect.stringContaining('shakespeare_stash.json'),
|
||||
'[]'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('command aliases', () => {
|
||||
it('should accept "save" as alias for "push"', async () => {
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['file.txt', 1, 2, 2],
|
||||
]);
|
||||
vi.mocked(mockFS.readFile).mockImplementation((path: string) => {
|
||||
if (path.includes('file.txt')) {
|
||||
return Promise.resolve('content');
|
||||
}
|
||||
if (path.includes('shakespeare_stash.json')) {
|
||||
return Promise.reject(new Error('ENOENT'));
|
||||
}
|
||||
return Promise.resolve('');
|
||||
});
|
||||
|
||||
const result = await stashCommand.execute(['save']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Saved working directory');
|
||||
});
|
||||
|
||||
it('should default to "push" when no subcommand given', async () => {
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['file.txt', 1, 2, 2],
|
||||
]);
|
||||
vi.mocked(mockFS.readFile).mockImplementation((path: string) => {
|
||||
if (path.includes('file.txt')) {
|
||||
return Promise.resolve('content');
|
||||
}
|
||||
if (path.includes('shakespeare_stash.json')) {
|
||||
return Promise.reject(new Error('ENOENT'));
|
||||
}
|
||||
return Promise.resolve('');
|
||||
});
|
||||
|
||||
const result = await stashCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Saved working directory');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,449 @@
|
||||
import { join } from "path-browserify";
|
||||
import type { JSRuntimeFS } from "../../JSRuntime";
|
||||
import type { ShellCommandResult } from "../ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "../ShellCommand";
|
||||
import type { GitSubcommand, GitSubcommandOptions } from "../git";
|
||||
import type { Git } from "../../git";
|
||||
|
||||
interface StashEntry {
|
||||
message: string;
|
||||
branch: string;
|
||||
timestamp: number;
|
||||
files: Array<{
|
||||
filepath: string;
|
||||
content: string;
|
||||
status: 'modified' | 'added' | 'deleted';
|
||||
}>;
|
||||
stagedFiles: string[];
|
||||
}
|
||||
|
||||
export class GitStashCommand implements GitSubcommand {
|
||||
name = 'stash';
|
||||
description = 'Stash the changes in a dirty working directory away';
|
||||
usage = 'git stash [push | list | apply | pop | drop | clear | show] [<options>]';
|
||||
|
||||
private git: Git;
|
||||
private fs: JSRuntimeFS;
|
||||
private pwd: string;
|
||||
|
||||
constructor(options: GitSubcommandOptions) {
|
||||
this.git = options.git;
|
||||
this.fs = options.fs;
|
||||
this.pwd = options.pwd;
|
||||
}
|
||||
|
||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Check if we're in a git repository
|
||||
try {
|
||||
await this.fs.stat(`${this.pwd}/.git`);
|
||||
} catch {
|
||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||
}
|
||||
|
||||
const subcommand = args[0] || 'push';
|
||||
const subcommandArgs = args.slice(1);
|
||||
|
||||
switch (subcommand) {
|
||||
case 'push':
|
||||
case 'save':
|
||||
return await this.stashPush(subcommandArgs);
|
||||
case 'list':
|
||||
return await this.stashList();
|
||||
case 'apply':
|
||||
return await this.stashApply(subcommandArgs);
|
||||
case 'pop':
|
||||
return await this.stashPop(subcommandArgs);
|
||||
case 'drop':
|
||||
return await this.stashDrop(subcommandArgs);
|
||||
case 'clear':
|
||||
return await this.stashClear();
|
||||
case 'show':
|
||||
return await this.stashShow(subcommandArgs);
|
||||
case '--help':
|
||||
case '-h':
|
||||
return this.showHelp();
|
||||
default:
|
||||
// If first arg doesn't look like a subcommand, treat it as 'push'
|
||||
if (subcommand.startsWith('-')) {
|
||||
return await this.stashPush(args);
|
||||
}
|
||||
return createErrorResult(`git stash: '${subcommand}' is not a stash command. See 'git stash --help'.`);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
return createErrorResult(`git stash: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async stashPush(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Parse arguments
|
||||
let message = 'WIP on';
|
||||
let includeUntracked = false;
|
||||
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
if (args[i] === '-m' || args[i] === '--message') {
|
||||
if (i + 1 < args.length) {
|
||||
message = args[i + 1];
|
||||
i++;
|
||||
}
|
||||
} else if (args[i] === '-u' || args[i] === '--include-untracked') {
|
||||
includeUntracked = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Get current branch
|
||||
let currentBranch: string | null = null;
|
||||
try {
|
||||
currentBranch = await this.git.currentBranch({ dir: this.pwd }) || null;
|
||||
} catch {
|
||||
currentBranch = 'HEAD';
|
||||
}
|
||||
|
||||
// Get status to find changed files
|
||||
const statusMatrix = await this.git.statusMatrix({ dir: this.pwd });
|
||||
|
||||
const filesToStash: StashEntry['files'] = [];
|
||||
const stagedFiles: string[] = [];
|
||||
|
||||
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) {
|
||||
try {
|
||||
// Track staged files
|
||||
if (headStatus !== stageStatus) {
|
||||
stagedFiles.push(filepath);
|
||||
}
|
||||
|
||||
const hasWorkdirChanges = stageStatus !== workdirStatus;
|
||||
const hasStagedChanges = headStatus !== stageStatus;
|
||||
|
||||
// Skip if no changes at all
|
||||
if (!hasWorkdirChanges && !hasStagedChanges) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Untracked files (only with -u flag)
|
||||
if (includeUntracked && headStatus === 0 && stageStatus === 0 && workdirStatus === 2) {
|
||||
const content = await this.fs.readFile(join(this.pwd, filepath), 'utf8');
|
||||
filesToStash.push({
|
||||
filepath,
|
||||
content,
|
||||
status: 'added',
|
||||
});
|
||||
}
|
||||
// Deleted files (deleted in working dir)
|
||||
else if (workdirStatus === 0 && (stageStatus === 1 || stageStatus === 2)) {
|
||||
filesToStash.push({
|
||||
filepath,
|
||||
content: '',
|
||||
status: 'deleted',
|
||||
});
|
||||
}
|
||||
// Staged new files or modified files (staged changes)
|
||||
else if (hasStagedChanges && workdirStatus === 2) {
|
||||
const content = await this.fs.readFile(join(this.pwd, filepath), 'utf8');
|
||||
const status = headStatus === 0 ? 'added' : 'modified';
|
||||
filesToStash.push({
|
||||
filepath,
|
||||
content,
|
||||
status,
|
||||
});
|
||||
}
|
||||
// Unstaged modifications in working directory
|
||||
else if (hasWorkdirChanges && workdirStatus === 2) {
|
||||
const content = await this.fs.readFile(join(this.pwd, filepath), 'utf8');
|
||||
filesToStash.push({
|
||||
filepath,
|
||||
content,
|
||||
status: 'modified',
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`Failed to process ${filepath}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
if (filesToStash.length === 0) {
|
||||
return createErrorResult('No local changes to save');
|
||||
}
|
||||
|
||||
// Create stash entry
|
||||
const stashEntry: StashEntry = {
|
||||
message: message === 'WIP on' ? `WIP on ${currentBranch}` : message,
|
||||
branch: currentBranch || 'HEAD',
|
||||
timestamp: Date.now(),
|
||||
files: filesToStash,
|
||||
stagedFiles,
|
||||
};
|
||||
|
||||
// Save stash
|
||||
await this.saveStash(stashEntry);
|
||||
|
||||
// Revert changes in working directory
|
||||
for (const file of filesToStash) {
|
||||
try {
|
||||
if (file.status === 'deleted') {
|
||||
// Restore deleted file from HEAD
|
||||
await this.git.checkout({
|
||||
dir: this.pwd,
|
||||
filepaths: [file.filepath],
|
||||
force: true,
|
||||
});
|
||||
} else if (file.status === 'modified') {
|
||||
// Restore file from HEAD using checkout
|
||||
await this.git.checkout({
|
||||
dir: this.pwd,
|
||||
filepaths: [file.filepath],
|
||||
force: true,
|
||||
});
|
||||
} else if (file.status === 'added') {
|
||||
// Delete new file (it doesn't exist in HEAD)
|
||||
try {
|
||||
await this.fs.unlink(join(this.pwd, file.filepath));
|
||||
} catch {
|
||||
// File might already be gone
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`Failed to revert ${file.filepath}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
// Clear staging area
|
||||
for (const file of stagedFiles) {
|
||||
try {
|
||||
await this.git.resetIndex({
|
||||
dir: this.pwd,
|
||||
filepath: file,
|
||||
});
|
||||
} catch {
|
||||
// Continue if reset fails
|
||||
}
|
||||
}
|
||||
|
||||
return createSuccessResult(`Saved working directory and index state ${stashEntry.message}\n`);
|
||||
|
||||
} catch (error) {
|
||||
return createErrorResult(`Failed to stash changes: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async stashList(): Promise<ShellCommandResult> {
|
||||
try {
|
||||
const stashes = await this.loadStashes();
|
||||
|
||||
if (stashes.length === 0) {
|
||||
return createSuccessResult('');
|
||||
}
|
||||
|
||||
const lines = stashes.map((stash, index) => {
|
||||
return `stash@{${index}}: ${stash.message}`;
|
||||
});
|
||||
|
||||
return createSuccessResult(lines.join('\n') + '\n');
|
||||
|
||||
} catch (error) {
|
||||
return createErrorResult(`Failed to list stashes: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async stashApply(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
const stashes = await this.loadStashes();
|
||||
|
||||
if (stashes.length === 0) {
|
||||
return createErrorResult('No stash entries found.');
|
||||
}
|
||||
|
||||
// Parse stash reference (e.g., stash@{0} or just 0)
|
||||
const stashRef = args[0] || 'stash@{0}';
|
||||
const index = this.parseStashRef(stashRef);
|
||||
|
||||
if (index < 0 || index >= stashes.length) {
|
||||
return createErrorResult(`stash@{${index}} is not a valid reference`);
|
||||
}
|
||||
|
||||
const stash = stashes[index];
|
||||
|
||||
// Apply stashed changes
|
||||
for (const file of stash.files) {
|
||||
try {
|
||||
if (file.status === 'deleted') {
|
||||
// Delete the file
|
||||
try {
|
||||
await this.fs.unlink(join(this.pwd, file.filepath));
|
||||
} catch {
|
||||
// File might not exist
|
||||
}
|
||||
} else {
|
||||
// Create file with stashed content
|
||||
const dir = join(this.pwd, file.filepath, '..');
|
||||
try {
|
||||
await this.fs.mkdir(dir, { recursive: true });
|
||||
} catch {
|
||||
// Directory might exist
|
||||
}
|
||||
await this.fs.writeFile(join(this.pwd, file.filepath), file.content);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`Failed to apply ${file.filepath}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
// Restore staging area
|
||||
for (const filepath of stash.stagedFiles) {
|
||||
try {
|
||||
await this.git.add({
|
||||
dir: this.pwd,
|
||||
filepath,
|
||||
});
|
||||
} catch {
|
||||
// Continue if add fails
|
||||
}
|
||||
}
|
||||
|
||||
return createSuccessResult(`On branch ${stash.branch}: ${stash.message}\n`);
|
||||
|
||||
} catch (error) {
|
||||
return createErrorResult(`Failed to apply stash: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async stashPop(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Apply the stash first
|
||||
const result = await this.stashApply(args);
|
||||
|
||||
if (result.exitCode !== 0) {
|
||||
return result;
|
||||
}
|
||||
|
||||
// If apply succeeded, drop the stash
|
||||
const dropResult = await this.stashDrop(args);
|
||||
|
||||
if (dropResult.exitCode !== 0) {
|
||||
return createErrorResult(`Applied stash successfully but failed to drop: ${dropResult.stderr}`);
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
} catch (error) {
|
||||
return createErrorResult(`Failed to pop stash: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async stashDrop(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
const stashes = await this.loadStashes();
|
||||
|
||||
if (stashes.length === 0) {
|
||||
return createErrorResult('No stash entries found.');
|
||||
}
|
||||
|
||||
// Parse stash reference
|
||||
const stashRef = args[0] || 'stash@{0}';
|
||||
const index = this.parseStashRef(stashRef);
|
||||
|
||||
if (index < 0 || index >= stashes.length) {
|
||||
return createErrorResult(`stash@{${index}} is not a valid reference`);
|
||||
}
|
||||
|
||||
// Remove the stash
|
||||
stashes.splice(index, 1);
|
||||
await this.saveStashes(stashes);
|
||||
|
||||
return createSuccessResult(`Dropped stash@{${index}}\n`);
|
||||
|
||||
} catch (error) {
|
||||
return createErrorResult(`Failed to drop stash: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async stashClear(): Promise<ShellCommandResult> {
|
||||
try {
|
||||
await this.saveStashes([]);
|
||||
return createSuccessResult('');
|
||||
|
||||
} catch (error) {
|
||||
return createErrorResult(`Failed to clear stashes: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async stashShow(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
const stashes = await this.loadStashes();
|
||||
|
||||
if (stashes.length === 0) {
|
||||
return createErrorResult('No stash entries found.');
|
||||
}
|
||||
|
||||
// Parse stash reference
|
||||
const stashRef = args[0] || 'stash@{0}';
|
||||
const index = this.parseStashRef(stashRef);
|
||||
|
||||
if (index < 0 || index >= stashes.length) {
|
||||
return createErrorResult(`stash@{${index}} is not a valid reference`);
|
||||
}
|
||||
|
||||
const stash = stashes[index];
|
||||
const lines: string[] = [];
|
||||
|
||||
// Show file changes
|
||||
for (const file of stash.files) {
|
||||
const status = file.status === 'added' ? 'A' : file.status === 'deleted' ? 'D' : 'M';
|
||||
lines.push(`${status}\t${file.filepath}`);
|
||||
}
|
||||
|
||||
if (lines.length === 0) {
|
||||
lines.push('No changes in stash');
|
||||
}
|
||||
|
||||
return createSuccessResult(lines.join('\n') + '\n');
|
||||
|
||||
} catch (error) {
|
||||
return createErrorResult(`Failed to show stash: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
private parseStashRef(ref: string): number {
|
||||
// Parse stash@{N} or just N
|
||||
const match = ref.match(/^(?:stash@\{)?(\d+)\}?$/);
|
||||
if (match) {
|
||||
return parseInt(match[1], 10);
|
||||
}
|
||||
return 0; // Default to stash@{0}
|
||||
}
|
||||
|
||||
private async loadStashes(): Promise<StashEntry[]> {
|
||||
try {
|
||||
const stashPath = join(this.pwd, '.git', 'shakespeare_stash.json');
|
||||
const data = await this.fs.readFile(stashPath, 'utf8');
|
||||
return JSON.parse(data) as StashEntry[];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private async saveStash(stash: StashEntry): Promise<void> {
|
||||
const stashes = await this.loadStashes();
|
||||
stashes.unshift(stash); // Add to beginning of array
|
||||
await this.saveStashes(stashes);
|
||||
}
|
||||
|
||||
private async saveStashes(stashes: StashEntry[]): Promise<void> {
|
||||
const stashPath = join(this.pwd, '.git', 'shakespeare_stash.json');
|
||||
await this.fs.writeFile(stashPath, JSON.stringify(stashes, null, 2));
|
||||
}
|
||||
|
||||
private showHelp(): ShellCommandResult {
|
||||
const helpText = `usage: git stash list [<options>]
|
||||
or: git stash show [<stash>]
|
||||
or: git stash drop [<stash>]
|
||||
or: git stash ( pop | apply ) [<stash>]
|
||||
or: git stash push [-m <message>] [-u | --include-untracked]
|
||||
or: git stash clear
|
||||
`;
|
||||
|
||||
return createSuccessResult(helpText);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user