Refactor git subcommands to accept a git instance

This commit is contained in:
Alex Gleason committed 2025-09-14 17:15:07 -05:00
1 parent 772a2f424b
commit 1ab895bd59
23 files changed
+581 -413

No files matched your search

+3 -1
View File
@@ -32,6 +32,7 @@ import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool';
import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool';
import { ShellTool } from '@/lib/tools/ShellTool';
import { TypecheckTool } from '@/lib/tools/TypecheckTool';
import { Git } from '@/lib/git';
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
import { Tool } from '@/lib/tools/Tool';
import OpenAI from 'openai';
@@ -89,6 +90,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
// Initialize AI chat with tools
const cwd = `/projects/${projectId}`;
const customTools = useMemo(() => {
const git = new Git(fs);
const baseTools = {
git_commit: new GitCommitTool(fs, cwd),
text_editor_view: new TextEditorViewTool(fs, cwd),
@@ -105,7 +107,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
nostr_read_protocol: new NostrReadProtocolTool(),
nostr_read_nips_index: new NostrReadNipsIndexTool(),
nostr_generate_kind: new NostrGenerateKindTool(),
shell: new ShellTool(fs, cwd),
shell: new ShellTool(fs, cwd, git),
};
// Add deploy tool only if user is logged in
+3 -1
View File
@@ -1,4 +1,5 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { Git } from '../git';
import { GitCommand } from './git';
import type { JSRuntimeFS } from '../JSRuntime';
@@ -39,7 +40,8 @@ describe('GitCommand', () => {
beforeEach(() => {
mockFS = createMockFS();
gitCommand = new GitCommand(mockFS);
const git = new Git(mockFS);
gitCommand = new GitCommand({ git, fs: mockFS, cwd: testCwd });
});
it('should have correct command properties', () => {
+45 -22
View File
@@ -1,3 +1,4 @@
import type { Git } from "../git";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
@@ -24,7 +25,19 @@ export interface GitSubcommand {
name: string;
description: string;
usage: string;
execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise<ShellCommandResult>;
execute(args: string[]): Promise<ShellCommandResult>;
}
export interface GitSubcommandOptions {
git: Git;
fs: JSRuntimeFS;
pwd: string;
}
export interface GitCommandOptions {
git: Git;
fs: JSRuntimeFS;
cwd: string;
}
/**
@@ -36,37 +49,47 @@ export class GitCommand implements ShellCommand {
description = 'Git version control system';
usage = 'git <command> [<args>]';
private git: Git;
private fs: JSRuntimeFS;
private cwd: string;
private subcommands: Map<string, GitSubcommand>;
constructor(fs: JSRuntimeFS) {
this.fs = fs;
constructor(options: GitCommandOptions) {
this.git = options.git;
this.fs = options.fs;
this.cwd = options.cwd;
this.subcommands = new Map();
// Register all subcommands
this.registerSubcommand(new GitInitCommand());
this.registerSubcommand(new GitStatusCommand());
this.registerSubcommand(new GitAddCommand());
this.registerSubcommand(new GitCommitCommand());
this.registerSubcommand(new GitLogCommand());
this.registerSubcommand(new GitBranchCommand());
this.registerSubcommand(new GitCheckoutCommand());
this.registerSubcommand(new GitRemoteCommand());
this.registerSubcommand(new GitPushCommand());
this.registerSubcommand(new GitPullCommand());
this.registerSubcommand(new GitCloneCommand());
this.registerSubcommand(new GitConfigCommand());
this.registerSubcommand(new GitResetCommand());
this.registerSubcommand(new GitDiffCommand());
this.registerSubcommand(new GitTagCommand());
this.registerSubcommand(new GitShowCommand());
const subcommandOptions: GitSubcommandOptions = {
git: this.git,
fs: this.fs,
pwd: this.cwd,
};
this.registerSubcommand(new GitInitCommand(subcommandOptions));
this.registerSubcommand(new GitStatusCommand(subcommandOptions));
this.registerSubcommand(new GitAddCommand(subcommandOptions));
this.registerSubcommand(new GitCommitCommand(subcommandOptions));
this.registerSubcommand(new GitLogCommand(subcommandOptions));
this.registerSubcommand(new GitBranchCommand(subcommandOptions));
this.registerSubcommand(new GitCheckoutCommand(subcommandOptions));
this.registerSubcommand(new GitRemoteCommand(subcommandOptions));
this.registerSubcommand(new GitPushCommand(subcommandOptions));
this.registerSubcommand(new GitPullCommand(subcommandOptions));
this.registerSubcommand(new GitCloneCommand(subcommandOptions));
this.registerSubcommand(new GitConfigCommand(subcommandOptions));
this.registerSubcommand(new GitResetCommand(subcommandOptions));
this.registerSubcommand(new GitDiffCommand(subcommandOptions));
this.registerSubcommand(new GitTagCommand(subcommandOptions));
this.registerSubcommand(new GitShowCommand(subcommandOptions));
}
private registerSubcommand(subcommand: GitSubcommand): void {
this.subcommands.set(subcommand.name, subcommand);
}
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
async execute(args: string[], _cwd: string, _input?: string): Promise<ShellCommandResult> {
try {
// Handle no arguments or help
if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
@@ -88,7 +111,7 @@ export class GitCommand implements ShellCommand {
}
// Execute the subcommand
return await subcommand.execute(subcommandArgs, cwd, this.fs);
return await subcommand.execute(subcommandArgs);
} catch (error) {
return createErrorResult(`git: ${error instanceof Error ? error.message : 'Unknown error'}`);
+51 -42
View File
@@ -1,20 +1,30 @@
import git from 'isomorphic-git';
import { join } from "@std/path";
import type { JSRuntimeFS } from "../../JSRuntime";
import type { ShellCommandResult } from "../ShellCommand";
import { createSuccessResult, createErrorResult } from "../ShellCommand";
import type { GitSubcommand } from "../git";
import type { GitSubcommand, GitSubcommandOptions } from "../git";
import type { Git } from "../../git";
export class GitAddCommand implements GitSubcommand {
name = 'add';
description = 'Add file contents to the index';
usage = 'git add [--all | -A] [--] [<pathspec>...]';
async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise<ShellCommandResult> {
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 fs.stat(`${cwd}/.git`);
await this.fs.stat(`${this.pwd}/.git`);
} catch {
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
}
@@ -23,12 +33,12 @@ export class GitAddCommand implements GitSubcommand {
if (options.all) {
// Add all files (git add -A)
return await this.addAllFiles(fs, cwd);
return await this.addAllFiles();
} else if (paths.length === 0) {
return createErrorResult('Nothing specified, nothing added.\nMaybe you wanted to say \'git add .\'?');
} else {
// Add specific files
return await this.addSpecificFiles(fs, cwd, paths);
return await this.addSpecificFiles(paths);
}
} catch (error) {
@@ -60,12 +70,11 @@ export class GitAddCommand implements GitSubcommand {
return { options, paths };
}
private async addAllFiles(fs: JSRuntimeFS, cwd: string): Promise<ShellCommandResult> {
private async addAllFiles(): Promise<ShellCommandResult> {
try {
// Get status to find all changed files
const statusMatrix = await git.statusMatrix({
fs,
dir: cwd,
const statusMatrix = await this.git.statusMatrix({
dir: this.pwd,
});
let addedCount = 0;
@@ -75,17 +84,17 @@ export class GitAddCommand implements GitSubcommand {
try {
if (workdirStatus === 0 && headStatus === 1) {
// File was deleted
await git.remove({
fs,
dir: cwd,
await this.git.remove({
dir: this.pwd,
filepath,
});
removedCount++;
} else if (workdirStatus === 1) {
// File exists (new or modified)
await git.add({
fs,
dir: cwd,
await this.git.add({
dir: this.pwd,
filepath,
});
addedCount++;
@@ -115,7 +124,7 @@ export class GitAddCommand implements GitSubcommand {
}
}
private async addSpecificFiles(fs: JSRuntimeFS, cwd: string, paths: string[]): Promise<ShellCommandResult> {
private async addSpecificFiles(paths: string[]): Promise<ShellCommandResult> {
const addedFiles: string[] = [];
const errors: string[] = [];
@@ -123,26 +132,26 @@ export class GitAddCommand implements GitSubcommand {
try {
if (path === '.') {
// Add current directory (all files in it)
const statusMatrix = await git.statusMatrix({
fs,
dir: cwd,
const statusMatrix = await this.git.statusMatrix({
dir: this.pwd,
});
for (const [filepath, headStatus, workdirStatus] of statusMatrix) {
try {
if (workdirStatus === 0 && headStatus === 1) {
// File was deleted
await git.remove({
fs,
dir: cwd,
await this.git.remove({
dir: this.pwd,
filepath,
});
addedFiles.push(filepath);
} else if (workdirStatus === 1) {
// File exists
await git.add({
fs,
dir: cwd,
await this.git.add({
dir: this.pwd,
filepath,
});
addedFiles.push(filepath);
@@ -158,20 +167,20 @@ export class GitAddCommand implements GitSubcommand {
continue;
}
const absolutePath = join(cwd, path);
const absolutePath = join(this.pwd, path);
// Check if file/directory exists
try {
const stats = await fs.stat(absolutePath);
const stats = await this.fs.stat(absolutePath);
if (stats.isDirectory()) {
// Add all files in directory
await this.addDirectory(fs, cwd, path, addedFiles);
await this.addDirectory(path, addedFiles);
} else {
// Add single file
await git.add({
fs,
dir: cwd,
await this.git.add({
dir: this.pwd,
filepath: path,
});
addedFiles.push(path);
@@ -179,9 +188,9 @@ export class GitAddCommand implements GitSubcommand {
} catch {
// Check if it's a deleted file
try {
await git.remove({
fs,
dir: cwd,
await this.git.remove({
dir: this.pwd,
filepath: path,
});
addedFiles.push(path);
@@ -206,9 +215,9 @@ export class GitAddCommand implements GitSubcommand {
return createSuccessResult(`Added ${addedFiles.length} file${addedFiles.length !== 1 ? 's' : ''}\n`);
}
private async addDirectory(fs: JSRuntimeFS, cwd: string, dirPath: string, addedFiles: string[]): Promise<void> {
const absolutePath = join(cwd, dirPath);
const entries = await fs.readdir(absolutePath, { withFileTypes: true });
private async addDirectory(dirPath: string, addedFiles: string[]): Promise<void> {
const absolutePath = join(this.pwd, dirPath);
const entries = await this.fs.readdir(absolutePath, { withFileTypes: true });
for (const entry of entries) {
if (entry.name.startsWith('.')) {
@@ -218,12 +227,12 @@ export class GitAddCommand implements GitSubcommand {
const entryPath = join(dirPath, entry.name);
if (entry.isDirectory()) {
await this.addDirectory(fs, cwd, entryPath, addedFiles);
await this.addDirectory(entryPath, addedFiles);
} else {
try {
await git.add({
fs,
dir: cwd,
await this.git.add({
dir: this.pwd,
filepath: entryPath,
});
addedFiles.push(entryPath);
+41 -36
View File
@@ -1,19 +1,29 @@
import git from 'isomorphic-git';
import type { JSRuntimeFS } from "../../JSRuntime";
import type { ShellCommandResult } from "../ShellCommand";
import { createSuccessResult, createErrorResult } from "../ShellCommand";
import type { GitSubcommand } from "../git";
import type { GitSubcommand, GitSubcommandOptions } from "../git";
import type { Git } from "../../git";
export class GitBranchCommand implements GitSubcommand {
name = 'branch';
description = 'List, create, or delete branches';
usage = 'git branch [--list] | git branch <branchname> | git branch (-d | -D) <branchname>';
async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise<ShellCommandResult> {
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 fs.stat(`${cwd}/.git`);
await this.fs.stat(`${this.pwd}/.git`);
} catch {
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
}
@@ -22,13 +32,13 @@ export class GitBranchCommand implements GitSubcommand {
switch (action) {
case 'list':
return await this.listBranches(fs, cwd);
return await this.listBranches();
case 'create':
return await this.createBranch(fs, cwd, branchName!);
return await this.createBranch(branchName!);
case 'delete':
return await this.deleteBranch(fs, cwd, branchName!, options.force);
return await this.deleteBranch(branchName!, options.force);
default:
return await this.listBranches(fs, cwd);
return await this.listBranches();
}
} catch (error) {
@@ -73,11 +83,10 @@ export class GitBranchCommand implements GitSubcommand {
return { action, branchName, options };
}
private async listBranches(fs: JSRuntimeFS, cwd: string): Promise<ShellCommandResult> {
private async listBranches(): Promise<ShellCommandResult> {
try {
const branches = await git.listBranches({
fs,
dir: cwd,
const branches = await this.git.listBranches({
dir: this.pwd,
});
if (branches.length === 0) {
@@ -87,9 +96,9 @@ export class GitBranchCommand implements GitSubcommand {
// Get current branch
let currentBranch: string | null = null;
try {
currentBranch = await git.currentBranch({
fs,
dir: cwd,
currentBranch = await this.git.currentBranch({
dir: this.pwd,
}) || null;
} catch {
// Might be in detached HEAD state
@@ -111,12 +120,11 @@ export class GitBranchCommand implements GitSubcommand {
}
}
private async createBranch(fs: JSRuntimeFS, cwd: string, branchName: string): Promise<ShellCommandResult> {
private async createBranch(branchName: string): Promise<ShellCommandResult> {
try {
// Check if branch already exists
const branches = await git.listBranches({
fs,
dir: cwd,
const branches = await this.git.listBranches({
dir: this.pwd,
});
if (branches.includes(branchName)) {
@@ -126,9 +134,9 @@ export class GitBranchCommand implements GitSubcommand {
// Get current HEAD to base the new branch on
let currentRef: string;
try {
currentRef = await git.resolveRef({
fs,
dir: cwd,
currentRef = await this.git.resolveRef({
dir: this.pwd,
ref: 'HEAD',
});
} catch {
@@ -136,9 +144,8 @@ export class GitBranchCommand implements GitSubcommand {
}
// Create the new branch
await git.branch({
fs,
dir: cwd,
await this.git.branch({
dir: this.pwd,
ref: branchName,
object: currentRef,
});
@@ -150,12 +157,11 @@ export class GitBranchCommand implements GitSubcommand {
}
}
private async deleteBranch(fs: JSRuntimeFS, cwd: string, branchName: string, force: boolean): Promise<ShellCommandResult> {
private async deleteBranch(branchName: string, force: boolean): Promise<ShellCommandResult> {
try {
// Check if branch exists
const branches = await git.listBranches({
fs,
dir: cwd,
const branches = await this.git.listBranches({
dir: this.pwd,
});
if (!branches.includes(branchName)) {
@@ -165,22 +171,21 @@ export class GitBranchCommand implements GitSubcommand {
// Check if it's the current branch
let currentBranch: string | null = null;
try {
currentBranch = await git.currentBranch({
fs,
dir: cwd,
currentBranch = await this.git.currentBranch({
dir: this.pwd,
}) || null;
} catch {
// Continue
}
if (currentBranch === branchName) {
return createErrorResult(`error: Cannot delete branch '${branchName}' checked out at '${cwd}'`);
return createErrorResult(`error: Cannot delete branch '${branchName}' checked out at '${this.pwd}'`);
}
// Delete the branch
await git.deleteBranch({
fs,
dir: cwd,
await this.git.deleteBranch({
dir: this.pwd,
ref: branchName,
});
+41 -37
View File
@@ -1,19 +1,29 @@
import git from 'isomorphic-git';
import type { JSRuntimeFS } from "../../JSRuntime";
import type { ShellCommandResult } from "../ShellCommand";
import { createSuccessResult, createErrorResult } from "../ShellCommand";
import type { GitSubcommand } from "../git";
import type { GitSubcommand, GitSubcommandOptions } from "../git";
import type { Git } from "../../git";
export class GitCheckoutCommand implements GitSubcommand {
name = 'checkout';
description = 'Switch branches or restore working tree files';
usage = 'git checkout <branch> | git checkout -b <new-branch> | git checkout -- <file>';
async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise<ShellCommandResult> {
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 fs.stat(`${cwd}/.git`);
await this.fs.stat(`${this.pwd}/.git`);
} catch {
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
}
@@ -22,11 +32,11 @@ export class GitCheckoutCommand implements GitSubcommand {
switch (action) {
case 'switch':
return await this.switchBranch(fs, cwd, target!);
return await this.switchBranch(target!);
case 'create':
return await this.createAndSwitchBranch(fs, cwd, target!);
return await this.createAndSwitchBranch(target!);
case 'restore':
return await this.restoreFiles(fs, cwd, target!);
return await this.restoreFiles(target!);
default:
return createErrorResult('error: pathspec did not match any file(s) known to git');
}
@@ -72,12 +82,11 @@ export class GitCheckoutCommand implements GitSubcommand {
return { action, target, options };
}
private async switchBranch(fs: JSRuntimeFS, cwd: string, branchName: string): Promise<ShellCommandResult> {
private async switchBranch(branchName: string): Promise<ShellCommandResult> {
try {
// Check if branch exists
const branches = await git.listBranches({
fs,
dir: cwd,
const branches = await this.git.listBranches({
dir: this.pwd,
});
if (!branches.includes(branchName)) {
@@ -87,9 +96,9 @@ export class GitCheckoutCommand implements GitSubcommand {
// Get current branch
let currentBranch: string | null = null;
try {
currentBranch = await git.currentBranch({
fs,
dir: cwd,
currentBranch = await this.git.currentBranch({
dir: this.pwd,
}) || null;
} catch {
// Continue
@@ -100,9 +109,8 @@ export class GitCheckoutCommand implements GitSubcommand {
}
// Check for uncommitted changes
const statusMatrix = await git.statusMatrix({
fs,
dir: cwd,
const statusMatrix = await this.git.statusMatrix({
dir: this.pwd,
});
const hasChanges = statusMatrix.some(([, headStatus, workdirStatus, stageStatus]) => {
@@ -114,9 +122,8 @@ export class GitCheckoutCommand implements GitSubcommand {
}
// Switch to the branch
await git.checkout({
fs,
dir: cwd,
await this.git.checkout({
dir: this.pwd,
ref: branchName,
});
@@ -127,12 +134,11 @@ export class GitCheckoutCommand implements GitSubcommand {
}
}
private async createAndSwitchBranch(fs: JSRuntimeFS, cwd: string, branchName: string): Promise<ShellCommandResult> {
private async createAndSwitchBranch(branchName: string): Promise<ShellCommandResult> {
try {
// Check if branch already exists
const branches = await git.listBranches({
fs,
dir: cwd,
const branches = await this.git.listBranches({
dir: this.pwd,
});
if (branches.includes(branchName)) {
@@ -142,9 +148,9 @@ export class GitCheckoutCommand implements GitSubcommand {
// Get current HEAD
let currentRef: string;
try {
currentRef = await git.resolveRef({
fs,
dir: cwd,
currentRef = await this.git.resolveRef({
dir: this.pwd,
ref: 'HEAD',
});
} catch {
@@ -152,17 +158,15 @@ export class GitCheckoutCommand implements GitSubcommand {
}
// Create the branch
await git.branch({
fs,
dir: cwd,
await this.git.branch({
dir: this.pwd,
ref: branchName,
object: currentRef,
});
// Switch to the new branch
await git.checkout({
fs,
dir: cwd,
await this.git.checkout({
dir: this.pwd,
ref: branchName,
});
@@ -173,16 +177,16 @@ export class GitCheckoutCommand implements GitSubcommand {
}
}
private async restoreFiles(fs: JSRuntimeFS, cwd: string, filePath: string): Promise<ShellCommandResult> {
private async restoreFiles(filePath: string): Promise<ShellCommandResult> {
try {
// This is a simplified implementation
// In a full git implementation, this would restore files from the index or HEAD
// Get the file from HEAD
try {
await git.checkout({
fs,
dir: cwd,
await this.git.checkout({
dir: this.pwd,
ref: 'HEAD',
filepaths: [filePath],
});
+17 -7
View File
@@ -1,16 +1,26 @@
import git from 'isomorphic-git';
import http from 'isomorphic-git/http/web';
import type { JSRuntimeFS } from "../../JSRuntime";
import type { ShellCommandResult } from "../ShellCommand";
import { createSuccessResult, createErrorResult } from "../ShellCommand";
import type { GitSubcommand } from "../git";
import type { GitSubcommand, GitSubcommandOptions } from "../git";
import type { Git } from "../../git";
export class GitCloneCommand implements GitSubcommand {
name = 'clone';
description = 'Clone a repository into a new directory';
usage = 'git clone [--depth <depth>] [--single-branch] <repository> [<directory>]';
async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise<ShellCommandResult> {
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 {
const { options, repository, directory } = this.parseArgs(args);
@@ -27,11 +37,11 @@ export class GitCloneCommand implements GitSubcommand {
targetDir = repoName.replace(/\.git$/, ''); // Remove .git suffix if present
}
const targetPath = `${cwd}/${targetDir}`;
const targetPath = `${this.pwd}/${targetDir}`;
// Check if target directory already exists
try {
await fs.stat(targetPath);
await this.fs.stat(targetPath);
return createErrorResult(`fatal: destination path '${targetDir}' already exists and is not an empty directory.`);
} catch {
// Directory doesn't exist, which is what we want
@@ -46,8 +56,8 @@ export class GitCloneCommand implements GitSubcommand {
}
// Clone the repository
await git.clone({
fs,
await this.git.clone({
http,
dir: targetPath,
url: repository,
+33 -25
View File
@@ -1,19 +1,29 @@
import git from 'isomorphic-git';
import type { JSRuntimeFS } from "../../JSRuntime";
import type { ShellCommandResult } from "../ShellCommand";
import { createSuccessResult, createErrorResult } from "../ShellCommand";
import type { GitSubcommand } from "../git";
import type { GitSubcommand, GitSubcommandOptions } from "../git";
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]';
async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise<ShellCommandResult> {
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 fs.stat(`${cwd}/.git`);
await this.fs.stat(`${this.pwd}/.git`);
} catch {
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
}
@@ -25,9 +35,8 @@ export class GitCommitCommand implements GitSubcommand {
}
// Get current status
const statusMatrix = await git.statusMatrix({
fs,
dir: cwd,
const statusMatrix = await this.git.statusMatrix({
dir: this.pwd,
});
// Check for staged changes
@@ -46,14 +55,14 @@ export class GitCommitCommand implements GitSubcommand {
};
try {
const configName = await git.getConfig({
fs,
dir: cwd,
const configName = await this.git.getConfig({
dir: this.pwd,
path: 'user.name',
});
const configEmail = await git.getConfig({
fs,
dir: cwd,
const configEmail = await this.git.getConfig({
dir: this.pwd,
path: 'user.email',
});
if (configName) author.name = configName;
@@ -66,9 +75,9 @@ export class GitCommitCommand implements GitSubcommand {
if (options.amend) {
// Get the last commit message if amending
try {
const commits = await git.log({
fs,
dir: cwd,
const commits = await this.git.log({
dir: this.pwd,
depth: 1,
});
if (commits.length > 0 && !message) {
@@ -85,9 +94,9 @@ export class GitCommitCommand implements GitSubcommand {
// Get current branch
let currentBranch = 'main';
try {
currentBranch = await git.currentBranch({
fs,
dir: cwd,
currentBranch = await this.git.currentBranch({
dir: this.pwd,
}) || 'main';
} catch {
// Use default
@@ -102,8 +111,7 @@ export class GitCommitCommand implements GitSubcommand {
committer: { name: string; email: string };
parent?: string[];
} = {
fs,
dir: cwd,
dir: this.pwd,
message: commitMessage || 'Empty commit',
author,
committer: author,
@@ -112,9 +120,9 @@ export class GitCommitCommand implements GitSubcommand {
if (options.amend) {
// For amend, we need to reset to the parent of the current commit
try {
const commits = await git.log({
fs,
dir: cwd,
const commits = await this.git.log({
dir: this.pwd,
depth: 2,
});
if (commits.length > 1) {
@@ -125,7 +133,7 @@ export class GitCommitCommand implements GitSubcommand {
}
}
const commitSha = await git.commit(commitOptions);
const commitSha = await this.git.commit(commitOptions);
// Get short hash
const shortHash = commitSha.substring(0, 7);
+35 -25
View File
@@ -1,22 +1,32 @@
import git from 'isomorphic-git';
import type { JSRuntimeFS } from "../../JSRuntime";
import type { ShellCommandResult } from "../ShellCommand";
import { createSuccessResult, createErrorResult } from "../ShellCommand";
import type { GitSubcommand } from "../git";
import type { GitSubcommand, GitSubcommandOptions } from "../git";
import type { Git } from "../../git";
export class GitConfigCommand implements GitSubcommand {
name = 'config';
description = 'Get and set repository or global options';
usage = 'git config [--global] <name> [<value>] | git config [--global] --list';
async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise<ShellCommandResult> {
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 {
const { action, key, value, options } = this.parseArgs(args);
// Check if we're in a git repository (unless --global is used)
if (!options.global) {
try {
await fs.stat(`${cwd}/.git`);
await this.fs.stat(`${this.pwd}/.git`);
} catch {
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
}
@@ -24,11 +34,11 @@ export class GitConfigCommand implements GitSubcommand {
switch (action) {
case 'list':
return await this.listConfig(fs, cwd, options.global);
return await this.listConfig(options.global);
case 'get':
return await this.getConfig(fs, cwd, key!, options.global);
return await this.getConfig(key!, options.global);
case 'set':
return await this.setConfig(fs, cwd, key!, value!, options.global);
return await this.setConfig(key!, value!, options.global);
default:
return createErrorResult('usage: git config [--global] <name> [<value>] | git config [--global] --list');
}
@@ -38,11 +48,11 @@ export class GitConfigCommand implements GitSubcommand {
}
}
private parseArgs(args: string[]): {
action: 'list' | 'get' | 'set';
key?: string;
value?: string;
options: { global: boolean }
private parseArgs(args: string[]): {
action: 'list' | 'get' | 'set';
key?: string;
value?: string;
options: { global: boolean }
} {
const options = { global: false };
let action: 'list' | 'get' | 'set' = 'get';
@@ -51,7 +61,7 @@ export class GitConfigCommand implements GitSubcommand {
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === '--global') {
options.global = true;
} else if (arg === '--list' || arg === '-l') {
@@ -70,7 +80,7 @@ export class GitConfigCommand implements GitSubcommand {
return { action, key, value, options };
}
private async listConfig(fs: JSRuntimeFS, cwd: string, global: boolean): Promise<ShellCommandResult> {
private async listConfig(global: boolean): Promise<ShellCommandResult> {
try {
// For simplicity, we'll only show the most common config values
// isomorphic-git doesn't have a direct way to list all config
@@ -86,9 +96,9 @@ export class GitConfigCommand implements GitSubcommand {
for (const key of commonKeys) {
try {
const value = await git.getConfig({
fs,
dir: global ? undefined : cwd,
const value = await this.git.getConfig({
dir: global ? undefined : this.pwd,
path: key,
});
if (value !== undefined) {
@@ -106,11 +116,11 @@ export class GitConfigCommand implements GitSubcommand {
}
}
private async getConfig(fs: JSRuntimeFS, cwd: string, key: string, global: boolean): Promise<ShellCommandResult> {
private async getConfig(key: string, global: boolean): Promise<ShellCommandResult> {
try {
const value = await git.getConfig({
fs,
dir: global ? undefined : cwd,
const value = await this.git.getConfig({
dir: global ? undefined : this.pwd,
path: key,
});
@@ -125,11 +135,11 @@ export class GitConfigCommand implements GitSubcommand {
}
}
private async setConfig(fs: JSRuntimeFS, cwd: string, key: string, value: string, global: boolean): Promise<ShellCommandResult> {
private async setConfig(key: string, value: string, global: boolean): Promise<ShellCommandResult> {
try {
await git.setConfig({
fs,
dir: global ? undefined : cwd,
await this.git.setConfig({
dir: global ? undefined : this.pwd,
path: key,
value: value,
});
+31 -20
View File
@@ -1,19 +1,30 @@
import git from 'isomorphic-git';
import type { JSRuntimeFS } from "../../JSRuntime";
import type { ShellCommandResult } from "../ShellCommand";
import { createSuccessResult, createErrorResult } from "../ShellCommand";
import type { GitSubcommand } from "../git";
import type { GitSubcommand, GitSubcommandOptions } from "../git";
import type { Git } from "../../git";
export class GitDiffCommand implements GitSubcommand {
name = 'diff';
description = 'Show changes between commits, commit and working tree, etc';
usage = 'git diff [<commit>] [<commit>] [-- <path>...]';
async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise<ShellCommandResult> {
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 fs.stat(`${cwd}/.git`);
await this.fs.stat(`${this.pwd}/.git`);
} catch {
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
}
@@ -22,13 +33,13 @@ export class GitDiffCommand implements GitSubcommand {
if (commits.length === 0) {
// Show working directory changes vs index
return await this.showWorkingDirectoryDiff(fs, cwd, paths);
return await this.showWorkingDirectoryDiff(paths);
} else if (commits.length === 1) {
// Show changes between commit and working directory
return await this.showCommitDiff(fs, cwd, commits[0], paths);
return await this.showCommitDiff(commits[0], paths);
} else if (commits.length === 2) {
// Show changes between two commits
return await this.showCommitRangeDiff(fs, cwd, commits[0], commits[1], paths);
return await this.showCommitRangeDiff(commits[0], commits[1], paths);
} else {
return createErrorResult('usage: git diff [<commit>] [<commit>] [-- <path>...]');
}
@@ -68,12 +79,12 @@ export class GitDiffCommand implements GitSubcommand {
return { commits, paths, options };
}
private async showWorkingDirectoryDiff(fs: JSRuntimeFS, cwd: string, paths: string[]): Promise<ShellCommandResult> {
private async showWorkingDirectoryDiff(paths: string[]): Promise<ShellCommandResult> {
try {
// Get status to find changed files
const statusMatrix = await git.statusMatrix({
fs,
dir: cwd,
const statusMatrix = await this.git.statusMatrix({
dir: this.pwd,
});
// Filter for modified files in working directory
@@ -96,9 +107,9 @@ export class GitDiffCommand implements GitSubcommand {
// Get file content from HEAD
let headContent = '';
try {
const headBlob = await git.readBlob({
fs,
dir: cwd,
const headBlob = await this.git.readBlob({
dir: this.pwd,
oid: 'HEAD',
filepath,
});
@@ -110,7 +121,7 @@ export class GitDiffCommand implements GitSubcommand {
// Get file content from working directory
let workdirContent = '';
try {
workdirContent = await fs.readFile(`${cwd}/${filepath}`, 'utf8');
workdirContent = await this.fs.readFile(`${this.pwd}/${filepath}`, 'utf8');
} catch {
// File might be deleted
}
@@ -154,12 +165,12 @@ export class GitDiffCommand implements GitSubcommand {
}
}
private async showCommitDiff(fs: JSRuntimeFS, cwd: string, commit: string, _paths: string[]): Promise<ShellCommandResult> {
private async showCommitDiff(commit: string, _paths: string[]): Promise<ShellCommandResult> {
try {
// For simplicity, show the commit message and changed files
const commits = await git.log({
fs,
dir: cwd,
const commits = await this.git.log({
dir: this.pwd,
depth: 1,
ref: commit,
});
@@ -188,7 +199,7 @@ export class GitDiffCommand implements GitSubcommand {
}
}
private async showCommitRangeDiff(_fs: JSRuntimeFS, _cwd: string, _commit1: string, _commit2: string, _paths: string[]): Promise<ShellCommandResult> {
private async showCommitRangeDiff(_commit1: string, _commit2: string, _paths: string[]): Promise<ShellCommandResult> {
// This would require complex implementation to compare two commits
return createErrorResult('Commit range diff is not implemented in this git command');
}
+21 -14
View File
@@ -1,62 +1,69 @@
import git from 'isomorphic-git';
import type { JSRuntimeFS } from "../../JSRuntime";
import type { ShellCommandResult } from "../ShellCommand";
import { createSuccessResult, createErrorResult } from "../ShellCommand";
import type { GitSubcommand } from "../git";
import type { GitSubcommand, GitSubcommandOptions } from "../git";
import type { Git } from "../../git";
export class GitInitCommand implements GitSubcommand {
name = 'init';
description = 'Create an empty Git repository or reinitialize an existing one';
usage = 'git init [--bare] [<directory>]';
async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise<ShellCommandResult> {
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 {
// Parse arguments
const { options, directory } = this.parseArgs(args);
const targetDir = directory || cwd;
const targetDir = directory || this.pwd;
// Check if directory exists, create if needed
if (directory) {
try {
await fs.stat(targetDir);
await this.fs.stat(targetDir);
} catch {
// Directory doesn't exist, create it
await fs.mkdir(targetDir, { recursive: true });
await this.fs.mkdir(targetDir, { recursive: true });
}
}
// Check if already a git repository
try {
await fs.stat(`${targetDir}/.git`);
await this.fs.stat(`${targetDir}/.git`);
return createSuccessResult(`Reinitialized existing Git repository in ${targetDir}/.git/\n`);
} catch {
// Not a git repository, proceed with initialization
}
// Initialize the repository
await git.init({
fs,
await this.git.init({
dir: targetDir,
bare: options.bare,
defaultBranch: 'main'
});
// Set up basic configuration
await git.setConfig({
fs,
await this.git.setConfig({
dir: targetDir,
path: 'user.name',
value: 'shakespeare.diy'
});
await git.setConfig({
fs,
await this.git.setConfig({
dir: targetDir,
path: 'user.email',
value: '[email protected]'
});
const message = options.bare
const message = options.bare
? `Initialized empty Git repository in ${targetDir}/\n`
: `Initialized empty Git repository in ${targetDir}/.git/\n`;
+17 -7
View File
@@ -1,19 +1,29 @@
import git from 'isomorphic-git';
import type { JSRuntimeFS } from "../../JSRuntime";
import type { ShellCommandResult } from "../ShellCommand";
import { createSuccessResult, createErrorResult } from "../ShellCommand";
import type { GitSubcommand } from "../git";
import type { GitSubcommand, GitSubcommandOptions } from "../git";
import type { Git } from "../../git";
export class GitLogCommand implements GitSubcommand {
name = 'log';
description = 'Show commit logs';
usage = 'git log [--oneline] [--graph] [-n <number>] [<since>..<until>]';
async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise<ShellCommandResult> {
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 fs.stat(`${cwd}/.git`);
await this.fs.stat(`${this.pwd}/.git`);
} catch {
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
}
@@ -21,9 +31,9 @@ export class GitLogCommand implements GitSubcommand {
const { options, limit } = this.parseArgs(args);
try {
const commits = await git.log({
fs,
dir: cwd,
const commits = await this.git.log({
dir: this.pwd,
depth: limit,
});
+36 -31
View File
@@ -1,20 +1,29 @@
import git from 'isomorphic-git';
import http from 'isomorphic-git/http/web';
import type { JSRuntimeFS } from "../../JSRuntime";
import type { ShellCommandResult } from "../ShellCommand";
import { createSuccessResult, createErrorResult } from "../ShellCommand";
import type { GitSubcommand } from "../git";
import type { GitSubcommand, GitSubcommandOptions } from "../git";
import type { Git } from "../../git";
export class GitPullCommand implements GitSubcommand {
name = 'pull';
description = 'Fetch from and integrate with another repository or a local branch';
usage = 'git pull [<remote>] [<branch>]';
async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise<ShellCommandResult> {
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 fs.stat(`${cwd}/.git`);
await this.fs.stat(`${this.pwd}/.git`);
} catch {
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
}
@@ -25,9 +34,9 @@ export class GitPullCommand implements GitSubcommand {
let targetBranch = branch;
let currentBranch: string | null = null;
try {
currentBranch = await git.currentBranch({
fs,
dir: cwd,
currentBranch = await this.git.currentBranch({
dir: this.pwd,
}) || null;
if (!targetBranch) {
targetBranch = currentBranch || 'main';
@@ -41,9 +50,9 @@ export class GitPullCommand implements GitSubcommand {
// Get remote URL
let remoteUrl: string;
try {
const remotes = await git.listRemotes({
fs,
dir: cwd,
const remotes = await this.git.listRemotes({
dir: this.pwd,
});
const targetRemote = remotes.find(r => r.remote === remote);
@@ -56,9 +65,8 @@ export class GitPullCommand implements GitSubcommand {
}
// Check for uncommitted changes
const statusMatrix = await git.statusMatrix({
fs,
dir: cwd,
const statusMatrix = await this.git.statusMatrix({
dir: this.pwd,
});
const hasChanges = statusMatrix.some(([, headStatus, workdirStatus, stageStatus]) => {
@@ -71,22 +79,19 @@ export class GitPullCommand implements GitSubcommand {
try {
// Fetch from remote
await git.fetch({
fs,
http,
dir: cwd,
await this.git.fetch({
dir: this.pwd,
remote: remote,
ref: targetBranch,
corsProxy: 'https://cors.isomorphic-git.org',
});
// Get the remote ref
const remoteRef = `refs/remotes/${remote}/${targetBranch}`;
let remoteOid: string;
try {
remoteOid = await git.resolveRef({
fs,
dir: cwd,
remoteOid = await this.git.resolveRef({
dir: this.pwd,
ref: remoteRef,
});
} catch {
@@ -96,16 +101,16 @@ export class GitPullCommand implements GitSubcommand {
// Get current HEAD
let currentOid: string;
try {
currentOid = await git.resolveRef({
fs,
dir: cwd,
currentOid = await this.git.resolveRef({
dir: this.pwd,
ref: 'HEAD',
});
} catch {
// Empty repository, just checkout the remote branch
await git.checkout({
fs,
dir: cwd,
await this.git.checkout({
dir: this.pwd,
ref: targetBranch,
});
return createSuccessResult(`From ${remoteUrl}\n * branch ${targetBranch} -> FETCH_HEAD\nUpdating empty repository\nFast-forward\n`);
@@ -117,9 +122,9 @@ export class GitPullCommand implements GitSubcommand {
}
// Perform fast-forward merge (simplified)
await git.merge({
fs,
dir: cwd,
await this.git.merge({
dir: this.pwd,
ours: currentBranch || 'HEAD',
theirs: remoteRef,
fastForwardOnly: true,
+22 -16
View File
@@ -1,20 +1,29 @@
import git from 'isomorphic-git';
import http from 'isomorphic-git/http/web';
import type { JSRuntimeFS } from "../../JSRuntime";
import type { ShellCommandResult } from "../ShellCommand";
import { createSuccessResult, createErrorResult } from "../ShellCommand";
import type { GitSubcommand } from "../git";
import type { GitSubcommand, GitSubcommandOptions } from "../git";
import type { Git } from "../../git";
export class GitPushCommand implements GitSubcommand {
name = 'push';
description = 'Update remote refs along with associated objects';
usage = 'git push [<remote>] [<branch>]';
async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise<ShellCommandResult> {
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 fs.stat(`${cwd}/.git`);
await this.fs.stat(`${this.pwd}/.git`);
} catch {
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
}
@@ -25,9 +34,9 @@ export class GitPushCommand implements GitSubcommand {
let targetBranch = branch;
if (!targetBranch) {
try {
targetBranch = await git.currentBranch({
fs,
dir: cwd,
targetBranch = await this.git.currentBranch({
dir: this.pwd,
}) || undefined;
if (!targetBranch) {
return createErrorResult('fatal: You are not currently on a branch.');
@@ -40,9 +49,9 @@ export class GitPushCommand implements GitSubcommand {
// Get remote URL
let remoteUrl: string;
try {
const remotes = await git.listRemotes({
fs,
dir: cwd,
const remotes = await this.git.listRemotes({
dir: this.pwd,
});
const targetRemote = remotes.find(r => r.remote === remote);
@@ -55,14 +64,11 @@ export class GitPushCommand implements GitSubcommand {
}
try {
await git.push({
fs,
http,
dir: cwd,
await this.git.push({
dir: this.pwd,
remote: remote,
ref: targetBranch,
remoteRef: targetBranch,
corsProxy: 'https://cors.isomorphic-git.org',
});
return createSuccessResult(`To ${remoteUrl}\n ${targetBranch} -> ${targetBranch}\n`);
+41 -33
View File
@@ -1,19 +1,30 @@
import git from 'isomorphic-git';
import type { JSRuntimeFS } from "../../JSRuntime";
import type { ShellCommandResult } from "../ShellCommand";
import { createSuccessResult, createErrorResult } from "../ShellCommand";
import type { GitSubcommand } from "../git";
import type { GitSubcommand, GitSubcommandOptions } from "../git";
import type { Git } from "../../git";
export class GitRemoteCommand implements GitSubcommand {
name = 'remote';
description = 'Manage set of tracked repositories';
usage = 'git remote [-v] | git remote add <name> <url> | git remote remove <name>';
async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise<ShellCommandResult> {
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 fs.stat(`${cwd}/.git`);
await this.fs.stat(`${this.pwd}/.git`);
} catch {
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
}
@@ -22,13 +33,13 @@ export class GitRemoteCommand implements GitSubcommand {
switch (action) {
case 'list':
return await this.listRemotes(fs, cwd, options.verbose);
return await this.listRemotes(options.verbose);
case 'add':
return await this.addRemote(fs, cwd, name!, url!);
return await this.addRemote(name!, url!);
case 'remove':
return await this.removeRemote(fs, cwd, name!);
return await this.removeRemote(name!);
default:
return await this.listRemotes(fs, cwd, options.verbose);
return await this.listRemotes(options.verbose);
}
} catch (error) {
@@ -36,11 +47,11 @@ export class GitRemoteCommand implements GitSubcommand {
}
}
private parseArgs(args: string[]): {
action: 'list' | 'add' | 'remove';
name?: string;
url?: string;
options: { verbose: boolean }
private parseArgs(args: string[]): {
action: 'list' | 'add' | 'remove';
name?: string;
url?: string;
options: { verbose: boolean }
} {
const options = { verbose: false };
let action: 'list' | 'add' | 'remove' = 'list';
@@ -49,7 +60,7 @@ export class GitRemoteCommand implements GitSubcommand {
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === '-v' || arg === '--verbose') {
options.verbose = true;
} else if (arg === 'add') {
@@ -74,11 +85,10 @@ export class GitRemoteCommand implements GitSubcommand {
return { action, name, url, options };
}
private async listRemotes(fs: JSRuntimeFS, cwd: string, verbose: boolean): Promise<ShellCommandResult> {
private async listRemotes(verbose: boolean): Promise<ShellCommandResult> {
try {
const remotes = await git.listRemotes({
fs,
dir: cwd,
const remotes = await this.git.listRemotes({
dir: this.pwd,
});
if (remotes.length === 0) {
@@ -86,7 +96,7 @@ export class GitRemoteCommand implements GitSubcommand {
}
const lines: string[] = [];
if (verbose) {
for (const remote of remotes) {
lines.push(`${remote.remote}\t${remote.url} (fetch)`);
@@ -105,7 +115,7 @@ export class GitRemoteCommand implements GitSubcommand {
}
}
private async addRemote(fs: JSRuntimeFS, cwd: string, name: string, url: string): Promise<ShellCommandResult> {
private async addRemote(name: string, url: string): Promise<ShellCommandResult> {
try {
if (!name || !url) {
return createErrorResult('usage: git remote add <name> <url>');
@@ -113,9 +123,9 @@ export class GitRemoteCommand implements GitSubcommand {
// Check if remote already exists
try {
const remotes = await git.listRemotes({
fs,
dir: cwd,
const remotes = await this.git.listRemotes({
dir: this.pwd,
});
const existingRemote = remotes.find(r => r.remote === name);
@@ -127,9 +137,8 @@ export class GitRemoteCommand implements GitSubcommand {
}
// Add the remote
await git.addRemote({
fs,
dir: cwd,
await this.git.addRemote({
dir: this.pwd,
remote: name,
url: url,
});
@@ -141,7 +150,7 @@ export class GitRemoteCommand implements GitSubcommand {
}
}
private async removeRemote(fs: JSRuntimeFS, cwd: string, name: string): Promise<ShellCommandResult> {
private async removeRemote(name: string): Promise<ShellCommandResult> {
try {
if (!name) {
return createErrorResult('usage: git remote remove <name>');
@@ -149,9 +158,9 @@ export class GitRemoteCommand implements GitSubcommand {
// Check if remote exists
try {
const remotes = await git.listRemotes({
fs,
dir: cwd,
const remotes = await this.git.listRemotes({
dir: this.pwd,
});
const existingRemote = remotes.find(r => r.remote === name);
@@ -163,9 +172,8 @@ export class GitRemoteCommand implements GitSubcommand {
}
// Remove the remote
await git.deleteRemote({
fs,
dir: cwd,
await this.git.deleteRemote({
dir: this.pwd,
remote: name,
});
+11 -8
View File
@@ -1,5 +1,6 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { GitResetCommand } from './reset';
import type { Git } from '../../git';
import type { JSRuntimeFS } from '../../JSRuntime';
// Mock isomorphic-git
@@ -48,11 +49,13 @@ const createMockFS = (): JSRuntimeFS => ({
describe('GitResetCommand', () => {
let resetCommand: GitResetCommand;
let mockFS: JSRuntimeFS;
let mockGit: Git;
const testCwd = '/test';
beforeEach(() => {
mockFS = createMockFS();
resetCommand = new GitResetCommand();
mockGit = {} as Git; // Mock Git instance
resetCommand = new GitResetCommand({ git: mockGit, fs: mockFS, pwd: testCwd });
vi.clearAllMocks();
vi.resetAllMocks();
});
@@ -67,7 +70,7 @@ describe('GitResetCommand', () => {
// Mock stat to throw for .git directory
mockFS.stat = vi.fn().mockRejectedValue(new Error('ENOENT'));
const result = await resetCommand.execute(['--hard', 'HEAD'], testCwd, mockFS);
const result = await resetCommand.execute([]);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('fatal: not a git repository');
@@ -95,7 +98,7 @@ describe('GitResetCommand', () => {
vi.mocked(git.writeRef).mockResolvedValue(undefined);
vi.mocked(git.checkout).mockResolvedValue(undefined);
const result = await resetCommand.execute(['--hard', 'HEAD'], testCwd, mockFS);
const result = await resetCommand.execute(['--hard', 'HEAD']);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('HEAD is now at');
@@ -128,7 +131,7 @@ describe('GitResetCommand', () => {
.mockResolvedValueOnce(currentOid); // Second call for current HEAD
vi.mocked(git.checkout).mockResolvedValue(undefined);
const result = await resetCommand.execute(['HEAD'], testCwd, mockFS);
const result = await resetCommand.execute(['HEAD']);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('HEAD is now at');
@@ -143,7 +146,7 @@ describe('GitResetCommand', () => {
it('should handle file-specific reset', async () => {
vi.mocked(git.resetIndex).mockResolvedValue(undefined);
const result = await resetCommand.execute(['HEAD', 'file.txt'], testCwd, mockFS);
const result = await resetCommand.execute(['HEAD', 'file.txt']);
expect(result.exitCode).toBe(0);
expect(git.resetIndex).toHaveBeenCalledWith({
@@ -158,7 +161,7 @@ describe('GitResetCommand', () => {
vi.mocked(git.resolveRef).mockRejectedValue(new Error('Unknown ref'));
// Use a commit hash that looks valid but doesn't exist
const result = await resetCommand.execute(['--hard', 'abc123def456'], testCwd, mockFS);
const result = await resetCommand.execute(['unknown-ref']);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('unknown revision or path not in the working tree');
@@ -173,7 +176,7 @@ describe('GitResetCommand', () => {
.mockResolvedValueOnce(targetOid) // First call for target
.mockResolvedValueOnce(currentOid); // Second call for current HEAD
const result = await resetCommand.execute(['--soft', 'HEAD'], testCwd, mockFS);
const result = await resetCommand.execute(['--soft', 'HEAD']);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('--soft reset is not implemented');
@@ -187,7 +190,7 @@ describe('GitResetCommand', () => {
.mockResolvedValueOnce(mockOid) // First call for target
.mockResolvedValueOnce(mockOid); // Second call for current HEAD
const result = await resetCommand.execute(['--hard', 'HEAD'], testCwd, mockFS);
const result = await resetCommand.execute(['HEAD']);
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('');
+40 -29
View File
@@ -1,19 +1,30 @@
import git from 'isomorphic-git';
import type { JSRuntimeFS } from "../../JSRuntime";
import type { ShellCommandResult } from "../ShellCommand";
import { createSuccessResult, createErrorResult } from "../ShellCommand";
import type { GitSubcommand } from "../git";
import type { GitSubcommand, GitSubcommandOptions } from "../git";
import type { Git } from "../../git";
export class GitResetCommand implements GitSubcommand {
name = 'reset';
description = 'Reset current HEAD to the specified state';
usage = 'git reset [--soft | --mixed | --hard] [<commit>] | git reset HEAD [<file>...]';
async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise<ShellCommandResult> {
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 fs.stat(`${cwd}/.git`);
await this.fs.stat(`${this.pwd}/.git`);
} catch {
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
}
@@ -22,10 +33,10 @@ export class GitResetCommand implements GitSubcommand {
if (files.length > 0) {
// Reset specific files (unstage)
return await this.resetFiles(fs, cwd, files);
return await this.resetFiles(files);
} else {
// Reset to commit
return await this.resetToCommit(fs, cwd, target, mode);
return await this.resetToCommit(target, mode);
}
} catch (error) {
@@ -63,7 +74,7 @@ export class GitResetCommand implements GitSubcommand {
return { mode, target, files };
}
private async resetFiles(fs: JSRuntimeFS, cwd: string, files: string[]): Promise<ShellCommandResult> {
private async resetFiles(files: string[]): Promise<ShellCommandResult> {
try {
const resetFiles: string[] = [];
const errors: string[] = [];
@@ -71,9 +82,9 @@ export class GitResetCommand implements GitSubcommand {
for (const file of files) {
try {
// Remove from staging area (reset to HEAD)
await git.resetIndex({
fs,
dir: cwd,
await this.git.resetIndex({
dir: this.pwd,
filepath: file,
});
resetFiles.push(file);
@@ -97,14 +108,14 @@ export class GitResetCommand implements GitSubcommand {
}
}
private async resetToCommit(fs: JSRuntimeFS, cwd: string, target: string, mode: 'soft' | 'mixed' | 'hard'): Promise<ShellCommandResult> {
private async resetToCommit(target: string, mode: 'soft' | 'mixed' | 'hard'): Promise<ShellCommandResult> {
try {
// Resolve the target commit
let targetOid: string;
try {
targetOid = await git.resolveRef({
fs,
dir: cwd,
targetOid = await this.git.resolveRef({
dir: this.pwd,
ref: target,
});
} catch {
@@ -114,9 +125,9 @@ export class GitResetCommand implements GitSubcommand {
// Get current HEAD for comparison
let currentOid: string;
try {
currentOid = await git.resolveRef({
fs,
dir: cwd,
currentOid = await this.git.resolveRef({
dir: this.pwd,
ref: 'HEAD',
});
} catch {
@@ -140,9 +151,9 @@ export class GitResetCommand implements GitSubcommand {
// Move HEAD and reset staging area (default)
// Reset the index to match the target commit
try {
await git.checkout({
fs,
dir: cwd,
await this.git.checkout({
dir: this.pwd,
ref: target,
noCheckout: true, // Only update the index, not the working directory
});
@@ -160,25 +171,25 @@ export class GitResetCommand implements GitSubcommand {
// 3. Reset the working directory to match the target
// Get the commit object to ensure it exists
await git.readCommit({
fs,
dir: cwd,
await this.git.readCommit({
dir: this.pwd,
oid: targetOid,
});
// Update HEAD to point to the target commit
await git.writeRef({
fs,
dir: cwd,
await this.git.writeRef({
dir: this.pwd,
ref: 'HEAD',
value: targetOid,
});
// Reset the working directory by checking out all files from the target commit
// Use force to overwrite any local changes
await git.checkout({
fs,
dir: cwd,
await this.git.checkout({
dir: this.pwd,
ref: targetOid,
force: true,
});
+23 -13
View File
@@ -1,26 +1,37 @@
import git from 'isomorphic-git';
import type { JSRuntimeFS } from "../../JSRuntime";
import type { ShellCommandResult } from "../ShellCommand";
import { createSuccessResult, createErrorResult } from "../ShellCommand";
import type { GitSubcommand } from "../git";
import type { GitSubcommand, GitSubcommandOptions } from "../git";
import type { Git } from "../../git";
export class GitShowCommand implements GitSubcommand {
name = 'show';
description = 'Show various types of objects';
usage = 'git show [<commit>]';
async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise<ShellCommandResult> {
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 fs.stat(`${cwd}/.git`);
await this.fs.stat(`${this.pwd}/.git`);
} catch {
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
}
const { commit } = this.parseArgs(args);
return await this.showCommit(fs, cwd, commit);
return await this.showCommit(commit);
} catch (error) {
return createErrorResult(`git show: ${error instanceof Error ? error.message : 'Unknown error'}`);
@@ -40,12 +51,11 @@ export class GitShowCommand implements GitSubcommand {
return { commit };
}
private async showCommit(fs: JSRuntimeFS, cwd: string, commitRef: string): Promise<ShellCommandResult> {
private async showCommit(commitRef: string): Promise<ShellCommandResult> {
try {
// Get the commit
const commits = await git.log({
fs,
dir: cwd,
const commits = await this.git.log({
dir: this.pwd,
depth: 1,
ref: commitRef,
});
@@ -59,7 +69,7 @@ export class GitShowCommand implements GitSubcommand {
// Show commit information
lines.push(`commit ${commit.oid}`);
// Show parent commits if any
if (commit.commit.parent && commit.commit.parent.length > 0) {
for (const parent of commit.commit.parent) {
@@ -81,9 +91,9 @@ export class GitShowCommand implements GitSubcommand {
// Try to show file changes (simplified)
try {
// Get the tree for this commit
const tree = await git.readTree({
fs,
dir: cwd,
const tree = await this.git.readTree({
dir: this.pwd,
oid: commit.oid,
});
+19 -10
View File
@@ -1,19 +1,29 @@
import git from 'isomorphic-git';
import type { JSRuntimeFS } from "../../JSRuntime";
import type { ShellCommandResult } from "../ShellCommand";
import { createSuccessResult, createErrorResult } from "../ShellCommand";
import type { GitSubcommand } from "../git";
import type { GitSubcommand, GitSubcommandOptions } from "../git";
import type { Git } from "../../git";
export class GitStatusCommand implements GitSubcommand {
name = 'status';
description = 'Show the working tree status';
usage = 'git status [--porcelain] [--short]';
async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise<ShellCommandResult> {
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 fs.stat(`${cwd}/.git`);
await this.fs.stat(`${this.pwd}/.git`);
} catch {
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
}
@@ -21,17 +31,16 @@ export class GitStatusCommand implements GitSubcommand {
const options = this.parseArgs(args);
// Get the status matrix
const statusMatrix = await git.statusMatrix({
fs,
dir: cwd,
const statusMatrix = await this.git.statusMatrix({
dir: this.pwd,
});
// Get current branch
let currentBranch: string | null = null;
try {
currentBranch = await git.currentBranch({
fs,
dir: cwd,
currentBranch = await this.git.currentBranch({
dir: this.pwd,
}) || null;
} catch {
// Might be an empty repository
+37 -29
View File
@@ -1,19 +1,30 @@
import git from 'isomorphic-git';
import type { JSRuntimeFS } from "../../JSRuntime";
import type { ShellCommandResult } from "../ShellCommand";
import { createSuccessResult, createErrorResult } from "../ShellCommand";
import type { GitSubcommand } from "../git";
import type { GitSubcommand, GitSubcommandOptions } from "../git";
import type { Git } from "../../git";
export class GitTagCommand implements GitSubcommand {
name = 'tag';
description = 'Create, list, delete or verify a tag object';
usage = 'git tag [-l] | git tag <tagname> [<commit>] | git tag -d <tagname>';
async execute(args: string[], cwd: string, fs: JSRuntimeFS): Promise<ShellCommandResult> {
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 fs.stat(`${cwd}/.git`);
await this.fs.stat(`${this.pwd}/.git`);
} catch {
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
}
@@ -22,13 +33,13 @@ export class GitTagCommand implements GitSubcommand {
switch (action) {
case 'list':
return await this.listTags(fs, cwd);
return await this.listTags();
case 'create':
return await this.createTag(fs, cwd, tagName!, commit);
return await this.createTag(tagName!, commit);
case 'delete':
return await this.deleteTag(fs, cwd, tagName!);
return await this.deleteTag(tagName!);
default:
return await this.listTags(fs, cwd);
return await this.listTags();
}
} catch (error) {
@@ -73,11 +84,10 @@ export class GitTagCommand implements GitSubcommand {
return { action, tagName, commit, options };
}
private async listTags(fs: JSRuntimeFS, cwd: string): Promise<ShellCommandResult> {
private async listTags(): Promise<ShellCommandResult> {
try {
const tags = await git.listTags({
fs,
dir: cwd,
const tags = await this.git.listTags({
dir: this.pwd,
});
if (tags.length === 0) {
@@ -94,7 +104,7 @@ export class GitTagCommand implements GitSubcommand {
}
}
private async createTag(fs: JSRuntimeFS, cwd: string, tagName: string, commit?: string): Promise<ShellCommandResult> {
private async createTag(tagName: string, commit?: string): Promise<ShellCommandResult> {
try {
if (!tagName) {
return createErrorResult('usage: git tag <tagname> [<commit>]');
@@ -102,9 +112,9 @@ export class GitTagCommand implements GitSubcommand {
// Check if tag already exists
try {
const tags = await git.listTags({
fs,
dir: cwd,
const tags = await this.git.listTags({
dir: this.pwd,
});
if (tags.includes(tagName)) {
@@ -117,9 +127,9 @@ export class GitTagCommand implements GitSubcommand {
// Resolve the target commit
let targetOid: string;
try {
targetOid = await git.resolveRef({
fs,
dir: cwd,
targetOid = await this.git.resolveRef({
dir: this.pwd,
ref: commit || 'HEAD',
});
} catch {
@@ -127,9 +137,8 @@ export class GitTagCommand implements GitSubcommand {
}
// Create the tag
await git.tag({
fs,
dir: cwd,
await this.git.tag({
dir: this.pwd,
ref: tagName,
object: targetOid,
});
@@ -141,7 +150,7 @@ export class GitTagCommand implements GitSubcommand {
}
}
private async deleteTag(fs: JSRuntimeFS, cwd: string, tagName: string): Promise<ShellCommandResult> {
private async deleteTag(tagName: string): Promise<ShellCommandResult> {
try {
if (!tagName) {
return createErrorResult('usage: git tag -d <tagname>');
@@ -149,9 +158,9 @@ export class GitTagCommand implements GitSubcommand {
// Check if tag exists
try {
const tags = await git.listTags({
fs,
dir: cwd,
const tags = await this.git.listTags({
dir: this.pwd,
});
if (!tags.includes(tagName)) {
@@ -162,9 +171,8 @@ export class GitTagCommand implements GitSubcommand {
}
// Delete the tag
await git.deleteTag({
fs,
dir: cwd,
await this.git.deleteTag({
dir: this.pwd,
ref: tagName,
});
+5 -4
View File
@@ -7,6 +7,7 @@
*/
import { ShellTool } from './ShellTool';
import { Git } from '../git';
import type { JSRuntimeFS } from '../JSRuntime';
/**
@@ -14,7 +15,7 @@ import type { JSRuntimeFS } from '../JSRuntime';
*/
export async function exampleShellUsage(fs: JSRuntimeFS, projectRoot: string) {
// Create a shell tool instance
const shell = new ShellTool(fs, projectRoot);
const shell = new ShellTool(fs, projectRoot, new Git(fs));
console.log('Available commands:', shell.getAvailableCommands());
console.log('Current directory:', shell.getCurrentWorkingDirectory());
@@ -111,7 +112,7 @@ export async function exampleShellUsage(fs: JSRuntimeFS, projectRoot: string) {
* Example React hook for using ShellTool
*/
export function useShell(fs: JSRuntimeFS, cwd: string) {
const shell = new ShellTool(fs, cwd);
const shell = new ShellTool(fs, cwd, new Git(fs));
const executeCommand = async (command: string): Promise<string> => {
try {
@@ -137,7 +138,7 @@ export class AIShellIntegration {
private shell: ShellTool;
constructor(fs: JSRuntimeFS, projectRoot: string) {
this.shell = new ShellTool(fs, projectRoot);
this.shell = new ShellTool(fs, projectRoot, new Git(fs));
}
/**
@@ -177,7 +178,7 @@ export class SimpleCLI {
private history: string[] = [];
constructor(fs: JSRuntimeFS, projectRoot: string) {
this.shell = new ShellTool(fs, projectRoot);
this.shell = new ShellTool(fs, projectRoot, new Git(fs));
}
async executeCommand(command: string): Promise<string> {
+4 -1
View File
@@ -1,5 +1,6 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { ShellTool } from './ShellTool';
import { Git } from '../git';
import type { JSRuntimeFS } from '../JSRuntime';
// Mock filesystem
@@ -19,12 +20,14 @@ const createMockFS = (): JSRuntimeFS => ({
describe('ShellTool', () => {
let mockFS: JSRuntimeFS;
let mockGit: Git;
let shellTool: ShellTool;
const testCwd = '/test/dir';
beforeEach(() => {
mockFS = createMockFS();
shellTool = new ShellTool(mockFS, testCwd);
mockGit = new Git(mockFS);
shellTool = new ShellTool(mockFS, testCwd, mockGit);
});
it('should have correct tool properties', () => {
+5 -2
View File
@@ -2,6 +2,7 @@ import { z } from "zod";
import type { Tool } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand } from "../commands/ShellCommand";
import { Git } from "../git";
import {
CatCommand,
CdCommand,
@@ -42,6 +43,7 @@ interface ShellToolParams {
export class ShellTool implements Tool<ShellToolParams> {
private fs: JSRuntimeFS;
private cwd: string;
private git: Git;
private commands: Map<string, ShellCommand>;
readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl. Supports compound commands with &&, ||, ;, and | operators";
@@ -52,9 +54,10 @@ export class ShellTool implements Tool<ShellToolParams> {
),
});
constructor(fs: JSRuntimeFS, cwd: string) {
constructor(fs: JSRuntimeFS, cwd: string, git: Git) {
this.fs = fs;
this.cwd = cwd;
this.git = git;
this.commands = new Map();
// Register available commands
@@ -69,7 +72,7 @@ export class ShellTool implements Tool<ShellToolParams> {
this.registerCommand(new EchoCommand());
this.registerCommand(new EnvCommand());
this.registerCommand(new FindCommand(fs));
this.registerCommand(new GitCommand(fs));
this.registerCommand(new GitCommand({ git: this.git, fs, cwd: this.cwd }));
this.registerCommand(new GrepCommand(fs));
this.registerCommand(new HeadCommand(fs));
this.registerCommand(new LsCommand(fs));