feat: phase 3 for git integration

This commit is contained in:
2026-02-16 11:46:47 +01:00
parent 4c437cbea2
commit 9d71aa63fb
18 changed files with 499 additions and 7 deletions

View File

@@ -36,6 +36,11 @@ export interface GitStatusDto {
counts: GitStatusCounts;
}
export interface GitDiffDto {
filePath: string;
patch: string;
}
export type GitInitPhase =
| 'checking-git'
| 'initializing-repo'
@@ -217,6 +222,16 @@ export class GitEngine {
};
}
async getDiff(projectPath: string, filePath: string): Promise<GitDiffDto> {
const git = simpleGit(projectPath);
const patch = await git.diff(['--', filePath]);
return {
filePath,
patch,
};
}
async ensureGitignore(projectPath: string): Promise<GitIgnoreEnsureResult> {
const gitignorePath = path.join(projectPath, '.gitignore');

View File

@@ -79,6 +79,7 @@ export {
type GitAvailability,
type RepoState,
type GitStatusDto,
type GitDiffDto,
type GitStatusFile,
type GitStatusCounts,
type GitInitResult,

View File

@@ -48,6 +48,11 @@ export function registerIpcHandlers(): void {
return engine.getStatus(projectPath);
});
safeHandle('git:diff', async (_, projectPath: string, filePath: string) => {
const engine = getGitEngine();
return engine.getDiff(projectPath, filePath);
});
safeHandle('git:init', async (event, projectPath: string, remoteUrl?: string) => {
const engine = getGitEngine();
return engine.initializeRepo(projectPath, remoteUrl, (progress) => {

View File

@@ -10,6 +10,7 @@ export const electronAPI: ElectronAPI = {
checkAvailability: () => ipcRenderer.invoke('git:checkAvailability'),
getRepoState: (projectPath: string) => ipcRenderer.invoke('git:getRepoState', projectPath),
getStatus: (projectPath: string) => ipcRenderer.invoke('git:status', projectPath),
getDiff: (projectPath: string, filePath: string) => ipcRenderer.invoke('git:diff', projectPath, filePath),
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) => {

View File

@@ -236,6 +236,11 @@ export interface GitStatusDto {
counts: GitStatusCounts;
}
export interface GitDiffDto {
filePath: string;
patch: string;
}
export type GitInitPhase =
| 'checking-git'
| 'initializing-repo'
@@ -348,6 +353,7 @@ export interface ElectronAPI {
checkAvailability: () => Promise<GitAvailability>;
getRepoState: (projectPath: string) => Promise<GitRepoState>;
getStatus: (projectPath: string) => Promise<GitStatusDto>;
getDiff: (projectPath: string, filePath: string) => Promise<GitDiffDto>;
ensureGitignore: (projectPath: string) => Promise<GitIgnoreEnsureResult>;
pruneLfs: (projectPath: string, options?: { dryRun?: boolean; verifyRemote?: boolean }) => Promise<GitLfsPruneResult>;
init: (projectPath: string, remoteUrl?: string) => Promise<GitInitResult>;

View File

@@ -14,6 +14,7 @@ import { TagInput } from '../TagInput';
import { ChatPanel } from '../ChatPanel';
import { ImportAnalysisView } from '../ImportAnalysisView';
import { MetadataDiffPanel } from '../MetadataDiffPanel';
import { GitDiffView } from '../GitDiffView/GitDiffView';
import { AutoSaveManager, getContrastColor } from '../../utils';
import { parseMacros, getMacro } from '../../macros/registry';
import { InsertModal } from '../InsertModal';
@@ -2214,6 +2215,7 @@ export const Editor: React.FC = () => {
const showChat = activeTab?.type === 'chat';
const showImport = activeTab?.type === 'import';
const showMetadataDiff = activeTab?.type === 'metadata-diff';
const showGitDiff = activeTab?.type === 'git-diff';
// Clear selectedPostId if the post doesn't exist (e.g., after project switch)
useEffect(() => {
@@ -2313,6 +2315,18 @@ export const Editor: React.FC = () => {
);
}
// Show git diff view if git-diff tab is active
if (showGitDiff && activeTabId) {
const filePath = activeTabId.startsWith('git-diff:') ? activeTabId.slice('git-diff:'.length) : activeTabId;
return (
<div className="editor">
<GitDiffView key={activeTabId} filePath={filePath} />
{renderErrorModal()}
{renderConfirmDeleteModal()}
</div>
);
}
// Show post editor if a post tab is active
if (showPost && activeTabId) {
return (

View File

@@ -0,0 +1,36 @@
.git-diff-view {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
background: var(--vscode-editor-background);
color: var(--vscode-editor-foreground);
}
.git-diff-header {
padding: 10px 12px;
font-size: 12px;
border-bottom: 1px solid var(--vscode-editorWidget-border);
color: var(--vscode-sideBar-foreground);
}
.git-diff-patch {
margin: 0;
padding: 12px;
overflow: auto;
white-space: pre;
font-family: var(--vscode-editor-font-family);
font-size: 12px;
line-height: 1.5;
}
.git-diff-message,
.git-diff-error {
padding: 12px;
font-size: 12px;
color: var(--vscode-descriptionForeground);
}
.git-diff-error {
color: var(--vscode-errorForeground);
}

View File

@@ -0,0 +1,71 @@
import React, { useEffect, useState } from 'react';
import { useAppStore } from '../../store';
import './GitDiffView.css';
interface GitDiffViewProps {
filePath: string;
}
export const GitDiffView: React.FC<GitDiffViewProps> = ({ filePath }) => {
const { activeProject } = useAppStore();
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [patch, setPatch] = useState('');
useEffect(() => {
const loadDiff = async () => {
setLoading(true);
setError(null);
try {
if (!activeProject) {
setError('No active project selected.');
return;
}
const projectPath = activeProject.dataPath
? activeProject.dataPath
: await window.electronAPI.app.getDefaultProjectPath(activeProject.id);
if (!projectPath) {
setError('Unable to resolve project path.');
return;
}
const diff = await window.electronAPI.git.getDiff(projectPath, filePath);
setPatch(diff.patch || '');
} catch {
setError('Failed to load diff.');
} finally {
setLoading(false);
}
};
void loadDiff();
}, [activeProject, filePath]);
if (loading) {
return (
<div className="git-diff-view">
<div className="git-diff-header">Diff: {filePath}</div>
<div className="git-diff-message">Loading diff...</div>
</div>
);
}
if (error) {
return (
<div className="git-diff-view">
<div className="git-diff-header">Diff: {filePath}</div>
<div className="git-diff-error">{error}</div>
</div>
);
}
return (
<div className="git-diff-view">
<div className="git-diff-header">Diff: {filePath}</div>
{patch ? <pre className="git-diff-patch">{patch}</pre> : <div className="git-diff-message">No diff available.</div>}
</div>
);
};

View File

@@ -22,6 +22,80 @@
font-size: 12px;
}
.git-sidebar-content {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
padding: 8px 0 0;
}
.git-sidebar-section {
display: flex;
flex-direction: column;
min-height: 0;
}
.git-sidebar-history {
margin-top: 12px;
border-top: 1px solid var(--vscode-editorWidget-border);
padding-top: 8px;
}
.git-sidebar-section-header {
padding: 0 12px 8px;
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
color: var(--vscode-sideBar-foreground);
letter-spacing: 0.3px;
}
.git-sidebar-empty-state {
padding: 0 12px 8px;
color: var(--vscode-descriptionForeground);
font-size: 12px;
}
.git-sidebar-file-list {
display: flex;
flex-direction: column;
overflow: auto;
}
.git-sidebar-file-item {
width: 100%;
border: none;
background: transparent;
color: var(--vscode-sideBar-foreground);
text-align: left;
padding: 6px 12px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.git-sidebar-file-item:hover {
background: var(--vscode-list-hoverBackground);
}
.git-sidebar-file-path {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 12px;
}
.git-sidebar-file-status {
text-transform: uppercase;
font-size: 10px;
color: var(--vscode-descriptionForeground);
}
.git-sidebar-main {
min-height: 0;
}

View File

@@ -4,18 +4,33 @@ import type { GitInitProgress } from '../../../main/shared/electronApi';
import './GitSidebar.css';
export const GitSidebar: React.FC = () => {
const { activeProject } = useAppStore();
const { activeProject, openTab } = useAppStore();
const [projectPath, setProjectPath] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [initializing, setInitializing] = useState(false);
const [statusLoading, setStatusLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [isRepo, setIsRepo] = useState(false);
const [currentBranch, setCurrentBranch] = useState<string | null>(null);
const [statusFiles, setStatusFiles] = useState<Array<{ path: string; status: string }>>([]);
const [initProgress, setInitProgress] = useState<GitInitProgress | null>(null);
const [initTranscript, setInitTranscript] = useState<GitInitProgress[]>([]);
const [isTranscriptExpanded, setIsTranscriptExpanded] = useState(false);
const remoteUrlInputRef = useRef<HTMLInputElement | null>(null);
const getDiffTabId = (filePath: string): string => `git-diff:${filePath}`;
const openDiffTab = useCallback(
(filePath: string, isTransient: boolean) => {
openTab({
type: 'git-diff',
id: getDiffTabId(filePath),
isTransient,
});
},
[openTab],
);
const resolveProjectPath = useCallback(async (): Promise<string | null> => {
if (!activeProject) {
return null;
@@ -52,9 +67,22 @@ export const GitSidebar: React.FC = () => {
const repoState = await window.electronAPI.git.getRepoState(resolvedProjectPath);
setIsRepo(repoState.isRepo);
setCurrentBranch(repoState.currentBranch || null);
if (repoState.isRepo) {
setStatusLoading(true);
try {
const status = await window.electronAPI.git.getStatus(resolvedProjectPath);
setStatusFiles(status.files);
} finally {
setStatusLoading(false);
}
} else {
setStatusFiles([]);
}
} catch {
setError('Unable to load repository status.');
setIsRepo(false);
setStatusFiles([]);
} finally {
setLoading(false);
}
@@ -146,10 +174,37 @@ export const GitSidebar: React.FC = () => {
return (
<div className="git-sidebar">
<div className="git-sidebar-header">SOURCE CONTROL</div>
<div className="git-sidebar-empty">
<div className="git-sidebar-main">
<p>Git repository ready</p>
{currentBranch && <p>Branch: {currentBranch}</p>}
<div className="git-sidebar-content">
<div className="git-sidebar-section">
<div className="git-sidebar-section-header">OPEN CHANGES</div>
{statusLoading ? (
<div className="git-sidebar-empty-state">Loading changes...</div>
) : statusFiles.length === 0 ? (
<div className="git-sidebar-empty-state">No changes</div>
) : (
<div className="git-sidebar-file-list" role="list" aria-label="Open Changes">
{statusFiles.map((file) => (
<button
key={file.path}
type="button"
className="git-sidebar-file-item"
onClick={() => openDiffTab(file.path, true)}
onDoubleClick={() => openDiffTab(file.path, false)}
title={`${file.status}: ${file.path}`}
>
<span className="git-sidebar-file-path">{file.path}</span>
<span className="git-sidebar-file-status">{file.status}</span>
</button>
))}
</div>
)}
</div>
<div className="git-sidebar-section git-sidebar-history">
<div className="git-sidebar-section-header">VERSION HISTORY</div>
<div className="git-sidebar-empty-state">
{currentBranch ? `Branch: ${currentBranch}` : 'No branch information'}
</div>
</div>
{transcriptSection}
</div>

View File

@@ -11,6 +11,12 @@ const getTabTitle = (
chatTitles: Map<string, string>,
importDefTitles: Map<string, string>
): string => {
if (tab.type === 'git-diff') {
const filePath = tab.id.startsWith('git-diff:') ? tab.id.slice('git-diff:'.length) : tab.id;
const filename = filePath.split('/').pop();
return filename || filePath;
}
if (tab.type === 'settings') {
return 'Settings';
}
@@ -52,6 +58,12 @@ const getTabTitle = (
const getTabIcon = (tab: Tab): React.ReactNode => {
switch (tab.type) {
case 'git-diff':
return (
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
<path d="M9 3H5a2 2 0 0 0-2 2v4h2V5h4V3zm10 6h2V5a2 2 0 0 0-2-2h-4v2h4v4zM5 15H3v4a2 2 0 0 0 2 2h4v-2H5v-4zm16 0h-2v4h-4v2h4a2 2 0 0 0 2-2v-4zM7 7h10v2H7V7zm0 4h10v2H7v-2zm0 4h10v2H7v-2z"/>
</svg>
);
case 'post':
return (
<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">

View File

@@ -12,7 +12,7 @@ import type {
const STORAGE_KEY = 'bds-app-state';
// Tab types
export type TabType = 'post' | 'media' | 'settings' | 'tags' | 'chat' | 'import' | 'metadata-diff';
export type TabType = 'post' | 'media' | 'settings' | 'tags' | 'chat' | 'import' | 'metadata-diff' | 'git-diff';
export interface Tab {
type: TabType;

View File

@@ -4,6 +4,7 @@ const mockVersion = vi.fn();
const mockCheckIsRepo = vi.fn();
const mockRevparse = vi.fn();
const mockStatus = vi.fn();
const mockDiff = vi.fn();
const mockInit = vi.fn();
const mockRaw = vi.fn();
const mockAdd = vi.fn();
@@ -30,6 +31,7 @@ vi.mock('simple-git', () => ({
checkIsRepo: mockCheckIsRepo,
revparse: mockRevparse,
status: mockStatus,
diff: mockDiff,
init: mockInit,
raw: mockRaw,
add: mockAdd,
@@ -139,6 +141,20 @@ describe('GitEngine', () => {
});
});
describe('getDiff', () => {
it('should return patch output for a repository file', async () => {
mockDiff.mockResolvedValue('diff --git a/posts/first.md b/posts/first.md\n+hello');
const result = await gitEngine.getDiff('/tmp/project', 'posts/first.md');
expect(mockDiff).toHaveBeenCalledWith(['--', 'posts/first.md']);
expect(result).toEqual({
filePath: 'posts/first.md',
patch: 'diff --git a/posts/first.md b/posts/first.md\n+hello',
});
});
});
describe('ensureGitignore', () => {
it('should create .gitignore with default system metadata entries when missing', async () => {
mockReadFile.mockRejectedValue(new Error('ENOENT'));

View File

@@ -144,6 +144,7 @@ const mockGitEngine = {
checkAvailability: vi.fn(),
getRepoState: vi.fn(),
getStatus: vi.fn(),
getDiff: vi.fn(),
initializeRepo: vi.fn(),
ensureGitignore: vi.fn(),
pruneLfsCache: vi.fn(),
@@ -318,6 +319,23 @@ describe('IPC Handlers', () => {
});
});
describe('git:diff', () => {
it('should pass project path and file path to GitEngine.getDiff', async () => {
mockGitEngine.getDiff.mockResolvedValue({
filePath: 'posts/first.md',
patch: 'diff --git a/posts/first.md b/posts/first.md',
});
const result = await invokeHandler('git:diff', '/repo', 'posts/first.md');
expect(mockGitEngine.getDiff).toHaveBeenCalledWith('/repo', 'posts/first.md');
expect(result).toEqual({
filePath: 'posts/first.md',
patch: 'diff --git a/posts/first.md b/posts/first.md',
});
});
});
describe('git:init', () => {
it('should pass project path to GitEngine.initializeRepo', async () => {
mockGitEngine.initializeRepo.mockResolvedValue({ success: true });

View File

@@ -0,0 +1,45 @@
import React from 'react';
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import { GitDiffView } from '../../../src/renderer/components/GitDiffView/GitDiffView';
import { useAppStore } from '../../../src/renderer/store';
describe('GitDiffView', () => {
beforeEach(() => {
vi.clearAllMocks();
useAppStore.setState({
activeProject: {
id: 'project-1',
name: 'Test Project',
slug: 'test-project',
isActive: true,
dataPath: '/repo/path',
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
});
(window as any).electronAPI = {
...(window as any).electronAPI,
git: {
...(window as any).electronAPI?.git,
getDiff: vi.fn().mockResolvedValue({
filePath: 'posts/first.md',
patch: 'diff --git a/posts/first.md b/posts/first.md\n+hello',
}),
},
app: {
...(window as any).electronAPI?.app,
getDefaultProjectPath: vi.fn().mockResolvedValue('/repo/path'),
},
};
});
it('loads and renders the git diff patch for the selected file', async () => {
render(<GitDiffView filePath="posts/first.md" />);
expect(await screen.findByText(/diff --git a\/posts\/first\.md b\/posts\/first\.md/i)).toBeInTheDocument();
expect((window as any).electronAPI.git.getDiff).toHaveBeenCalledWith('/repo/path', 'posts/first.md');
});
});

View File

@@ -4,6 +4,8 @@ import { render, screen, fireEvent, act } from '@testing-library/react';
import { GitSidebar } from '../../../src/renderer/components/GitSidebar/GitSidebar';
import { useAppStore } from '../../../src/renderer/store';
const getStore = () => useAppStore.getState();
describe('GitSidebar', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -17,6 +19,8 @@ describe('GitSidebar', () => {
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
tabs: [],
activeTabId: null,
});
(window as any).electronAPI = {
@@ -28,6 +32,8 @@ describe('GitSidebar', () => {
git: {
checkAvailability: vi.fn().mockResolvedValue({ gitFound: true, version: '2.49.0' }),
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' }),
init: vi.fn().mockResolvedValue({ success: true }),
ensureGitignore: vi.fn().mockResolvedValue({ updated: false, created: false, addedEntries: [] }),
onInitProgress: vi.fn().mockImplementation(() => () => {}),
@@ -49,6 +55,88 @@ describe('GitSidebar', () => {
expect(await screen.findByRole('button', { name: /initialize git/i })).toBeInTheDocument();
});
it('renders open changes list when repository exists', async () => {
(window as any).electronAPI.git.getRepoState = vi.fn().mockResolvedValue({
isRepo: true,
rootPath: '/repo/path',
currentBranch: 'main',
hasRemote: true,
});
(window as any).electronAPI.git.getStatus = vi.fn().mockResolvedValue({
files: [
{ path: 'posts/first.md', status: 'modified' },
{ path: 'posts/second.md', status: 'untracked' },
],
counts: { untracked: 1, modified: 1, deleted: 0, renamed: 0, staged: 0, total: 2 },
});
render(<GitSidebar />);
expect(await screen.findByText(/open changes/i)).toBeInTheDocument();
expect(screen.getByText('posts/first.md')).toBeInTheDocument();
expect(screen.getByText('posts/second.md')).toBeInTheDocument();
expect(screen.getByText(/version history/i)).toBeInTheDocument();
});
it('single click opens and reuses a transient git-diff tab', async () => {
(window as any).electronAPI.git.getRepoState = vi.fn().mockResolvedValue({
isRepo: true,
rootPath: '/repo/path',
currentBranch: 'main',
hasRemote: true,
});
(window as any).electronAPI.git.getStatus = vi.fn().mockResolvedValue({
files: [
{ path: 'posts/first.md', status: 'modified' },
{ path: 'posts/second.md', status: 'untracked' },
],
counts: { untracked: 1, modified: 1, deleted: 0, renamed: 0, staged: 0, total: 2 },
});
render(<GitSidebar />);
const first = await screen.findByRole('button', { name: /posts\/first\.md/i });
const second = screen.getByRole('button', { name: /posts\/second\.md/i });
await act(async () => {
fireEvent.click(first);
});
expect(getStore().tabs).toHaveLength(1);
expect(getStore().tabs[0]).toMatchObject({ type: 'git-diff', id: 'git-diff:posts/first.md', isTransient: true });
await act(async () => {
fireEvent.click(second);
});
expect(getStore().tabs).toHaveLength(1);
expect(getStore().tabs[0]).toMatchObject({ type: 'git-diff', id: 'git-diff:posts/second.md', isTransient: true });
});
it('double click opens a persistent git-diff tab', async () => {
(window as any).electronAPI.git.getRepoState = vi.fn().mockResolvedValue({
isRepo: true,
rootPath: '/repo/path',
currentBranch: 'main',
hasRemote: true,
});
(window as any).electronAPI.git.getStatus = vi.fn().mockResolvedValue({
files: [{ path: 'posts/first.md', status: 'modified' }],
counts: { untracked: 0, modified: 1, deleted: 0, renamed: 0, staged: 0, total: 1 },
});
render(<GitSidebar />);
const first = await screen.findByRole('button', { name: /posts\/first\.md/i });
await act(async () => {
fireEvent.doubleClick(first);
});
expect(getStore().tabs).toHaveLength(1);
expect(getStore().tabs[0]).toMatchObject({ type: 'git-diff', id: 'git-diff:posts/first.md', isTransient: false });
});
it('initializes repository and refreshes repo state after clicking Initialize Git', async () => {
const getRepoStateMock = vi
.fn()
@@ -70,7 +158,7 @@ describe('GitSidebar', () => {
});
await vi.waitFor(() => {
expect(screen.getByText(/git repository ready/i)).toBeInTheDocument();
expect(screen.getByText(/open changes/i)).toBeInTheDocument();
});
});

View File

@@ -147,6 +147,40 @@ describe('Tab Management', () => {
expect(getStore().tabs).toHaveLength(2);
expect(getStore().activeTabId).toBe('post-1');
});
it('should open git diff in a transient tab on single click', () => {
getStore().openTab({ type: 'git-diff', id: 'git-diff:posts/first.md', isTransient: true });
expect(getStore().tabs).toHaveLength(1);
expect(getStore().tabs[0]).toMatchObject({
type: 'git-diff',
id: 'git-diff:posts/first.md',
isTransient: true,
});
});
it('should reuse transient git diff tab on subsequent single click', () => {
getStore().openTab({ type: 'git-diff', id: 'git-diff:posts/first.md', isTransient: true });
getStore().openTab({ type: 'git-diff', id: 'git-diff:posts/second.md', isTransient: true });
expect(getStore().tabs).toHaveLength(1);
expect(getStore().tabs[0]).toMatchObject({
type: 'git-diff',
id: 'git-diff:posts/second.md',
isTransient: true,
});
});
it('should open git diff in a persistent tab on double click', () => {
getStore().openTab({ type: 'git-diff', id: 'git-diff:posts/first.md', isTransient: false });
expect(getStore().tabs).toHaveLength(1);
expect(getStore().tabs[0]).toMatchObject({
type: 'git-diff',
id: 'git-diff:posts/first.md',
isTransient: false,
});
});
});
describe('Closing Tabs', () => {

View File

@@ -48,6 +48,7 @@ Object.defineProperty(globalThis, 'window', {
checkAvailability: vi.fn(),
getRepoState: vi.fn(),
getStatus: vi.fn(),
getDiff: vi.fn(),
init: vi.fn(),
},
posts: {