From 56931f81bac2deccf6aa7cb9d714a787efe99a59 Mon Sep 17 00:00:00 2001 From: hugo Date: Mon, 16 Feb 2026 12:24:36 +0100 Subject: [PATCH] feat: commit push/pull/fetch and others --- src/main/engine/GitEngine.ts | 66 +++++++++ src/main/ipc/handlers.ts | 20 +++ src/main/preload.ts | 4 + src/main/shared/electronApi.ts | 9 ++ .../components/GitDiffView/GitDiffView.tsx | 9 ++ .../components/GitSidebar/GitSidebar.css | 17 +++ .../components/GitSidebar/GitSidebar.tsx | 126 +++++++++++++++++- tests/engine/GitEngine.test.ts | 54 ++++++++ tests/ipc/handlers.test.ts | 48 +++++++ .../renderer/components/GitDiffView.test.tsx | 13 +- tests/renderer/components/GitSidebar.test.tsx | 65 +++++++++ 11 files changed, 429 insertions(+), 2 deletions(-) diff --git a/src/main/engine/GitEngine.ts b/src/main/engine/GitEngine.ts index c923f2c..65e6ffc 100644 --- a/src/main/engine/GitEngine.ts +++ b/src/main/engine/GitEngine.ts @@ -98,6 +98,11 @@ export interface GitLfsPruneResult { error?: string; } +export interface GitActionResult { + success: boolean; + error?: string; +} + let gitEngineInstance: GitEngine | null = null; export function getGitEngine(): GitEngine { @@ -274,6 +279,67 @@ export class GitEngine { })); } + async fetch(projectPath: string): Promise { + const git = simpleGit(projectPath); + try { + await git.fetch(['--prune']); + return { success: true }; + } catch (error) { + return { + success: false, + error: error instanceof Error ? error.message : 'Failed to fetch remote updates.', + }; + } + } + + async pull(projectPath: string): Promise { + const git = simpleGit(projectPath); + try { + await git.pull(); + return { success: true }; + } catch (error) { + return { + success: false, + error: error instanceof Error ? error.message : 'Failed to pull remote changes.', + }; + } + } + + async push(projectPath: string): Promise { + const git = simpleGit(projectPath); + try { + await git.push(); + return { success: true }; + } catch (error) { + return { + success: false, + error: error instanceof Error ? error.message : 'Failed to push local commits.', + }; + } + } + + async commitAll(projectPath: string, message: string): Promise { + const normalizedMessage = message.trim(); + if (!normalizedMessage) { + return { + success: false, + error: 'Commit message is required.', + }; + } + + const git = simpleGit(projectPath); + try { + await git.add(['-A']); + await git.commit(normalizedMessage); + return { success: true }; + } catch (error) { + return { + success: false, + error: error instanceof Error ? error.message : 'Failed to create commit.', + }; + } + } + async ensureGitignore(projectPath: string): Promise { const gitignorePath = path.join(projectPath, '.gitignore'); diff --git a/src/main/ipc/handlers.ts b/src/main/ipc/handlers.ts index a0f8266..c826206 100644 --- a/src/main/ipc/handlers.ts +++ b/src/main/ipc/handlers.ts @@ -63,6 +63,26 @@ export function registerIpcHandlers(): void { return engine.getHistory(projectPath, limit); }); + safeHandle('git:fetch', async (_, projectPath: string) => { + const engine = getGitEngine(); + return engine.fetch(projectPath); + }); + + safeHandle('git:pull', async (_, projectPath: string) => { + const engine = getGitEngine(); + return engine.pull(projectPath); + }); + + safeHandle('git:push', async (_, projectPath: string) => { + const engine = getGitEngine(); + return engine.push(projectPath); + }); + + safeHandle('git:commitAll', async (_, projectPath: string, message: string) => { + const engine = getGitEngine(); + return engine.commitAll(projectPath, message); + }); + safeHandle('git:init', async (event, projectPath: string, remoteUrl?: string) => { const engine = getGitEngine(); return engine.initializeRepo(projectPath, remoteUrl, (progress) => { diff --git a/src/main/preload.ts b/src/main/preload.ts index 824ef05..1e3c1ed 100644 --- a/src/main/preload.ts +++ b/src/main/preload.ts @@ -13,6 +13,10 @@ export const electronAPI: ElectronAPI = { getDiff: (projectPath: string, filePath: string) => ipcRenderer.invoke('git:diff', projectPath, filePath), getDiffContent: (projectPath: string, filePath: string) => ipcRenderer.invoke('git:diffContent', projectPath, filePath), getHistory: (projectPath: string, limit?: number) => ipcRenderer.invoke('git:history', projectPath, limit), + fetch: (projectPath: string) => ipcRenderer.invoke('git:fetch', projectPath), + pull: (projectPath: string) => ipcRenderer.invoke('git:pull', projectPath), + push: (projectPath: string) => ipcRenderer.invoke('git:push', projectPath), + commitAll: (projectPath: string, message: string) => ipcRenderer.invoke('git:commitAll', projectPath, message), ensureGitignore: (projectPath: string) => ipcRenderer.invoke('git:ensureGitignore', projectPath), pruneLfs: (projectPath: string, options?: { dryRun?: boolean; verifyRemote?: boolean }) => ipcRenderer.invoke('git:pruneLfs', projectPath, options), init: (projectPath: string, remoteUrl?: string) => { diff --git a/src/main/shared/electronApi.ts b/src/main/shared/electronApi.ts index e93b5de..6280540 100644 --- a/src/main/shared/electronApi.ts +++ b/src/main/shared/electronApi.ts @@ -293,6 +293,11 @@ export interface GitLfsPruneResult { error?: string; } +export interface GitActionResult { + success: boolean; + error?: string; +} + // Post-Media Link types export interface MediaLinkData { id: string; @@ -370,6 +375,10 @@ export interface ElectronAPI { getDiff: (projectPath: string, filePath: string) => Promise; getDiffContent: (projectPath: string, filePath: string) => Promise; getHistory: (projectPath: string, limit?: number) => Promise; + fetch: (projectPath: string) => Promise; + pull: (projectPath: string) => Promise; + push: (projectPath: string) => Promise; + commitAll: (projectPath: string, message: string) => Promise; ensureGitignore: (projectPath: string) => Promise; pruneLfs: (projectPath: string, options?: { dryRun?: boolean; verifyRemote?: boolean }) => Promise; init: (projectPath: string, remoteUrl?: string) => Promise; diff --git a/src/renderer/components/GitDiffView/GitDiffView.tsx b/src/renderer/components/GitDiffView/GitDiffView.tsx index 97e3925..6394558 100644 --- a/src/renderer/components/GitDiffView/GitDiffView.tsx +++ b/src/renderer/components/GitDiffView/GitDiffView.tsx @@ -35,6 +35,11 @@ function detectLanguage(filePath: string): string { } } +function toModelPath(filePath: string, side: 'original' | 'modified'): string { + const normalized = filePath.replace(/^\/+/, ''); + return `inmemory://model/git-diff/${side}/${normalized}`; +} + export const GitDiffView: React.FC = ({ filePath }) => { const { activeProject, gitDiffPreferences } = useAppStore(); const [loading, setLoading] = useState(true); @@ -100,6 +105,10 @@ export const GitDiffView: React.FC = ({ filePath }) => { { - const { activeProject, openTab } = useAppStore(); + const { activeProject, openTab, tabs, closeTab } = useAppStore(); const [projectPath, setProjectPath] = useState(null); const [loading, setLoading] = useState(true); const [initializing, setInitializing] = useState(false); const [statusLoading, setStatusLoading] = useState(false); + const [actionLoading, setActionLoading] = useState<'fetch' | 'pull' | 'push' | 'commit' | null>(null); const [error, setError] = useState(null); const [isRepo, setIsRepo] = useState(false); const [currentBranch, setCurrentBranch] = useState(null); const [statusFiles, setStatusFiles] = useState>([]); + const [commitMessage, setCommitMessage] = useState(''); const [historyLoading, setHistoryLoading] = useState(false); const [historyEntries, setHistoryEntries] = useState([]); const [initProgress, setInitProgress] = useState(null); const [initTranscript, setInitTranscript] = useState([]); const [isTranscriptExpanded, setIsTranscriptExpanded] = useState(false); const remoteUrlInputRef = useRef(null); + const commitMessageInputRef = useRef(null); const getDiffTabId = (filePath: string): string => `git-diff:${filePath}`; @@ -149,6 +152,78 @@ export const GitSidebar: React.FC = () => { } }; + const handleRepoAction = async (action: 'fetch' | 'pull' | 'push') => { + if (actionLoading) { + return; + } + + const effectiveProjectPath = projectPath ?? (await resolveProjectPath()); + if (!effectiveProjectPath) { + setError('No active project selected.'); + return; + } + if (!projectPath) { + setProjectPath(effectiveProjectPath); + } + + setActionLoading(action); + setError(null); + try { + const result = + action === 'fetch' + ? await window.electronAPI.git.fetch(effectiveProjectPath) + : action === 'pull' + ? await window.electronAPI.git.pull(effectiveProjectPath) + : await window.electronAPI.git.push(effectiveProjectPath); + if (!result.success) { + setError(result.error || `Failed to ${action}.`); + return; + } + await loadRepoState(); + } catch { + setError(`Failed to ${action}.`); + } finally { + setActionLoading(null); + } + }; + + const handleCommit = async () => { + if (actionLoading) { + return; + } + + const effectiveProjectPath = projectPath ?? (await resolveProjectPath()); + if (!effectiveProjectPath) { + setError('No active project selected.'); + return; + } + if (!projectPath) { + setProjectPath(effectiveProjectPath); + } + + setActionLoading('commit'); + setError(null); + try { + const messageToCommit = commitMessageInputRef.current?.value ?? commitMessage; + const result = await window.electronAPI.git.commitAll(effectiveProjectPath, messageToCommit); + if (!result.success) { + setError(result.error || 'Failed to commit changes.'); + return; + } + + tabs + .filter((tab) => tab.type === 'git-diff') + .forEach((tab) => closeTab(tab.id)); + + setCommitMessage(''); + await loadRepoState(); + } catch { + setError('Failed to commit changes.'); + } finally { + setActionLoading(null); + } + }; + if (loading) { return (
@@ -186,8 +261,56 @@ export const GitSidebar: React.FC = () => {
SOURCE CONTROL
+
+ + + +
+
Open Changes ({statusFiles.length})
+ +
+ setCommitMessage(event.target.value)} + disabled={actionLoading !== null} + /> + +
+ {statusLoading ? (
Loading changes...
) : statusFiles.length === 0 ? ( @@ -233,6 +356,7 @@ export const GitSidebar: React.FC = () => { )} {currentBranch &&
Branch: {currentBranch}
}
+ {error &&
{error}
} {transcriptSection}
diff --git a/tests/engine/GitEngine.test.ts b/tests/engine/GitEngine.test.ts index 3dc103f..360a846 100644 --- a/tests/engine/GitEngine.test.ts +++ b/tests/engine/GitEngine.test.ts @@ -11,6 +11,9 @@ const mockInit = vi.fn(); const mockRaw = vi.fn(); const mockAdd = vi.fn(); const mockCommit = vi.fn(); +const mockFetch = vi.fn(); +const mockPull = vi.fn(); +const mockPush = vi.fn(); const mockGetRemotes = vi.fn(); const mockAddRemote = vi.fn(); const mockRemote = vi.fn(); @@ -40,6 +43,9 @@ vi.mock('simple-git', () => ({ raw: mockRaw, add: mockAdd, commit: mockCommit, + fetch: mockFetch, + pull: mockPull, + push: mockPush, getRemotes: mockGetRemotes, addRemote: mockAddRemote, remote: mockRemote, @@ -451,4 +457,52 @@ describe('GitEngine', () => { expect(result.error).toContain('prune failed'); }); }); + + describe('repo actions', () => { + it('should run fetch with prune and return success', async () => { + mockFetch.mockResolvedValue(undefined); + + const result = await gitEngine.fetch('/tmp/project'); + + expect(mockFetch).toHaveBeenCalledWith(['--prune']); + expect(result).toEqual({ success: true }); + }); + + it('should run pull and return success', async () => { + mockPull.mockResolvedValue(undefined); + + const result = await gitEngine.pull('/tmp/project'); + + expect(mockPull).toHaveBeenCalled(); + expect(result).toEqual({ success: true }); + }); + + it('should run push and return success', async () => { + mockPush.mockResolvedValue(undefined); + + const result = await gitEngine.push('/tmp/project'); + + expect(mockPush).toHaveBeenCalled(); + expect(result).toEqual({ success: true }); + }); + + it('should stage all files and commit with message', async () => { + mockAdd.mockResolvedValue(undefined); + mockCommit.mockResolvedValue(undefined); + + const result = await gitEngine.commitAll('/tmp/project', 'feat: commit changes'); + + expect(mockAdd).toHaveBeenCalledWith(['-A']); + expect(mockCommit).toHaveBeenCalledWith('feat: commit changes'); + expect(result).toEqual({ success: true }); + }); + + it('should reject empty commit messages', async () => { + const result = await gitEngine.commitAll('/tmp/project', ' '); + + expect(mockAdd).not.toHaveBeenCalled(); + expect(mockCommit).not.toHaveBeenCalled(); + expect(result).toEqual({ success: false, error: 'Commit message is required.' }); + }); + }); }); diff --git a/tests/ipc/handlers.test.ts b/tests/ipc/handlers.test.ts index 2019403..6ce5c80 100644 --- a/tests/ipc/handlers.test.ts +++ b/tests/ipc/handlers.test.ts @@ -147,6 +147,10 @@ const mockGitEngine = { getDiff: vi.fn(), getDiffContent: vi.fn(), getHistory: vi.fn(), + fetch: vi.fn(), + pull: vi.fn(), + push: vi.fn(), + commitAll: vi.fn(), initializeRepo: vi.fn(), ensureGitignore: vi.fn(), pruneLfsCache: vi.fn(), @@ -454,6 +458,50 @@ describe('IPC Handlers', () => { expect(result.success).toBe(true); }); }); + + describe('git:fetch', () => { + it('should pass project path to GitEngine.fetch', async () => { + mockGitEngine.fetch.mockResolvedValue({ success: true }); + + const result = await invokeHandler('git:fetch', '/repo'); + + expect(mockGitEngine.fetch).toHaveBeenCalledWith('/repo'); + expect(result).toEqual({ success: true }); + }); + }); + + describe('git:pull', () => { + it('should pass project path to GitEngine.pull', async () => { + mockGitEngine.pull.mockResolvedValue({ success: true }); + + const result = await invokeHandler('git:pull', '/repo'); + + expect(mockGitEngine.pull).toHaveBeenCalledWith('/repo'); + expect(result).toEqual({ success: true }); + }); + }); + + describe('git:push', () => { + it('should pass project path to GitEngine.push', async () => { + mockGitEngine.push.mockResolvedValue({ success: true }); + + const result = await invokeHandler('git:push', '/repo'); + + expect(mockGitEngine.push).toHaveBeenCalledWith('/repo'); + expect(result).toEqual({ success: true }); + }); + }); + + describe('git:commitAll', () => { + it('should pass project path and message to GitEngine.commitAll', async () => { + mockGitEngine.commitAll.mockResolvedValue({ success: true }); + + const result = await invokeHandler('git:commitAll', '/repo', 'feat: commit'); + + expect(mockGitEngine.commitAll).toHaveBeenCalledWith('/repo', 'feat: commit'); + expect(result).toEqual({ success: true }); + }); + }); }); // ============ Project Handlers ============ diff --git a/tests/renderer/components/GitDiffView.test.tsx b/tests/renderer/components/GitDiffView.test.tsx index 9ae7378..05eff38 100644 --- a/tests/renderer/components/GitDiffView.test.tsx +++ b/tests/renderer/components/GitDiffView.test.tsx @@ -7,7 +7,14 @@ import { useAppStore } from '../../../src/renderer/store'; vi.mock('@monaco-editor/react', () => ({ __esModule: true, default: (_props: unknown) => null, - DiffEditor: (props: { original: string; modified: string; language?: string; options?: Record }) => ( + DiffEditor: (props: { + original: string; + modified: string; + language?: string; + options?: Record; + keepCurrentOriginalModel?: boolean; + keepCurrentModifiedModel?: boolean; + }) => (
original:{props.original}
modified:{props.modified}
@@ -15,6 +22,8 @@ vi.mock('@monaco-editor/react', () => ({
renderSideBySide:{String(props.options?.renderSideBySide)}
wordWrap:{String(props.options?.wordWrap)}
hideUnchanged:{String((props.options?.hideUnchangedRegions as { enabled?: boolean } | undefined)?.enabled)}
+
keepOriginal:{String(props.keepCurrentOriginalModel)}
+
keepModified:{String(props.keepCurrentModifiedModel)}
), })); @@ -67,5 +76,7 @@ describe('GitDiffView', () => { expect(screen.getByText('renderSideBySide:false')).toBeInTheDocument(); expect(screen.getByText('wordWrap:on')).toBeInTheDocument(); expect(screen.getByText('hideUnchanged:false')).toBeInTheDocument(); + expect(screen.getByText('keepOriginal:true')).toBeInTheDocument(); + expect(screen.getByText('keepModified:true')).toBeInTheDocument(); }); }); diff --git a/tests/renderer/components/GitSidebar.test.tsx b/tests/renderer/components/GitSidebar.test.tsx index 67c184b..a6e835d 100644 --- a/tests/renderer/components/GitSidebar.test.tsx +++ b/tests/renderer/components/GitSidebar.test.tsx @@ -34,7 +34,12 @@ describe('GitSidebar', () => { getRepoState: vi.fn().mockResolvedValue({ isRepo: false, hasRemote: false }), getStatus: vi.fn().mockResolvedValue({ files: [], counts: { untracked: 0, modified: 0, deleted: 0, renamed: 0, staged: 0, total: 0 } }), getDiff: vi.fn().mockResolvedValue({ filePath: 'posts/a.md', patch: 'diff --git a/posts/a.md b/posts/a.md' }), + getDiffContent: vi.fn().mockResolvedValue({ filePath: 'posts/a.md', original: '', modified: '' }), getHistory: vi.fn().mockResolvedValue([]), + fetch: vi.fn().mockResolvedValue({ success: true }), + pull: vi.fn().mockResolvedValue({ success: true }), + push: vi.fn().mockResolvedValue({ success: true }), + commitAll: vi.fn().mockResolvedValue({ success: true }), init: vi.fn().mockResolvedValue({ success: true }), ensureGitignore: vi.fn().mockResolvedValue({ updated: false, created: false, addedEntries: [] }), onInitProgress: vi.fn().mockImplementation(() => () => {}), @@ -328,4 +333,64 @@ describe('GitSidebar', () => { expect(transcriptToggle).toHaveAttribute('aria-expanded', 'true'); expect(screen.getByText(/100% — failed to configure remote repository/i)).toBeInTheDocument(); }); + + it('wires fetch, pull, and push buttons', async () => { + (window as any).electronAPI.git.getRepoState = vi.fn().mockResolvedValue({ + isRepo: true, + rootPath: '/repo/path', + currentBranch: 'main', + hasRemote: true, + }); + + render(); + + const fetchButton = await screen.findByRole('button', { name: /fetch/i }); + const pullButton = screen.getByRole('button', { name: /pull/i }); + const pushButton = screen.getByRole('button', { name: /push/i }); + + await act(async () => { + fireEvent.click(fetchButton); + fireEvent.click(pullButton); + fireEvent.click(pushButton); + }); + + expect((window as any).electronAPI.git.fetch).toHaveBeenCalledWith('/repo/path'); + expect((window as any).electronAPI.git.pull).toHaveBeenCalledWith('/repo/path'); + expect((window as any).electronAPI.git.push).toHaveBeenCalledWith('/repo/path'); + }); + + it('commits all changes and closes open git-diff tabs', async () => { + (window as any).electronAPI.git.getRepoState = vi.fn().mockResolvedValue({ + isRepo: true, + rootPath: '/repo/path', + currentBranch: 'main', + hasRemote: true, + }); + + useAppStore.setState({ + tabs: [ + { type: 'git-diff', id: 'git-diff:posts/first.md', isTransient: false }, + { type: 'post', id: 'post-1', isTransient: false }, + { type: 'git-diff', id: 'git-diff:posts/second.md', isTransient: true }, + ], + activeTabId: 'git-diff:posts/first.md', + }); + + render(); + + const commitInput = await screen.findByPlaceholderText(/commit message/i); + await act(async () => { + fireEvent.change(commitInput, { target: { value: 'feat: commit from sidebar' } }); + }); + + const commitButton = screen.getByRole('button', { name: /^commit$/i }); + await act(async () => { + fireEvent.click(commitButton); + }); + + expect((window as any).electronAPI.git.commitAll).toHaveBeenCalledWith('/repo/path', 'feat: commit from sidebar'); + expect(getStore().tabs).toEqual([ + { type: 'post', id: 'post-1', isTransient: false }, + ]); + }); });