From 874bca5d614d6d3c3ca7ddbb7f32ee03a49dfbf7 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sat, 13 Sep 2025 12:11:30 -0500 Subject: [PATCH] Simplify credentials in GitDialog, use configured credentials --- README.md | 25 +++++ src/components/GitDialog.test.tsx | 29 +++++- src/components/GitDialog.tsx | 149 ++++++++++++++++++------------ src/lib/gitCredentials.test.ts | 92 ++++++++++++++++++ src/lib/gitCredentials.ts | 74 +++++++++++++++ 5 files changed, 310 insertions(+), 59 deletions(-) create mode 100644 src/lib/gitCredentials.test.ts create mode 100644 src/lib/gitCredentials.ts diff --git a/README.md b/README.md index 33ebde34..1ffead42 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,31 @@ The AI assistant can: 3. **File Explorer**: Navigate your project files in the code view 4. **File Editor**: Edit files with syntax highlighting and save changes +## Git Integration + +Shakespeare includes full Git functionality with credential management: + +### Features +- **Version Control**: Full Git repository support with commit history and branch management +- **Global Credentials**: Configure Git credentials once and use them across all projects +- **Automatic Matching**: Credentials are automatically matched to repository origins +- **Popular Providers**: Built-in support for GitHub, GitLab, and custom Git providers +- **Secure Storage**: Credentials are stored locally in your browser using IndexedDB + +### Setting Up Git Credentials + +1. **Access Git Settings**: Click the gear icon in any Git dialog or use the Git Settings option +2. **Add Provider**: Choose from GitHub, GitLab, or add a custom Git provider +3. **Enter Token**: Use your username and personal access token for authentication +4. **Automatic Usage**: Credentials are automatically used for push/pull operations in matching repositories + +### Repository Operations + +- **Push/Pull**: Sync changes with remote repositories using configured credentials +- **Status Monitoring**: Real-time Git status with file changes and sync information +- **Commit History**: View commit history and repository information +- **Branch Management**: Work with different branches and track remote changes + ## Development Built with: diff --git a/src/components/GitDialog.test.tsx b/src/components/GitDialog.test.tsx index b9e57c78..faf4e17b 100644 --- a/src/components/GitDialog.test.tsx +++ b/src/components/GitDialog.test.tsx @@ -43,6 +43,19 @@ vi.mock('@/hooks/useToast', () => ({ })), })); +vi.mock('@/hooks/useGitSettings', () => ({ + useGitSettings: vi.fn(() => ({ + settings: { + credentials: { + 'https://github.com': { + username: 'git', + password: 'github-token', + }, + }, + }, + })), +})); + describe('GitDialog', () => { beforeEach(() => { mockUseGitStatus.mockReturnValue({ @@ -64,7 +77,7 @@ describe('GitDialog', () => { expect(screen.getByText('Repository Information')).toBeInTheDocument(); expect(screen.getByText('main')).toBeInTheDocument(); expect(screen.getByText('5')).toBeInTheDocument(); - expect(screen.getByText('origin')).toBeInTheDocument(); + expect(screen.getAllByText('origin')).toHaveLength(2); // Appears in remotes and credentials sections }); it('shows sync status', () => { @@ -131,4 +144,18 @@ describe('GitDialog', () => { expect(pushButton).toBeInTheDocument(); expect(pushButton.closest('button')).toBeDisabled(); }); + + it('shows configured credentials status', () => { + render( + + {}}> + + + + ); + + expect(screen.getByText('Authentication')).toBeInTheDocument(); + expect(screen.getByText('github.com')).toBeInTheDocument(); + expect(screen.getByText('Configured')).toBeInTheDocument(); + }); }); \ No newline at end of file diff --git a/src/components/GitDialog.tsx b/src/components/GitDialog.tsx index 571d0baa..73512c3e 100644 --- a/src/components/GitDialog.tsx +++ b/src/components/GitDialog.tsx @@ -17,8 +17,7 @@ import { } from '@/components/ui/card'; import { Badge } from '@/components/ui/badge'; import { ScrollArea } from '@/components/ui/scroll-area'; -import { Input } from '@/components/ui/input'; -import { Label } from '@/components/ui/label'; +import { Alert, AlertDescription } from '@/components/ui/alert'; import { GitBranch, Upload, @@ -32,13 +31,16 @@ import { Minus, Edit, RefreshCw, - Eye, - EyeOff, + Settings, + AlertTriangle, } from 'lucide-react'; import { useGitStatus } from '@/hooks/useGitStatus'; +import { useGitSettings } from '@/hooks/useGitSettings'; import { useFS } from '@/hooks/useFS'; import { useToast } from '@/hooks/useToast'; import { cn } from '@/lib/utils'; +import { findCredentialsForRepo, getOriginDisplayName } from '@/lib/gitCredentials'; +import { GitSettingsDialog } from './GitSettingsDialog'; import git from 'isomorphic-git'; import http from 'isomorphic-git/http/web'; @@ -54,16 +56,24 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog const [isPulling, setIsPulling] = useState(false); const [pushResult, setPushResult] = useState(null); const [pullResult, setPullResult] = useState(null); - const [username, setUsername] = useState(''); - const [password, setPassword] = useState(''); - const [showPassword, setShowPassword] = useState(false); + const [showGitSettings, setShowGitSettings] = useState(false); const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId); + const { settings } = useGitSettings(); const { fs } = useFS(); const { toast } = useToast(); const projectPath = `/projects/${projectId}`; + // Get credentials for the current repository + const getCredentialsForCurrentRepo = () => { + if (!gitStatus?.remotes.length) return null; + const remoteUrl = gitStatus.remotes[0].url; // Use first remote (usually 'origin') + return findCredentialsForRepo(remoteUrl, settings.credentials); + }; + + const currentCredentials = getCredentialsForCurrentRepo(); + const handlePush = async () => { if (!gitStatus?.isGitRepo || !gitStatus.currentBranch) { toast({ @@ -98,9 +108,12 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog try { const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin') - // Prepare authentication if username and password are provided - const authOptions = username && password ? { - onAuth: () => ({ username, password }), + // Prepare authentication if credentials are available + const authOptions = currentCredentials ? { + onAuth: () => ({ + username: currentCredentials.username, + password: currentCredentials.password + }), } : {}; await git.push({ @@ -159,9 +172,12 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog try { const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin') - // Prepare authentication if username and password are provided - const authOptions = username && password ? { - onAuth: () => ({ username, password }), + // Prepare authentication if credentials are available + const authOptions = currentCredentials ? { + onAuth: () => ({ + username: currentCredentials.username, + password: currentCredentials.password + }), } : {}; await git.pull({ @@ -357,60 +373,71 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog - {/* Authentication */} + {/* Credentials Status */} {gitStatus?.isGitRepo && gitStatus.remotes.length > 0 && ( - Authentication + + Authentication + + - Enter credentials for push/pull operations (optional) + Credentials for push/pull operations - -
-
- - setUsername(e.target.value)} - disabled={isPushing || isPulling} - /> -
-
- -
- setPassword(e.target.value)} - disabled={isPushing || isPulling} - className="pr-10" - /> - +
+ + {!credentials && ( + + + + No credentials configured for {originDisplayName}. + Push/pull operations may fail for private repositories.{' '} + + + + )}
-
- -
- Leave empty for public repositories or if using SSH keys. For private repositories, use your username and personal access token. -
+ ); + })}
)} @@ -529,6 +556,12 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog )} + + {/* Git Settings Dialog */} + ); diff --git a/src/lib/gitCredentials.test.ts b/src/lib/gitCredentials.test.ts new file mode 100644 index 00000000..fe2838dd --- /dev/null +++ b/src/lib/gitCredentials.test.ts @@ -0,0 +1,92 @@ +import { describe, it, expect } from 'vitest'; +import { extractGitOrigin, findCredentialsForRepo, getOriginDisplayName } from './gitCredentials'; +import type { GitCredential } from '@/contexts/GitSettingsContext'; + +describe('gitCredentials', () => { + describe('extractGitOrigin', () => { + it('should extract origin from HTTPS URLs', () => { + expect(extractGitOrigin('https://github.com/user/repo.git')).toBe('https://github.com'); + expect(extractGitOrigin('https://gitlab.com/user/repo.git')).toBe('https://gitlab.com'); + expect(extractGitOrigin('https://git.example.com:8080/user/repo.git')).toBe('https://git.example.com:8080'); + }); + + it('should extract origin from HTTP URLs', () => { + expect(extractGitOrigin('http://git.example.com/user/repo.git')).toBe('http://git.example.com'); + }); + + it('should extract origin from SSH URLs', () => { + expect(extractGitOrigin('git@github.com:user/repo.git')).toBe('https://github.com'); + expect(extractGitOrigin('git@gitlab.com:user/repo.git')).toBe('https://gitlab.com'); + expect(extractGitOrigin('git@git.example.com:user/repo.git')).toBe('https://git.example.com'); + }); + + it('should return null for invalid URLs', () => { + expect(extractGitOrigin('')).toBe(null); + expect(extractGitOrigin('invalid-url')).toBe(null); + expect(extractGitOrigin('ftp://example.com/repo')).toBe(null); + }); + }); + + describe('findCredentialsForRepo', () => { + const mockCredentials: Record = { + 'https://github.com': { username: 'git', password: 'github-token' }, + 'https://gitlab.com': { username: 'git', password: 'gitlab-token' }, + 'https://git.example.com': { username: 'user', password: 'custom-token' }, + }; + + it('should find exact matches', () => { + expect(findCredentialsForRepo('https://github.com/user/repo.git', mockCredentials)) + .toEqual({ username: 'git', password: 'github-token' }); + + expect(findCredentialsForRepo('https://gitlab.com/user/repo.git', mockCredentials)) + .toEqual({ username: 'git', password: 'gitlab-token' }); + }); + + it('should find matches for SSH URLs', () => { + expect(findCredentialsForRepo('git@github.com:user/repo.git', mockCredentials)) + .toEqual({ username: 'git', password: 'github-token' }); + }); + + it('should handle case-insensitive matching', () => { + expect(findCredentialsForRepo('https://GitHub.com/user/repo.git', mockCredentials)) + .toEqual({ username: 'git', password: 'github-token' }); + }); + + it('should handle www variations', () => { + const credentialsWithWww = { + 'https://www.github.com': { username: 'git', password: 'github-token' }, + }; + + expect(findCredentialsForRepo('https://github.com/user/repo.git', credentialsWithWww)) + .toEqual({ username: 'git', password: 'github-token' }); + + expect(findCredentialsForRepo('https://www.github.com/user/repo.git', mockCredentials)) + .toEqual({ username: 'git', password: 'github-token' }); + }); + + it('should return null when no credentials found', () => { + expect(findCredentialsForRepo('https://unknown.com/user/repo.git', mockCredentials)) + .toBe(null); + + expect(findCredentialsForRepo('invalid-url', mockCredentials)) + .toBe(null); + }); + + it('should return null for empty credentials', () => { + expect(findCredentialsForRepo('https://github.com/user/repo.git', {})) + .toBe(null); + }); + }); + + describe('getOriginDisplayName', () => { + it('should extract hostname from valid URLs', () => { + expect(getOriginDisplayName('https://github.com')).toBe('github.com'); + expect(getOriginDisplayName('https://git.example.com:8080')).toBe('git.example.com:8080'); + }); + + it('should return original string for invalid URLs', () => { + expect(getOriginDisplayName('invalid-url')).toBe('invalid-url'); + expect(getOriginDisplayName('')).toBe(''); + }); + }); +}); \ No newline at end of file diff --git a/src/lib/gitCredentials.ts b/src/lib/gitCredentials.ts new file mode 100644 index 00000000..ed90ed80 --- /dev/null +++ b/src/lib/gitCredentials.ts @@ -0,0 +1,74 @@ +import type { GitCredential } from '@/contexts/GitSettingsContext'; + +/** + * Extract the origin (protocol + hostname + port) from a Git URL + */ +export function extractGitOrigin(gitUrl: string): string | null { + try { + // Handle SSH URLs like git@github.com:user/repo.git + if (gitUrl.startsWith('git@')) { + const match = gitUrl.match(/^git@([^:]+):/); + if (match) { + return `https://${match[1]}`; + } + } + + // Handle HTTP/HTTPS URLs + if (gitUrl.startsWith('http://') || gitUrl.startsWith('https://')) { + const url = new URL(gitUrl); + return `${url.protocol}//${url.host}`; + } + + return null; + } catch { + return null; + } +} + +/** + * Find matching credentials for a repository URL + */ +export function findCredentialsForRepo( + repoUrl: string, + credentials: Record +): GitCredential | null { + const repoOrigin = extractGitOrigin(repoUrl); + if (!repoOrigin) return null; + + // Direct match + if (credentials[repoOrigin]) { + return credentials[repoOrigin]; + } + + // Try to find a match by normalizing common variations + const normalizedRepoOrigin = repoOrigin.toLowerCase(); + + for (const [origin, credential] of Object.entries(credentials)) { + const normalizedOrigin = origin.toLowerCase(); + + // Exact match (case-insensitive) + if (normalizedOrigin === normalizedRepoOrigin) { + return credential; + } + + // Handle www variations + if (normalizedOrigin.replace(/^https?:\/\/www\./, 'https://') === + normalizedRepoOrigin.replace(/^https?:\/\/www\./, 'https://')) { + return credential; + } + } + + return null; +} + +/** + * Get the display name for a Git origin URL + */ +export function getOriginDisplayName(origin: string): string { + try { + const url = new URL(origin); + return url.host; // Use host instead of hostname to include port + } catch { + return origin; + } +} \ No newline at end of file