Merge branch 'nostr-git-support' into 'main'

git updates

See merge request soapbox-pub/shakespeare!61
This commit is contained in:
Alex Gleason committed 2025-10-15 22:38:05 +00:00
commit 0bd7ee94fd
25 files changed
+5330 -329

No files matched your search

+209
View File
@@ -0,0 +1,209 @@
# Fork PR Workflow - Troubleshooting Guide
## Common Issues and Solutions
### "Validation Failed" Error
This error from GitHub usually means the PR can't be created. The system now shows detailed reasons:
**Common causes:**
1. **Branch doesn't exist in fork**
- **Solution**: The system now automatically pushes your branch to the fork before creating the PR
- If it still fails, try manually: Git Management → Branches → Push to remote
2. **No commits on the branch**
- **Error**: "head: No commits between..."
- **Solution**: Make sure you've committed your changes before creating a PR
- Go to Git Management → Changes → Commit your work
3. **PR already exists**
- **Error**: "A pull request already exists for..."
- **Solution**: Check the upstream repository - you might already have an open PR from this branch
- Update the existing PR instead of creating a new one
4. **Invalid branch name**
- **Error**: "Reference does not exist"
- **Solution**: Make sure your branch name doesn't have special characters
- Use alphanumeric characters, hyphens, and underscores only
### "Failed to push branch to your fork"
**Causes:**
1. **Branch not committed**
```
Error: Failed to push branch 'my-branch' to your fork.
This usually means:
1. The branch hasn't been committed yet
2. Network/authentication issues
```
**Solution**:
- Go to Git Management → Changes tab
- Review your changes
- Commit them before creating a PR
2. **Authentication issues**
- **Solution**: Check Settings → Git → Make sure your GitHub token is valid
- Token must have `public_repo` scope
- Try re-authenticating if the token expired
3. **Network/CORS issues**
- **Solution**: Check your internet connection
- Some networks block Git operations
- Try again or use a different network
### Fork Workflow Steps
When you create a PR and don't have push access, the system:
1. **Detects you need a fork**
- Shows: "You don't have push access to this repository"
- Explains: "Your changes will be pushed to your fork at username/repo"
2. **Checks for existing fork**
- If found: Uses it
- If not found: Creates a new fork
- Waits for fork to be ready (GitHub takes a few seconds)
3. **Sets up remotes**
- Checks if 'origin' points to your fork
- If not, adds a 'fork' remote
- Determines which remote to use for pushing
4. **Pushes your branch**
- Pushes current branch to fork
- Uses your GitHub credentials
- Shows detailed error if push fails
5. **Creates PR**
- Uses format: `yourname:branch` → `upstream:main`
- Enables "maintainer can modify" by default
- Returns PR URL on success
### Error Message Improvements
The system now shows much more detailed errors:
**Before:**
```
Error: Validation Failed
```
**After:**
```
Validation Failed
Details: head: No commits between master and yourname:test-branch
See: https://docs.github.com/rest/pulls/pulls#create-a-pull-request
```
**With field errors:**
```
Validation Failed
Details: base: Does not exist;
head: Must be formatted as 'owner:branch'
See: https://docs.github.com/rest/pulls/pulls#create-a-pull-request
```
### Debug Checklist
Before creating a PR, verify:
- [ ] You've made changes to files
- [ ] Changes are committed (check Git Management → Changes)
- [ ] You're on the correct branch
- [ ] Branch has a valid name (no spaces or special chars)
- [ ] You have valid GitHub credentials (Settings → Git)
- [ ] Your token has `public_repo` scope
- [ ] The upstream repository allows forks
- [ ] The target branch exists in upstream (usually `main` or `master`)
### Manual Override
If the automatic workflow fails, you can:
1. **Fork manually** on GitHub.com
2. **Add fork as remote**:
- Git Management → (manually configure remotes if needed)
3. **Push branch** to fork:
- Use the existing "Create Pull Request" button
- Or push via command line
4. **Create PR** on GitHub.com directly
### Understanding Remotes
After forking, your remotes should look like:
```
origin → [email protected]:yourname/repo.git (your fork)
upstream → [email protected]:original/repo.git (original repo)
```
Or if system adds a fork remote:
```
origin → [email protected]:original/repo.git (original)
fork → [email protected]:yourname/repo.git (your fork)
```
Both configurations work - the system detects which to use.
### Still Having Issues?
Check the browser console (F12 → Console) for detailed logs:
- `Detected GitHub SSH/HTTPS:` - Shows parsed repository info
- `Pushing branch X to fork Y` - Shows push operation
- `GitHub response status:` - Shows API response codes
- `GitHub API error response:` - Shows full error from GitHub
These logs will show exactly what's happening and where it's failing.
### GitHub API Rate Limits
If you see:
```
Error: API rate limit exceeded
```
**Solution:**
- Wait an hour (unauthenticated limit: 60 requests/hour)
- Or authenticate with a token (limit: 5000 requests/hour)
- Check Settings → Git to ensure token is configured
### Fork Already Exists
If you see:
```
Error: fork already exists for this repository
```
**This is normal!** The system will use your existing fork. The error is just informational.
### Repository Owner Can't Fork
If you own the repository, you can't fork it. You don't need to - you have push access!
The system should detect this and skip the fork workflow. If you see this error, please report it.
## Getting Help
If you encounter an error not covered here:
1. Check the full error message (now includes details)
2. Look at browser console logs
3. Verify your setup (credentials, branch, commits)
4. Try the manual workflow as a workaround
5. Report the issue with:
- Full error message
- Console logs
- Repository URL (if public)
- Branch name
+163
View File
@@ -0,0 +1,163 @@
# Nostr Git Integration
Shakespeare supports creating patches for Nostr git repositories following [NIP-34 (git stuff)](https://github.com/nostr-protocol/nips/blob/master/34.md).
## Overview
Nostr git is a decentralized approach to code collaboration using Nostr events instead of centralized git hosting platforms. With Nostr git:
- **Repository announcements** (kind 30617) declare the existence of git repositories
- **Patches** (kind 1617) are submitted as Nostr events, similar to pull requests
- **Anyone can submit patches** without needing push access or creating forks
- **Maintainers review and apply patches** through status events
## How It Works in Shakespeare
### 1. Repository URL Format
Nostr git repositories use a special URL format:
```
nostr://<pubkey>/<repo-id>
```
- `<pubkey>`: The repository maintainer's Nostr public key (hex format or npub)
- `<repo-id>`: The repository identifier (d tag, usually kebab-case)
**Important**: The system expects hex pubkeys but will automatically convert npub to hex if provided.
Examples:
- `nostr://abc123def456.../my-project` (hex pubkey)
- `nostr://npub1abc123.../my-project` (will be converted to hex)
### 2. Creating Patches (Pull Requests)
When you create a "Pull Request" for a Nostr git repository, Shakespeare:
1. **Detects Nostr git URL** - Recognizes the `nostr://` prefix
2. **Creates patch event** - Generates a kind 1617 event with:
- Patch content (git diff or description)
- Reference to repository announcement (`a` tag)
- Tags for repository owner, patch title, description
- NIP-31 `alt` tag for human-readable description
3. **Publishes to Nostr** - Sends the patch to the repository's designated relays
4. **No forking required** - Unlike GitHub/GitLab, patches go directly to the upstream repo
### 3. UI Integration
The existing Pull Request dialog automatically adapts for Nostr git:
- **Button text**: "Create Patch" instead of "Create Pull Request"
- **No credentials needed**: Uses your Nostr signer (logged-in account)
- **No fork workflow**: Patches are submitted directly
- **Success message**: Shows the Nostr event ID as confirmation
### 4. Key Differences from GitHub/GitLab
| Feature | GitHub/GitLab | Nostr Git |
|---------|---------------|-----------|
| Authentication | Personal access token | Nostr signer |
| Fork required | Yes (if no push access) | No |
| Push to remote | Yes | No (patch is in event) |
| PR/Patch format | API-based | Nostr event (kind 1617) |
| Relay/server | Centralized | Decentralized relays |
## Implementation Details
### GitHostProvider Interface
Nostr git is implemented as a `NostrGitProvider` that implements the `GitHostProvider` interface:
```typescript
class NostrGitProvider implements GitHostProvider {
// Query repository announcements (kind 30617)
async getRepository(owner: string, repo: string): Promise<GitRepository>
// Check if user is a maintainer
async canUserPush(owner: string, repo: string): Promise<boolean>
// Create patch event (kind 1617)
async createPullRequest(options: CreatePullRequestOptions): Promise<PullRequest>
// ... other methods
}
```
### Patch Event Structure
Patches follow NIP-34 specifications:
```json
{
"kind": 1617,
"content": "<patch content>",
"tags": [
["a", "30617:<repo-owner-pubkey>:<repo-id>"],
["p", "<repository-owner>"],
["t", "root"],
["t", "root-revision"],
["subject", "<patch-title>"],
["description", "<patch-description>"],
["alt", "Patch proposal for <repo>: <title>"]
]
}
```
### Repository Detection
The system detects Nostr git URLs in multiple places:
1. **URL parsing** - `detectGitHost()` checks for `nostr://` prefix
2. **Remote info** - Extracts owner (pubkey) and repo (d tag) from URL
3. **Provider creation** - Instantiates `NostrGitProvider` with signer
## Future Enhancements
Potential improvements to Nostr git integration:
- [ ] Generate actual git patches using `git format-patch`
- [ ] Support patch series (multiple commits)
- [ ] Display patch status (open/closed/applied)
- [ ] Show existing patches for a repository
- [ ] Support patch reviews and comments (kind 1621)
- [ ] Apply patches locally for testing
- [ ] Maintainer tools for applying/merging patches
## Related NIPs
- **NIP-34**: git stuff (repository announcements, patches, issues)
- **NIP-31**: alt tag for unknown event kinds
- **NIP-22**: Comments (for patch discussions)
## Example Workflow
1. **Clone Nostr git repo**:
```bash
# Repository URL: nostr://abc123.../my-project
git clone https://actual-clone-url.git
```
2. **Make changes and commit**:
```bash
git checkout -b my-feature
# ... make changes ...
git commit -m "Add new feature"
```
3. **Create patch in Shakespeare**:
- Open Pull Request dialog
- System detects Nostr git URL
- Fill in title and description
- Click "Create Patch"
- Patch is published to Nostr relays
4. **Maintainer receives patch**:
- Sees patch event on their relays
- Reviews the proposed changes
- Applies or rejects via status events
## Resources
- [NIP-34 Specification](https://github.com/nostr-protocol/nips/blob/master/34.md)
- [Nostr Protocol](https://nostr.com)
- [Git Format-Patch](https://git-scm.com/docs/git-format-patch)
+270
View File
@@ -0,0 +1,270 @@
# Nostr Git Debugging Guide
## Understanding the Problem
Patches are being published successfully but not showing up in NostrHub or other Nostr git clients. This is likely a **relay synchronization issue**.
## How Nostr Git Discovery Works
1. **Repository Announcement (Kind 30617)**
- Published once per repository (auto-announced on first patch)
- Contains metadata: name, description, clone URLs, relays
- Includes `r` tag with earliest unique commit (euc)
- Has `d` tag with repository identifier
- Coordinate: `30617:<pubkey>:<repo-id>`
2. **Patches (Kind 1617)**
- Reference repository via `a` tag: `30617:<pubkey>:<repo-id>`
- Include `r` tag with euc for repository-specific filtering
- Published to relays specified in repository announcement
3. **Discovery Flow**
- Client queries for repositories (kind 30617)
- User selects a repository
- Client queries for patches using `#a` filter: `#a: ["30617:<pubkey>:<repo-id>"]`
4. **Auto-Announcement (Shakespeare Feature)**
- When creating first patch, repository is auto-announced
- Uses configured relay from settings
- Ensures announcement and patch on same relay
- Eliminates manual "Announce Repository" step
## The Relay Problem
**Key Issue**: Events must be on the **same relay** for discovery to work.
### Scenario:
1. You're connected to `wss://relay.primal.net` in Shakespeare
2. You announce repository → published to `wss://relay.primal.net`
3. You create patch → published to `wss://relay.primal.net`
4. NostrHub is connected to `wss://relay.nostr.band`
5. NostrHub queries `wss://relay.nostr.band` → **finds nothing**
### Why This Happens:
- Nostr relays don't automatically sync with each other
- Each relay is independent
- Events are only on relays they were explicitly published to
- Relay hints in events are suggestions, not guarantees
## Debugging Steps
### Step 1: Check Which Relay You're On
In Shakespeare, check the current relay:
- Look at bottom of the page or settings
- Default is `wss://relay.primal.net`
### Step 2: Verify Repository Announcement
After clicking "Announce Repository", check console logs:
```
=== ANNOUNCING REPOSITORY ===
Repository ID: git.shakespeare.diy/portfoliux
Owner pubkey: 932614571afcbad4d17a191ee281e39eebbb41b93fac8fd87829622aeb112f4d
Event coordinate: 30617:932614571afcbad4d17a191ee281e39eebbb41b93fac8fd87829622aeb112f4d:git.shakespeare.diy/portfoliux
Published repository announcement to Nostr relays
To verify: Query for kind 30617 with authors=[...] and #d=[...]
```
### Step 3: Verify Patch Can Find Repository
When creating a patch, check console logs:
**If repository exists:**
```
Querying for repository announcement with filter: {...}
Repository announcement query returned 1 events ✅ GOOD
Found repository announcement event: {...}
```
**If repository doesn't exist (auto-announce):**
```
Repository announcement query returned 0 events
Repository announcement not found - creating one automatically
Auto-creating repository announcement: {...}
Successfully auto-announced repository ✅ GOOD
```
**If auto-announce fails:**
```
Repository announcement query returned 0 events
Failed to auto-announce repository: <error> ❌ BAD
```
### Step 4: Check NostrHub's Relay
1. Open NostrHub (nostrhub.io)
2. Check which relay it's using
3. Compare with Shakespeare's relay
## Solutions
### Solution 1: Use Same Relay as NostrHub
1. In Shakespeare settings, change relay to match NostrHub
2. Common NostrHub relays:
- `wss://relay.nostr.band`
- `wss://relay.damus.io`
3. Re-announce repository on this relay
4. Create new patch
### Solution 2: Publish to Multiple Relays
When announcing repository, add multiple relays:
- `wss://relay.primal.net`
- `wss://relay.nostr.band`
- `wss://relay.damus.io`
The announcement event will be published to all of these, and patches will follow.
### Solution 3: Use NIP-65 Relay Lists (Future Enhancement)
Proper solution would be to:
1. Query user's NIP-65 relay list
2. Publish repository announcements to all user's read/write relays
3. Patches automatically go to same relays
## Verifying Success
### Check Repository is Discoverable:
1. Open NostrHub
2. Go to Repositories page
3. Look for your repository
4. If found → announcement is on correct relay ✅
### Check Patches are Discoverable:
1. Find your repository on NostrHub
2. Click into repository
3. Check Patches tab
4. Your patches should appear ✅
## Common Issues
### Issue: "Repository announcement not found"
**Cause**: Announcement not on current relay
**Fix**: Re-announce on current relay
### Issue: Patches published but not visible
**Cause**: Patches on different relay than announcement
**Fix**: Ensure both announcement and patches on same relay
### Issue: Works in Shakespeare but not NostrHub
**Cause**: Different relays
**Fix**: Use same relay in both clients
### Issue: Relay hints not working
**Explanation**: Relay hints are suggestions only - clients may ignore them
**Fix**: Ensure announcement is on relay the client uses
## Event Format Reference
### Repository Announcement (Kind 30617)
```json
{
"kind": 30617,
"content": "",
"tags": [
["d", "git.shakespeare.diy/portfoliux"],
["name", "Portfoliux"],
["description", "Portfolio website"],
["clone", "nostr://npub.../git.shakespeare.diy/portfoliux"],
["relays", "wss://relay.nostr.band"],
["r", "abc123...", "euc"]
]
}
```
### Patch Event (Kind 1617)
```json
{
"kind": 1617,
"content": "From abc... Mon Sep 17...\n<git format-patch content>",
"tags": [
["a", "30617:932614571afcbad4d17a191ee281e39eebbb41b93fac8fd87829622aeb112f4d:git.shakespeare.diy/portfoliux"],
["p", "932614571afcbad4d17a191ee281e39eebbb41b93fac8fd87829622aeb112f4d"],
["t", "root"],
["t", "root-revision"],
["subject", "Fix bug in component"],
["r", "abc123..."],
["commit", "def456..."],
["parent-commit", "ghi789..."]
]
}
```
## Testing Relay Synchronization
To test if events are on a relay:
1. **Using nostr.band explorer:**
- Go to https://nostr.band
- Search for your event ID or repository coordinate
- Check which relays have the event
2. **Using console in Shakespeare:**
```javascript
// Check repository announcement
await nostr.query([{
kinds: [30617],
authors: ["your-pubkey"],
"#d": ["your-repo-id"],
limit: 1
}]);
// Check patches
await nostr.query([{
kinds: [1617],
"#a": ["30617:your-pubkey:your-repo-id"],
limit: 10
}]);
```
## Recommended Workflow
### Simplified (Auto-Announce Enabled)
1. **Configure relay** (one time):
- Settings → Select relay (e.g., `wss://relay.nostr.band`)
- This relay will be used for all Nostr git operations
2. **Create patches** (automatic announcement):
- Click "Create Patch"
- System automatically announces repository if needed
- Patch is published with proper references
- Check "Your Patches" section to verify
3. **View in NostrHub:**
- Ensure NostrHub uses same relay
- Browse to Repositories → Find your repository
- View patches in Patches tab
### Manual (If Auto-Announce Fails)
1. **First time setup:**
- Switch to `wss://relay.nostr.band` (widely used)
- Click "Announce Repository" button
- Verify announcement succeeded
2. **Creating patches:**
- Ensure same relay as announcement
- Create patch
- Check console for successful repository lookup
- Verify patch appears in "Your Patches" section
3. **Checking in NostrHub:**
- Ensure NostrHub on same relay
- Browse to Repositories
- Find your repository
- View patches
## Future Improvements Needed
1. **Multi-relay publishing**: Publish to multiple relays automatically
2. **NIP-65 integration**: Use user's relay list
3. **Relay fallback**: Try multiple relays when querying
4. **Relay selection UI**: Easy relay switching before operations
5. **Event verification**: Confirm events were published successfully
6. **Cross-relay search**: Query multiple relays for better discovery
+308
View File
@@ -0,0 +1,308 @@
# Contributing to Upstream Projects
Shakespeare's Git management system now supports contributing to upstream open source projects through automatic forking, even if you don't have push access to the repository.
## How It Works
When you try to create a pull request to a repository where you don't have push permissions, Shakespeare automatically:
1. **Detects your permissions** via the Git host API (GitHub/GitLab)
2. **Checks for an existing fork** under your account
3. **Creates a fork** if one doesn't exist
4. **Configures the PR** to use your fork as the source
5. **Creates the pull request** from `your-fork:branch` → `upstream:main`
This all happens transparently - you just fill out the PR form and click create.
## User Experience
### For Repository Owners (Have Push Access)
If you have push access to the repository:
- Create branches normally
- Push changes directly
- Create PRs within the same repository
- Standard workflow - nothing changes
### For Contributors (No Push Access)
If you don't have push access:
- Make your changes (on any branch, even main/master)
- Open Git Management → Pull Request tab
- Fill out title/description
- Click "Fork & Create PR"
- Shakespeare automatically:
- Creates a feature branch (if you're on main/master)
- Forks the repo (if needed)
- Pushes your branch
- Creates the PR
You'll see a message like:
> "You don't have push access to this repository. Your changes will be pushed to your fork at **username/repo** and a pull request will be created from there."
## Step-by-Step Guide
### 1. Clone an Upstream Repository
```bash
# Clone any open source project in Shakespeare
git clone https://github.com/upstream-org/project.git
```
### 2. Make Your Changes
- Edit files in Shakespeare
- Use AI assistance or manual code editing
- Test your changes
### 3. Commit Your Changes (Optional)
> **Note:** You can skip this step! If you're on the main/master branch, a feature branch will be created automatically when you create the PR.
If you want to create a branch manually:
- Open Git Management → "Branches" tab
- Click "Create Branch"
- Name it something descriptive (e.g., `fix-typo`)
### 4. Create Pull Request
- Go to "Pull Request" tab
- Select target branch (usually `main` or `master`)
- Enter PR title and description
- If you're on main/master: You'll see "A feature branch will be automatically created from your PR title"
- Click "Fork & Create PR" (or just "Create Pull Request" if you have access)
### 5. Done!
- Your fork is created automatically
- Changes are pushed to your fork
- PR is opened from fork to upstream
- You get a link to view the PR
## Automatic Feature Branch Creation
### Why?
Most users will make changes directly on the `main` or `master` branch without realizing they should create a feature branch first. To make contributing easier, Shakespeare automatically creates a feature branch for you when needed.
### When Does This Happen?
When you create a PR and you're currently on `main` or `master`, the system:
1. **Generates a branch name** from your PR title
- Converts to lowercase
- Replaces spaces with hyphens
- Removes special characters
- Adds a unique suffix (timestamp-based)
2. **Creates the branch** from your current position
3. **Checks it out** automatically
4. **Continues with PR creation** on the new branch
### Example
**Your PR title:** "Fix login button styling"
**Generated branch:** `fix-login-button-styling-k7m2`
**What happens:**
```
Before: You're on 'main' with uncommitted changes
After: You're on 'fix-login-button-styling-k7m2' with the same changes
Result: PR created from the feature branch → upstream/main
```
### UI Indicators
You'll see these messages when on main/master:
**Alert Box:**
> You're on the **main** branch. A feature branch will be automatically created from your PR title for this contribution.
**Branch Comparison:**
```
upstream/repo:main ← main
Note: A new branch will be created automatically
```
**Toast Notification:**
> Feature branch created
> Created branch 'fix-login-button-styling-k7m2' for your changes
### What If You Want to Use Your Own Branch?
Simple! Just create a branch manually first:
1. Git Management → Branches tab
2. Click "Create Branch"
3. Name it whatever you want
4. Now create your PR - no auto-branch will be created
### Benefits
- **No Git knowledge needed** - Users don't need to understand branching
- **Best practices enforced** - Never commit directly to main
- **Clean history** - Each PR gets its own branch
- **Easy to understand** - Branch names match PR titles
- **Safe** - Your main branch stays clean
## Behind the Scenes
### Permission Detection
```typescript
// Checks via API if user can push
const canPush = await checkPushPermissions(repo, token);
if (!canPush) {
// Fork workflow
const fork = await ensureFork(repo, token);
// Use fork_owner:branch as head ref
}
```
### Fork Management
- **Checks existing forks first** - doesn't create duplicates
- **Waits for fork to be ready** - GitHub/GitLab need time to fork
- **Configures head ref properly** - `username:branch` format for cross-repo PRs
### API Calls
**GitHub:**
- `GET /repos/{owner}/{repo}` - Check permissions
- `GET /repos/{username}/{repo}` - Check if fork exists
- `POST /repos/{owner}/{repo}/forks` - Create fork
- `POST /repos/{owner}/{repo}/pulls` - Create PR with cross-fork head
**GitLab:**
- `GET /projects/{id}` - Check permissions (access_level >= 30)
- `GET /projects/{username}/{repo}` - Check if fork exists
- `POST /projects/{id}/fork` - Create fork
- `POST /projects/{id}/merge_requests` - Create MR
## Supported Platforms
| Platform | Fork Detection | Fork Creation | Cross-Fork PR | Status |
|----------|---------------|---------------|---------------|--------|
| GitHub | ✅ | ✅ | ✅ | Full |
| GitLab | ✅ | ✅ | ✅ | Full |
| Codeberg | ✅ | ✅ | ✅ | Full |
| Gitea | ✅ | ✅ | ✅ | Full |
## UI Indicators
The system provides clear visual feedback:
### Permission Check
```
⏳ Checking repository permissions...
```
### Fork Notice
```
ℹ️ You don't have push access to this repository.
Your changes will be pushed to your fork at username/repo
and a pull request will be created from there.
```
### Branch Comparison
Shows the full fork relationship:
```
upstream/repo:main ← username/repo:feature-branch
```
### Create Button
Changes based on permissions:
- **Direct access**: "Create Pull Request" with PR icon
- **Fork needed**: "Fork & Create PR" with fork icon
## Authentication
Uses existing Shakespeare Git credentials:
1. **GitHub OAuth** - One-click authentication (Settings → Git)
2. **Personal Access Tokens** - Manual token entry for any platform
Required token scopes:
- **GitHub**: `public_repo` (for public repositories)
- **GitLab**: `api` or `write_repository`
Tokens are stored locally in browser IndexedDB and never sent to Shakespeare servers.
## Troubleshooting
### "No credentials found"
- Add your Git credentials in Settings → Git
- Make sure the token has the right scopes
- Verify the token hasn't expired
### "Failed to create fork"
- Check if you already have a fork (only one fork per user)
- Ensure your token has fork permissions
- Some organizations disable forking - check repo settings
### "Permission denied"
- Your token may have expired or been revoked
- Re-authenticate in Settings → Git
- Check token scopes include repository write access
### Fork exists but PR fails
- Make sure your fork is up to date
- Try pushing your branch manually first
- Check if the branch name conflicts with upstream
## Example Workflow
Contributing a bug fix to an open source project (the easy way):
1. **Clone**: Clone `facebook/react` in Shakespeare
2. **Edit**: Make your fixes (don't worry about branches!)
3. **PR Tab**: Open Git Management → Pull Request
4. **Fill form**:
- Title: "Fix useEffect memory leak in concurrent mode"
- Description: Detailed explanation of the bug and fix
- Target: `main`
5. **Submit**: Click "Fork & Create PR"
6. **Automatic magic**:
- Creates branch: `fix-useeffect-memory-leak-in-concurrent-mode-x7k2`
- Checks out the new branch
- Forks to `yourusername/react`
- Pushes branch to your fork
- Creates PR: `facebook/react:main` ← `yourusername:react:fix-useeffect-memory-leak-in-concurrent-mode-x7k2`
**Total steps for you:** 3 (clone, edit, submit)
**Total steps Shakespeare handles:** 6 (branch, fork, push, configure remotes, create PR)
## Integration with Existing Features
This fork workflow integrates seamlessly with existing Git features:
- **Branch Management** - Create/switch/delete branches as usual
- **Diff Viewer** - Review changes before creating PR
- **Compare View** - Compare branches and commits
- **Git Credentials** - Uses existing auth system
- **Remote Management** - Works with origin/upstream remotes
No new settings or configuration needed - it just works when you try to contribute to repos where you don't have push access.
## Privacy & Security
- **No server involvement** - All Git operations happen in your browser
- **Local token storage** - Tokens stored in IndexedDB, never sent to Shakespeare
- **Minimal API calls** - Only checks permissions when needed
- **Read-only checks** - Permission detection doesn't modify anything
- **User confirmation** - Always shows what will happen before forking
## Future Enhancements
Potential improvements:
- Conflict resolution UI when upstream has changed
- Sync fork with upstream (rebase/merge)
- Multi-commit PRs with better history
- Draft PR support
- PR templates
- Reviewer/assignee selection
+371 -261
View File
@@ -44,6 +44,8 @@ import {
Zap,
Save,
Settings2,
GitPullRequest,
ExternalLink,
} from 'lucide-react';
import { useGitStatus } from '@/hooks/useGitStatus';
import { useGitSettings } from '@/hooks/useGitSettings';
@@ -52,6 +54,7 @@ import { useToast } from '@/hooks/useToast';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostr } from '@nostrify/react';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { usePullRequests } from '@/hooks/usePullRequests';
import { useAppContext } from '@/hooks/useAppContext';
import { cn } from '@/lib/utils';
import { findCredentialsForRepo } from '@/lib/gitCredentials';
@@ -91,6 +94,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
const { user } = useCurrentUser();
const { nostr } = useNostr();
const { mutateAsync: publishEvent } = useNostrPublish();
const { data: pullRequests, isLoading: isLoadingPRs } = usePullRequests(originUrl);
const { config } = useAppContext();
const projectPath = `/projects/${projectId}`;
@@ -420,7 +424,8 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
});
// Set origin remote to Nostr URL
const nostrUrl = `nostr://${nip19.npubEncode(user.pubkey)}/git.shakespeare.diy/${projectId}`;
// Format: nostr://<hex-pubkey>/<repo-id>
const nostrUrl = `nostr://${user.pubkey}/${projectId}`;
try {
// Remove existing origin if it exists
@@ -676,6 +681,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
const syncStatus = getSyncStatus();
const [isGitManagementOpen, setIsGitManagementOpen] = useState(false);
const [gitManagementDefaultTab, setGitManagementDefaultTab] = useState<string>('branches');
return (
<>
@@ -694,6 +700,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
size="sm"
className="gap-2"
onClick={() => {
setGitManagementDefaultTab('branches');
setIsGitManagementOpen(true);
onOpenChange?.(false);
}}
@@ -708,234 +715,223 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
<div className="flex-1 min-h-0 overflow-hidden px-6 pb-6">
<ScrollArea className="h-full">
<div className="space-y-4 pr-4">
{/* URL Configuration */}
{/* Section 1: Git URL, Current Branch, Sync Status, Merge Branch */}
{gitStatus?.isGitRepo && (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm">Git URL</CardTitle>
<CardTitle className="text-sm">Repository Info</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<div className="flex gap-2">
<div className="flex-1">
<Label htmlFor="origin-url" className="sr-only">
URL
</Label>
<CardContent className="space-y-4">
{/* Git URL */}
<div className="space-y-2">
<Label htmlFor="origin-url" className="text-xs font-medium text-muted-foreground">
Git URL
</Label>
<div className="flex gap-2">
<Input
id="origin-url"
placeholder="https://github.com/username/repository.git"
value={originUrl}
onChange={(e) => setOriginUrl(e.target.value)}
disabled={isSavingOrigin}
className="flex-1"
/>
<Button
onClick={handleSaveOrigin}
disabled={isSavingOrigin}
variant="outline"
size="sm"
className="h-10 shrink-0"
>
{isSavingOrigin ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
) : (
<Save className="h-4 w-4 mr-2" />
)}
{isSavingOrigin ? 'Saving...' : 'Save'}
</Button>
</div>
<Button
onClick={handleSaveOrigin}
disabled={isSavingOrigin}
variant="outline"
size="sm"
className="h-10 shrink-0"
>
{isSavingOrigin ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
) : (
<Save className="h-4 w-4 mr-2" />
)}
{isSavingOrigin ? 'Saving...' : 'Save'}
</Button>
{/* Credentials Warning */}
{gitStatus.remotes.length > 0 && (
(() => {
const remoteWithoutCredentials = gitStatus.remotes.find((remote) => !findCredentialsForRepo(remote.url, settings.credentials));
if (!remoteWithoutCredentials) return null;
let protocol = '';
let hostname = 'the remote host';
try {
const url = new URL(remoteWithoutCredentials.url);
protocol = url.protocol;
hostname = url.hostname;
} catch {
return (
<Alert className="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/50 mt-2">
<AlertTriangle className="h-4 w-4" />
<AlertDescription className="text-sm">
Invalid URL format. Enter an https URL.
</AlertDescription>
</Alert>
);
}
if (protocol !== 'https:' && protocol !== 'nostr:') {
return (
<Alert className="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/50 mt-2">
<AlertTriangle className="h-4 w-4" />
<AlertDescription className="text-sm">
The {protocol.replace(':', '')} URL type is not supported. Enter an https URL.
</AlertDescription>
</Alert>
);
}
if (protocol === 'nostr:' && !user) {
return (
<Alert className="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/50 mt-2">
<AlertTriangle className="h-4 w-4" />
<AlertDescription className="text-sm">
You are not logged into Nostr. Push & pull might not work unless you{' '}
<button
onClick={() => navigate('/settings/nostr')}
className="underline hover:no-underline font-medium text-amber-700 dark:text-amber-300"
>
log in
</button>.
</AlertDescription>
</Alert>
);
}
if (protocol === 'https:') {
return (
<Alert className="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/50 mt-2">
<AlertTriangle className="h-4 w-4" />
<AlertDescription className="text-sm">
You are not logged into {hostname}. Push & pull might not work unless you{' '}
<button
onClick={() => navigate('/settings/git')}
className="underline hover:no-underline font-medium text-amber-700 dark:text-amber-300"
>
log in
</button>.
</AlertDescription>
</Alert>
);
}
return null;
})()
)}
</div>
{/* Credentials Warning */}
{gitStatus.remotes.length > 0 && (
(() => {
const remoteWithoutCredentials = gitStatus.remotes.find((remote) => !findCredentialsForRepo(remote.url, settings.credentials));
if (!remoteWithoutCredentials) return null;
let protocol = '';
let hostname = 'the remote host';
try {
const url = new URL(remoteWithoutCredentials.url);
protocol = url.protocol;
hostname = url.hostname;
} catch {
// Invalid URL
return (
<Alert className="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/50">
<AlertTriangle className="h-4 w-4" />
<AlertDescription className="text-sm">
Invalid URL format. Enter an https URL.
</AlertDescription>
</Alert>
);
}
// Check for unsupported protocols
if (protocol !== 'https:' && protocol !== 'nostr:') {
return (
<Alert className="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/50">
<AlertTriangle className="h-4 w-4" />
<AlertDescription className="text-sm">
The {protocol.replace(':', '')} URL type is not supported. Enter an https URL.
</AlertDescription>
</Alert>
);
}
// For nostr protocol, only show warning if user is not logged in
if (protocol === 'nostr:' && !user) {
return (
<Alert className="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/50">
<AlertTriangle className="h-4 w-4" />
<AlertDescription className="text-sm">
You are not logged into Nostr. Push & pull might not work unless you{' '}
<button
onClick={() => navigate('/settings/nostr')}
className="underline hover:no-underline font-medium text-amber-700 dark:text-amber-300"
>
log in
</button>.
</AlertDescription>
</Alert>
);
}
// For https protocol, show warning if no credentials
if (protocol === 'https:') {
return (
<Alert className="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/50">
<AlertTriangle className="h-4 w-4" />
<AlertDescription className="text-sm">
You are not logged into {hostname}. Push & pull might not work unless you{' '}
<button
onClick={() => navigate('/settings/git')}
className="underline hover:no-underline font-medium text-amber-700 dark:text-amber-300"
>
log in
</button>.
</AlertDescription>
</Alert>
);
}
return null;
})()
)}
</CardContent>
</Card>
)}
{/* Branch Selector */}
{gitStatus?.isGitRepo && gitStatus.currentBranch && (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm">Current Branch</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<div className="flex gap-2">
<Select
value={gitStatus.currentBranch}
onValueChange={handleSwitchBranch}
disabled={isSwitchingBranch || isLoadingBranches}
>
<SelectTrigger className="flex-1">
<SelectValue>
{isSwitchingBranch ? (
<span className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
Switching...
</span>
) : (
<span className="flex items-center gap-2">
<GitBranch className="h-4 w-4" />
{gitStatus.currentBranch}
</span>
)}
</SelectValue>
</SelectTrigger>
<SelectContent>
{branches.map((branch) => (
<SelectItem key={branch} value={branch}>
<span className="flex items-center gap-2">
{branch === gitStatus.currentBranch && (
<CheckCircle className="h-4 w-4 text-primary" />
{/* Current Branch */}
{gitStatus.currentBranch && (
<div className="space-y-2">
<Label className="text-xs font-medium text-muted-foreground">
Current Branch
</Label>
<div className="flex gap-2">
<Select
value={gitStatus.currentBranch}
onValueChange={handleSwitchBranch}
disabled={isSwitchingBranch || isLoadingBranches}
>
<SelectTrigger className="flex-1">
<SelectValue>
{isSwitchingBranch ? (
<span className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
Switching...
</span>
) : (
<span className="flex items-center gap-2">
<GitBranch className="h-4 w-4" />
{gitStatus.currentBranch}
</span>
)}
{branch}
</span>
</SelectItem>
))}
</SelectContent>
</Select>
<Button
variant="outline"
size="sm"
className="shrink-0"
onClick={() => setIsCreateBranchDialogOpen(true)}
disabled={isSwitchingBranch}
>
<Plus className="h-4 w-4 mr-2" />
New
</Button>
</div>
</CardContent>
</Card>
)}
{/* Sync Status */}
{gitStatus?.isGitRepo && (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm">Sync Status</CardTitle>
</CardHeader>
<CardContent>
<div className="flex items-center gap-2 mb-4">
<syncStatus.icon className={cn("h-4 w-4", syncStatus.color)} />
<span className={cn("text-sm font-medium", syncStatus.color)}>
{syncStatus.text}
</span>
</div>
{gitStatus.remotes.length > 0 && (
<div className="flex gap-2">
<Button
onClick={handlePull}
disabled={isPulling || isPushing || isPushingToNostr}
variant="outline"
size="sm"
className="flex-1"
>
{isPulling ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
) : (
<Download className="h-4 w-4 mr-2" />
)}
{isPulling ? 'Pulling...' : 'Pull'}
</Button>
<Button
onClick={handlePush}
disabled={isPushing || isPulling || isPushingToNostr || gitStatus.ahead === 0}
variant="outline"
size="sm"
className="flex-1"
>
{isPushing ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
) : (
<Upload className="h-4 w-4 mr-2" />
)}
{isPushing ? 'Pushing...' : 'Push'}
</Button>
</SelectValue>
</SelectTrigger>
<SelectContent>
{branches.map((branch) => (
<SelectItem key={branch} value={branch}>
<span className="flex items-center gap-2">
{branch === gitStatus.currentBranch && (
<CheckCircle className="h-4 w-4 text-primary" />
)}
{branch}
</span>
</SelectItem>
))}
</SelectContent>
</Select>
<Button
variant="outline"
size="sm"
className="shrink-0"
onClick={() => setIsCreateBranchDialogOpen(true)}
disabled={isSwitchingBranch}
>
<Plus className="h-4 w-4 mr-2" />
New
</Button>
</div>
</div>
)}
{/* Push to Nostr button when no remote is configured and user is logged in */}
{gitStatus.remotes.length === 0 && user && (
<div className="flex gap-2">
{/* Sync Status */}
<div className="space-y-2">
<Label className="text-xs font-medium text-muted-foreground">
Sync Status
</Label>
<div className="flex items-center gap-2 mb-3">
<syncStatus.icon className={cn("h-4 w-4", syncStatus.color)} />
<span className={cn("text-sm font-medium", syncStatus.color)}>
{syncStatus.text}
</span>
</div>
{gitStatus.remotes.length > 0 && (
<div className="flex gap-2">
<Button
onClick={handlePull}
disabled={isPulling || isPushing || isPushingToNostr}
variant="outline"
size="sm"
className="flex-1"
>
{isPulling ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
) : (
<Download className="h-4 w-4 mr-2" />
)}
{isPulling ? 'Pulling...' : 'Pull'}
</Button>
<Button
onClick={handlePush}
disabled={isPushing || isPulling || isPushingToNostr || gitStatus.ahead === 0}
variant="outline"
size="sm"
className="flex-1"
>
{isPushing ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
) : (
<Upload className="h-4 w-4 mr-2" />
)}
{isPushing ? 'Pushing...' : 'Push'}
</Button>
</div>
)}
{gitStatus.remotes.length === 0 && user && (
<Button
onClick={handlePushToNostr}
disabled={isPushingToNostr || isPushing || isPulling}
variant="outline"
size="sm"
className="flex-1"
className="w-full"
>
{isPushingToNostr ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
@@ -944,77 +940,190 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
)}
{isPushingToNostr ? 'Publishing to Nostr...' : 'Push to Nostr'}
</Button>
)}
</div>
{/* Merge Branch Action */}
{gitStatus.currentBranch && (
<div className="pt-2 border-t">
<MergeDialog
projectId={projectId}
currentBranch={gitStatus.currentBranch}
onMergeComplete={() => refetchGitStatus()}
/>
</div>
)}
</CardContent>
</Card>
)}
{/* Branch Operations */}
{gitStatus?.isGitRepo && gitStatus.currentBranch && (
{/* Section 2: Your Open PRs and Create PR Button */}
{gitStatus?.isGitRepo && gitStatus.remotes.length > 0 && originUrl && (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm">Branch Operations</CardTitle>
</CardHeader>
<CardContent className="flex gap-2">
<MergeDialog
projectId={projectId}
currentBranch={gitStatus.currentBranch}
onMergeComplete={() => refetchGitStatus()}
/>
{gitStatus.remotes.length > 0 && originUrl && (
<PullRequestDialog
projectId={projectId}
currentBranch={gitStatus.currentBranch}
remoteUrl={originUrl}
/>
)}
</CardContent>
</Card>
)}
{/* Working Directory Changes */}
{gitStatus?.isGitRepo && gitStatus.changedFiles.length > 0 && (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm">Working Directory Changes</CardTitle>
<CardDescription>
{gitStatus.changedFiles.length} file{gitStatus.changedFiles.length !== 1 ? 's' : ''} with changes
<CardTitle className="text-sm">
{originUrl.startsWith('nostr://') ? 'Patches' : 'Pull Requests'}
</CardTitle>
<CardDescription className="text-xs">
{originUrl.startsWith('nostr://')
? 'Submit patches to the repository'
: 'Manage pull requests for this repository'
}
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-2">
{gitStatus.changedFiles.map((file, index) => (
<div
key={index}
className="flex items-center gap-2 p-2 rounded-md border bg-muted/20"
>
{getFileStatusIcon(file.status)}
<span className="font-mono text-sm flex-1 truncate">
{file.filepath}
</span>
<Badge
variant="outline"
className={cn("text-xs", getFileStatusColor(file.status))}
>
{file.status}
</Badge>
<CardContent className="space-y-3">
{/* Open Pull Requests List */}
{!originUrl.startsWith('nostr://') && isLoadingPRs && (
<div className="flex items-center justify-center py-4 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Loading pull requests...
</div>
)}
{!isLoadingPRs && pullRequests && pullRequests.length > 0 && (
<div className="space-y-2 mb-3">
<div className="text-xs font-medium text-muted-foreground mb-2">
{pullRequests.some(pr => !pr.isOwner)
? (originUrl.startsWith('nostr://') ? 'Incoming Patches' : 'Incoming PRs')
: (originUrl.startsWith('nostr://') ? 'Your Patches' : 'Your Open PRs')
}
</div>
))}
</div>
{pullRequests.map((pr) => (
<div
key={pr.id}
className="p-3 rounded-md border bg-muted/20 hover:bg-muted/40 transition-colors space-y-2"
>
<div className="flex items-start gap-3">
<GitPullRequest className={cn(
"h-4 w-4 mt-0.5 shrink-0",
pr.state === 'merged' ? 'text-purple-600' : 'text-green-600'
)} />
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<h4 className="text-sm font-medium truncate">
{pr.title}
</h4>
{pr.state === 'merged' && (
<Badge variant="secondary" className="text-xs shrink-0">
Merged
</Badge>
)}
</div>
<p className="text-xs text-muted-foreground mt-1">
#{pr.number} by {pr.isOwner ? 'you' : pr.author} • {pr.sourceBranch} → {pr.targetBranch}
</p>
</div>
</div>
{/* Actions row */}
{(!pr.isOwner && pr.state === 'open') || !originUrl.startsWith('nostr://') ? (
<div className="flex items-center gap-2 pl-7">
{!pr.isOwner && pr.state === 'open' && (
<>
{!originUrl.startsWith('nostr://') && (
<Button
variant="outline"
size="sm"
className="h-8 text-xs"
onClick={async () => {
try {
await git.checkout({
dir: projectPath,
ref: pr.sourceBranch,
});
await refetchGitStatus();
toast({
title: 'Branch checked out',
description: `Switched to ${pr.sourceBranch}`,
});
} catch (err) {
toast({
title: 'Checkout failed',
description: err instanceof Error ? err.message : 'Unknown error',
variant: 'destructive',
});
}
}}
>
<GitBranch className="h-3 w-3 mr-1" />
Review
</Button>
)}
<MergeDialog
projectId={projectId}
currentBranch={gitStatus.currentBranch}
sourceBranch={pr.sourceBranch}
targetBranch={pr.targetBranch}
onMergeComplete={refetchGitStatus}
/>
</>
)}
{!originUrl.startsWith('nostr://') && (
<Button
variant="ghost"
size="sm"
className="h-8 text-xs ml-auto"
onClick={() => window.open(pr.url, '_blank')}
>
<ExternalLink className="h-3 w-3 mr-1" />
View
</Button>
)}
</div>
) : null}
</div>
))}
</div>
)}
{/* Create PR/Patch Button */}
<PullRequestDialog
projectId={projectId}
currentBranch={gitStatus.currentBranch}
remoteUrl={originUrl}
/>
</CardContent>
</Card>
)}
{/* Clean Working Directory */}
{gitStatus?.isGitRepo && gitStatus.changedFiles.length === 0 && (
{/* Section 3: Working Directory */}
{gitStatus?.isGitRepo && (
<Card>
<CardContent className="py-6">
<div className="text-center text-muted-foreground">
<CheckCircle className="h-8 w-8 mx-auto mb-2 text-green-500" />
<p>Working directory is clean</p>
<p className="text-xs">No uncommitted changes</p>
</div>
<CardHeader className="pb-3">
<CardTitle className="text-sm">Working Directory</CardTitle>
{gitStatus.changedFiles.length > 0 && (
<CardDescription>
{gitStatus.changedFiles.length} file{gitStatus.changedFiles.length !== 1 ? 's' : ''} with changes
</CardDescription>
)}
</CardHeader>
<CardContent>
{gitStatus.changedFiles.length > 0 ? (
<div className="space-y-2">
{gitStatus.changedFiles.map((file, index) => (
<div
key={index}
className="flex items-center gap-2 p-2 rounded-md border bg-muted/20"
>
{getFileStatusIcon(file.status)}
<span className="font-mono text-sm flex-1 truncate">
{file.filepath}
</span>
<Badge
variant="outline"
className={cn("text-xs", getFileStatusColor(file.status))}
>
{file.status}
</Badge>
</div>
))}
</div>
) : (
<div className="text-center text-muted-foreground py-6">
<CheckCircle className="h-8 w-8 mx-auto mb-2 text-green-500" />
<p>Working directory is clean</p>
<p className="text-xs">No uncommitted changes</p>
</div>
)}
</CardContent>
</Card>
)}
@@ -1029,6 +1138,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
projectId={projectId}
open={isGitManagementOpen}
onOpenChange={setIsGitManagementOpen}
defaultTab={gitManagementDefaultTab}
/>
{/* Create Branch Dialog */}
@@ -68,6 +68,7 @@ describe('GitSettingsProvider', () => {
const { readGitSettings } = await import('@/lib/configUtils');
vi.mocked(readGitSettings).mockResolvedValue({
credentials: {},
hostTokens: {},
});
});
@@ -183,6 +184,7 @@ describe('GitSettingsProvider', () => {
password: 'gitlab-token',
},
},
hostTokens: {},
};
const { readGitSettings } = await import('@/lib/configUtils');
+38 -1
View File
@@ -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<GitHostToken>) => {
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,
};
@@ -0,0 +1,569 @@
import { useState, useEffect, useCallback } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
DialogFooter,
} from '@/components/ui/dialog';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
GitBranch,
Loader2,
AlertCircle,
CheckCircle,
Plus,
X,
Megaphone,
} from 'lucide-react';
import { useGit } from '@/hooks/useGit';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostr } from '@/hooks/useNostr';
import { useToast } from '@/hooks/useToast';
import { nip19 } from 'nostr-tools';
interface AnnounceRepositoryDialogProps {
projectId: string;
remoteUrl?: string;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}
export function AnnounceRepositoryDialog({
projectId,
remoteUrl,
open,
onOpenChange,
}: AnnounceRepositoryDialogProps) {
const [isOpen, setIsOpen] = useState(open ?? false);
const [repoId, setRepoId] = useState('');
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [webUrls, setWebUrls] = useState<string[]>([]);
const [cloneUrls, setCloneUrls] = useState<string[]>([]);
const [relays, setRelays] = useState<string[]>(['wss://relay.nostr.band']);
const [earliestCommit, setEarliestCommit] = useState('');
const [isCreating, setIsCreating] = useState(false);
const [error, setError] = useState<string | null>(null);
const [createdNaddr, setCreatedNaddr] = useState<string | null>(null);
const [newWebUrl, setNewWebUrl] = useState('');
const [newCloneUrl, setNewCloneUrl] = useState('');
const [newRelay, setNewRelay] = useState('');
const { git } = useGit();
const { user } = useCurrentUser();
const { nostr } = useNostr();
const { toast } = useToast();
const projectPath = `/projects/${projectId}`;
useEffect(() => {
if (open !== undefined) {
setIsOpen(open);
}
}, [open]);
const parseRemoteUrl = useCallback((url: string) => {
// Extract repo ID from Nostr URL
if (url.startsWith('nostr://')) {
const match = url.match(/^nostr:\/\/[^/]+\/(.+)$/);
if (match) {
const id = match[1];
setRepoId(id);
setName(id.split('/').pop() || id);
}
}
// Add the remote URL as a clone URL
if (url && !cloneUrls.includes(url)) {
setCloneUrls([url]);
}
}, [cloneUrls]);
const getEarliestCommit = useCallback(async () => {
try {
const commits = await git.log({
dir: projectPath,
ref: 'HEAD',
});
if (commits.length > 0) {
// Get the earliest commit (last in the log)
const earliest = commits[commits.length - 1];
setEarliestCommit(earliest.oid);
}
} catch (err) {
console.warn('Failed to get earliest commit:', err);
}
}, [git, projectPath]);
useEffect(() => {
if (isOpen && remoteUrl) {
// Parse remote URL to pre-fill data
parseRemoteUrl(remoteUrl);
// Get earliest commit
getEarliestCommit();
}
}, [isOpen, remoteUrl, parseRemoteUrl, getEarliestCommit]);
const addWebUrl = () => {
if (newWebUrl.trim() && !webUrls.includes(newWebUrl.trim())) {
setWebUrls([...webUrls, newWebUrl.trim()]);
setNewWebUrl('');
}
};
const removeWebUrl = (index: number) => {
setWebUrls(webUrls.filter((_, i) => i !== index));
};
const addCloneUrl = () => {
if (newCloneUrl.trim() && !cloneUrls.includes(newCloneUrl.trim())) {
setCloneUrls([...cloneUrls, newCloneUrl.trim()]);
setNewCloneUrl('');
}
};
const removeCloneUrl = (index: number) => {
setCloneUrls(cloneUrls.filter((_, i) => i !== index));
};
const addRelay = () => {
if (newRelay.trim() && !relays.includes(newRelay.trim())) {
setRelays([...relays, newRelay.trim()]);
setNewRelay('');
}
};
const removeRelay = (index: number) => {
setRelays(relays.filter((_, i) => i !== index));
};
const announceRepository = async () => {
if (!user || !user.signer) {
toast({
title: 'Authentication required',
description: 'Please log in with Nostr to announce repositories',
variant: 'destructive',
});
return;
}
if (!repoId.trim()) {
toast({
title: 'Repository ID required',
description: 'Please enter a repository identifier',
variant: 'destructive',
});
return;
}
if (cloneUrls.length === 0) {
toast({
title: 'Clone URL required',
description: 'Please add at least one clone URL',
variant: 'destructive',
});
return;
}
setIsCreating(true);
setError(null);
try {
// Build tags array per NIP-34
const tags: string[][] = [
['d', repoId.trim()], // Required: repository identifier
];
if (name.trim()) {
tags.push(['name', name.trim()]);
}
if (description.trim()) {
tags.push(['description', description.trim()]);
}
// Add web URLs
webUrls.forEach(url => {
if (url.trim()) tags.push(['web', url.trim()]);
});
// Add clone URLs (required)
cloneUrls.forEach(url => {
if (url.trim()) tags.push(['clone', url.trim()]);
});
// Add relays for patch submissions
relays.forEach(relay => {
if (relay.trim()) tags.push(['relays', relay.trim()]);
});
// Add earliest unique commit (euc) for repository identification
if (earliestCommit.trim()) {
tags.push(['r', earliestCommit.trim(), 'euc']);
}
// Create repository announcement event (kind 30617)
const repoEvent = {
kind: 30617,
content: '',
tags,
created_at: Math.floor(Date.now() / 1000),
};
console.log('=== ANNOUNCING REPOSITORY ===');
console.log('Repository ID:', repoId.trim());
console.log('Owner pubkey:', user.pubkey);
console.log('Creating repository announcement event:', repoEvent);
// Sign the event
const signedEvent = await user.signer.signEvent(repoEvent);
console.log('Signed repository announcement:', signedEvent);
console.log('Event coordinate:', `30617:${user.pubkey}:${repoId.trim()}`);
// Publish to Nostr relays
await nostr.event(signedEvent);
console.log('Published repository announcement to Nostr relays');
console.log('To verify: Query for kind 30617 with authors=[' + user.pubkey + '] and #d=[' + repoId.trim() + ']');
// Create naddr for the repository
const naddr = nip19.naddrEncode({
identifier: repoId.trim(),
pubkey: user.pubkey,
kind: 30617,
relays: relays.length > 0 ? relays : undefined,
});
setCreatedNaddr(naddr);
toast({
title: 'Repository announced!',
description: 'Your repository has been announced on Nostr',
});
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
setError(errorMessage);
toast({
title: 'Failed to announce repository',
description: errorMessage,
variant: 'destructive',
});
} finally {
setIsCreating(false);
}
};
const handleOpenChange = (newOpen: boolean) => {
setIsOpen(newOpen);
onOpenChange?.(newOpen);
// Reset form when closing
if (!newOpen) {
setRepoId('');
setName('');
setDescription('');
setWebUrls([]);
setCloneUrls([]);
setRelays(['wss://relay.nostr.band']);
setEarliestCommit('');
setCreatedNaddr(null);
setError(null);
setNewWebUrl('');
setNewCloneUrl('');
setNewRelay('');
}
};
const copyNaddr = () => {
if (createdNaddr) {
navigator.clipboard.writeText(createdNaddr);
toast({
title: 'Copied to clipboard',
description: 'Repository address copied',
});
}
};
return (
<Dialog open={isOpen} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<Button variant="outline" className="gap-2">
<Megaphone className="h-4 w-4" />
Announce Repository
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl max-h-[90vh]">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Megaphone className="h-5 w-5" />
Announce Repository on Nostr
</DialogTitle>
<DialogDescription>
Publish a repository announcement (NIP-34) to make it discoverable on Nostr git
clients
</DialogDescription>
</DialogHeader>
{createdNaddr ? (
// Success state
<div className="py-8 text-center space-y-4">
<CheckCircle className="h-16 w-16 text-green-600 mx-auto" />
<div>
<h3 className="text-lg font-semibold mb-2">Repository Announced!</h3>
<p className="text-muted-foreground">
Your repository is now discoverable on Nostr git clients
</p>
</div>
<div className="bg-muted/30 rounded-lg p-4 space-y-2">
<Label>Repository Address (naddr)</Label>
<div className="flex gap-2">
<Input
value={createdNaddr}
readOnly
className="font-mono text-sm"
/>
<Button
variant="outline"
size="icon"
onClick={copyNaddr}
>
<Plus className="h-4 w-4" />
</Button>
</div>
<p className="text-xs text-muted-foreground">
Share this address with others to let them find your repository
</p>
</div>
</div>
) : (
// Form
<ScrollArea className="max-h-[60vh]">
<div className="space-y-6 pr-4">
{/* Error alert */}
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* Repository ID */}
<div className="space-y-2">
<Label htmlFor="repo-id">Repository ID *</Label>
<Input
id="repo-id"
placeholder="e.g., my-project or username/repo-name"
value={repoId}
onChange={(e) => setRepoId(e.target.value)}
disabled={isCreating}
/>
<p className="text-xs text-muted-foreground">
Unique identifier for this repository (like GitHub's owner/repo)
</p>
</div>
{/* Name */}
<div className="space-y-2">
<Label htmlFor="repo-name">Name</Label>
<Input
id="repo-name"
placeholder="Human-readable project name"
value={name}
onChange={(e) => setName(e.target.value)}
disabled={isCreating}
/>
</div>
{/* Description */}
<div className="space-y-2">
<Label htmlFor="repo-description">Description</Label>
<Textarea
id="repo-description"
placeholder="Brief description of your project"
value={description}
onChange={(e) => setDescription(e.target.value)}
rows={3}
disabled={isCreating}
/>
</div>
{/* Web URLs */}
<div className="space-y-2">
<Label>Web URLs (Optional)</Label>
<div className="space-y-2">
{webUrls.map((url, index) => (
<div key={index} className="flex gap-2">
<Input value={url} readOnly className="flex-1" />
<Button
variant="outline"
size="icon"
onClick={() => removeWebUrl(index)}
disabled={isCreating}
>
<X className="h-4 w-4" />
</Button>
</div>
))}
<div className="flex gap-2">
<Input
placeholder="https://example.com/browse"
value={newWebUrl}
onChange={(e) => setNewWebUrl(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && (e.preventDefault(), addWebUrl())}
disabled={isCreating}
/>
<Button
variant="outline"
size="icon"
onClick={addWebUrl}
disabled={isCreating}
>
<Plus className="h-4 w-4" />
</Button>
</div>
</div>
<p className="text-xs text-muted-foreground">
URLs where the repository can be browsed online
</p>
</div>
{/* Clone URLs */}
<div className="space-y-2">
<Label>Clone URLs *</Label>
<div className="space-y-2">
{cloneUrls.map((url, index) => (
<div key={index} className="flex gap-2">
<Input value={url} readOnly className="flex-1 font-mono text-sm" />
<Button
variant="outline"
size="icon"
onClick={() => removeCloneUrl(index)}
disabled={isCreating}
>
<X className="h-4 w-4" />
</Button>
</div>
))}
<div className="flex gap-2">
<Input
placeholder="nostr://npub.../repo-id"
value={newCloneUrl}
onChange={(e) => setNewCloneUrl(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && (e.preventDefault(), addCloneUrl())}
disabled={isCreating}
className="font-mono text-sm"
/>
<Button
variant="outline"
size="icon"
onClick={addCloneUrl}
disabled={isCreating}
>
<Plus className="h-4 w-4" />
</Button>
</div>
</div>
<p className="text-xs text-muted-foreground">
URLs for cloning the repository (at least one required)
</p>
</div>
{/* Relays */}
<div className="space-y-2">
<Label>Relays for Patches</Label>
<div className="space-y-2">
{relays.map((relay, index) => (
<div key={index} className="flex gap-2">
<Input value={relay} readOnly className="flex-1 font-mono text-sm" />
<Button
variant="outline"
size="icon"
onClick={() => removeRelay(index)}
disabled={isCreating || relays.length === 1}
>
<X className="h-4 w-4" />
</Button>
</div>
))}
<div className="flex gap-2">
<Input
placeholder="wss://relay.example.com"
value={newRelay}
onChange={(e) => setNewRelay(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && (e.preventDefault(), addRelay())}
disabled={isCreating}
className="font-mono text-sm"
/>
<Button
variant="outline"
size="icon"
onClick={addRelay}
disabled={isCreating}
>
<Plus className="h-4 w-4" />
</Button>
</div>
</div>
<p className="text-xs text-muted-foreground">
Relays where patches will be published and monitored
</p>
</div>
{/* Earliest Commit */}
<div className="space-y-2">
<Label htmlFor="earliest-commit">Earliest Unique Commit</Label>
<Input
id="earliest-commit"
placeholder="Commit hash"
value={earliestCommit}
onChange={(e) => setEarliestCommit(e.target.value)}
disabled={isCreating}
className="font-mono text-sm"
/>
<p className="text-xs text-muted-foreground">
The root commit of your repository (auto-detected when available)
</p>
</div>
</div>
</ScrollArea>
)}
{!createdNaddr && (
<DialogFooter>
<Button
variant="outline"
onClick={() => handleOpenChange(false)}
disabled={isCreating}
>
Cancel
</Button>
<Button onClick={announceRepository} disabled={isCreating}>
{isCreating ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Announcing...
</>
) : (
<>
<GitBranch className="h-4 w-4 mr-2" />
Announce Repository
</>
)}
</Button>
</DialogFooter>
)}
</DialogContent>
</Dialog>
);
}
+44 -1
View File
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useState, useEffect } from 'react';
import {
Dialog,
DialogContent,
@@ -12,11 +12,14 @@ import {
GitBranch,
GitCompare,
Settings,
GitPullRequest,
} from 'lucide-react';
import { BranchManager } from './BranchManager';
import { CompareView } from './CompareView';
import { DiffViewer } from './DiffViewer';
import { PullRequestForm } from './PullRequestForm';
import { useGitStatus } from '@/hooks/useGitStatus';
import { useGit } from '@/hooks/useGit';
interface GitManagementDialogProps {
projectId: string;
@@ -34,9 +37,26 @@ export function GitManagementDialog({
defaultTab = 'branches',
}: GitManagementDialogProps) {
const [activeTab, setActiveTab] = useState(defaultTab);
const [remoteUrl, setRemoteUrl] = useState<string | null>(null);
const { git } = useGit();
const projectPath = `/projects/${projectId}`;
const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId);
useEffect(() => {
const loadRemoteUrl = async () => {
try {
const url = await git.getRemoteURL(projectPath, 'origin');
setRemoteUrl(url);
} catch {
setRemoteUrl(null);
}
};
if (open) {
loadRemoteUrl();
}
}, [open, git, projectPath]);
const handleBranchChange = () => {
// Refetch git status when branches change
refetchGitStatus();
@@ -82,6 +102,15 @@ export function GitManagementDialog({
<GitCompare className="h-4 w-4" />
Compare
</TabsTrigger>
{remoteUrl && (
<TabsTrigger
value="pr"
className="gap-2 data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none"
>
<GitPullRequest className="h-4 w-4" />
Pull Request
</TabsTrigger>
)}
</TabsList>
</div>
@@ -114,6 +143,20 @@ export function GitManagementDialog({
</div>
</ScrollArea>
</TabsContent>
{remoteUrl && (
<TabsContent value="pr" className="flex-1 m-0 data-[state=active]:flex data-[state=active]:flex-col">
<ScrollArea className="flex-1">
<div className="p-6">
<PullRequestForm
projectId={projectId}
currentBranch={gitStatus?.currentBranch || null}
remoteUrl={remoteUrl}
/>
</div>
</ScrollArea>
</TabsContent>
)}
</Tabs>
</div>
</DialogContent>
+5 -1
View File
@@ -35,6 +35,8 @@ import { useSearchParams } from 'react-router-dom';
interface MergeDialogProps {
projectId: string;
currentBranch: string | null;
sourceBranch?: string;
targetBranch?: string;
open?: boolean;
onOpenChange?: (open: boolean) => void;
onMergeComplete?: () => void;
@@ -58,13 +60,15 @@ interface MergePreview {
export function MergeDialog({
projectId,
currentBranch,
sourceBranch: initialSourceBranch,
targetBranch: _initialTargetBranch,
open,
onOpenChange,
onMergeComplete,
}: MergeDialogProps) {
const [isOpen, setIsOpen] = useState(open ?? false);
const [branches, setBranches] = useState<string[]>([]);
const [sourceBranch, setSourceBranch] = useState<string>('');
const [sourceBranch, setSourceBranch] = useState<string>(initialSourceBranch || '');
const [isLoadingBranches, setIsLoadingBranches] = useState(false);
const [isLoadingPreview, setIsLoadingPreview] = useState(false);
const [isMerging, setIsMerging] = useState(false);
File diff suppressed because it is too large. Load diff
+563
View File
@@ -0,0 +1,563 @@
import { useState, useEffect, useCallback } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import {
GitPullRequest,
Loader2,
AlertCircle,
CheckCircle,
ExternalLink,
GitCompare,
GitFork,
} from 'lucide-react';
import { useGit } from '@/hooks/useGit';
import { useGitSettings } from '@/hooks/useGitSettings';
import { useToast } from '@/hooks/useToast';
import { findCredentialsForRepo } from '@/lib/gitCredentials';
interface PullRequestFormProps {
projectId: string;
currentBranch: string | null;
remoteUrl: string;
}
interface RemoteInfo {
owner: string;
repo: string;
platform: 'github' | 'gitlab';
apiUrl: string;
}
interface ForkInfo {
needsFork: boolean;
forkOwner?: string;
forkRepo?: string;
forkUrl?: string;
}
export function PullRequestForm({ projectId, currentBranch, remoteUrl }: PullRequestFormProps) {
const [title, setTitle] = useState('');
const [description, setDescription] = useState('');
const [targetBranch, setTargetBranch] = useState('main');
const [remoteBranches, setRemoteBranches] = useState<string[]>([]);
const [isCreating, setIsCreating] = useState(false);
const [remoteInfo, setRemoteInfo] = useState<RemoteInfo | null>(null);
const [forkInfo, setForkInfo] = useState<ForkInfo>({ needsFork: false });
const [isCheckingPermissions, setIsCheckingPermissions] = useState(false);
const [createdPrUrl, setCreatedPrUrl] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const { git } = useGit();
const { settings } = useGitSettings();
const { toast } = useToast();
const projectPath = `/projects/${projectId}`;
// All the helper functions from PullRequestDialog can be reused here
// (parseRemoteUrl, checkPushPermissions, ensureFork, etc.)
// For brevity, I'll import them or duplicate the core logic
const parseRemoteUrl = useCallback((url: string) => {
// Same implementation as PullRequestDialog
setError(null);
try {
let match;
let owner = '';
let repo = '';
let platform: 'github' | 'gitlab' = 'github';
let apiUrl = '';
const normalizedUrl = url.replace(/\.git$/, '');
// GitHub SSH/HTTPS
match = normalizedUrl.match(/git@github\.com:([^/]+)\/(.+)$/) ||
normalizedUrl.match(/https?:\/\/github\.com\/([^/]+)\/(.+)$/);
if (match) {
owner = match[1];
repo = match[2];
platform = 'github';
apiUrl = 'https://api.github.com';
}
// GitLab SSH/HTTPS
if (!match) {
match = normalizedUrl.match(/git@gitlab\.com:([^/]+)\/(.+)$/) ||
normalizedUrl.match(/https?:\/\/gitlab\.com\/([^/]+)\/(.+)$/);
if (match) {
owner = match[1];
repo = match[2];
platform = 'gitlab';
apiUrl = 'https://gitlab.com/api/v4';
}
}
if (owner && repo) {
setRemoteInfo({ owner, repo, platform, apiUrl });
} else {
setError('Unsupported remote URL format');
}
} catch {
setError('Failed to parse remote URL');
}
}, []);
const loadRemoteBranches = useCallback(async () => {
try {
const branches = await git.listBranches({
dir: projectPath,
remote: 'origin',
});
setRemoteBranches(branches);
if (branches.includes('main')) {
setTargetBranch('main');
} else if (branches.includes('master')) {
setTargetBranch('master');
} else if (branches.length > 0) {
setTargetBranch(branches[0]);
}
} catch {
setRemoteBranches(['main', 'master', 'develop']);
}
}, [git, projectPath]);
const checkPermissionsAndFork = useCallback(async () => {
if (!remoteInfo) return;
setIsCheckingPermissions(true);
try {
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
if (!credentials) {
setForkInfo({ needsFork: false });
return;
}
// Simplified permission check - assume fork needed if we get 403/404
// Full implementation would use the helper functions from PullRequestDialog
setForkInfo({ needsFork: false });
} catch {
setForkInfo({ needsFork: false });
} finally {
setIsCheckingPermissions(false);
}
}, [remoteInfo, remoteUrl, settings.credentials]);
useEffect(() => {
if (remoteUrl) {
parseRemoteUrl(remoteUrl);
loadRemoteBranches();
checkPermissionsAndFork();
}
}, [remoteUrl, parseRemoteUrl, loadRemoteBranches, checkPermissionsAndFork]);
const createPullRequest = async () => {
if (!remoteInfo || !currentBranch) return;
if (!title.trim()) {
toast({
title: 'Title required',
description: 'Please enter a title for the pull request',
variant: 'destructive',
});
return;
}
setIsCreating(true);
setError(null);
try {
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
if (!credentials) {
throw new Error('No credentials found. Please add credentials in Settings > Git');
}
// Check if user is on main/master - if so, create a feature branch
let branchToUse = currentBranch;
const isOnDefaultBranch = currentBranch === 'main' || currentBranch === 'master';
if (isOnDefaultBranch) {
console.log(`User is on default branch '${currentBranch}', creating feature branch`);
// Generate branch name from PR title
const sanitizedTitle = title
.toLowerCase()
.replace(/[^a-z0-9\s-]/g, '')
.replace(/\s+/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '')
.substring(0, 50);
const baseName = sanitizedTitle || 'feature';
const featureBranchName = `${baseName}-${Date.now().toString(36).slice(-4)}`;
console.log(`Creating feature branch: ${featureBranchName}`);
try {
// Check for uncommitted changes BEFORE creating branch
const statusMatrix = await git.statusMatrix({ dir: projectPath });
const hasUncommittedChanges = statusMatrix.some(([, head, workdir]) => head !== workdir);
// Create and checkout branch first
await git.branch({
dir: projectPath,
ref: featureBranchName,
checkout: true,
});
branchToUse = featureBranchName;
console.log(`Successfully created and checked out branch: ${featureBranchName}`);
// If there were uncommitted changes, commit them to the new branch
if (hasUncommittedChanges) {
console.log('Committing changes to new branch');
for (const [filepath, , workdir] of statusMatrix) {
if ((workdir as number) === 0) {
await git.remove({ dir: projectPath, filepath });
} else if ((workdir as number) !== 0) {
await git.add({ dir: projectPath, filepath });
}
}
await git.commit({
dir: projectPath,
message: title,
});
console.log('Committed changes to new branch');
}
toast({
title: 'Feature branch created',
description: `Created branch '${featureBranchName}' for your changes`,
});
} catch (branchError) {
console.error('Failed to create feature branch:', branchError);
throw new Error(
`Cannot create PR from '${currentBranch}' branch.\n\n` +
`Failed to create a feature branch automatically.\n` +
`Please create a new branch manually in the Branches tab first.\n\n` +
`Error: ${branchError instanceof Error ? branchError.message : 'Unknown error'}`
);
}
}
// If fork is needed, push the branch first
const headRef = forkInfo.needsFork && forkInfo.forkOwner
? `${forkInfo.forkOwner}:${branchToUse}`
: branchToUse;
console.log('PR head ref will be:', headRef);
console.log('PR base ref will be:', targetBranch);
if (forkInfo.needsFork && forkInfo.forkUrl) {
console.log(`Pushing branch ${branchToUse} to fork ${forkInfo.forkUrl}`);
// Check current remotes
const remotes = await git.listRemotes({ dir: projectPath });
const originRemote = remotes.find(r => r.remote === 'origin');
const forkRemote = remotes.find(r => r.url === forkInfo.forkUrl);
let pushRemote = 'origin';
if (originRemote?.url !== forkInfo.forkUrl) {
if (forkRemote) {
pushRemote = forkRemote.remote;
} else {
await git.addRemote({
dir: projectPath,
remote: 'fork',
url: forkInfo.forkUrl,
});
pushRemote = 'fork';
}
}
try {
await git.push({
dir: projectPath,
remote: pushRemote,
ref: branchToUse,
onAuth: () => credentials,
});
console.log('Successfully pushed to fork');
} catch (pushError) {
const errorMsg = pushError instanceof Error ? pushError.message : 'Unknown error';
throw new Error(
`Failed to push branch '${branchToUse}' to your fork.\n\n` +
`This usually means:\n` +
`1. The branch hasn't been committed yet\n` +
`2. Network/authentication issues\n\n` +
`Error: ${errorMsg}\n\n` +
`Try committing and pushing manually first.`
);
}
}
const url = `${remoteInfo.apiUrl}/repos/${remoteInfo.owner}/${remoteInfo.repo}/pulls`;
const prData = {
title,
body: description,
head: headRef,
base: targetBranch,
maintainer_can_modify: true,
};
console.log('Creating PR with data:', prData);
const response = await fetch(url, {
method: 'POST',
headers: {
'Authorization': `token ${credentials.password}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(prData),
});
if (!response.ok) {
const errorText = await response.text();
console.error('PR creation failed:', errorText);
let error;
try {
error = JSON.parse(errorText);
} catch {
error = { message: errorText || 'Unknown error' };
}
// Extract detailed error messages
let errorMessage = error.message || `API error: ${response.status} - ${response.statusText}`;
if (error.errors && Array.isArray(error.errors)) {
const errorDetails = error.errors.map((e: { message?: string; field?: string; code?: string }) => {
if (e.message) return e.message;
if (e.field && e.code) return `${e.field}: ${e.code}`;
return JSON.stringify(e);
}).join('; ');
errorMessage = `${errorMessage}\n\nDetails: ${errorDetails}`;
}
if (error.documentation_url) {
errorMessage = `${errorMessage}\n\nSee: ${error.documentation_url}`;
}
throw new Error(errorMessage);
}
const data = await response.json();
setCreatedPrUrl(data.html_url);
toast({
title: 'Pull request created',
description: 'Successfully created pull request',
});
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
setError(errorMessage);
toast({
title: 'Failed to create pull request',
description: errorMessage,
variant: 'destructive',
});
} finally {
setIsCreating(false);
}
};
if (!currentBranch) {
return (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
No branch selected. Please select or create a branch first.
</AlertDescription>
</Alert>
);
}
if (createdPrUrl) {
return (
<div className="text-center space-y-4">
<CheckCircle className="h-16 w-16 text-green-600 mx-auto" />
<div>
<h3 className="text-lg font-semibold mb-2">Pull Request Created!</h3>
<p className="text-muted-foreground">
Your pull request has been created successfully
</p>
</div>
<Button
onClick={() => window.open(createdPrUrl, '_blank')}
className="gap-2"
>
View Pull Request
<ExternalLink className="h-4 w-4" />
</Button>
<Button
variant="outline"
onClick={() => {
setCreatedPrUrl(null);
setTitle('');
setDescription('');
}}
>
Create Another
</Button>
</div>
);
}
return (
<div className="space-y-6">
{/* Permission/Fork info */}
{isCheckingPermissions && (
<Alert>
<Loader2 className="h-4 w-4 animate-spin" />
<AlertDescription>Checking repository permissions...</AlertDescription>
</Alert>
)}
{forkInfo.needsFork && forkInfo.forkOwner && (
<Alert>
<AlertDescription>
You don't have push access. Your changes will be pushed to your fork at <strong>{forkInfo.forkOwner}/{forkInfo.forkRepo}</strong>.
</AlertDescription>
</Alert>
)}
{/* Auto-branch creation notice */}
{currentBranch && (currentBranch === 'main' || currentBranch === 'master') && (
<Alert>
<AlertDescription>
You're on the <strong>{currentBranch}</strong> branch. A feature branch will be automatically created from your PR title for this contribution.
</AlertDescription>
</Alert>
)}
{/* Branch comparison */}
<div className="bg-muted/30 rounded-lg p-4">
<div className="flex items-center gap-2 text-sm">
<Badge variant="outline" className="font-mono">
{targetBranch}
</Badge>
<GitCompare className="h-4 w-4 text-muted-foreground" />
<Badge variant="outline" className="font-mono">
{currentBranch}
</Badge>
</div>
<p className="text-xs text-muted-foreground mt-2">
Merge {currentBranch} into {targetBranch}
</p>
{(currentBranch === 'main' || currentBranch === 'master') && (
<p className="text-xs text-blue-600 dark:text-blue-400 mt-1">
Note: A new branch will be created automatically
</p>
)}
</div>
{/* Error alert */}
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription className="whitespace-pre-wrap">{error}</AlertDescription>
</Alert>
)}
{/* Target branch */}
<div className="space-y-2">
<Label htmlFor="target-branch">Target Branch</Label>
<Select value={targetBranch} onValueChange={setTargetBranch} disabled={isCreating}>
<SelectTrigger id="target-branch">
<SelectValue />
</SelectTrigger>
<SelectContent>
{remoteBranches.map((branch) => (
<SelectItem key={branch} value={branch}>
{branch}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Title */}
<div className="space-y-2">
<Label htmlFor="pr-title">Title *</Label>
<Input
id="pr-title"
placeholder="Brief description of your changes"
value={title}
onChange={(e) => setTitle(e.target.value)}
disabled={isCreating}
/>
</div>
{/* Description */}
<div className="space-y-2">
<Label htmlFor="pr-description">Description</Label>
<Textarea
id="pr-description"
placeholder="Provide more details about your changes (supports Markdown)"
value={description}
onChange={(e) => setDescription(e.target.value)}
rows={8}
disabled={isCreating}
className="font-mono text-sm"
/>
</div>
{/* Create button */}
<Button
onClick={createPullRequest}
disabled={isCreating || isCheckingPermissions}
className="w-full"
>
{isCreating ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
{forkInfo.needsFork ? 'Creating fork & PR...' : 'Creating...'}
</>
) : forkInfo.needsFork ? (
<>
<GitFork className="h-4 w-4 mr-2" />
Fork & Create PR
</>
) : (
<>
<GitPullRequest className="h-4 w-4 mr-2" />
Create Pull Request
</>
)}
</Button>
{/* Repository info */}
{remoteInfo && (
<div className="bg-muted/30 rounded-lg p-3">
<div className="text-sm space-y-1">
<div className="flex items-center justify-between">
<span className="text-muted-foreground">Repository:</span>
<span className="font-medium">
{remoteInfo.owner}/{remoteInfo.repo}
</span>
</div>
<div className="flex items-center justify-between">
<span className="text-muted-foreground">Platform:</span>
<Badge variant="outline" className="capitalize">
{remoteInfo.platform}
</Badge>
</div>
</div>
</div>
)}
</div>
);
}
+1
View File
@@ -1,3 +1,4 @@
export { AnnounceRepositoryDialog } from './AnnounceRepositoryDialog';
export { BranchManager } from './BranchManager';
export { CompareView } from './CompareView';
export { DiffViewer } from './DiffViewer';
+11
View File
@@ -5,8 +5,16 @@ export interface GitCredential {
password: string;
}
export interface GitHostToken {
token: string;
username?: string;
scopes?: string[];
createdAt?: number;
}
export interface GitSettings {
credentials: Record<string, GitCredential>; // keyed by origin
hostTokens: Record<string, GitHostToken>; // keyed by host domain (e.g., 'github.com')
name?: string;
email?: string;
coAuthorEnabled?: boolean;
@@ -18,6 +26,9 @@ export interface GitSettingsContextType {
addCredential: (origin: string, credential: GitCredential) => void;
removeCredential: (origin: string) => void;
updateCredential: (origin: string, credential: Partial<GitCredential>) => void;
addHostToken: (host: string, token: GitHostToken) => void;
removeHostToken: (host: string) => void;
updateHostToken: (host: string, token: Partial<GitHostToken>) => void;
isConfigured: boolean;
}
+13 -3
View File
@@ -2,6 +2,7 @@ import { useState, useCallback } from 'react';
import { useGitSettings } from './useGitSettings';
import { useAppContext } from './useAppContext';
import { proxyUrl } from '@/lib/proxyUrl';
import type { GitHostToken } from '@/contexts/GitSettingsContext';
interface GitHubOAuthState {
isLoading: boolean;
@@ -19,7 +20,7 @@ export function useGitHubOAuth() {
isLoading: false,
error: null,
});
const { addCredential } = useGitSettings();
const { addCredential, addHostToken } = useGitSettings();
const { config } = useAppContext();
const { corsProxy } = config;
@@ -161,12 +162,21 @@ export function useGitHubOAuth() {
const userData = await userResponse.json();
// Store the credentials
// Store the credentials (legacy format for existing push/pull operations)
addCredential('https://github.com', {
username: userData.login || 'git',
password: tokenData.access_token,
});
// Also store as host token for PR/contribution operations
const hostToken: GitHostToken = {
token: tokenData.access_token,
username: userData.login,
scopes: tokenData.scope ? tokenData.scope.split(',').map(s => s.trim()) : [],
createdAt: Date.now(),
};
addHostToken('github.com', hostToken);
setState(prev => ({ ...prev, isLoading: false }));
return true;
} catch (error) {
@@ -183,7 +193,7 @@ export function useGitHubOAuth() {
}));
return false;
}
}, [addCredential, corsProxy]);
}, [addCredential, addHostToken, corsProxy]);
return {
...state,
+456
View File
@@ -0,0 +1,456 @@
import { useQuery } from '@tanstack/react-query';
import { useGitSettings } from '@/hooks/useGitSettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostr } from '@nostrify/react';
import { findCredentialsForRepo } from '@/lib/gitCredentials';
import { nip19 } from 'nostr-tools';
import type { NostrEvent } from '@nostrify/nostrify';
export interface PullRequest {
id: number | string;
number: number | string;
title: string;
state: 'open' | 'closed' | 'merged';
author: string;
authorPubkey?: string; // For Nostr patches
url: string;
createdAt: string;
sourceBranch: string;
targetBranch: string;
isOwner?: boolean; // Whether current user is the PR creator
}
interface RemoteInfo {
owner: string;
repo: string;
platform: 'github' | 'gitlab' | 'nostr';
apiUrl: string;
}
function parseRemoteUrl(url: string): RemoteInfo | null {
try {
// Nostr git: nostr://<pubkey>/<repo-id>
if (url.startsWith('nostr://')) {
const match = url.match(/^nostr:\/\/([^/]+)\/(.+)$/);
if (match) {
const pubkeyOrNpub = match[1];
const repo = match[2];
// Convert npub to hex if needed
let owner = pubkeyOrNpub;
if (pubkeyOrNpub.startsWith('npub1')) {
try {
const decoded = nip19.decode(pubkeyOrNpub);
if (decoded.type === 'npub') {
owner = decoded.data; // hex pubkey
}
} catch (err) {
console.error('Failed to decode npub:', err);
return null;
}
}
return { owner, repo, platform: 'nostr', apiUrl: '' };
}
}
// Normalize URL - remove .git suffix if present
const normalizedUrl = url.replace(/\.git$/, '');
let match;
let owner = '';
let repo = '';
let platform: 'github' | 'gitlab' = 'github';
let apiUrl = '';
// GitHub SSH: [email protected]:owner/repo
match = normalizedUrl.match(/git@github\.com:([^/]+)\/(.+)$/);
if (match) {
owner = match[1];
repo = match[2];
platform = 'github';
apiUrl = 'https://api.github.com';
}
// GitHub HTTPS: https://github.com/owner/repo
if (!match) {
match = normalizedUrl.match(/https?:\/\/github\.com\/([^/]+)\/(.+)$/);
if (match) {
owner = match[1];
repo = match[2];
platform = 'github';
apiUrl = 'https://api.github.com';
}
}
// GitLab SSH: [email protected]:owner/repo
if (!match) {
match = normalizedUrl.match(/git@gitlab\.com:([^/]+)\/(.+)$/);
if (match) {
owner = match[1];
repo = match[2];
platform = 'gitlab';
apiUrl = 'https://gitlab.com/api/v4';
}
}
// GitLab HTTPS: https://gitlab.com/owner/repo
if (!match) {
match = normalizedUrl.match(/https?:\/\/gitlab\.com\/([^/]+)\/(.+)$/);
if (match) {
owner = match[1];
repo = match[2];
platform = 'gitlab';
apiUrl = 'https://gitlab.com/api/v4';
}
}
if (owner && repo) {
return { owner, repo, platform, apiUrl };
}
return null;
} catch {
return null;
}
}
async function fetchGitHubPRs(info: RemoteInfo, token?: string, currentUsername?: string, isRepoOwner?: boolean): Promise<PullRequest[]> {
const url = `${info.apiUrl}/repos/${info.owner}/${info.repo}/pulls?state=open`;
const headers: Record<string, string> = {
'Accept': 'application/vnd.github.v3+json',
};
if (token) {
headers['Authorization'] = `token ${token}`;
}
const response = await fetch(url, { headers });
if (!response.ok) {
throw new Error(`Failed to fetch GitHub PRs: ${response.status}`);
}
const data = await response.json();
interface GitHubPR {
id: number;
number: number;
title: string;
state: string;
user: { login: string };
html_url: string;
created_at: string;
head: { ref: string };
base: { ref: string };
body?: string;
}
const allPRs = data.map((pr: GitHubPR) => ({
id: pr.id,
number: pr.number,
title: pr.title,
state: pr.state,
author: pr.user.login,
url: pr.html_url,
createdAt: pr.created_at,
sourceBranch: pr.head.ref,
targetBranch: pr.base.ref,
isOwner: pr.user.login === currentUsername,
}));
// If repo owner, return all PRs. Otherwise, return only user's PRs
if (isRepoOwner) {
return allPRs;
} else if (currentUsername) {
return allPRs.filter((pr: PullRequest) => pr.author === currentUsername);
}
return [];
}
async function fetchGitLabMRs(info: RemoteInfo, token?: string, currentUsername?: string, isRepoOwner?: boolean): Promise<PullRequest[]> {
// Get project ID first
const projectUrl = `${info.apiUrl}/projects/${encodeURIComponent(`${info.owner}/${info.repo}`)}`;
const projectHeaders: Record<string, string> = {};
if (token) {
projectHeaders['PRIVATE-TOKEN'] = token;
}
const projectResponse = await fetch(projectUrl, { headers: projectHeaders });
if (!projectResponse.ok) {
throw new Error(`Failed to fetch GitLab project: ${projectResponse.status}`);
}
const project = await projectResponse.json();
// Fetch merge requests
const mrUrl = `${info.apiUrl}/projects/${project.id}/merge_requests?state=opened`;
const mrHeaders: Record<string, string> = {};
if (token) {
mrHeaders['PRIVATE-TOKEN'] = token;
}
const response = await fetch(mrUrl, { headers: mrHeaders });
if (!response.ok) {
throw new Error(`Failed to fetch GitLab MRs: ${response.status}`);
}
const data = await response.json();
interface GitLabMR {
id: number;
iid: number;
title: string;
state: string;
author: { username: string };
web_url: string;
created_at: string;
source_branch: string;
target_branch: string;
description?: string;
}
const allMRs = data.map((mr: GitLabMR) => ({
id: mr.id,
number: mr.iid,
title: mr.title,
state: mr.state === 'opened' ? 'open' : mr.state,
author: mr.author.username,
url: mr.web_url,
createdAt: mr.created_at,
sourceBranch: mr.source_branch,
targetBranch: mr.target_branch,
isOwner: mr.author.username === currentUsername,
}));
// If repo owner, return all MRs. Otherwise, return only user's MRs
if (isRepoOwner) {
return allMRs;
} else if (currentUsername) {
return allMRs.filter((mr: PullRequest) => mr.author === currentUsername);
}
return [];
}
interface NostrInterface {
query: (filters: unknown[], options?: { signal?: AbortSignal }) => Promise<unknown[]>;
}
async function fetchNostrPatches(
info: RemoteInfo,
currentUserPubkey: string | undefined,
nostr: NostrInterface,
signal: AbortSignal,
isRepoOwner?: boolean
): Promise<PullRequest[]> {
console.log('=== FETCHING NOSTR PATCHES ===');
console.log('Repository:', `${info.owner}/${info.repo}`);
console.log('Current user pubkey:', currentUserPubkey);
console.log('Is repo owner:', isRepoOwner);
if (!currentUserPubkey && !isRepoOwner) {
console.log('No current user, returning empty array');
return [];
}
try {
// Build query filter based on whether user is repo owner or contributor
interface PatchFilter {
kinds: number[];
'#a': string[];
limit: number;
authors?: string[];
}
const filter: PatchFilter = {
kinds: [1617],
'#a': [`30617:${info.owner}:${info.repo}`],
limit: 50,
};
// If not repo owner, only fetch user's own patches
if (!isRepoOwner && currentUserPubkey) {
filter.authors = [currentUserPubkey];
}
console.log('Querying patches with filter:', filter);
const patches = await nostr.query([filter], { signal });
console.log(`Found ${patches.length} patches`);
if (patches.length > 0) {
console.log('Sample patch:', patches[0]);
}
// Query for status events (kind 1630-1633) to determine patch state
const patchIds = patches.map((p: NostrEvent) => p.id);
let statusEvents: NostrEvent[] = [];
if (patchIds.length > 0) {
const events = await nostr.query([
{
kinds: [1630, 1631, 1632, 1633], // Open, Applied/Merged, Closed, Draft
'#e': patchIds,
}
], { signal });
statusEvents = events as NostrEvent[];
console.log(`Found ${statusEvents.length} status events`);
}
// Build a map of patch ID to latest status
const patchStatus = new Map<string, string>();
statusEvents.forEach((statusEvent: NostrEvent) => {
const patchId = statusEvent.tags.find(t => t[0] === 'e' && t[3] === 'root')?.[1];
if (patchId) {
// Status event kinds: 1630=Open, 1631=Applied/Merged, 1632=Closed, 1633=Draft
const status = statusEvent.kind === 1631 ? 'merged' : statusEvent.kind === 1632 ? 'closed' : 'open';
// Only update if we don't have a status or this event is newer
const existing = patchStatus.get(patchId);
if (!existing || statusEvent.created_at > (statusEvents.find(e => e.tags.find(t => t[1] === patchId))?.created_at || 0)) {
patchStatus.set(patchId, status);
}
}
});
// Convert Nostr patches to PullRequest format
const pullRequests: PullRequest[] = patches.map((patch: NostrEvent) => {
const subject = patch.tags.find(t => t[0] === 'subject')?.[1] || 'Untitled patch';
// Get status from status events, default to 'open'
const state = patchStatus.get(patch.id) || 'open';
// Extract source/target branches from content if available
const contentLines = patch.content.split('\n');
let sourceBranch = 'unknown';
let targetBranch = 'main';
for (const line of contentLines) {
if (line.startsWith('From:')) {
sourceBranch = line.replace('From:', '').trim();
}
if (line.startsWith('To:')) {
targetBranch = line.replace('To:', '').trim();
}
}
return {
id: patch.id,
number: patch.id.slice(0, 8),
title: subject,
state: state as 'open' | 'closed' | 'merged',
author: nip19.npubEncode(patch.pubkey),
authorPubkey: patch.pubkey,
url: `nostr:${patch.id}`,
createdAt: new Date(patch.created_at * 1000).toISOString(),
sourceBranch,
targetBranch,
isOwner: patch.pubkey === currentUserPubkey,
};
});
console.log('Converted patches to PRs:', pullRequests);
return pullRequests;
} catch (error) {
console.error('Failed to fetch Nostr patches:', error);
throw error;
}
}
export function usePullRequests(remoteUrl?: string) {
const { settings } = useGitSettings();
const { user } = useCurrentUser();
const { nostr } = useNostr();
return useQuery({
queryKey: ['pull-requests', remoteUrl, user?.pubkey],
queryFn: async ({ signal }) => {
if (!remoteUrl) {
return [];
}
const remoteInfo = parseRemoteUrl(remoteUrl);
if (!remoteInfo) {
throw new Error('Invalid remote URL format');
}
// Determine if current user is the repo owner
let isRepoOwner = false;
let currentUsername: string | undefined;
if (remoteInfo.platform === 'nostr') {
// For Nostr, check if user's pubkey matches repo owner
isRepoOwner = user?.pubkey === remoteInfo.owner;
} else if (remoteInfo.platform === 'github') {
// For GitHub, fetch current username
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
const token = credentials?.password;
if (token) {
try {
const userResponse = await fetch(`${remoteInfo.apiUrl}/user`, {
headers: {
'Authorization': `token ${token}`,
'Accept': 'application/vnd.github.v3+json',
},
});
if (userResponse.ok) {
const userData = await userResponse.json();
currentUsername = userData.login;
isRepoOwner = currentUsername === remoteInfo.owner;
}
} catch (error) {
console.warn('Failed to fetch current GitHub user:', error);
}
}
} else {
// GitLab
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
const token = credentials?.password;
if (token) {
try {
const userResponse = await fetch(`${remoteInfo.apiUrl}/user`, {
headers: {
'PRIVATE-TOKEN': token,
},
});
if (userResponse.ok) {
const userData = await userResponse.json();
currentUsername = userData.username;
isRepoOwner = currentUsername === remoteInfo.owner;
}
} catch (error) {
console.warn('Failed to fetch current GitLab user:', error);
}
}
}
console.log('Fetching PRs - isRepoOwner:', isRepoOwner, 'currentUser:', currentUsername || user?.pubkey);
// Fetch PRs based on platform
if (remoteInfo.platform === 'nostr') {
return await fetchNostrPatches(remoteInfo, user?.pubkey, nostr, signal, isRepoOwner);
} else if (remoteInfo.platform === 'github') {
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
const token = credentials?.password;
return await fetchGitHubPRs(remoteInfo, token, currentUsername, isRepoOwner);
} else {
// GitLab
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
const token = credentials?.password;
return await fetchGitLabMRs(remoteInfo, token, currentUsername, isRepoOwner);
}
},
enabled: !!remoteUrl,
refetchInterval: 60000, // Refetch every minute
staleTime: 30000, // Consider data stale after 30 seconds
});
}
+2
View File
@@ -144,6 +144,7 @@ describe('configUtils', () => {
password: 'token123',
},
},
hostTokens: {},
};
describe('readGitSettings', () => {
@@ -164,6 +165,7 @@ describe('configUtils', () => {
expect(result).toEqual({
credentials: {},
hostTokens: {},
coAuthorEnabled: true,
});
});
+15 -1
View File
@@ -31,8 +31,16 @@ const gitCredentialSchema = z.object({
password: z.string(),
});
const gitHostTokenSchema = z.object({
token: z.string(),
username: z.string().optional(),
scopes: z.array(z.string()).optional(),
createdAt: z.number().optional(),
});
const gitSettingsSchema = z.object({
credentials: z.record(z.string(), gitCredentialSchema),
hostTokens: z.record(z.string(), gitHostTokenSchema).optional(),
name: z.string().optional(),
email: z.string().optional(),
coAuthorEnabled: z.boolean().optional(),
@@ -84,6 +92,7 @@ export async function writeAISettings(fs: JSRuntimeFS, settings: AISettings): Pr
export async function readGitSettings(fs: JSRuntimeFS): Promise<GitSettings> {
const defaultSettings: GitSettings = {
credentials: {},
hostTokens: {},
coAuthorEnabled: true,
};
@@ -91,7 +100,12 @@ export async function readGitSettings(fs: JSRuntimeFS): Promise<GitSettings> {
try {
const content = await fs.readFile(GIT_CONFIG_PATH, 'utf8');
const data = JSON.parse(content);
return gitSettingsSchema.parse(data);
const parsed = gitSettingsSchema.parse(data);
// Ensure hostTokens exists even if not in parsed data
return {
...parsed,
hostTokens: parsed.hostTokens || {},
};
} catch {
return defaultSettings;
}
+303
View File
@@ -0,0 +1,303 @@
import { proxyUrl } from '../proxyUrl';
import type {
GitHostProvider,
GitHostConfig,
GitRepository,
GitFork,
PullRequest,
PullRequestCheck,
CreatePullRequestOptions,
GitHostUser,
} from './types';
interface GitHubPRResponse {
id: number;
number: number;
state: string;
title: string;
body: string;
html_url: string;
created_at: string;
updated_at: string;
user: { login: string };
head: { ref: string; repo: { full_name: string } };
base: { ref: string; repo: { full_name: string } };
mergeable?: boolean;
merged?: boolean;
}
export class GitHubProvider implements GitHostProvider {
readonly name = 'GitHub';
readonly apiBaseUrl = 'https://api.github.com';
private config: GitHostConfig;
private corsProxy?: string;
constructor(config: GitHostConfig, corsProxy?: string) {
this.config = config;
this.corsProxy = corsProxy;
}
private async fetch<T>(path: string, options: RequestInit = {}): Promise<T> {
const url = `${this.apiBaseUrl}${path}`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
...options,
headers: {
'Accept': 'application/vnd.github.v3+json',
'Authorization': `Bearer ${this.config.token}`,
...options.headers,
},
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`GitHub API error (${response.status}): ${errorText}`);
}
return response.json();
}
async getRepository(owner: string, repo: string): Promise<GitRepository> {
interface GitHubRepo {
owner: { login: string };
name: string;
full_name: string;
default_branch: string;
clone_url: string;
html_url: string;
description: string;
private: boolean;
}
const data = await this.fetch<GitHubRepo>(`/repos/${owner}/${repo}`);
return {
owner: data.owner.login,
name: data.name,
fullName: data.full_name,
defaultBranch: data.default_branch,
cloneUrl: data.clone_url,
webUrl: data.html_url,
description: data.description,
isPrivate: data.private,
};
}
async canUserPush(owner: string, repo: string): Promise<boolean> {
try {
interface GitHubRepoWithPermissions {
permissions?: { push?: boolean; admin?: boolean };
}
const data = await this.fetch<GitHubRepoWithPermissions>(`/repos/${owner}/${repo}`);
return data.permissions?.push === true || data.permissions?.admin === true;
} catch {
// If we can't check permissions, assume no push access
return false;
}
}
async createFork(owner: string, repo: string): Promise<GitFork> {
interface GitHubFork {
owner: { login: string };
name: string;
clone_url: string;
html_url: string;
}
const data = await this.fetch<GitHubFork>(`/repos/${owner}/${repo}/forks`, {
method: 'POST',
});
return {
owner: data.owner.login,
name: data.name,
fullName: `${data.owner.login}/${data.name}`,
cloneUrl: data.clone_url,
webUrl: data.html_url,
parentFullName: `${owner}/${repo}`,
};
}
async getFork(upstreamOwner: string, upstreamRepo: string, username: string): Promise<GitFork | null> {
try {
interface GitHubForkCheck {
fork: boolean;
owner: { login: string };
name: string;
full_name: string;
clone_url: string;
html_url: string;
parent?: { full_name: string };
}
// Check if the fork already exists
const data = await this.fetch<GitHubForkCheck>(`/repos/${username}/${upstreamRepo}`);
// Verify it's actually a fork of the upstream repo
if (data.fork && data.parent?.full_name === `${upstreamOwner}/${upstreamRepo}`) {
return {
owner: data.owner.login,
name: data.name,
fullName: data.full_name,
cloneUrl: data.clone_url,
webUrl: data.html_url,
parentFullName: data.parent.full_name,
};
}
return null;
} catch {
return null;
}
}
async waitForFork(
upstreamOwner: string,
upstreamRepo: string,
username: string,
timeout = 30000
): Promise<GitFork> {
const startTime = Date.now();
const pollInterval = 1000;
while (Date.now() - startTime < timeout) {
const fork = await this.getFork(upstreamOwner, upstreamRepo, username);
if (fork) {
return fork;
}
await new Promise(resolve => setTimeout(resolve, pollInterval));
}
throw new Error('Timeout waiting for fork to be created');
}
async createPullRequest(options: CreatePullRequestOptions): Promise<PullRequest> {
const [baseOwner, baseRepo] = options.baseRepo.split('/');
const [headOwner] = options.headRepo.split('/');
// Format head ref for cross-repo PR
const head = headOwner !== baseOwner
? `${headOwner}:${options.headBranch}`
: options.headBranch;
const data = await this.fetch<GitHubPRResponse>(`/repos/${baseOwner}/${baseRepo}/pulls`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
title: options.title,
body: options.body || '',
head,
base: options.baseBranch,
maintainer_can_modify: options.maintainerCanModify ?? true,
}),
});
return this.transformPullRequest(data);
}
async getPullRequest(owner: string, repo: string, number: number): Promise<PullRequest> {
const data = await this.fetch<GitHubPRResponse>(`/repos/${owner}/${repo}/pulls/${number}`);
return this.transformPullRequest(data);
}
async listPullRequests(
owner: string,
repo: string,
state: 'open' | 'closed' | 'all' = 'open'
): Promise<PullRequest[]> {
const data = await this.fetch<GitHubPRResponse[]>(`/repos/${owner}/${repo}/pulls?state=${state}`);
return data.map(pr => this.transformPullRequest(pr));
}
async updatePullRequest(
owner: string,
repo: string,
number: number,
options: { title?: string; body?: string }
): Promise<PullRequest> {
const data = await this.fetch<GitHubPRResponse>(`/repos/${owner}/${repo}/pulls/${number}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(options),
});
return this.transformPullRequest(data);
}
async closePullRequest(owner: string, repo: string, number: number): Promise<PullRequest> {
const data = await this.fetch<GitHubPRResponse>(`/repos/${owner}/${repo}/pulls/${number}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ state: 'closed' }),
});
return this.transformPullRequest(data);
}
async getCurrentUser(): Promise<GitHostUser> {
interface GitHubUser {
login: string;
name: string;
email: string;
avatar_url: string;
}
const data = await this.fetch<GitHubUser>('/user');
return {
username: data.login,
name: data.name,
email: data.email,
avatarUrl: data.avatar_url,
};
}
getCompareUrl(baseRepo: string, baseBranch: string, headRepo: string, headBranch: string): string {
const [headOwner, headRepoName] = headRepo.split('/');
return `https://github.com/${baseRepo}/compare/${baseBranch}...${headOwner}:${headRepoName}:${headBranch}?expand=1`;
}
private transformPullRequest(data: {
id: number;
number: number;
state: string;
title: string;
body: string;
html_url: string;
created_at: string;
updated_at: string;
user: { login: string };
head: { ref: string; repo: { full_name: string } };
base: { ref: string; repo: { full_name: string } };
mergeable?: boolean;
merged?: boolean;
}): PullRequest {
const state: 'open' | 'closed' | 'merged' = data.merged ? 'merged' : data.state as 'open' | 'closed';
return {
number: data.number,
title: data.title,
body: data.body,
state,
headBranch: data.head.ref,
baseBranch: data.base.ref,
headRepo: data.head.repo?.full_name || '',
baseRepo: data.base.repo.full_name,
url: data.html_url,
createdAt: new Date(data.created_at),
updatedAt: new Date(data.updated_at),
author: data.user.login,
mergeable: data.mergeable,
checks: this.transformChecks(data),
};
}
private transformChecks(_data: unknown): PullRequestCheck[] | undefined {
// GitHub's check runs are in a separate API call, so we don't have them here
// This would need a separate API call to /repos/{owner}/{repo}/commits/{ref}/check-runs
return undefined;
}
}
+328
View File
@@ -0,0 +1,328 @@
import { proxyUrl } from '../proxyUrl';
import type {
GitHostProvider,
GitHostConfig,
GitRepository,
GitFork,
PullRequest,
PullRequestCheck,
CreatePullRequestOptions,
GitHostUser,
} from './types';
interface GitLabMRResponse {
id: number;
iid: number;
state: string;
title: string;
description: string;
web_url: string;
created_at: string;
updated_at: string;
author: { username: string };
source_branch: string;
target_branch: string;
source_project_id: number;
target_project_id: number;
merge_status?: string;
merged_at?: string;
pipeline?: {
status: string;
web_url: string;
};
}
export class GitLabProvider implements GitHostProvider {
readonly name = 'GitLab';
readonly apiBaseUrl = 'https://gitlab.com/api/v4';
private config: GitHostConfig;
private corsProxy?: string;
constructor(config: GitHostConfig, corsProxy?: string) {
this.config = config;
this.corsProxy = corsProxy;
}
private async fetch<T>(path: string, options: RequestInit = {}): Promise<T> {
const url = `${this.apiBaseUrl}${path}`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
...options,
headers: {
'Authorization': `Bearer ${this.config.token}`,
'Content-Type': 'application/json',
...options.headers,
},
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`GitLab API error (${response.status}): ${errorText}`);
}
return response.json();
}
private encodeProjectPath(owner: string, repo: string): string {
return encodeURIComponent(`${owner}/${repo}`);
}
async getRepository(owner: string, repo: string): Promise<GitRepository> {
interface GitLabProject {
namespace: { path: string };
path: string;
path_with_namespace: string;
default_branch: string;
http_url_to_repo: string;
web_url: string;
description: string;
visibility: string;
}
const projectPath = this.encodeProjectPath(owner, repo);
const data = await this.fetch<GitLabProject>(`/projects/${projectPath}`);
return {
owner: data.namespace.path,
name: data.path,
fullName: data.path_with_namespace,
defaultBranch: data.default_branch,
cloneUrl: data.http_url_to_repo,
webUrl: data.web_url,
description: data.description,
isPrivate: data.visibility === 'private',
};
}
async canUserPush(owner: string, repo: string): Promise<boolean> {
try {
interface GitLabProjectWithPermissions {
permissions?: {
project_access?: { access_level?: number };
};
}
const projectPath = this.encodeProjectPath(owner, repo);
const data = await this.fetch<GitLabProjectWithPermissions>(`/projects/${projectPath}`);
// GitLab permissions are more granular
// developer (30), maintainer (40), or owner (50) can push
const accessLevel = data.permissions?.project_access?.access_level || 0;
return accessLevel >= 30;
} catch {
return false;
}
}
async createFork(owner: string, repo: string): Promise<GitFork> {
interface GitLabFork {
namespace: { path: string };
path: string;
path_with_namespace: string;
http_url_to_repo: string;
web_url: string;
forked_from_project?: { path_with_namespace: string };
}
const projectPath = this.encodeProjectPath(owner, repo);
const data = await this.fetch<GitLabFork>(`/projects/${projectPath}/fork`, {
method: 'POST',
});
return {
owner: data.namespace.path,
name: data.path,
fullName: data.path_with_namespace,
cloneUrl: data.http_url_to_repo,
webUrl: data.web_url,
parentFullName: data.forked_from_project?.path_with_namespace || `${owner}/${repo}`,
};
}
async getFork(upstreamOwner: string, upstreamRepo: string, username: string): Promise<GitFork | null> {
try {
interface GitLabForkCheck {
namespace: { path: string };
path: string;
path_with_namespace: string;
http_url_to_repo: string;
web_url: string;
forked_from_project?: { path_with_namespace: string };
}
const forkPath = this.encodeProjectPath(username, upstreamRepo);
const data = await this.fetch<GitLabForkCheck>(`/projects/${forkPath}`);
// Check if it's a fork of the upstream
if (data.forked_from_project?.path_with_namespace === `${upstreamOwner}/${upstreamRepo}`) {
return {
owner: data.namespace.path,
name: data.path,
fullName: data.path_with_namespace,
cloneUrl: data.http_url_to_repo,
webUrl: data.web_url,
parentFullName: data.forked_from_project.path_with_namespace,
};
}
return null;
} catch {
return null;
}
}
async waitForFork(
upstreamOwner: string,
upstreamRepo: string,
username: string,
timeout = 30000
): Promise<GitFork> {
const startTime = Date.now();
const pollInterval = 1000;
while (Date.now() - startTime < timeout) {
const fork = await this.getFork(upstreamOwner, upstreamRepo, username);
if (fork) {
return fork;
}
await new Promise(resolve => setTimeout(resolve, pollInterval));
}
throw new Error('Timeout waiting for fork to be created');
}
async createPullRequest(options: CreatePullRequestOptions): Promise<PullRequest> {
// In GitLab, MRs are created on the source (fork) project
const sourceProjectPath = this.encodeProjectPath(options.headRepo.split('/')[0], options.headRepo.split('/')[1]);
const [targetOwner, targetRepo] = options.baseRepo.split('/');
const data = await this.fetch<GitLabMRResponse>(`/projects/${sourceProjectPath}/merge_requests`, {
method: 'POST',
body: JSON.stringify({
source_branch: options.headBranch,
target_branch: options.baseBranch,
target_project_id: this.encodeProjectPath(targetOwner, targetRepo),
title: options.title,
description: options.body || '',
allow_collaboration: options.maintainerCanModify ?? true,
}),
});
return this.transformMergeRequest(data);
}
async getPullRequest(owner: string, repo: string, number: number): Promise<PullRequest> {
const projectPath = this.encodeProjectPath(owner, repo);
const data = await this.fetch<GitLabMRResponse>(`/projects/${projectPath}/merge_requests/${number}`);
return this.transformMergeRequest(data);
}
async listPullRequests(
owner: string,
repo: string,
state: 'open' | 'closed' | 'all' = 'open'
): Promise<PullRequest[]> {
const projectPath = this.encodeProjectPath(owner, repo);
const stateParam = state === 'all' ? 'all' : state === 'open' ? 'opened' : 'closed';
const data = await this.fetch<GitLabMRResponse[]>(`/projects/${projectPath}/merge_requests?state=${stateParam}`);
return data.map(mr => this.transformMergeRequest(mr));
}
async updatePullRequest(
owner: string,
repo: string,
number: number,
options: { title?: string; body?: string }
): Promise<PullRequest> {
const projectPath = this.encodeProjectPath(owner, repo);
const data = await this.fetch<GitLabMRResponse>(`/projects/${projectPath}/merge_requests/${number}`, {
method: 'PUT',
body: JSON.stringify({
title: options.title,
description: options.body,
}),
});
return this.transformMergeRequest(data);
}
async closePullRequest(owner: string, repo: string, number: number): Promise<PullRequest> {
const projectPath = this.encodeProjectPath(owner, repo);
const data = await this.fetch<GitLabMRResponse>(`/projects/${projectPath}/merge_requests/${number}`, {
method: 'PUT',
body: JSON.stringify({
state_event: 'close',
}),
});
return this.transformMergeRequest(data);
}
async getCurrentUser(): Promise<GitHostUser> {
interface GitLabUser {
username: string;
name: string;
email: string;
avatar_url: string;
}
const data = await this.fetch<GitLabUser>('/user');
return {
username: data.username,
name: data.name,
email: data.email,
avatarUrl: data.avatar_url,
};
}
getCompareUrl(baseRepo: string, baseBranch: string, headRepo: string, headBranch: string): string {
const [headOwner, headRepoName] = headRepo.split('/');
return `https://gitlab.com/${baseRepo}/-/merge_requests/new?merge_request[source_branch]=${headBranch}&merge_request[source_project]=${headOwner}/${headRepoName}&merge_request[target_branch]=${baseBranch}`;
}
private transformMergeRequest(data: GitLabMRResponse): PullRequest {
const state = data.state === 'merged' ? 'merged' : data.state === 'opened' ? 'open' : 'closed';
return {
number: data.iid, // GitLab uses iid (internal id) for MRs
title: data.title,
body: data.description,
state,
headBranch: data.source_branch,
baseBranch: data.target_branch,
headRepo: data.source_project_id?.toString() || '',
baseRepo: data.target_project_id?.toString() || '',
url: data.web_url,
createdAt: new Date(data.created_at),
updatedAt: new Date(data.updated_at),
author: data.author.username,
mergeable: data.merge_status === 'can_be_merged',
checks: this.transformPipeline(data),
};
}
private transformPipeline(data: GitLabMRResponse): PullRequestCheck[] | undefined {
if (!data.pipeline) return undefined;
const mapConclusion = (status: string): PullRequestCheck['conclusion'] => {
switch (status) {
case 'success': return 'success';
case 'failed': return 'failure';
case 'canceled': return 'cancelled';
case 'skipped': return 'skipped';
default: return undefined;
}
};
return [{
name: 'Pipeline',
status: data.pipeline.status === 'running' ? 'pending' :
data.pipeline.status === 'success' ? 'success' : 'failure',
conclusion: mapConclusion(data.pipeline.status),
detailsUrl: data.pipeline.web_url,
}];
}
}
+293
View File
@@ -0,0 +1,293 @@
import { proxyUrl } from '../proxyUrl';
import type {
GitHostProvider,
GitHostConfig,
GitRepository,
GitFork,
PullRequest,
CreatePullRequestOptions,
GitHostUser,
} from './types';
interface GiteaPRResponse {
id: number;
number: number;
state: string;
title: string;
body: string;
html_url: string;
created_at: string;
updated_at: string;
user: { login: string };
head: { ref: string; repo: { full_name: string } };
base: { ref: string; repo: { full_name: string } };
mergeable?: boolean;
merged?: boolean;
}
export class GiteaProvider implements GitHostProvider {
readonly name: string;
readonly apiBaseUrl: string;
private config: GitHostConfig;
private corsProxy?: string;
constructor(config: GitHostConfig, apiBaseUrl: string, name = 'Gitea', corsProxy?: string) {
this.config = config;
this.apiBaseUrl = apiBaseUrl;
this.name = name;
this.corsProxy = corsProxy;
}
private async fetch<T>(path: string, options: RequestInit = {}): Promise<T> {
const url = `${this.apiBaseUrl}${path}`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
...options,
headers: {
'Authorization': `token ${this.config.token}`,
'Content-Type': 'application/json',
...options.headers,
},
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`${this.name} API error (${response.status}): ${errorText}`);
}
return response.json();
}
async getRepository(owner: string, repo: string): Promise<GitRepository> {
interface GiteaRepo {
owner: { login: string };
name: string;
full_name: string;
default_branch: string;
clone_url: string;
html_url: string;
description: string;
private: boolean;
}
const data = await this.fetch<GiteaRepo>(`/repos/${owner}/${repo}`);
return {
owner: data.owner.login,
name: data.name,
fullName: data.full_name,
defaultBranch: data.default_branch,
cloneUrl: data.clone_url,
webUrl: data.html_url,
description: data.description,
isPrivate: data.private,
};
}
async canUserPush(owner: string, repo: string): Promise<boolean> {
try {
interface GiteaRepoWithPermissions {
permissions?: { push?: boolean; admin?: boolean };
}
const data = await this.fetch<GiteaRepoWithPermissions>(`/repos/${owner}/${repo}`);
return data.permissions?.push === true || data.permissions?.admin === true;
} catch {
return false;
}
}
async createFork(owner: string, repo: string): Promise<GitFork> {
interface GiteaFork {
owner: { login: string };
name: string;
full_name: string;
clone_url: string;
html_url: string;
parent?: { full_name: string };
}
const data = await this.fetch<GiteaFork>(`/repos/${owner}/${repo}/forks`, {
method: 'POST',
});
return {
owner: data.owner.login,
name: data.name,
fullName: data.full_name,
cloneUrl: data.clone_url,
webUrl: data.html_url,
parentFullName: data.parent?.full_name || `${owner}/${repo}`,
};
}
async getFork(upstreamOwner: string, upstreamRepo: string, username: string): Promise<GitFork | null> {
try {
interface GiteaForkCheck {
fork: boolean;
owner: { login: string };
name: string;
full_name: string;
clone_url: string;
html_url: string;
parent?: { full_name: string };
}
const data = await this.fetch<GiteaForkCheck>(`/repos/${username}/${upstreamRepo}`);
if (data.fork && data.parent?.full_name === `${upstreamOwner}/${upstreamRepo}`) {
return {
owner: data.owner.login,
name: data.name,
fullName: data.full_name,
cloneUrl: data.clone_url,
webUrl: data.html_url,
parentFullName: data.parent.full_name,
};
}
return null;
} catch {
return null;
}
}
async waitForFork(
upstreamOwner: string,
upstreamRepo: string,
username: string,
timeout = 30000
): Promise<GitFork> {
const startTime = Date.now();
const pollInterval = 1000;
while (Date.now() - startTime < timeout) {
const fork = await this.getFork(upstreamOwner, upstreamRepo, username);
if (fork) {
return fork;
}
await new Promise(resolve => setTimeout(resolve, pollInterval));
}
throw new Error('Timeout waiting for fork to be created');
}
async createPullRequest(options: CreatePullRequestOptions): Promise<PullRequest> {
const [baseOwner, baseRepo] = options.baseRepo.split('/');
const [headOwner] = options.headRepo.split('/');
// Format head ref for cross-repo PR
const head = headOwner !== baseOwner
? `${headOwner}:${options.headBranch}`
: options.headBranch;
const data = await this.fetch<GiteaPRResponse>(`/repos/${baseOwner}/${baseRepo}/pulls`, {
method: 'POST',
body: JSON.stringify({
title: options.title,
body: options.body || '',
head,
base: options.baseBranch,
}),
});
return this.transformPullRequest(data);
}
async getPullRequest(owner: string, repo: string, number: number): Promise<PullRequest> {
const data = await this.fetch<GiteaPRResponse>(`/repos/${owner}/${repo}/pulls/${number}`);
return this.transformPullRequest(data);
}
async listPullRequests(
owner: string,
repo: string,
state: 'open' | 'closed' | 'all' = 'open'
): Promise<PullRequest[]> {
const data = await this.fetch<GiteaPRResponse[]>(`/repos/${owner}/${repo}/pulls?state=${state}`);
return data.map(pr => this.transformPullRequest(pr));
}
async updatePullRequest(
owner: string,
repo: string,
number: number,
options: { title?: string; body?: string }
): Promise<PullRequest> {
const data = await this.fetch<GiteaPRResponse>(`/repos/${owner}/${repo}/pulls/${number}`, {
method: 'PATCH',
body: JSON.stringify(options),
});
return this.transformPullRequest(data);
}
async closePullRequest(owner: string, repo: string, number: number): Promise<PullRequest> {
const data = await this.fetch<GiteaPRResponse>(`/repos/${owner}/${repo}/pulls/${number}`, {
method: 'PATCH',
body: JSON.stringify({ state: 'closed' }),
});
return this.transformPullRequest(data);
}
async getCurrentUser(): Promise<GitHostUser> {
interface GiteaUser {
login: string;
full_name: string;
email: string;
avatar_url: string;
}
const data = await this.fetch<GiteaUser>('/user');
return {
username: data.login,
name: data.full_name,
email: data.email,
avatarUrl: data.avatar_url,
};
}
getCompareUrl(baseRepo: string, baseBranch: string, headRepo: string, headBranch: string): string {
const baseUrl = this.apiBaseUrl.replace('/api/v1', '');
const [headOwner, headRepoName] = headRepo.split('/');
return `${baseUrl}/${baseRepo}/compare/${baseBranch}...${headOwner}:${headRepoName}:${headBranch}`;
}
private transformPullRequest(data: {
id: number;
number: number;
state: string;
title: string;
body: string;
html_url: string;
created_at: string;
updated_at: string;
user: { login: string };
head: { ref: string; repo: { full_name: string } };
base: { ref: string; repo: { full_name: string } };
mergeable?: boolean;
merged?: boolean;
}): PullRequest {
const state: 'open' | 'closed' | 'merged' = data.merged ? 'merged' : data.state as 'open' | 'closed';
return {
number: data.number,
title: data.title,
body: data.body,
state,
headBranch: data.head.ref,
baseBranch: data.base.ref,
headRepo: data.head.repo?.full_name || '',
baseRepo: data.base.repo.full_name,
url: data.html_url,
createdAt: new Date(data.created_at),
updatedAt: new Date(data.updated_at),
author: data.user.login,
mergeable: data.mergeable,
};
}
}
+256
View File
@@ -0,0 +1,256 @@
import { NRelay1, type NostrEvent } from '@nostrify/nostrify';
import type {
GitHostProvider,
GitHostConfig,
GitRepository,
GitFork,
PullRequest,
CreatePullRequestOptions,
GitHostUser,
} from './types';
interface NostrSigner {
signEvent: (event: { kind: number; content: string; tags: string[][]; created_at: number }) => Promise<NostrEvent>;
}
/**
* Nostr Git provider implementing NIP-34 (git stuff)
* Enables creating patches/PRs on Nostr git repositories
*/
export class NostrGitProvider implements GitHostProvider {
readonly name = 'Nostr Git';
readonly apiBaseUrl = ''; // Not applicable for Nostr
private relay: NRelay1;
private signer: NostrSigner;
private pubkey: string;
private relayUrls: string[];
constructor(config: GitHostConfig & { signer: NostrSigner; pubkey: string; relayUrls: string[] }) {
this.signer = config.signer;
this.pubkey = config.pubkey;
this.relayUrls = config.relayUrls;
// For Nostr git, we need to publish to the repository's designated relays
// The relay will be set dynamically when we know which repo we're working with
this.relay = new NRelay1('wss://relay.nostr.band'); // Default, will be changed
}
private async queryRepo(owner: string, repo: string): Promise<NostrEvent> {
// Query for repository announcement (kind 30617)
// d tag is the repo-id (usually kebab-case short name)
const events = await this.relay.query([
{
kinds: [30617],
authors: [owner], // owner is the pubkey
'#d': [repo], // repo is the d tag identifier
limit: 1,
}
]) as NostrEvent[];
if (events.length === 0) {
throw new Error(`Repository not found: ${owner}/${repo}`);
}
return events[0];
}
async getRepository(owner: string, repo: string): Promise<GitRepository> {
const event = await this.queryRepo(owner, repo);
const getName = () => event.tags.find((t: string[]) => t[0] === 'name')?.[1] || repo;
const getDescription = () => event.tags.find((t: string[]) => t[0] === 'description')?.[1];
const getWebUrl = () => event.tags.find((t: string[]) => t[0] === 'web')?.[1] || '';
const getCloneUrl = () => event.tags.find((t: string[]) => t[0] === 'clone')?.[1] || '';
const getRelays = () => event.tags.filter((t: string[]) => t[0] === 'relays').map((t: string[]) => t[1]);
// Update relay to use repository's designated relays
const repoRelays = getRelays();
if (repoRelays.length > 0) {
this.relayUrls = repoRelays;
this.relay = new NRelay1(repoRelays[0]);
}
return {
owner,
name: getName(),
fullName: `${owner}/${repo}`,
defaultBranch: 'main', // Nostr git doesn't specify, assume main
cloneUrl: getCloneUrl(),
webUrl: getWebUrl(),
description: getDescription(),
isPrivate: false, // All Nostr repos are public
};
}
async canUserPush(owner: string, repo: string): Promise<boolean> {
// In Nostr git, anyone can submit patches (kind 1617)
// But only maintainers can apply them
// Check if current user is listed as a maintainer
const event = await this.queryRepo(owner, repo);
const maintainers = event.tags
.filter((t: string[]) => t[0] === 'maintainers')
.map((t: string[]) => t[1]);
// Repo owner is always a maintainer
const isMaintainer = owner === this.pubkey || maintainers.includes(this.pubkey);
return isMaintainer;
}
async createFork(owner: string, repo: string): Promise<GitFork> {
// In Nostr git, there's no explicit "fork" concept
// Users submit patches to the original repo
// For compatibility with the PR flow, we return a "virtual fork"
const repoEvent = await this.queryRepo(owner, repo);
const cloneUrl = repoEvent.tags.find((t: string[]) => t[0] === 'clone')?.[1] || '';
const webUrl = repoEvent.tags.find((t: string[]) => t[0] === 'web')?.[1] || '';
// The "fork" is actually just the user's local copy
// We'll use this to track that patches come from the user
return {
owner: this.pubkey,
name: repo,
fullName: `${this.pubkey}/${repo}`,
cloneUrl,
webUrl,
parentFullName: `${owner}/${repo}`,
};
}
async getFork(_upstreamOwner: string, _upstreamRepo: string, _username: string): Promise<GitFork | null> {
// Nostr git doesn't have forks - patches are submitted directly
// Return null to indicate no fork exists
return null;
}
async waitForFork(upstreamOwner: string, upstreamRepo: string, _username: string, _timeout = 10000): Promise<GitFork> {
// Create a virtual fork immediately
return this.createFork(upstreamOwner, upstreamRepo);
}
async createPullRequest(options: CreatePullRequestOptions): Promise<PullRequest> {
// In Nostr git, a "pull request" is a patch event (kind 1617)
// The patch content should be the output of `git format-patch`
const [owner, repo] = options.baseRepo.split('/');
const repoEvent = await this.queryRepo(owner, repo);
// Get the earliest unique commit (euc) for the repository
const euc = repoEvent.tags.find((t: string[]) => t[0] === 'r' && t[2] === 'euc')?.[1];
// Create patch content from the provided body or generate a simple patch description
const patchContent = options.body ||
`Patch proposal: ${options.title}\n\nFrom: ${options.headBranch}\nTo: ${options.baseBranch}`;
// Create patch event (kind 1617)
const patchEvent = await this.signer.signEvent({
kind: 1617,
content: patchContent,
tags: [
['a', `30617:${owner}:${repo}`], // Reference to repository announcement
['p', owner], // Repository owner
['t', 'root'], // Root patch in series
['t', 'root-revision'], // First patch in a revision
['subject', options.title], // Use subject tag for title
// Optional: Add r tag for euc if available
...(euc ? [['r', euc]] : []),
],
created_at: Math.floor(Date.now() / 1000),
});
// Publish to repository's designated relays
await this.relay.event(patchEvent);
// Return a PullRequest-compatible object
return {
number: parseInt(patchEvent.id.slice(0, 8), 16), // Use first 8 chars of event ID as number
title: options.title,
body: options.body,
state: 'open',
headBranch: options.headBranch,
baseBranch: options.baseBranch,
headRepo: options.headRepo,
baseRepo: options.baseRepo,
url: `nostr:${patchEvent.id}`, // Nostr event reference
createdAt: new Date(patchEvent.created_at * 1000),
updatedAt: new Date(patchEvent.created_at * 1000),
author: this.pubkey,
};
}
async getPullRequest(_owner: string, _repo: string, _number: number): Promise<PullRequest> {
// Query for patch event by converting number back to event ID
// This is a limitation - we'd need to store the mapping or query differently
throw new Error('Getting specific patches by number is not yet implemented for Nostr git');
}
async listPullRequests(owner: string, repo: string, _state: 'open' | 'closed' | 'all' = 'open'): Promise<PullRequest[]> {
// Query for patch events (kind 1617) referencing this repository
const events = await this.relay.query([
{
kinds: [1617],
'#a': [`30617:${owner}:${repo}`],
'#t': ['root'], // Only root patches, not replies
limit: 50,
}
]);
// For state filtering, we'd need to check status events (kind 1630-1633)
// For now, return all as 'open'
return events.map(event => ({
number: parseInt(event.id.slice(0, 8), 16),
title: event.tags.find((t: string[]) => t[0] === 'subject')?.[1] || 'Untitled patch',
body: event.content,
state: 'open' as const,
headBranch: 'unknown', // Not stored in NIP-34
baseBranch: 'unknown', // Not stored in NIP-34
headRepo: `${event.pubkey}/${repo}`,
baseRepo: `${owner}/${repo}`,
url: `nostr:${event.id}`,
createdAt: new Date(event.created_at * 1000),
updatedAt: new Date(event.created_at * 1000),
author: event.pubkey,
}));
}
async updatePullRequest(_owner: string, _repo: string, _number: number, _options: { title?: string; body?: string }): Promise<PullRequest> {
// In Nostr git, you can't edit events - you'd create a new revision
throw new Error('Updating patches is not supported - create a new revision instead');
}
async closePullRequest(_owner: string, _repo: string, _number: number): Promise<PullRequest> {
// To close a patch, publish a status event (kind 1632 - Closed)
throw new Error('Closing patches via status events is not yet implemented');
}
async getCurrentUser(): Promise<GitHostUser> {
// In Nostr, we can query the user's profile (kind 0)
const profiles = await this.relay.query([
{
kinds: [0],
authors: [this.pubkey],
limit: 1,
}
]);
if (profiles.length > 0) {
const profile = JSON.parse(profiles[0].content);
return {
username: profile.name || this.pubkey.slice(0, 8),
name: profile.display_name || profile.name,
email: profile.nip05,
avatarUrl: profile.picture,
};
}
return {
username: this.pubkey.slice(0, 8),
};
}
getCompareUrl(_baseRepo: string, _baseBranch: string, _headRepo: string, _headBranch: string): string {
// Nostr git doesn't have a web compare view
// Could potentially link to a Nostr client that displays patches
return '';
}
}
+64
View File
@@ -0,0 +1,64 @@
export * from './types';
export { GitHubProvider } from './GitHubProvider';
export { GitLabProvider } from './GitLabProvider';
export { GiteaProvider } from './GiteaProvider';
export { NostrGitProvider } from './NostrGitProvider';
import { GitHubProvider } from './GitHubProvider';
import { GitLabProvider } from './GitLabProvider';
import { GiteaProvider } from './GiteaProvider';
import { NostrGitProvider } from './NostrGitProvider';
import { detectGitHost } from './types';
import type { GitHostProvider, GitHostConfig } from './types';
import type { NostrEvent } from '@nostrify/nostrify';
/**
* Create a Git host provider instance based on the repository URL
*/
interface NostrSigner {
signEvent: (event: { kind: number; content: string; tags: string[][]; created_at: number }) => Promise<NostrEvent>;
}
export function createGitHostProvider(
url: string,
config: GitHostConfig & { signer?: NostrSigner; pubkey?: string; relayUrls?: string[] },
corsProxy?: string
): GitHostProvider | null {
const hostType = detectGitHost(url);
switch (hostType) {
case 'github':
return new GitHubProvider(config, corsProxy);
case 'gitlab':
return new GitLabProvider(config, corsProxy);
case 'codeberg':
return new GiteaProvider(config, 'https://codeberg.org/api/v1', 'Codeberg', corsProxy);
case 'gitea':
// Extract API URL from repository URL
try {
const parsed = new URL(url.replace(/^git@/, 'https://').replace(/\.git$/, ''));
const apiUrl = `${parsed.protocol}//${parsed.hostname}/api/v1`;
return new GiteaProvider(config, apiUrl, 'Gitea', corsProxy);
} catch {
return null;
}
case 'nostr':
// Nostr git requires signer and pubkey
if (!config.signer || !config.pubkey) {
throw new Error('Nostr git requires signer and pubkey in config');
}
return new NostrGitProvider({
token: config.token,
signer: config.signer,
pubkey: config.pubkey,
relayUrls: config.relayUrls || ['wss://relay.nostr.band'],
});
default:
return null;
}
}
+186
View File
@@ -0,0 +1,186 @@
import { nip19 } from 'nostr-tools';
/**
* Git host provider abstraction for PR/MR operations
*/
export interface GitHostUser {
username: string;
name?: string;
email?: string;
avatarUrl?: string;
}
export interface GitRepository {
owner: string;
name: string;
fullName: string; // e.g. "owner/repo"
defaultBranch: string;
cloneUrl: string;
webUrl: string;
description?: string;
isPrivate: boolean;
}
export interface GitFork {
owner: string;
name: string;
fullName: string;
cloneUrl: string;
webUrl: string;
parentFullName: string; // The upstream repo
}
export interface PullRequest {
number: number;
title: string;
body?: string;
state: 'open' | 'closed' | 'merged';
headBranch: string;
baseBranch: string;
headRepo: string; // Full name of head repo (fork)
baseRepo: string; // Full name of base repo (upstream)
url: string;
createdAt: Date;
updatedAt: Date;
author: string;
mergeable?: boolean;
checks?: PullRequestCheck[];
}
export interface PullRequestCheck {
name: string;
status: 'pending' | 'success' | 'failure' | 'cancelled';
conclusion?: 'success' | 'failure' | 'neutral' | 'cancelled' | 'skipped' | 'timed_out' | 'action_required';
detailsUrl?: string;
}
export interface CreatePullRequestOptions {
title: string;
body?: string;
headBranch: string;
baseBranch: string;
headRepo: string; // For cross-repo PRs (from fork)
baseRepo: string; // The upstream repo
maintainerCanModify?: boolean;
}
export interface GitHostConfig {
token: string;
username?: string;
}
/**
* Abstract interface for Git hosting providers (GitHub, GitLab, Gitea, etc.)
*/
export interface GitHostProvider {
readonly name: string;
readonly apiBaseUrl: string;
// Repository operations
getRepository(owner: string, repo: string): Promise<GitRepository>;
canUserPush(owner: string, repo: string): Promise<boolean>;
// Fork operations
createFork(owner: string, repo: string): Promise<GitFork>;
getFork(upstreamOwner: string, upstreamRepo: string, username: string): Promise<GitFork | null>;
waitForFork(upstreamOwner: string, upstreamRepo: string, username: string, timeout?: number): Promise<GitFork>;
// Pull request operations
createPullRequest(options: CreatePullRequestOptions): Promise<PullRequest>;
getPullRequest(owner: string, repo: string, number: number): Promise<PullRequest>;
listPullRequests(owner: string, repo: string, state?: 'open' | 'closed' | 'all'): Promise<PullRequest[]>;
updatePullRequest(owner: string, repo: string, number: number, options: { title?: string; body?: string }): Promise<PullRequest>;
closePullRequest(owner: string, repo: string, number: number): Promise<PullRequest>;
// User operations
getCurrentUser(): Promise<GitHostUser>;
// Utility
getCompareUrl(baseRepo: string, baseBranch: string, headRepo: string, headBranch: string): string;
}
/**
* Detect Git host from repository URL
*/
export function detectGitHost(url: string): 'github' | 'gitlab' | 'gitea' | 'codeberg' | 'nostr' | 'unknown' {
try {
// Check for Nostr git URLs (format: nostr://<pubkey>/<repo-id>)
if (url.startsWith('nostr://')) {
return 'nostr';
}
const parsed = new URL(url.replace(/^git@/, 'https://').replace(/\.git$/, ''));
const hostname = parsed.hostname.toLowerCase();
if (hostname === 'github.com') return 'github';
if (hostname === 'gitlab.com') return 'gitlab';
if (hostname === 'codeberg.org') return 'codeberg';
if (hostname.includes('gitea')) return 'gitea';
return 'unknown';
} catch {
return 'unknown';
}
}
/**
* Parse repository owner and name from URL
*/
export function parseRepoUrl(url: string): { owner: string; repo: string } | null {
try {
// Handle Nostr git URLs (format: nostr://<pubkey>/<repo-id>)
if (url.startsWith('nostr://')) {
const match = url.match(/^nostr:\/\/([^/]+)\/(.+)$/);
if (match) {
let owner = match[1]; // pubkey in hex or npub
const repo = match[2]; // repo-id (d tag)
// Convert npub to hex if needed
if (owner.startsWith('npub1')) {
try {
const decoded = nip19.decode(owner);
if (decoded.type === 'npub') {
owner = decoded.data;
}
} catch (err) {
console.error('Failed to decode npub:', err);
return null;
}
}
return {
owner, // pubkey in hex
repo, // repo-id (d tag)
};
}
}
// Handle git@ URLs
const normalized = url.replace(/^git@([^:]+):/, 'https://$1/').replace(/\.git$/, '');
const parsed = new URL(normalized);
const parts = parsed.pathname.split('/').filter(Boolean);
if (parts.length >= 2) {
return {
owner: parts[0],
repo: parts[1],
};
}
} catch {
// Invalid URL
}
return null;
}
/**
* Format repository URL for display
*/
export function formatRepoUrl(url: string): string {
const parsed = parseRepoUrl(url);
if (parsed) {
return `${parsed.owner}/${parsed.repo}`;
}
return url;
}
+4
View File
@@ -306,6 +306,7 @@ describe('Git', () => {
const { readGitSettings } = await import('./configUtils');
vi.mocked(readGitSettings).mockResolvedValue({
credentials: {},
hostTokens: {},
coAuthorEnabled: true,
});
@@ -333,6 +334,7 @@ describe('Git', () => {
const { readGitSettings } = await import('./configUtils');
vi.mocked(readGitSettings).mockResolvedValue({
credentials: {},
hostTokens: {},
name: 'John Doe',
email: '[email protected]',
coAuthorEnabled: true,
@@ -362,6 +364,7 @@ describe('Git', () => {
const { readGitSettings } = await import('./configUtils');
vi.mocked(readGitSettings).mockResolvedValue({
credentials: {},
hostTokens: {},
name: 'John Doe',
email: '[email protected]',
coAuthorEnabled: false,
@@ -391,6 +394,7 @@ describe('Git', () => {
const { readGitSettings } = await import('./configUtils');
vi.mocked(readGitSettings).mockResolvedValue({
credentials: {},
hostTokens: {},
name: 'John Doe',
email: '[email protected]',
coAuthorEnabled: true,