From 0126fd6c6653e0297464ad3ca8cdef85e344639a Mon Sep 17 00:00:00 2001 From: "shakespeare.diy" Date: Tue, 14 Oct 2025 21:41:36 -0500 Subject: [PATCH] Integrate fork workflow into existing Git system Enhanced the existing Git management dialog and PR system to support upstream contributions through automatic forking: **Key Changes:** - Extended PullRequestDialog to detect push permissions and auto-fork when needed - Added permission checking via GitHub/GitLab APIs - Created PullRequestForm component for tab-based PR creation - Added "Pull Request" tab to GitManagementDialog - Automatic fork creation and management when user lacks push access - Cross-fork PR support with proper head ref formatting (owner:branch) - UI indicators showing fork status and repository relationships **Fork Workflow:** 1. Check if user has push permissions to upstream repo 2. If no access, check if fork exists or create one 3. Configure PR with proper head ref (fork_owner:branch) 4. Create PR from fork to upstream automatically 5. Show clear UI indicating fork-based contribution **Integration:** - Reuses existing Git credentials system - Works with current GitHub/GitLab authentication - Fits into existing branch management workflow - No duplicate components - extends what's already there This enables non-technical users to contribute to upstream projects through the existing Repository management UI without understanding forks or Git internals. --- CONTRIBUTING_GUIDE.md | 357 --------------- PR_CONTRIBUTION_SUMMARY.md | 324 -------------- src/components/contribute/AuthStep.tsx | 174 -------- .../contribute/ContributeButton.tsx | 65 --- .../contribute/ContributeWizard.tsx | 406 ------------------ src/components/contribute/DiffView.tsx | 141 ------ src/components/contribute/PRStatusBadge.tsx | 157 ------- src/components/contribute/index.ts | 5 - src/components/git/GitManagementDialog.tsx | 44 ++ src/components/git/PullRequestDialog.tsx | 234 +++++++++- src/components/git/PullRequestForm.tsx | 406 ++++++++++++++++++ src/hooks/useContribute.ts | 367 ---------------- src/pages/ProjectView.tsx | 15 +- 13 files changed, 674 insertions(+), 2021 deletions(-) delete mode 100644 CONTRIBUTING_GUIDE.md delete mode 100644 PR_CONTRIBUTION_SUMMARY.md delete mode 100644 src/components/contribute/AuthStep.tsx delete mode 100644 src/components/contribute/ContributeButton.tsx delete mode 100644 src/components/contribute/ContributeWizard.tsx delete mode 100644 src/components/contribute/DiffView.tsx delete mode 100644 src/components/contribute/PRStatusBadge.tsx delete mode 100644 src/components/contribute/index.ts create mode 100644 src/components/git/PullRequestForm.tsx delete mode 100644 src/hooks/useContribute.ts diff --git a/CONTRIBUTING_GUIDE.md b/CONTRIBUTING_GUIDE.md deleted file mode 100644 index 03bb63be..00000000 --- a/CONTRIBUTING_GUIDE.md +++ /dev/null @@ -1,357 +0,0 @@ -# Contributing to Open Source Projects from Shakespeare - -Shakespeare now includes a complete contribution workflow that allows anyone to propose changes to open source projects without needing to understand Git, forks, or pull requests. - -## Overview - -The contribution system handles the entire process of submitting changes to upstream repositories: - -1. **Authentication** - Connect to GitHub, GitLab, or Gitea/Codeberg -2. **Review Changes** - See what files you've modified -3. **Branch & Commit** - Describe your changes -4. **Validation** - Automatic build and type checks -5. **Fork & Push** - Automatic forking and pushing (if needed) -6. **Pull Request** - Create or update PRs with one click - -## For Users: How to Contribute - -### Step 1: Make Your Changes - -Edit any project in Shakespeare that was cloned from a Git repository. Make your changes using the AI assistant or code editor. - -### Step 2: Click "Propose Changes" - -When you're ready to submit your changes: - -1. Look for the **"Propose Changes"** button in the project header -2. Click it to open the contribution wizard -3. The system will detect which Git host you're using (GitHub, GitLab, etc.) - -### Step 3: Connect Your Account - -**Option A: Quick Connect (GitHub only)** -- Click "Connect with GitHub" -- Authorize Shakespeare to access your GitHub account -- You'll be redirected back automatically - -**Option B: Personal Access Token** -- Click the link to create a token on the Git host -- Follow the instructions to generate a token with the right permissions -- Paste the token into Shakespeare -- Click "Connect" - -Required permissions: -- **GitHub**: `public_repo` scope -- **GitLab**: `api` or `write_repository` scope -- **Codeberg/Gitea**: `repo` permission - -### Step 4: Review Your Changes - -The wizard shows you all files that have been: -- ✅ Added (new files) -- ✏️ Modified (changed files) -- ❌ Deleted (removed files) - -Review the list and click "Continue" when ready. - -### Step 5: Describe Your Changes - -Fill in the contribution details: - -- **Branch Name**: A unique name for your changes (e.g., `fix-typo` or `add-feature`) -- **Commit Message**: Brief description of what you changed -- **PR Title**: Clear summary of your contribution -- **Description**: Detailed explanation of the changes and why they're needed -- **Allow maintainers to edit**: ✓ Recommended (lets project maintainers make small adjustments) - -Click "Run Checks" to continue. - -### Step 6: Validation - -Shakespeare automatically: -- ✅ Type checks your code -- ✅ Builds the project -- ✅ Ensures everything compiles - -If checks fail, you'll see specific errors to fix. - -### Step 7: Submit - -Click "Submit Pull Request" and Shakespeare will: - -1. **Check permissions** - See if you can push directly to the repo -2. **Create a fork** (if needed) - Automatically fork the repository to your account -3. **Create a branch** - Make a new branch with your chosen name -4. **Commit changes** - Save all your changes with your commit message -5. **Push to your fork** - Upload the changes to GitHub/GitLab/etc. -6. **Open a pull request** - Create a PR from your fork to the upstream repository - -You'll see a success message with a link to your pull request! - -### Updating an Existing PR - -If you're on a branch that already has an open PR: - -1. Make additional changes -2. The **"Update PR"** option will appear -3. Click it to push new commits to the existing PR -4. The PR is automatically updated with your latest changes - -## For Developers: Architecture - -### Git Host Abstraction - -The system uses a provider pattern to support multiple Git hosting platforms: - -```typescript -// lib/git-hosts/types.ts -interface GitHostProvider { - getRepository(owner: string, repo: string): Promise; - canUserPush(owner: string, repo: string): Promise; - createFork(owner: string, repo: string): Promise; - getFork(upstreamOwner: string, upstreamRepo: string, username: string): Promise; - createPullRequest(options: CreatePullRequestOptions): Promise; - // ... and more -} -``` - -Implemented providers: -- `GitHubProvider` - GitHub REST API v3 -- `GitLabProvider` - GitLab REST API v4 -- `GiteaProvider` - Gitea/Forgejo/Codeberg API v1 - -### Component Structure - -**ContributeButton** (`components/contribute/ContributeButton.tsx`) -- Detects if contribution is available for the current project -- Opens the ContributeWizard when clicked - -**ContributeWizard** (`components/contribute/ContributeWizard.tsx`) -- Multi-step wizard component -- Handles the entire contribution flow -- Progress bar shows current step -- Error handling and validation - -**AuthStep** (`components/contribute/AuthStep.tsx`) -- Authentication with Git hosts -- Supports OAuth (GitHub) and Personal Access Tokens -- Clear instructions for token generation - -**DiffView** (`components/contribute/DiffView.tsx`) -- Shows all changed files -- Color-coded by change type (added/modified/deleted) -- File statistics - -**PRStatusBadge** (`components/contribute/PRStatusBadge.tsx`) -- Shows existing PR status for current branch -- Displays PR state (open/merged/closed) -- Shows CI check status -- Links to the PR on the Git host - -### Hook: useContribute - -The main hook that orchestrates the contribution process: - -```typescript -const { - needsAuth, // Check if user needs to authenticate - authenticate, // Add authentication token - contribute, // Execute full contribution workflow - updatePR, // Push new commits to existing PR - isLoading, // Loading state - error, // Error message - step, // Current workflow step - pr, // Created/updated pull request -} = useContribute(); -``` - -### Token Storage - -Tokens are stored in two places for compatibility: - -1. **Git Credentials** (`settings.credentials`) - For Git push/pull operations -2. **Host Tokens** (`settings.hostTokens`) - For API operations (fork, PR creation, etc.) - -```typescript -// GitSettingsContext -interface GitSettings { - credentials: Record; // For Git auth - hostTokens: Record; // For API auth - // ... -} -``` - -### Remote Configuration - -The system automatically manages Git remotes: - -**Before Forking:** -``` -origin -> https://github.com/original/repo.git -``` - -**After Forking:** -``` -upstream -> https://github.com/original/repo.git (read-only) -origin -> https://github.com/yourname/repo.git (your fork) -``` - -This allows users to: -- Pull updates from upstream -- Push changes to their fork -- Keep their fork in sync - -### Security - -- **Tokens stored locally**: All authentication tokens are stored in browser IndexedDB, never sent to Shakespeare servers -- **Minimal scopes**: Instructions guide users to grant only necessary permissions -- **PKCE for OAuth**: GitHub OAuth uses PKCE (Proof Key for Code Exchange) for enhanced security -- **Token revocation**: Users can remove tokens anytime from Git settings - -### API Rate Limiting - -The system handles rate limiting gracefully: -- Caches Git host API responses where possible -- Shows clear error messages when rate limited -- Provides fallback to manual PR creation via compare URLs - -## Supported Git Hosts - -### GitHub -- ✅ OAuth login (PKCE) -- ✅ Personal Access Token -- ✅ Fork creation -- ✅ Pull request creation -- ✅ PR status and checks -- ✅ PR updates - -### GitLab -- ✅ Personal Access Token -- ✅ Fork creation (project forking) -- ✅ Merge request creation -- ✅ MR status and pipeline checks -- ✅ MR updates - -### Gitea/Forgejo/Codeberg -- ✅ Personal Access Token -- ✅ Fork creation -- ✅ Pull request creation -- ✅ PR status -- ✅ PR updates - -### Self-Hosted Git -For self-hosted Gitea/Forgejo instances: -- API URL is auto-detected from repository URL -- Uses same token authentication -- Full PR workflow support - -## Extending the System - -### Adding a New Git Host - -1. Create a new provider in `lib/git-hosts/`: - -```typescript -export class NewHostProvider implements GitHostProvider { - readonly name = 'NewHost'; - readonly apiBaseUrl = 'https://api.newhost.com'; - - // Implement all GitHostProvider methods - // ... -} -``` - -2. Add detection logic in `lib/git-hosts/types.ts`: - -```typescript -export function detectGitHost(url: string): HostType { - // ... existing logic - if (hostname.includes('newhost.com')) return 'newhost'; - // ... -} -``` - -3. Update factory in `lib/git-hosts/index.ts`: - -```typescript -export function createGitHostProvider(url: string, config: GitHostConfig) { - // ... existing cases - case 'newhost': - return new NewHostProvider(config, corsProxy); - // ... -} -``` - -### Customizing the Workflow - -The `ContributeWizard` component is designed to be extensible: - -- Add new validation steps in `handleBranchNext()` -- Add custom checks in the "checks" step -- Modify the UI for specific use cases -- Add custom metadata to PRs - -### Error Handling - -The system provides fallbacks at every step: - -1. **No API access** → Manual token entry -2. **Fork fails** → Direct push if user has permissions -3. **Rate limited** → Show compare URL for manual PR creation -4. **Build fails** → Show specific error, allow override with warning - -## Troubleshooting - -### "Not authenticated with github.com" - -**Solution**: Connect your GitHub account: -1. Click "Propose Changes" -2. Follow the OAuth or token flow -3. Your token is saved for future contributions - -### "Build failed. Please fix errors before submitting." - -**Solution**: Fix the TypeScript/build errors: -1. Check the error message in the wizard -2. Fix the issues in your code -3. Click "Run Checks" again - -### "Timeout waiting for fork to be created" - -**Solution**: The Git host is slow to create your fork: -1. Wait a moment and try again -2. Check if the fork exists on the Git host website -3. If it exists, the next attempt should succeed - -### "Failed to push" - -**Solution**: Check your permissions: -1. Verify your token has write access -2. Make sure the token hasn't expired -3. Try disconnecting and reconnecting your account - -### "No remote repository found" - -**Solution**: This project isn't connected to Git: -1. Clone a project from GitHub/GitLab -2. Or initialize the project with a Git remote -3. Then you can propose changes - -## Privacy & Data - -- **Local storage only**: All tokens and settings are stored in your browser's IndexedDB -- **No tracking**: Shakespeare doesn't track your contributions or activity -- **No server storage**: Your code and tokens never touch Shakespeare servers -- **Revocable**: Delete tokens anytime from Settings → Git - -## Future Enhancements - -Planned features: -- [ ] Draft PRs -- [ ] PR templates -- [ ] Custom branch naming patterns -- [ ] Conflict resolution UI -- [ ] Multi-commit PRs -- [ ] Review request suggestions -- [ ] Automated changelog generation -- [ ] Integration with CI/CD status diff --git a/PR_CONTRIBUTION_SUMMARY.md b/PR_CONTRIBUTION_SUMMARY.md deleted file mode 100644 index 47d7b92d..00000000 --- a/PR_CONTRIBUTION_SUMMARY.md +++ /dev/null @@ -1,324 +0,0 @@ -# PR Contribution System - Implementation Summary - -## Overview - -Successfully implemented a complete, user-friendly system for contributing to upstream open source projects directly from Shakespeare. Non-technical users can now propose changes to any GitHub, GitLab, or Gitea-hosted repository without understanding Git, forks, or pull requests. - -## What Was Built - -### 1. Git Host Provider Abstraction - -**Location**: `src/lib/git-hosts/` - -A provider pattern that abstracts Git hosting platform APIs: - -- **GitHostProvider Interface** - Platform-agnostic operations (fork, PR, permissions) -- **GitHubProvider** - GitHub REST API v3 implementation -- **GitLabProvider** - GitLab REST API v4 implementation -- **GiteaProvider** - Gitea/Forgejo/Codeberg API v1 implementation -- **Auto-detection** - Identifies Git host from repository URL - -### 2. User Interface Components - -**Location**: `src/components/contribute/` - -Five new React components for the contribution flow: - -#### ContributeButton -- Detects if project has upstream remote -- Shows "Propose Changes" button when available -- Supports multiple Git hosts automatically -- Hides if project isn't from a Git repository - -#### ContributeWizard -- 5-step wizard dialog with progress bar -- Guides users through complete contribution process -- Steps: Auth → Review → Branch/Commit → Checks → Submit -- Error handling with clear messages -- Loading states for async operations - -#### AuthStep -- OAuth login for GitHub (with PKCE) -- Personal Access Token entry for all hosts -- Clear instructions with links to token creation -- Host-specific guidance (GitHub/GitLab/Codeberg) - -#### DiffView -- Shows all changed files with icons -- Color-coded by type (added/modified/deleted) -- File statistics summary -- Scrollable list for many changes - -#### PRStatusBadge -- Shows existing PR for current branch -- Badge with PR number and state -- Popover with PR details -- Links to PR on Git host -- CI/CD check status display - -### 3. Contribution Workflow Hook - -**Location**: `src/hooks/useContribute.ts` - -Main orchestration hook with these capabilities: - -```typescript -const { - needsAuth, // Check authentication status - authenticate, // Save authentication token - contribute, // Execute full workflow - updatePR, // Update existing PR - isLoading, // Current loading state - error, // Error messages - step, // Current step in workflow - message, // Status messages - pr, // Created/updated PR object -} = useContribute(); -``` - -**Workflow Steps:** -1. Get upstream repository info -2. Check user permissions -3. Create fork if needed (with polling to wait for completion) -4. Configure remotes (upstream + origin) -5. Create and checkout feature branch -6. Commit all changes -7. Push to remote (fork or direct) -8. Create pull request via API - -### 4. Settings & Storage - -**Extended GitSettings Context:** - -```typescript -interface GitSettings { - credentials: Record; // Git operations - hostTokens: Record; // API operations - name?: string; - email?: string; - coAuthorEnabled?: boolean; -} - -interface GitHostToken { - token: string; - username?: string; - scopes?: string[]; - createdAt?: number; -} -``` - -**Storage:** -- All tokens stored in browser IndexedDB -- Persisted via VFS config system -- Never sent to Shakespeare servers -- Users can revoke anytime - -### 5. Integration Points - -**ProjectView Updates:** -- Added ContributeButton to mobile header -- Added ContributeButton to desktop header -- Added PRStatusBadge to both headers -- Shows before StarButton for visibility - -**OAuth Updates:** -- Extended useGitHubOAuth to save host tokens -- Maintains backward compatibility with credentials -- Stores scopes and metadata for tokens - -## User Experience Flow - -### First-Time Contributor - -1. **User edits a cloned project** in Shakespeare -2. **Clicks "Propose Changes"** button in header -3. **Connects account** via OAuth or PAT - - GitHub: One-click OAuth - - Others: PAT with clear instructions -4. **Reviews changes** in diff view -5. **Fills out PR form**: - - Branch name (auto-suggested) - - Commit message - - PR title and description -6. **Validation runs automatically**: - - TypeScript type check - - Project build -7. **Clicks "Submit"** and system: - - Creates fork (if needed) - - Pushes changes - - Opens PR -8. **Success screen** shows PR link - -**Total time: 2-3 minutes** (mostly waiting for API operations) - -### Subsequent Contributions - -1. **Makes more changes** on same branch -2. **Clicks "Update PR"** (or goes through wizard) -3. **Commits and pushes** new changes -4. **PR automatically updated** - -## Technical Highlights - -### Security -- ✅ PKCE for GitHub OAuth -- ✅ Minimal token scopes (read + write only what's needed) -- ✅ Local-only storage (IndexedDB) -- ✅ Clear security warnings in UI -- ✅ Token revocation support - -### Error Handling -- ✅ Graceful API failures with retries -- ✅ Fork creation polling with timeout -- ✅ Rate limit detection and messaging -- ✅ Validation before submission -- ✅ Fallback to compare URLs if needed - -### Compatibility -- ✅ Works with existing Git workflow -- ✅ Compatible with isomorphic-git -- ✅ Supports CORS via configurable proxy -- ✅ Mobile and desktop responsive -- ✅ Works offline for local operations - -### Performance -- ✅ Async operations with loading states -- ✅ Caches remote info where possible -- ✅ Minimal API calls -- ✅ Progress indicators for long operations - -## Files Changed - -### New Files (17) -``` -src/lib/git-hosts/types.ts -src/lib/git-hosts/GitHubProvider.ts -src/lib/git-hosts/GitLabProvider.ts -src/lib/git-hosts/GiteaProvider.ts -src/lib/git-hosts/index.ts -src/hooks/useContribute.ts -src/components/contribute/ContributeButton.tsx -src/components/contribute/ContributeWizard.tsx -src/components/contribute/AuthStep.tsx -src/components/contribute/DiffView.tsx -src/components/contribute/PRStatusBadge.tsx -src/components/contribute/index.ts -CONTRIBUTING_GUIDE.md -PR_CONTRIBUTION_SUMMARY.md -``` - -### Modified Files (3) -``` -src/contexts/GitSettingsContext.ts # Added hostTokens -src/components/GitSettingsProvider.tsx # Host token methods -src/hooks/useGitHubOAuth.ts # Save to hostTokens -src/lib/configUtils.ts # Schema for hostTokens -src/pages/ProjectView.tsx # UI integration -``` - -## Testing Checklist - -### Supported Scenarios - -- [x] Clone GitHub repo → Contribute → OAuth → Success -- [x] Clone GitHub repo → Contribute → PAT → Success -- [x] Clone GitLab repo → Contribute → PAT → Success -- [x] Clone Codeberg repo → Contribute → PAT → Success -- [x] User has push access → Direct push (no fork) -- [x] User lacks access → Auto fork → Push to fork -- [x] Update existing PR → Push new commits -- [x] Build fails → Show error, block submit -- [x] Rate limited → Show message with compare URL -- [x] Network error → Show retry option - -### Edge Cases Handled - -- ✅ Fork already exists → Reuse it -- ✅ Branch already exists → Use it or error -- ✅ No changes to commit → Inform user -- ✅ Detached HEAD → Show error -- ✅ Merge conflicts → Not yet supported (future) -- ✅ Token expired → Clear error message -- ✅ CORS issues → Proxy support - -## Platform Support - -| Git Host | Fork | PR Create | PR Update | OAuth | PAT | Status | -|----------|------|-----------|-----------|-------|-----|--------| -| GitHub | ✅ | ✅ | ✅ | ✅ | ✅ | Full | -| GitLab | ✅ | ✅ | ✅ | ❌ | ✅ | Full | -| Codeberg | ✅ | ✅ | ✅ | ❌ | ✅ | Full | -| Gitea | ✅ | ✅ | ✅ | ❌ | ✅ | Full | -| Forgejo | ✅ | ✅ | ✅ | ❌ | ✅ | Full | - -## What's NOT Included (Future Work) - -- ❌ Merge conflict resolution UI -- ❌ Draft PRs -- ❌ PR templates -- ❌ Multi-commit PRs (currently single commit) -- ❌ Reviewers/assignees selection -- ❌ Labels/milestone selection -- ❌ Automated tests in Shakespeare -- ❌ PR comments/discussions -- ❌ Rebase/squash options -- ❌ GitLab/Gitea OAuth (only GitHub) - -## Key Design Decisions - -### 1. Provider Pattern -**Why**: Different Git hosts have different APIs. The provider pattern allows adding new hosts without changing core logic. - -### 2. Automatic Forking -**Why**: Users don't understand forks. The system detects if they can push and handles forking transparently. - -### 3. Single Commit Model -**Why**: Simpler for non-technical users. They don't think in commits, just "here are my changes." - -### 4. Pre-submission Validation -**Why**: Prevents broken PRs. Better to fail before submission than after. - -### 5. OAuth + PAT Support -**Why**: OAuth is easier but not all hosts support it. PAT works everywhere as fallback. - -### 6. Local Token Storage -**Why**: Privacy and security. No server means no token leaks. - -## Performance Metrics - -Typical workflow times (on good connection): - -- Fork creation: 2-5 seconds -- PR creation: 1-2 seconds -- Build validation: 3-10 seconds (depends on project) -- Total first contribution: 2-3 minutes -- Update existing PR: 30-60 seconds - -## Known Limitations - -1. **No Merge Conflict Resolution**: If remote has changed and conflicts exist, user must manually resolve -2. **No Multi-Commit Support**: All changes go into single commit (can update later) -3. **No Draft PRs**: Always creates as open PR (could add toggle) -4. **No CI Integration**: Shows CI status from API but doesn't run checks in Shakespeare -5. **Rate Limiting**: GitHub unauthenticated rate limit applies to some operations - -## Success Criteria Met - -✅ **Zero Git Knowledge Required** - Users never see Git commands -✅ **Seamless UX** - Guided wizard with clear steps -✅ **Multiple Platforms** - GitHub, GitLab, Gitea support -✅ **Secure** - Local-only token storage -✅ **Robust** - Error handling and fallbacks -✅ **Integrated** - Works with existing Shakespeare Git features -✅ **Documented** - Comprehensive user and developer docs - -## Next Steps - -To use this system: - -1. **Clone any open source project** in Shakespeare -2. **Make your changes** using AI or code editor -3. **Click "Propose Changes"** in the header -4. **Follow the wizard** - it handles everything! - -The system is production-ready and will enable Shakespeare users to contribute to thousands of open source projects with ease. diff --git a/src/components/contribute/AuthStep.tsx b/src/components/contribute/AuthStep.tsx deleted file mode 100644 index bcb7e5bb..00000000 --- a/src/components/contribute/AuthStep.tsx +++ /dev/null @@ -1,174 +0,0 @@ -import { useState } from 'react'; -import { Button } from '@/components/ui/button'; -import { Input } from '@/components/ui/input'; -import { Label } from '@/components/ui/label'; -import { Alert, AlertDescription } from '@/components/ui/alert'; -import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; -import { useGitHubOAuth } from '@/hooks/useGitHubOAuth'; -import { InfoIcon, KeyRound, ExternalLink } from 'lucide-react'; - -interface AuthStepProps { - host: string; - onComplete: (host: string, token: string, username?: string) => void; -} - -export function AuthStep({ host, onComplete }: AuthStepProps) { - const { isOAuthConfigured, initiateOAuth } = useGitHubOAuth(); - const [token, setToken] = useState(''); - const [username, setUsername] = useState(''); - - const handleTokenSubmit = () => { - if (!token.trim()) return; - onComplete(host, token.trim(), username.trim() || undefined); - }; - - const getTokenInstructions = () => { - switch (host) { - case 'github.com': - return { - url: 'https://github.com/settings/tokens/new', - scopes: 'public_repo (for public repositories)', - steps: [ - 'Click "Generate new token (classic)"', - 'Set a descriptive note like "Shakespeare Contributions"', - 'Select the "public_repo" scope', - 'Click "Generate token" at the bottom', - 'Copy the token and paste it below', - ], - }; - case 'gitlab.com': - return { - url: 'https://gitlab.com/-/profile/personal_access_tokens', - scopes: 'api or write_repository', - steps: [ - 'Enter a token name like "Shakespeare"', - 'Select the "api" or "write_repository" scope', - 'Click "Create personal access token"', - 'Copy the token and paste it below', - ], - }; - case 'codeberg.org': - return { - url: 'https://codeberg.org/user/settings/applications', - scopes: 'repo', - steps: [ - 'Go to Applications > Access Tokens', - 'Click "Generate New Token"', - 'Enter a description like "Shakespeare"', - 'Select the "repo" permission', - 'Click "Generate Token"', - 'Copy the token and paste it below', - ], - }; - default: - return { - url: `https://${host}/user/settings/applications`, - scopes: 'repo or write access', - steps: [ - 'Navigate to your user settings', - 'Find the access tokens or applications section', - 'Create a new token with repository write permissions', - 'Copy the token and paste it below', - ], - }; - } - }; - - const instructions = getTokenInstructions(); - const showOAuth = host === 'github.com' && isOAuthConfigured; - - return ( -
-
-

Connect to {host}

-

- To propose changes, you need to authenticate with {host} -

-
- - - {showOAuth && ( - - Quick Connect - Access Token - - )} - - {showOAuth && ( - - - - - The fastest way to connect. You'll be redirected to {host} to authorize Shakespeare. - - - - - - )} - - - - - - Create a personal access token on {host} with the following scope: {instructions.scopes} - - - -
-

How to create a token:

-
    - {instructions.steps.map((step, index) => ( -
  1. {step}
  2. - ))} -
- - Open {host} token settings - - -
- -
- - setUsername(e.target.value)} - /> -

- Your username on {host} (helpful but not required) -

-
- -
- - setToken(e.target.value)} - /> -

- - Your token is stored locally and never sent to Shakespeare servers -

-
- - -
-
-
- ); -} diff --git a/src/components/contribute/ContributeButton.tsx b/src/components/contribute/ContributeButton.tsx deleted file mode 100644 index cb72dc31..00000000 --- a/src/components/contribute/ContributeButton.tsx +++ /dev/null @@ -1,65 +0,0 @@ -import { useState, useEffect } from 'react'; -import { useGit } from '@/hooks/useGit'; -import { Button } from '@/components/ui/button'; -import { ContributeWizard } from './ContributeWizard'; -import { GitPullRequest } from 'lucide-react'; -import { detectGitHost } from '@/lib/git-hosts'; - -interface ContributeButtonProps { - projectDir: string; - variant?: 'default' | 'outline' | 'ghost'; - size?: 'default' | 'sm' | 'lg' | 'icon'; - className?: string; -} - -export function ContributeButton({ projectDir, variant = 'outline', size = 'default', className }: ContributeButtonProps) { - const { git } = useGit(); - const [showWizard, setShowWizard] = useState(false); - const [canContribute, setCanContribute] = useState(false); - - useEffect(() => { - const checkContributeAvailable = async () => { - try { - // Check if there's a remote with a supported host - const upstreamUrl = await git.getRemoteURL(projectDir, 'upstream'); - const originUrl = await git.getRemoteURL(projectDir, 'origin'); - const remoteUrl = upstreamUrl || originUrl; - - if (remoteUrl) { - const hostType = detectGitHost(remoteUrl); - setCanContribute(hostType !== 'unknown'); - } else { - setCanContribute(false); - } - } catch { - setCanContribute(false); - } - }; - - checkContributeAvailable(); - }, [git, projectDir]); - - if (!canContribute) { - return null; - } - - return ( - <> - - - - - ); -} diff --git a/src/components/contribute/ContributeWizard.tsx b/src/components/contribute/ContributeWizard.tsx deleted file mode 100644 index b7342f51..00000000 --- a/src/components/contribute/ContributeWizard.tsx +++ /dev/null @@ -1,406 +0,0 @@ -import { useState, useEffect } from 'react'; -import { useContribute } from '@/hooks/useContribute'; -import { useGit } from '@/hooks/useGit'; -import { useBuildProject } from '@/hooks/useBuildProject'; -import { Button } from '@/components/ui/button'; -import { - Dialog, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, -} from '@/components/ui/dialog'; -import { Input } from '@/components/ui/input'; -import { Label } from '@/components/ui/label'; -import { Textarea } from '@/components/ui/textarea'; -import { Alert, AlertDescription } from '@/components/ui/alert'; -import { Progress } from '@/components/ui/progress'; -import { Checkbox } from '@/components/ui/checkbox'; -import { AuthStep } from './AuthStep'; -import { DiffView } from './DiffView'; -import { AlertCircle, CheckCircle2, Loader2, GitFork, Upload, GitPullRequest } from 'lucide-react'; -import type { PullRequest } from '@/lib/git-hosts'; - -interface ContributeWizardProps { - projectDir: string; - open: boolean; - onOpenChange: (open: boolean) => void; - onComplete?: (pr: PullRequest) => void; -} - -export function ContributeWizard({ projectDir, open, onOpenChange, onComplete }: ContributeWizardProps) { - const { git } = useGit(); - const { mutateAsync: buildProject } = useBuildProject(); - const { needsAuth, authenticate, contribute, isLoading, error, step, message, pr } = useContribute(); - - const [wizardStep, setWizardStep] = useState<'auth' | 'review' | 'branch' | 'checks' | 'result'>('auth'); - const [authStatus, setAuthStatus] = useState<{ needsAuth: boolean; host?: string; url?: string } | null>(null); - const [formData, setFormData] = useState({ - branchName: '', - commitMessage: '', - prTitle: '', - prBody: '', - maintainerCanModify: true, - }); - const [validationErrors, setValidationErrors] = useState>({}); - const [buildPassed, setBuildPassed] = useState(false); - const [checkingBuild, setCheckingBuild] = useState(false); - - // Check auth status when dialog opens - useEffect(() => { - if (open) { - needsAuth(projectDir).then(status => { - setAuthStatus(status); - if (!status.needsAuth) { - setWizardStep('review'); - } else { - setWizardStep('auth'); - } - }); - } - }, [open, projectDir, needsAuth]); - - // Reset state when dialog closes - useEffect(() => { - if (!open) { - setWizardStep('auth'); - setFormData({ - branchName: '', - commitMessage: '', - prTitle: '', - prBody: '', - maintainerCanModify: true, - }); - setValidationErrors({}); - setBuildPassed(false); - } - }, [open]); - - const handleAuthComplete = (host: string, token: string, username?: string) => { - authenticate(host, token, username); - setWizardStep('review'); - }; - - const handleReviewNext = () => { - setWizardStep('branch'); - }; - - const validateBranchForm = () => { - const errors: Record = {}; - - if (!formData.branchName.trim()) { - errors.branchName = 'Branch name is required'; - } else if (!/^[a-zA-Z0-9._\/-]+$/.test(formData.branchName)) { - errors.branchName = 'Invalid branch name. Use only letters, numbers, dots, dashes, and slashes.'; - } - - if (!formData.commitMessage.trim()) { - errors.commitMessage = 'Commit message is required'; - } - - if (!formData.prTitle.trim()) { - errors.prTitle = 'Pull request title is required'; - } - - setValidationErrors(errors); - return Object.keys(errors).length === 0; - }; - - const handleBranchNext = async () => { - if (!validateBranchForm()) return; - - setWizardStep('checks'); - - // Run build check - setCheckingBuild(true); - try { - await buildProject(projectDir); - setBuildPassed(true); - } catch (error) { - setBuildPassed(false); - setValidationErrors(prev => ({ - ...prev, - build: 'Build failed. Please fix errors before submitting.', - })); - } finally { - setCheckingBuild(false); - } - }; - - const handleSubmit = async () => { - if (!buildPassed) { - setValidationErrors(prev => ({ - ...prev, - build: 'Build must pass before submitting', - })); - return; - } - - const result = await contribute({ - projectDir, - branchName: formData.branchName, - commitMessage: formData.commitMessage, - prTitle: formData.prTitle, - prBody: formData.prBody, - maintainerCanModify: formData.maintainerCanModify, - }); - - if (result) { - setWizardStep('result'); - onComplete?.(result); - } - }; - - const getProgress = () => { - switch (wizardStep) { - case 'auth': return 20; - case 'review': return 40; - case 'branch': return 60; - case 'checks': return 80; - case 'result': return 100; - default: return 0; - } - }; - - const getStepIcon = () => { - if (step === 'fork') return ; - if (step === 'push') return ; - if (step === 'pr') return ; - if (step === 'complete') return ; - return ; - }; - - return ( - - - - Propose Changes - - Submit your changes to the original project - - - - - - {error && ( - - - {error} - - )} - - {wizardStep === 'auth' && authStatus && ( - - )} - - {wizardStep === 'review' && ( -
-
-

Review Your Changes

-

- Review the changes you're proposing to submit -

-
- -
- )} - - {wizardStep === 'branch' && ( -
-
-

Branch & Commit Details

-

- Describe your changes and create a branch -

-
- -
- - setFormData(prev => ({ ...prev, branchName: e.target.value }))} - /> - {validationErrors.branchName && ( -

{validationErrors.branchName}

- )} -
- -
- - setFormData(prev => ({ ...prev, commitMessage: e.target.value }))} - /> - {validationErrors.commitMessage && ( -

{validationErrors.commitMessage}

- )} -
- -
- - setFormData(prev => ({ ...prev, prTitle: e.target.value }))} - /> - {validationErrors.prTitle && ( -

{validationErrors.prTitle}

- )} -
- -
- -