Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/app/api/git/fetch/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { NextRequest, NextResponse } from 'next/server';
import * as gitService from '@/lib/git/service';

export async function POST(req: NextRequest) {
const body = await req.json();
const cwd = body.cwd;

if (!cwd) {
return NextResponse.json({ error: 'cwd is required' }, { status: 400 });
}

try {
await gitService.fetchRemotes(cwd);
return NextResponse.json({ success: true });
} catch (err) {
return NextResponse.json(
{ error: err instanceof Error ? err.message : 'Failed to fetch remotes' },
{ status: 500 }
);
}
}
19 changes: 19 additions & 0 deletions src/app/api/git/remotes/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { NextRequest, NextResponse } from 'next/server';
import * as gitService from '@/lib/git/service';

export async function GET(req: NextRequest) {
const cwd = req.nextUrl.searchParams.get('cwd');
if (!cwd) {
return NextResponse.json({ error: 'cwd is required' }, { status: 400 });
}

try {
const remotes = await gitService.getRemotes(cwd);
return NextResponse.json({ remotes });
} catch (err) {
return NextResponse.json(
{ error: err instanceof Error ? err.message : 'Failed to get remotes' },
{ status: 500 }
);
}
}
11 changes: 11 additions & 0 deletions src/components/git/GitPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { GitStatusSection } from "./GitStatusSection";
import { GitBranchSelector } from "./GitBranchSelector";
import { GitHistorySection } from "./GitHistorySection";
import { GitWorktreeSection } from "./GitWorktreeSection";
import { GitRemoteSection } from "./GitRemoteSection";
import { GitCommitDetailDialog } from "./GitCommitDetailDialog";
import { DeriveWorktreeDialog } from "./DeriveWorktreeDialog";

Expand All @@ -19,6 +20,7 @@ export function GitPanel() {

// Collapsible sections
const [statusOpen, setStatusOpen] = useState(true);
const [remoteOpen, setRemoteOpen] = useState(false);
const [branchOpen, setBranchOpen] = useState(false);
const [historyOpen, setHistoryOpen] = useState(false);
const [worktreeOpen, setWorktreeOpen] = useState(false);
Expand Down Expand Up @@ -61,6 +63,15 @@ export function GitPanel() {
<GitStatusSection status={status} />
</CollapsibleSection>

{/* Remote section */}
<CollapsibleSection
title={t('git.remoteSection')}
open={remoteOpen}
onToggle={() => setRemoteOpen(!remoteOpen)}
>
<GitRemoteSection cwd={workingDirectory} />
</CollapsibleSection>

{/* Branch section */}
<CollapsibleSection
title={t('git.branchSection')}
Expand Down
168 changes: 168 additions & 0 deletions src/components/git/GitRemoteSection.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
"use client";

import { useState, useEffect, useCallback } from "react";
import { Globe, ArrowClockwise, GitBranch } from "@/components/ui/icon";
import { Button } from "@/components/ui/button";
import { useTranslation } from "@/hooks/useTranslation";
import { showToast } from "@/hooks/useToast";
import type { GitRemote, GitBranch as GitBranchType } from "@/types";

interface GitRemoteSectionProps {
cwd: string;
}

export function GitRemoteSection({ cwd }: GitRemoteSectionProps) {
const { t } = useTranslation();
const [remotes, setRemotes] = useState<GitRemote[]>([]);
const [branches, setBranches] = useState<GitBranchType[]>([]);
const [loading, setLoading] = useState(true);
const [fetching, setFetching] = useState(false);

const loadData = useCallback(async () => {
if (!cwd) return;
setLoading(true);
try {
const [remotesRes, branchesRes] = await Promise.all([
fetch(`/api/git/remotes?cwd=${encodeURIComponent(cwd)}`),
fetch(`/api/git/branches?cwd=${encodeURIComponent(cwd)}`),
]);
const remotesData = await remotesRes.json();
const branchesData = await branchesRes.json();
setRemotes(remotesData.remotes || []);
setBranches(branchesData.branches || []);
} catch {
// ignore
} finally {
setLoading(false);
}
}, [cwd]);

useEffect(() => {
loadData();
}, [loadData]);

// Listen for git-refresh events
useEffect(() => {
const handleRefresh = () => loadData();
window.addEventListener('git-refresh', handleRefresh);
return () => window.removeEventListener('git-refresh', handleRefresh);
}, [loadData]);

const handleFetch = async () => {
if (!cwd || fetching) return;
setFetching(true);
try {
const res = await fetch('/api/git/fetch', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ cwd }),
});
if (!res.ok) {
const data = await res.json().catch(() => ({ error: 'Fetch failed' }));
showToast({ type: 'error', message: data.error || 'Fetch failed' });
return;
}
showToast({ type: 'success', message: t('git.fetchSuccess') });
await loadData();
} catch (err) {
showToast({ type: 'error', message: err instanceof Error ? err.message : 'Fetch failed' });
} finally {
setFetching(false);
}
};

const remoteBranches = branches.filter(b => b.isRemote);

// Sort remote branches: current remote first, then alphabetically
const sortedRemoteBranches = [...remoteBranches].sort((a, b) => {
return a.name.localeCompare(b.name);
});

if (loading) {
return (
<div className="px-3 py-2 text-xs text-muted-foreground">
{t('git.loading')}
</div>
);
}

if (remotes.length === 0) {
return (
<div className="px-3 py-2 text-xs text-muted-foreground">
{t('git.noRemotes')}
</div>
);
}

return (
<div className="space-y-3">
{/* Remotes list */}
<div className="space-y-1">
{remotes.map(remote => (
<div key={remote.name} className="px-3">
<div className="flex items-center gap-1.5 text-sm font-medium">
<Globe size={12} className="text-muted-foreground shrink-0" />
<span>{remote.name}</span>
</div>
<div className="ml-[18px] text-[11px] text-muted-foreground truncate">
{formatUrl(remote.url)}
</div>
</div>
))}
</div>

{/* Remote branches */}
{sortedRemoteBranches.length > 0 && (
<div className="space-y-1">
<div className="px-3 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-1.5">
<GitBranch size={10} />
{t('git.remoteBranches')}
</div>
<div className="max-h-[180px] overflow-y-auto">
{sortedRemoteBranches.map(branch => (
<div
key={branch.name}
className="flex items-center gap-2 px-3 py-0.5 text-[12px] hover:bg-muted/50"
>
<span className="truncate text-foreground/80">{branch.name}</span>
</div>
))}
</div>
</div>
)}

{/* Fetch button */}
<div className="px-3">
<Button
size="sm"
variant="outline"
className="h-7 text-xs gap-1.5 w-full"
onClick={handleFetch}
disabled={fetching}
>
<ArrowClockwise size={14} className={fetching ? 'animate-spin' : ''} />
{fetching ? t('git.fetching') : t('git.fetch')}
</Button>
</div>
</div>
);
}

function formatUrl(url: string): string {
// Strip credentials from URLs for display
// git@github.com:user/repo.git -> github.com/user/repo
// https://user:pass@github.com/user/repo.git -> github.com/user/repo
try {
// SSH format: git@github.com:user/repo.git
const sshMatch = url.match(/^git@([^:]+):(.+?)(\.git)?$/);
if (sshMatch) {
return `${sshMatch[1]}/${sshMatch[2]}`;
}

// HTTPS format
const parsed = new URL(url);
return `${parsed.hostname}${parsed.pathname.replace(/\.git$/, '')}`;
} catch {
return url;
}
}
6 changes: 6 additions & 0 deletions src/i18n/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1027,6 +1027,12 @@ const en = {
'git.branchSection': 'Branches',
'git.historySection': 'History',
'git.worktreeSection': 'Worktrees',
'git.remoteSection': 'Remotes',
'git.remoteBranches': 'Remote Branches',
'git.noRemotes': 'No remotes configured',
'git.fetch': 'Fetch',
'git.fetching': 'Fetching...',
'git.fetchSuccess': 'Fetched successfully',
'git.commitSection': 'Commit',
'git.staged': 'Staged',
'git.unstaged': 'Unstaged',
Expand Down
6 changes: 6 additions & 0 deletions src/i18n/zh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1024,6 +1024,12 @@ const zh: Record<TranslationKey, string> = {
'git.branchSection': '分支',
'git.historySection': '历史',
'git.worktreeSection': '工作树',
'git.remoteSection': '远程仓库',
'git.remoteBranches': '远程分支',
'git.noRemotes': '未配置远程仓库',
'git.fetch': '获取',
'git.fetching': '获取中...',
'git.fetchSuccess': '获取成功',
'git.commitSection': '提交',
'git.staged': '已暂存',
'git.unstaged': '未暂存',
Expand Down
27 changes: 26 additions & 1 deletion src/lib/git/service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { execFile } from 'child_process';
import path from 'path';
import type { GitStatus, GitChangedFile, GitBranch, GitLogEntry, GitCommitDetail, GitWorktree } from '@/types';
import type { GitStatus, GitChangedFile, GitBranch, GitLogEntry, GitCommitDetail, GitWorktree, GitRemote } from '@/types';

function runGit(args: string[], opts: { cwd: string; timeoutMs?: number }): Promise<string> {
if (!path.isAbsolute(opts.cwd)) {
Expand Down Expand Up @@ -383,3 +383,28 @@ export async function deriveWorktree(cwd: string, branch: string, targetPath: st

return targetPath;
}

export async function getRemotes(cwd: string): Promise<GitRemote[]> {
const output = await runGit(['remote', '-v'], { cwd });
const remotes: GitRemote[] = [];
const seen = new Set<string>();

for (const line of output.split('\n')) {
if (!line.trim()) continue;
// Format: "origin git@github.com:user/repo.git (fetch)" or "origin https://github.com/user/repo.git (push)"
const match = line.match(/^(\S+)\s+(\S+)\s+\((fetch|push)\)$/);
if (match && !seen.has(match[1])) {
seen.add(match[1]);
remotes.push({
name: match[1],
url: match[2],
});
}
}

return remotes;
}

export async function fetchRemotes(cwd: string): Promise<void> {
await runGit(['fetch', '--all'], { cwd, timeoutMs: 60000 });
}
5 changes: 5 additions & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1080,3 +1080,8 @@ export interface GitWorktree {
bare: boolean;
dirty: boolean;
}

export interface GitRemote {
name: string;
url: string;
}