Refactor code to use our custom Git class

This commit is contained in:
Alex Gleason committed 2025-09-14 16:26:37 -05:00
1 parent 55120452c7
commit 772a2f424b
9 files changed
+93 -123

No files matched your search

+8 -19
View File
@@ -1,6 +1,5 @@
import git from 'isomorphic-git';
import http from 'isomorphic-git/http/web';
import { Buffer } from 'buffer';
import { Git } from '@/lib/git';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
@@ -21,10 +20,12 @@ export interface Project {
export class ProjectsManager {
fs: JSRuntimeFS;
git: Git;
dir: string;
constructor(fs: JSRuntimeFS) {
this.fs = fs;
this.git = new Git(fs, 'https://cors.isomorphic-git.org');
this.dir = '/projects';
}
@@ -60,8 +61,7 @@ export class ProjectsManager {
}
// Initialize new git repository
await git.init({
fs: this.fs,
await this.git.init({
dir: project.path,
defaultBranch: 'main',
});
@@ -71,8 +71,7 @@ export class ProjectsManager {
for (const file of files) {
// Skip .git directory and other hidden files we don't want to track
if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
await git.add({
fs: this.fs,
await this.git.add({
dir: project.path,
filepath: file,
});
@@ -80,8 +79,7 @@ export class ProjectsManager {
}
// Make initial commit
await git.commit({
fs: this.fs,
await this.git.commit({
dir: project.path,
message: 'New project created with Shakespeare',
author: {
@@ -94,7 +92,6 @@ export class ProjectsManager {
}
async cloneProject(name: string, repoUrl: string, customId?: string, options?: { depth?: number }): Promise<Project> {
const url = new URL(repoUrl);
const id = customId || await this.generateUniqueProjectId(name);
// Check if project with this ID already exists when using custom ID
@@ -107,18 +104,11 @@ export class ProjectsManager {
await this.fs.mkdir(projectPath);
// Clone the repository
await git.clone({
fs: this.fs,
http,
await this.git.clone({
dir: projectPath,
url: repoUrl,
singleBranch: true,
depth: options?.depth, // Use depth if provided, otherwise clone full history
// Use the CORS proxy only for GitHub and GitLab URLs
// More info: https://github.com/isomorphic-git/isomorphic-git#cors-support
corsProxy: url.hostname === 'github.com' || url.hostname === 'gitlab.com'
? 'https://cors.isomorphic-git.org'
: undefined,
});
// Get filesystem stats for timestamps
@@ -319,8 +309,7 @@ export class ProjectsManager {
async getNostrRepoAddress(projectId: string): Promise<string | null> {
try {
const projectPath = `${this.dir}/${projectId}`;
const config = await git.getConfig({
fs: this.fs,
const config = await this.git.getConfig({
dir: projectPath,
path: 'nostr.repo',
});
+27 -29
View File
@@ -2,19 +2,19 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import { GitCommitTool } from './GitCommitTool';
import type { JSRuntimeFS } from '../JSRuntime';
// Mock isomorphic-git
vi.mock('isomorphic-git', () => ({
default: {
statusMatrix: vi.fn(),
add: vi.fn(),
remove: vi.fn(),
commit: vi.fn(),
currentBranch: vi.fn(),
getConfig: vi.fn(),
},
}));
// Mock the Git class
const mockGitInstance = {
statusMatrix: vi.fn(),
add: vi.fn(),
remove: vi.fn(),
commit: vi.fn(),
currentBranch: vi.fn(),
getConfig: vi.fn(),
};
import git from 'isomorphic-git';
vi.mock('../git', () => ({
Git: vi.fn().mockImplementation(() => mockGitInstance),
}));
// Mock filesystem
const mockFS: JSRuntimeFS = {
@@ -39,14 +39,15 @@ describe('GitCommitTool', () => {
tool = new GitCommitTool(mockFS, '/test/project');
// Setup default mocks
vi.mocked(git.statusMatrix).mockResolvedValue([
mockGitInstance.statusMatrix.mockResolvedValue([
['src/file1.ts', 1, 1, 0], // Modified file (present in head and workdir, but not staged)
['src/file2.ts', 0, 1, 0], // New file (absent in head, present in workdir, not staged)
]);
vi.mocked(git.add).mockResolvedValue();
vi.mocked(git.commit).mockResolvedValue('abcd1234567890abcdef1234567890abcdef12');
vi.mocked(git.currentBranch).mockResolvedValue('main');
vi.mocked(git.getConfig).mockRejectedValue(new Error('Config not found'));
mockGitInstance.add.mockResolvedValue(undefined);
mockGitInstance.remove.mockResolvedValue(undefined);
mockGitInstance.commit.mockResolvedValue('abcd1234567890abcdef1234567890abcdef12');
mockGitInstance.currentBranch.mockResolvedValue('main');
mockGitInstance.getConfig.mockRejectedValue(new Error('Config not found'));
});
it('should have correct description and inputSchema', () => {
@@ -64,13 +65,11 @@ describe('GitCommitTool', () => {
const result = await tool.execute({ message: 'Add new feature' });
expect(mockFS.stat).toHaveBeenCalledWith('/test/project/.git');
expect(git.statusMatrix).toHaveBeenCalledWith({
fs: mockFS,
expect(mockGitInstance.statusMatrix).toHaveBeenCalledWith({
dir: '/test/project',
});
expect(git.add).toHaveBeenCalled();
expect(git.commit).toHaveBeenCalledWith({
fs: mockFS,
expect(mockGitInstance.add).toHaveBeenCalled();
expect(mockGitInstance.commit).toHaveBeenCalledWith({
dir: '/test/project',
message: 'Add new feature',
author: {
@@ -124,7 +123,7 @@ describe('GitCommitTool', () => {
const specialMessage = 'Fix: handle "quotes" and \'apostrophes\' in commit message';
const result = await tool.execute({ message: specialMessage });
expect(git.commit).toHaveBeenCalledWith(expect.objectContaining({
expect(mockGitInstance.commit).toHaveBeenCalledWith(expect.objectContaining({
message: specialMessage,
}));
expect(result).toContain('✅ Successfully committed');
@@ -141,7 +140,7 @@ describe('GitCommitTool', () => {
const multilineMessage = 'Add new feature\n\nThis commit adds a new feature that allows users to do something amazing.\n\nCloses #123';
const result = await tool.execute({ message: multilineMessage });
expect(git.commit).toHaveBeenCalled();
expect(mockGitInstance.commit).toHaveBeenCalled();
expect(result).toContain('✅ Successfully committed');
expect(result).toContain('Add new feature');
});
@@ -154,12 +153,12 @@ describe('GitCommitTool', () => {
});
// Mock no changes in status matrix
vi.mocked(git.statusMatrix).mockResolvedValue([]);
vi.mocked(mockGitInstance.statusMatrix).mockResolvedValue([]);
const result = await tool.execute({ message: 'Update documentation' });
expect(result).toContain('ℹ️ No changes to commit. Working tree is clean.');
expect(git.commit).not.toHaveBeenCalled();
expect(mockGitInstance.commit).not.toHaveBeenCalled();
});
it('should provide detailed commit information', async () => {
@@ -185,14 +184,13 @@ describe('GitCommitTool', () => {
});
// Mock git config
vi.mocked(git.getConfig)
vi.mocked(mockGitInstance.getConfig)
.mockResolvedValueOnce('John Doe') // user.name
.mockResolvedValueOnce('[email protected]'); // user.email
const result = await tool.execute({ message: 'Test commit' });
expect(git.commit).toHaveBeenCalledWith({
fs: mockFS,
expect(mockGitInstance.commit).toHaveBeenCalledWith({
dir: '/test/project',
message: 'Test commit',
author: {
+10 -15
View File
@@ -1,5 +1,5 @@
import { z } from "zod";
import git from 'isomorphic-git';
import { Git } from "../git";
import type { Tool } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
@@ -10,6 +10,7 @@ interface GitCommitParams {
export class GitCommitTool implements Tool<GitCommitParams> {
private fs: JSRuntimeFS;
private git: Git;
private cwd: string;
readonly description = "Commit changes to git with a commit message. Automatically adds all unstaged files.";
@@ -20,6 +21,7 @@ export class GitCommitTool implements Tool<GitCommitParams> {
constructor(fs: JSRuntimeFS, cwd: string) {
this.fs = fs;
this.git = new Git(fs);
this.cwd = cwd;
}
@@ -40,8 +42,7 @@ export class GitCommitTool implements Tool<GitCommitParams> {
}
// Get git status to see what files have changed
const statusMatrix = await git.statusMatrix({
fs: this.fs,
const statusMatrix = await this.git.statusMatrix({
dir: this.cwd,
});
@@ -60,16 +61,14 @@ export class GitCommitTool implements Tool<GitCommitParams> {
// Add all changed files to staging
for (const [filepath] of changedFiles) {
try {
await git.add({
fs: this.fs,
await this.git.add({
dir: this.cwd,
filepath,
});
} catch {
// If file was deleted, use git.remove instead
try {
await git.remove({
fs: this.fs,
await this.git.remove({
dir: this.cwd,
filepath,
});
@@ -83,8 +82,7 @@ export class GitCommitTool implements Tool<GitCommitParams> {
// Get current branch name
let currentBranch = 'main';
try {
currentBranch = await git.currentBranch({
fs: this.fs,
currentBranch = await this.git.currentBranch({
dir: this.cwd,
}) || 'main';
} catch {
@@ -99,13 +97,11 @@ export class GitCommitTool implements Tool<GitCommitParams> {
// Try to get configured author from git config
try {
const configName = await git.getConfig({
fs: this.fs,
const configName = await this.git.getConfig({
dir: this.cwd,
path: 'user.name',
});
const configEmail = await git.getConfig({
fs: this.fs,
const configEmail = await this.git.getConfig({
dir: this.cwd,
path: 'user.email',
});
@@ -116,8 +112,7 @@ export class GitCommitTool implements Tool<GitCommitParams> {
}
// Commit the changes
const commitSha = await git.commit({
fs: this.fs,
const commitSha = await this.git.commit({
dir: this.cwd,
message: message.trim(),
author,