From 9987cfca6d015656d1761d831f97d714b511e9f5 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 25 Dec 2025 21:39:10 -0600 Subject: [PATCH] git basic test setup --- src/lib/git.test.ts | 1122 +++++++++++++++++-------------------------- 1 file changed, 452 insertions(+), 670 deletions(-) diff --git a/src/lib/git.test.ts b/src/lib/git.test.ts index a1d26282..f53afd37 100644 --- a/src/lib/git.test.ts +++ b/src/lib/git.test.ts @@ -1,700 +1,482 @@ -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { describe, it, expect, beforeEach, vi } from 'vitest'; import { Git } from './git'; -import git from 'isomorphic-git'; -import type { NPool } from '@nostrify/nostrify'; -import type { JSRuntimeFS } from './JSRuntime'; +import type { JSRuntimeFS, DirectoryEntry } from './JSRuntime'; +import type { NPool, NostrEvent } from '@nostrify/nostrify'; +import { NSecSigner } from '@nostrify/nostrify'; import { nip19 } from 'nostr-tools'; -// Mock isomorphic-git -vi.mock('isomorphic-git'); -vi.mock('isomorphic-git/http/web'); -vi.mock('nostr-tools', () => ({ - nip19: { - decode: vi.fn(), - naddrEncode: vi.fn(), - npubEncode: vi.fn((pubkey: string) => `npub1${pubkey.slice(0, 10)}`), - }, -})); -vi.mock('@nostrify/nostrify', () => ({ - NIP05: { - lookup: vi.fn(), - }, -})); -vi.mock('./configUtils', () => ({ - readGitSettings: vi.fn(), -})); +/** + * Minimal mock filesystem implementation for testing + * Implements only the essential methods needed by isomorphic-git + */ +class MockFS implements JSRuntimeFS { + private files: Map = new Map(); + private dirs: Set = new Set(['/']); -const mockGit = vi.mocked(git); + // Expose promises property for isomorphic-git compatibility + promises = this; -const createMockNostr = (): NPool => ({ - req: vi.fn(), - query: vi.fn(), - event: vi.fn(), - group: vi.fn(), - relay: vi.fn(), - relays: new Map(), - close: vi.fn(), -}) as unknown as NPool; + async readFile(path: string): Promise; + async readFile(path: string, options: 'utf8'): Promise; + async readFile(path: string, options: string): Promise; + async readFile(path: string, options: { encoding: 'utf8' }): Promise; + async readFile(path: string, options: { encoding: string }): Promise; + async readFile(path: string, options?: string | { encoding?: string }): Promise; + async readFile(path: string, options?: string | { encoding?: string }): Promise { + const content = this.files.get(path); + if (content === undefined) { + const error = new Error(`ENOENT: no such file or directory, open '${path}'`) as NodeJS.ErrnoException; + error.code = 'ENOENT'; + throw error; + } + const encoding = typeof options === 'string' ? options : options?.encoding; + if (encoding === 'utf8') { + if (typeof content === 'string') return content; + return new TextDecoder('utf-8').decode(content as Uint8Array); + } + if (typeof content === 'string') return new TextEncoder().encode(content); + return content as Uint8Array; + } + + async writeFile(path: string, data: string | Uint8Array): Promise { + this.files.set(path, data); + const dir = path.split('/').slice(0, -1).join('/') || '/'; + this.dirs.add(dir); + } + + readdir(path: string): Promise; + readdir(path: string, options: { withFileTypes: true }): Promise; + readdir(path: string, options?: { withFileTypes?: boolean }): Promise; + async readdir(path: string, options?: { withFileTypes?: boolean }): Promise { + if (!this.dirs.has(path)) { + const error = new Error(`ENOENT: no such file or directory, scandir '${path}'`) as NodeJS.ErrnoException; + error.code = 'ENOENT'; + throw error; + } + + const entries: string[] = []; + for (const dir of this.dirs) { + if (dir.startsWith(path + '/') && !dir.slice(path.length + 1).includes('/')) { + entries.push(dir.slice(path.length + 1)); + } + } + for (const file of this.files.keys()) { + if (file.startsWith(path + '/') && !file.slice(path.length + 1).includes('/')) { + entries.push(file.slice(path.length + 1)); + } + } + + const uniqueEntries = [...new Set(entries)]; + if (options?.withFileTypes) { + return uniqueEntries.map(name => { + const fullPath = path.endsWith('/') ? path + name : path + '/' + name; + const isDir = this.dirs.has(fullPath); + return { + name, + isDirectory: () => isDir, + isFile: () => !isDir, + isSymbolicLink: () => false, + } as unknown as DirectoryEntry; + }); + } + return uniqueEntries; + } + + async mkdir(path: string): Promise { + this.dirs.add(path); + } + + async stat(path: string): Promise<{ + isDirectory(): boolean; + isFile(): boolean; + isSymbolicLink(): boolean; + mtimeMs?: number; + mtime?: Date; + ctimeMs?: number; + ctime?: Date; + mode?: number; + size?: number; + ino?: number; + uid?: number; + gid?: number; + }> { + const now = new Date(); + const nowMs = now.getTime(); + if (this.dirs.has(path)) { + return { + isDirectory: () => true, + isFile: () => false, + isSymbolicLink: () => false, + mtimeMs: nowMs, + mtime: now, + ctimeMs: nowMs, + ctime: now, + mode: 0o40755, + size: 0, + ino: 1, + uid: 1000, + gid: 1000, + }; + } + if (this.files.has(path)) { + const content = this.files.get(path)!; + const size = typeof content === 'string' ? content.length : content.byteLength; + return { + isDirectory: () => false, + isFile: () => true, + isSymbolicLink: () => false, + mtimeMs: nowMs, + mtime: now, + ctimeMs: nowMs, + ctime: now, + mode: 0o100644, + size, + ino: 1, + uid: 1000, + gid: 1000, + }; + } + const error = new Error(`ENOENT: no such file or directory, stat '${path}'`) as NodeJS.ErrnoException; + error.code = 'ENOENT'; + throw error; + } + + async lstat(path: string): Promise<{ + isDirectory(): boolean; + isFile(): boolean; + isSymbolicLink(): boolean; + mtimeMs?: number; + mtime?: Date; + ctimeMs?: number; + ctime?: Date; + mode?: number; + size?: number; + ino?: number; + uid?: number; + gid?: number; + }> { + return this.stat(path); + } + + async readlink(_path: string): Promise { + const error = new Error('EINVAL: invalid argument') as NodeJS.ErrnoException; + error.code = 'EINVAL'; + throw error; + } + + async symlink(_target: string, _path: string): Promise { + // No-op for mock + } + + async unlink(path: string): Promise { + this.files.delete(path); + } + + async rmdir(path: string): Promise { + this.dirs.delete(path); + } + + async rename(oldPath: string, newPath: string): Promise { + if (this.files.has(oldPath)) { + const content = this.files.get(oldPath); + this.files.delete(oldPath); + this.files.set(newPath, content!); + } + if (this.dirs.has(oldPath)) { + this.dirs.delete(oldPath); + this.dirs.add(newPath); + } + } + + async chmod(_path: string, _mode: number): Promise { + // No-op for mock + } + + async rm(path: string, options?: { recursive?: boolean }): Promise { + if (options?.recursive) { + for (const file of [...this.files.keys()]) { + if (file.startsWith(path + '/') || file === path) this.files.delete(file); + } + for (const dir of [...this.dirs]) { + if (dir.startsWith(path + '/') || dir === path) this.dirs.delete(dir); + } + } else { + await this.unlink(path); + } + } +} + +/** + * Mock Nostr pool + */ +const createMockNostr = (): NPool => { + const events: NostrEvent[] = []; + return { + req: vi.fn(), + query: vi.fn(async () => events), + event: vi.fn(async (event: NostrEvent) => { events.push(event); }), + group: vi.fn().mockReturnValue({ query: vi.fn(async () => events) }), + relay: vi.fn(), + relays: new Map(), + close: vi.fn(), + } as unknown as NPool; +}; + +/** + * Create a test Nostr signer using NSecSigner + */ +const createTestSigner = () => { + // Generate a random test nsec (32 bytes of zeros as Uint8Array) + const testSecretKey = new Uint8Array(32).fill(1); + return new NSecSigner(testSecretKey); +}; describe('Git', () => { - const fs = {} as JSRuntimeFS; - const nostr = createMockNostr(); - const corsProxy = 'https://cors.example.com'; - let gitInstance: Git; + let fs: JSRuntimeFS; + let nostr: NPool; + let git: Git; beforeEach(() => { - vi.clearAllMocks(); - gitInstance = new Git({ fs, nostr, corsProxy }); + fs = new MockFS(); + nostr = createMockNostr(); + git = new Git({ + fs, + nostr, + systemAuthor: { name: 'Test User', email: 'test@example.com' }, + }); }); - describe('constructor', () => { - it('creates instance with default regex when none provided', () => { - const git = new Git({ fs, nostr, corsProxy }); - expect(git).toBeInstanceOf(Git); + describe('Basic Git Operations', () => { + describe('init', () => { + it('should initialize a new repository', async () => { + await git.init({ dir: '/repo', defaultBranch: 'main' }); + const gitDirStat = await fs.stat('/repo/.git'); + expect(gitDirStat.isDirectory()).toBe(true); + }); }); + describe('add and commit', () => { + it('should add and commit files', async () => { + await git.init({ dir: '/repo', defaultBranch: 'main' }); + await fs.mkdir('/repo/.shakespeare'); + await fs.writeFile('/repo/.shakespeare/git.json', JSON.stringify({ name: 'Test', email: 'test@test.com' })); + await fs.writeFile('/repo/test.txt', 'Hello World'); + await git.add({ dir: '/repo', filepath: 'test.txt' }); + const sha = await git.commit({ dir: '/repo', message: 'Initial commit' }); + expect(sha).toBeDefined(); + expect(typeof sha).toBe('string'); + expect(sha.length).toBe(40); + }); + it('should add co-author when enabled', async () => { + await git.init({ dir: '/repo', defaultBranch: 'main' }); + await fs.mkdir('/repo/.shakespeare'); + await fs.writeFile('/repo/.shakespeare/git.json', JSON.stringify({ name: 'Test', email: 'test@test.com', coAuthorEnabled: true })); + await fs.writeFile('/repo/test.txt', 'Hello'); + await git.add({ dir: '/repo', filepath: 'test.txt' }); + const sha = await git.commit({ dir: '/repo', message: 'Test' }); + const commit = await git.readCommit({ dir: '/repo', oid: sha }); + expect(commit.commit.message).toContain('Co-authored-by: Test User '); + }); + }); + + describe('status', () => { + it('should get file status', async () => { + await git.init({ dir: '/repo', defaultBranch: 'main' }); + await fs.writeFile('/repo/test.txt', 'Hello'); + const status = await git.status({ dir: '/repo', filepath: 'test.txt' }); + expect(status).toBeDefined(); + }); + }); + + describe('log', () => { + it('should get commit history', async () => { + await git.init({ dir: '/repo', defaultBranch: 'main' }); + await fs.mkdir('/repo/.shakespeare'); + await fs.writeFile('/repo/.shakespeare/git.json', JSON.stringify({ name: 'Test', email: 'test@test.com' })); + await fs.writeFile('/repo/test.txt', 'Hello'); + await git.add({ dir: '/repo', filepath: 'test.txt' }); + await git.commit({ dir: '/repo', message: 'First' }); + const commits = await git.log({ dir: '/repo' }); + expect(commits.length).toBeGreaterThan(0); + expect(commits[0].commit.message).toContain('First'); + }); + }); + + describe('branch operations', () => { + it('should create and list branches', async () => { + await git.init({ dir: '/repo', defaultBranch: 'main' }); + await fs.mkdir('/repo/.shakespeare'); + await fs.writeFile('/repo/.shakespeare/git.json', JSON.stringify({ name: 'Test', email: 'test@test.com' })); + await fs.writeFile('/repo/test.txt', 'Hello'); + await git.add({ dir: '/repo', filepath: 'test.txt' }); + await git.commit({ dir: '/repo', message: 'Initial' }); + await git.branch({ dir: '/repo', ref: 'feature' }); + const branches = await git.listBranches({ dir: '/repo' }); + expect(branches).toContain('main'); + expect(branches).toContain('feature'); + }); + + it('should checkout branches', async () => { + await git.init({ dir: '/repo', defaultBranch: 'main' }); + await fs.mkdir('/repo/.shakespeare'); + await fs.writeFile('/repo/.shakespeare/git.json', JSON.stringify({ name: 'Test', email: 'test@test.com' })); + await fs.writeFile('/repo/test.txt', 'Hello'); + await git.add({ dir: '/repo', filepath: 'test.txt' }); + await git.commit({ dir: '/repo', message: 'Initial' }); + await git.branch({ dir: '/repo', ref: 'feature' }); + await git.checkout({ dir: '/repo', ref: 'feature' }); + const currentBranch = await git.currentBranch({ dir: '/repo' }); + expect(currentBranch).toBe('feature'); + }); + }); + + describe('remote operations', () => { + it('should add and list remotes', async () => { + await git.init({ dir: '/repo', defaultBranch: 'main' }); + await git.addRemote({ dir: '/repo', remote: 'origin', url: 'https://github.com/user/repo.git' }); + const remotes = await git.listRemotes({ dir: '/repo' }); + expect(remotes).toHaveLength(1); + expect(remotes[0].remote).toBe('origin'); + expect(remotes[0].url).toBe('https://github.com/user/repo.git'); + }); + + it('should delete remotes', async () => { + await git.init({ dir: '/repo', defaultBranch: 'main' }); + await git.addRemote({ dir: '/repo', remote: 'origin', url: 'https://github.com/user/repo.git' }); + await git.deleteRemote({ dir: '/repo', remote: 'origin' }); + const remotes = await git.listRemotes({ dir: '/repo' }); + expect(remotes).toHaveLength(0); + }); + + it('should get and set remote URL', async () => { + await git.init({ dir: '/repo', defaultBranch: 'main' }); + await git.addRemote({ dir: '/repo', remote: 'origin', url: 'https://github.com/user/repo.git' }); + const url = await git.getRemoteURL('/repo', 'origin'); + expect(url).toBe('https://github.com/user/repo.git'); + await git.setRemoteURL({ dir: '/repo', remote: 'origin', url: 'https://github.com/user/new.git' }); + const newUrl = await git.getRemoteURL('/repo', 'origin'); + expect(newUrl).toBe('https://github.com/user/new.git'); + }); + }); + + describe('tag operations', () => { + it('should create and list tags', async () => { + await git.init({ dir: '/repo', defaultBranch: 'main' }); + await fs.mkdir('/repo/.shakespeare'); + await fs.writeFile('/repo/.shakespeare/git.json', JSON.stringify({ name: 'Test', email: 'test@test.com' })); + await fs.writeFile('/repo/test.txt', 'Hello'); + await git.add({ dir: '/repo', filepath: 'test.txt' }); + await git.commit({ dir: '/repo', message: 'Initial' }); + await git.tag({ dir: '/repo', ref: 'v1.0.0' }); + const tags = await git.listTags({ dir: '/repo' }); + expect(tags).toContain('v1.0.0'); + }); + + it('should delete tags', async () => { + await git.init({ dir: '/repo', defaultBranch: 'main' }); + await fs.mkdir('/repo/.shakespeare'); + await fs.writeFile('/repo/.shakespeare/git.json', JSON.stringify({ name: 'Test', email: 'test@test.com' })); + await fs.writeFile('/repo/test.txt', 'Hello'); + await git.add({ dir: '/repo', filepath: 'test.txt' }); + await git.commit({ dir: '/repo', message: 'Initial' }); + await git.tag({ dir: '/repo', ref: 'v1.0.0' }); + await git.deleteTag({ dir: '/repo', ref: 'v1.0.0' }); + const tags = await git.listTags({ dir: '/repo' }); + expect(tags).not.toContain('v1.0.0'); + }); + }); }); - describe('clone', () => { + describe('Nostr Git Operations', () => { + const testPubkey = 'a'.repeat(64); + const testNpub = nip19.npubEncode(testPubkey); + let signer: NSecSigner; + beforeEach(() => { - mockGit.clone = vi.fn().mockResolvedValue(undefined); - }); - - it('uses CORS proxy for all URLs', async () => { - await gitInstance.clone({ - dir: '/test', - url: 'https://github.com/user/repo.git', - }); - - expect(mockGit.clone).toHaveBeenCalledWith({ + signer = createTestSigner(); + git = new Git({ fs, - http: expect.any(Object), - onAuth: expect.any(Function), - dir: '/test', - url: 'https://github.com/user/repo.git', + nostr, + signer, + systemAuthor: { name: 'Test User', email: 'test@example.com' }, + relayList: [{ url: new URL('wss://relay.example.com'), read: true, write: true }], }); }); - it('uses CORS proxy for GitLab URLs', async () => { - await gitInstance.clone({ - dir: '/test', - url: 'https://gitlab.com/user/repo.git', + describe('nostr clone', () => { + it('should handle missing Nostr repository', async () => { + vi.mocked(nostr.group).mockReturnValue({ + query: vi.fn(async () => []), + } as unknown as ReturnType); + + await expect(git.clone({ + url: `nostr://${testNpub}/nonexistent`, + dir: '/nostr-repo', + })).rejects.toThrow('Repository not found on Nostr network'); }); - expect(mockGit.clone).toHaveBeenCalledWith({ - fs, - http: expect.any(Object), - onAuth: expect.any(Function), - dir: '/test', - url: 'https://gitlab.com/user/repo.git', - }); - }); - - it('uses CORS proxy for custom URLs', async () => { - await gitInstance.clone({ - dir: '/test', - url: 'https://custom.example.com/user/repo.git', - }); - - expect(mockGit.clone).toHaveBeenCalledWith({ - fs, - http: expect.any(Object), - onAuth: expect.any(Function), - dir: '/test', - url: 'https://custom.example.com/user/repo.git', - }); - }); - - it('handles HTTP URLs correctly', async () => { - await gitInstance.clone({ - dir: '/test', - url: 'http://github.com/user/repo.git', - }); - - expect(mockGit.clone).toHaveBeenCalledWith({ - fs, - http: expect.any(Object), - onAuth: expect.any(Function), - dir: '/test', - url: 'http://github.com/user/repo.git', - }); - }); - }); - - describe('getRemoteInfo', () => { - beforeEach(() => { - mockGit.getRemoteInfo = vi.fn().mockResolvedValue({}); - }); - - it('uses CORS proxy for matching URLs', async () => { - await gitInstance.getRemoteInfo({ - url: 'https://github.com/user/repo.git', - }); - - expect(mockGit.getRemoteInfo).toHaveBeenCalledWith({ - http: expect.any(Object), - onAuth: expect.any(Function), - url: 'https://github.com/user/repo.git', - }); - }); - - it('uses CORS proxy for all URLs', async () => { - await gitInstance.getRemoteInfo({ - url: 'https://custom.example.com/user/repo.git', - }); - - expect(mockGit.getRemoteInfo).toHaveBeenCalledWith({ - http: expect.any(Object), - onAuth: expect.any(Function), - url: 'https://custom.example.com/user/repo.git', - }); - }); - }); - - describe('fetch with remote resolution', () => { - beforeEach(() => { - mockGit.fetch = vi.fn().mockResolvedValue(undefined); - mockGit.listRemotes = vi.fn().mockResolvedValue([ - { remote: 'origin', url: 'https://github.com/user/repo.git' } - ]); - }); - - it('uses CORS proxy for all fetch operations', async () => { - await gitInstance.fetch({ - dir: '/test', - remote: 'origin', - }); - - expect(mockGit.fetch).toHaveBeenCalledWith({ - fs, - http: expect.any(Object), - onAuth: expect.any(Function), - dir: '/test', - remote: 'origin', - }); - }); - - it('handles fetch with direct URL parameter', async () => { - await gitInstance.fetch({ - dir: '/test', - url: 'https://gitlab.com/user/repo.git', - }); - - expect(mockGit.fetch).toHaveBeenCalledWith({ - fs, - http: expect.any(Object), - onAuth: expect.any(Function), - dir: '/test', - url: 'https://gitlab.com/user/repo.git', - remote: 'origin', - }); - }); - }); - - describe('Nostr URI cloning', () => { - beforeEach(() => { - mockGit.clone = vi.fn().mockResolvedValue(undefined); - mockGit.deleteRemote = vi.fn().mockResolvedValue(undefined); - mockGit.addRemote = vi.fn().mockResolvedValue(undefined); - mockGit.getRemoteInfo = vi.fn().mockResolvedValue({ refs: {} }); - - // Mock nip19 decode - vi.mocked(nip19.decode).mockReturnValue({ - type: 'npub', - data: 'abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab' - }); - - // Mock Nostr query to return a repository event - const mockRelay = { - query: vi.fn().mockResolvedValue([{ - id: 'event123', - pubkey: 'abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab', + it('should handle missing clone URLs', async () => { + const repoEvent: NostrEvent = { + id: 'repo-event-id', + pubkey: testPubkey, + created_at: Math.floor(Date.now() / 1000), kind: 30617, + tags: [['d', 'test-repo']], content: '', - tags: [ - ['d', 'my-repo'], - ['clone', 'https://github.com/user/repo.git', 'https://gitlab.com/user/repo.git'], - ], - created_at: Date.now(), - sig: 'signature' - }]) - }; + sig: 'test-sig', + }; - nostr.group = vi.fn().mockReturnValue(mockRelay); - nostr.relay = vi.fn().mockReturnValue(mockRelay); - }); - - it('successfully clones from Nostr URI and updates origin remote', async () => { - const nostrUrl = 'nostr://npub1abc123/my-repo'; - // The mock npubEncode creates npub1 + first 10 chars of the hex pubkey - // pubkey: 'abcd1234567890...' -> npub1abcd123456 - const expectedNostrUrl = 'nostr://npub1abcd123456/my-repo'; - - await gitInstance.clone({ - dir: '/test', - url: nostrUrl, - }); - - // Should attempt to clone from one of the URLs (implementation uses the last successfully checked URL) - expect(mockGit.clone).toHaveBeenCalledWith({ - fs, - http: expect.any(Object), - onAuth: expect.any(Function), - dir: '/test', - url: expect.stringMatching(/^https:\/\/(github|gitlab)\.com\/user\/repo\.git$/), - }); - - // Should delete the existing origin remote - expect(mockGit.deleteRemote).toHaveBeenCalledWith({ - fs, - dir: '/test', - remote: 'origin', - }); - - // Should add the Nostr URI as the new origin (with properly encoded npub) - expect(mockGit.addRemote).toHaveBeenCalledWith({ - fs, - dir: '/test', - remote: 'origin', - url: expectedNostrUrl, - }); - }); - }); - - describe('setRemoteURL', () => { - beforeEach(() => { - mockGit.deleteRemote = vi.fn().mockResolvedValue(undefined); - mockGit.addRemote = vi.fn().mockResolvedValue(undefined); - }); - - it('updates remote URL by deleting and re-adding remote', async () => { - await gitInstance.setRemoteURL({ - dir: '/test', - remote: 'origin', - url: 'https://new-repo.com/user/repo.git', - }); - - expect(mockGit.deleteRemote).toHaveBeenCalledWith({ - fs, - dir: '/test', - remote: 'origin', - }); - - expect(mockGit.addRemote).toHaveBeenCalledWith({ - fs, - dir: '/test', - remote: 'origin', - url: 'https://new-repo.com/user/repo.git', - }); - }); - - it('works with any remote name', async () => { - await gitInstance.setRemoteURL({ - dir: '/test', - remote: 'upstream', - url: 'nostr://npub1abc123/my-repo', - }); - - expect(mockGit.deleteRemote).toHaveBeenCalledWith({ - fs, - dir: '/test', - remote: 'upstream', - }); - - expect(mockGit.addRemote).toHaveBeenCalledWith({ - fs, - dir: '/test', - remote: 'upstream', - url: 'nostr://npub1abc123/my-repo', - }); - }); - }); - - describe('commit with Git identity settings', () => { - beforeEach(() => { - mockGit.commit = vi.fn().mockResolvedValue('abc123'); - }); - - it('uses shakespeare.diy as default author when no Git identity is configured', async () => { - const { readGitSettings } = await import('./configUtils'); - vi.mocked(readGitSettings).mockResolvedValue({ - credentials: [], - coAuthorEnabled: false, - }); - - await gitInstance.commit({ - dir: '/test', - message: 'Test commit', - }); - - expect(mockGit.commit).toHaveBeenCalledWith({ - fs, - dir: '/test', - message: 'Test commit', - author: { - name: 'shakespeare.diy', - email: 'assistant@shakespeare.diy', - }, - }); - }); - - it('uses custom identity when both name and email are configured', async () => { - const { readGitSettings } = await import('./configUtils'); - vi.mocked(readGitSettings).mockResolvedValue({ - credentials: [], - name: 'John Doe', - email: 'john@example.com', - coAuthorEnabled: true, - }); - - await gitInstance.commit({ - dir: '/test', - message: 'Test commit', - }); - - expect(mockGit.commit).toHaveBeenCalledWith({ - fs, - dir: '/test', - message: 'Test commit\n\nCo-authored-by: shakespeare.diy ', - author: { - name: 'John Doe', - email: 'john@example.com', - }, - }); - }); - - it('does not add co-author when coAuthorEnabled is false', async () => { - const { readGitSettings } = await import('./configUtils'); - vi.mocked(readGitSettings).mockResolvedValue({ - credentials: [], - name: 'John Doe', - email: 'john@example.com', - coAuthorEnabled: false, - }); - - await gitInstance.commit({ - dir: '/test', - message: 'Test commit', - }); - - expect(mockGit.commit).toHaveBeenCalledWith({ - fs, - dir: '/test', - message: 'Test commit', - author: { - name: 'John Doe', - email: 'john@example.com', - }, - }); - }); - }); - - describe('Nostr push with fast-forward checking', () => { - const mockSigner = { - signEvent: vi.fn().mockResolvedValue({ - id: 'state123', - pubkey: 'abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab', - kind: 30618, - content: '', - tags: [], - created_at: Date.now(), - sig: 'signature', - }), - getPublicKey: vi.fn().mockResolvedValue('abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab'), - }; - - let gitInstanceWithSigner: Git; - - beforeEach(() => { - // Mock timers to avoid waiting 5 seconds - vi.useFakeTimers(); - - // Create a Git instance with a signer - gitInstanceWithSigner = new Git({ fs, nostr, corsProxy, signer: mockSigner }); - - mockGit.push = vi.fn().mockResolvedValue(undefined); - mockGit.listRemotes = vi.fn().mockResolvedValue([ - { remote: 'origin', url: 'nostr://npub1abc123/my-repo' } - ]); - mockGit.listRefs = vi.fn().mockResolvedValue(['refs/heads/main']); - mockGit.resolveRef = vi.fn().mockResolvedValue('localcommit123'); - mockGit.isDescendent = vi.fn().mockResolvedValue(true); - mockGit.currentBranch = vi.fn().mockResolvedValue('main'); - mockGit.readCommit = vi.fn().mockResolvedValue({}); - - // Mock nip19 decode - vi.mocked(nip19.decode).mockReturnValue({ - type: 'npub', - data: 'abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab' - }); - - vi.mocked(nip19.naddrEncode).mockReturnValue('naddr1...'); - - // Mock Nostr query to return repository and state events - const mockRelay = { - query: vi.fn().mockResolvedValue([ - { - id: 'repo123', - pubkey: 'abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab', - kind: 30617, - content: '', - tags: [ - ['d', 'my-repo'], - ['clone', 'https://github.com/user/repo.git'], - ], - created_at: Date.now(), - sig: 'signature', - }, - { - id: 'state123', - pubkey: 'abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab', - kind: 30618, - content: '', - tags: [ - ['d', 'my-repo'], - ['refs/heads/main', 'remotecommit456'], - ['HEAD', 'ref: refs/heads/main'], - ], - created_at: Date.now(), - sig: 'signature', - }, - ]), - }; - - nostr.group = vi.fn().mockReturnValue(mockRelay); - nostr.relay = vi.fn().mockReturnValue(mockRelay); - nostr.event = vi.fn().mockResolvedValue(undefined); - - mockGit.setConfig = vi.fn().mockResolvedValue(undefined); - }); - - afterEach(() => { - vi.useRealTimers(); - }); - - it('rejects non-fast-forward push without --force flag', async () => { - // Mock isDescendent to return false (not a fast-forward) - mockGit.isDescendent = vi.fn().mockResolvedValue(false); - - await expect( - gitInstanceWithSigner.push({ - dir: '/test', - remote: 'origin', - ref: 'main', - force: false, - }) - ).rejects.toThrow('Updates were rejected'); - }); - - it('allows non-fast-forward push with --force flag', async () => { - // Mock isDescendent to return false (not a fast-forward) - mockGit.isDescendent = vi.fn().mockResolvedValue(false); - - // Should not throw with force flag - const pushPromise = gitInstanceWithSigner.push({ - dir: '/test', - remote: 'origin', - ref: 'main', - force: true, - }); - - // Advance timers to skip the 5 second wait - await vi.advanceTimersByTimeAsync(5000); - - await pushPromise; - - // Should have attempted to push to the Git remote - expect(mockGit.push).toHaveBeenCalled(); - }); - - it('allows fast-forward push without --force flag', async () => { - // Mock isDescendent to return true (is a fast-forward) - mockGit.isDescendent = vi.fn().mockResolvedValue(true); - - // Should not throw - const pushPromise = gitInstanceWithSigner.push({ - dir: '/test', - remote: 'origin', - ref: 'main', - force: false, - }); - - // Advance timers to skip the 5 second wait - await vi.advanceTimersByTimeAsync(5000); - - await pushPromise; - - // Should have attempted to push to the Git remote - expect(mockGit.push).toHaveBeenCalled(); - }); - - it('returns early when commits are already up-to-date', async () => { - // Mock resolveRef to return the same commit as remote - mockGit.resolveRef = vi.fn().mockResolvedValue('remotecommit456'); - - await gitInstanceWithSigner.push({ - dir: '/test', - remote: 'origin', - ref: 'main', - force: false, - }); - - // Should not have attempted to push (already up-to-date) - expect(mockGit.push).not.toHaveBeenCalled(); - }); - - it('skips fast-forward check when no state event exists', async () => { - // Mock Nostr query to return only repo event (no state) - const mockRelay = { - query: vi.fn().mockResolvedValue([ - { - id: 'repo123', - pubkey: 'abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab', - kind: 30617, - content: '', - tags: [ - ['d', 'my-repo'], - ['clone', 'https://github.com/user/repo.git'], - ], - created_at: Date.now(), - sig: 'signature', - }, - ]), - }; - - nostr.group = vi.fn().mockReturnValue(mockRelay); - nostr.relay = vi.fn().mockReturnValue(mockRelay); - - // Should not throw even if not a fast-forward (no state to check against) - const pushPromise = gitInstanceWithSigner.push({ - dir: '/test', - remote: 'origin', - ref: 'main', - force: false, - }); - - // Advance timers to skip the 5 second wait - await vi.advanceTimersByTimeAsync(5000); - - await pushPromise; - - // Should have attempted to push - expect(mockGit.push).toHaveBeenCalled(); - }); - - it('skips fast-forward check when state has no matching ref', async () => { - // Mock Nostr query to return state with different ref - const mockRelay = { - query: vi.fn().mockResolvedValue([ - { - id: 'repo123', - pubkey: 'abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab', - kind: 30617, - content: '', - tags: [ - ['d', 'my-repo'], - ['clone', 'https://github.com/user/repo.git'], - ], - created_at: Date.now(), - sig: 'signature', - }, - { - id: 'state123', - pubkey: 'abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab', - kind: 30618, - content: '', - tags: [ - ['d', 'my-repo'], - ['refs/heads/develop', 'othercommit789'], - ['HEAD', 'ref: refs/heads/develop'], - ], - created_at: Date.now(), - sig: 'signature', - }, - ]), - }; - - nostr.group = vi.fn().mockReturnValue(mockRelay); - nostr.relay = vi.fn().mockReturnValue(mockRelay); - - // Should not throw (no matching ref in state) - const pushPromise = gitInstanceWithSigner.push({ - dir: '/test', - remote: 'origin', - ref: 'main', - force: false, - }); - - // Advance timers to skip the 5 second wait - await vi.advanceTimersByTimeAsync(5000); - - await pushPromise; - - // Should have attempted to push - expect(mockGit.push).toHaveBeenCalled(); - }); - - it('publishes new state event to Nostr relays', async () => { - mockGit.isDescendent = vi.fn().mockResolvedValue(true); - - const mockGroupRelay = { - query: vi.fn().mockResolvedValue([ - { - id: 'repo123', - pubkey: 'abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab', - kind: 30617, - content: '', - tags: [ - ['d', 'my-repo'], - ['clone', 'https://github.com/user/repo.git'], - ], - created_at: Date.now(), - sig: 'signature', - }, - { - id: 'state123', - pubkey: 'abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab', - kind: 30618, - content: '', - tags: [ - ['d', 'my-repo'], - ['refs/heads/main', 'remotecommit456'], - ['HEAD', 'ref: refs/heads/main'], - ], - created_at: Date.now(), - sig: 'signature', - }, - ]), - event: vi.fn().mockResolvedValue(undefined), - }; - - nostr.group = vi.fn().mockReturnValue(mockGroupRelay); - - const pushPromise = gitInstanceWithSigner.push({ - dir: '/test', - remote: 'origin', - ref: 'main', - force: false, - }); - - // Advance timers to skip the 5 second wait - await vi.advanceTimersByTimeAsync(5000); - - await pushPromise; - - // Should have signed a new state event - expect(mockSigner.signEvent).toHaveBeenCalledWith( - expect.objectContaining({ + const stateEvent: NostrEvent = { + id: 'state-event-id', + pubkey: testPubkey, + created_at: Math.floor(Date.now() / 1000), kind: 30618, - tags: expect.arrayContaining([ - ['d', 'my-repo'], - ]), - }) - ); + tags: [['d', 'test-repo'], ['HEAD', 'ref: refs/heads/main']], + content: '', + sig: 'test-sig', + }; - // Should have published the state event to Nostr via group - expect(mockGroupRelay.event).toHaveBeenCalled(); + vi.mocked(nostr.group).mockReturnValue({ + query: vi.fn(async () => [repoEvent, stateEvent]), + } as unknown as ReturnType); + + await expect(git.clone({ + url: `nostr://${testNpub}/test-repo`, + dir: '/nostr-repo', + })).rejects.toThrow('No clone URLs found in repository announcement'); + }); + }); + + describe('nostr push', () => { + it('should require signer for Nostr push', async () => { + const gitWithoutSigner = new Git({ + fs, + nostr, + systemAuthor: { name: 'Test User', email: 'test@example.com' }, + }); + + const repoEvent: NostrEvent = { + id: 'repo-event-id', + pubkey: testPubkey, + created_at: Math.floor(Date.now() / 1000), + kind: 30617, + tags: [['d', 'test-repo'], ['clone', 'https://git.example.com/user/repo.git']], + content: '', + sig: 'test-sig', + }; + + vi.mocked(nostr.group).mockReturnValue({ + query: vi.fn(async () => [repoEvent]), + } as unknown as ReturnType); + + // Can't test actual push without complex setup, but we can verify signer requirement + await expect(async () => { + await git.init({ dir: '/nostr-repo', defaultBranch: 'main' }); + await git.addRemote({ dir: '/nostr-repo', remote: 'origin', url: `nostr://${testNpub}/test-repo` }); + await gitWithoutSigner.push({ dir: '/nostr-repo', remote: 'origin', ref: 'main' }); + }).rejects.toThrow('Signer required for Nostr push'); + }); }); }); -}); \ No newline at end of file +});