diff --git a/CONTRIBUTING_GUIDE.md b/CONTRIBUTING_GUIDE.md new file mode 100644 index 00000000..03bb63be --- /dev/null +++ b/CONTRIBUTING_GUIDE.md @@ -0,0 +1,357 @@ +# 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/src/components/GitSettingsProvider.tsx b/src/components/GitSettingsProvider.tsx index db168ebd..f6cdaa5b 100644 --- a/src/components/GitSettingsProvider.tsx +++ b/src/components/GitSettingsProvider.tsx @@ -1,5 +1,5 @@ import { ReactNode, useState, useEffect } from 'react'; -import { GitSettingsContext, type GitSettings, type GitCredential, type GitSettingsContextType } from '@/contexts/GitSettingsContext'; +import { GitSettingsContext, type GitSettings, type GitCredential, type GitHostToken, type GitSettingsContextType } from '@/contexts/GitSettingsContext'; import { useFS } from '@/hooks/useFS'; import { readGitSettings, writeGitSettings } from '@/lib/configUtils'; @@ -9,6 +9,7 @@ interface GitSettingsProviderProps { const DEFAULT_SETTINGS: GitSettings = { credentials: {}, + hostTokens: {}, }; export function GitSettingsProvider({ children }: GitSettingsProviderProps) { @@ -85,6 +86,39 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) { })); }; + const addHostToken = (host: string, token: GitHostToken) => { + setSettings(prev => ({ + ...prev, + hostTokens: { + ...prev.hostTokens, + [host]: token, + }, + })); + }; + + const removeHostToken = (host: string) => { + setSettings(prev => { + const { [host]: removed, ...rest } = prev.hostTokens; + return { + ...prev, + hostTokens: rest, + }; + }); + }; + + const updateHostToken = (host: string, token: Partial) => { + setSettings(prev => ({ + ...prev, + hostTokens: { + ...prev.hostTokens, + [host]: { + ...prev.hostTokens[host], + ...token, + }, + }, + })); + }; + const isConfigured = Object.entries(settings.credentials).length > 0; const contextValue: GitSettingsContextType = { @@ -93,6 +127,9 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) { addCredential, removeCredential, updateCredential, + addHostToken, + removeHostToken, + updateHostToken, isConfigured, }; diff --git a/src/components/contribute/AuthStep.tsx b/src/components/contribute/AuthStep.tsx new file mode 100644 index 00000000..bcb7e5bb --- /dev/null +++ b/src/components/contribute/AuthStep.tsx @@ -0,0 +1,174 @@ +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 new file mode 100644 index 00000000..cb72dc31 --- /dev/null +++ b/src/components/contribute/ContributeButton.tsx @@ -0,0 +1,65 @@ +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 new file mode 100644 index 00000000..b7342f51 --- /dev/null +++ b/src/components/contribute/ContributeWizard.tsx @@ -0,0 +1,406 @@ +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}

+ )} +
+ +
+ +