Fix git push handling of --force for nostr remotes

This commit is contained in:
DanConwayDev committed 2025-10-30 09:00:44 +00:00
1 parent 8f93a1b55a
commit 60f42c4d40
2 files changed
+376 -3

No files matched your search

+311 -1
View File
@@ -1,4 +1,4 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { Git } from './git';
import git from 'isomorphic-git';
import type { NPool } from '@nostrify/nostrify';
@@ -428,4 +428,314 @@ describe('Git', () => {
});
});
});
describe('Nostr push with fast-forward checking', () => {
const mockSigner = {
signEvent: vi.fn().mockResolvedValue({
id: 'state123',
pubkey: 'abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab',
kind: 30618,
content: '',
tags: [],
created_at: Date.now(),
sig: 'signature',
}),
getPublicKey: vi.fn().mockResolvedValue('abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab'),
};
beforeEach(() => {
// Mock timers to avoid waiting 5 seconds
vi.useFakeTimers();
mockGit.push = vi.fn().mockResolvedValue(undefined);
mockGit.listRemotes = vi.fn().mockResolvedValue([
{ remote: 'origin', url: 'nostr://npub1abc123/my-repo' }
]);
mockGit.listRefs = vi.fn().mockResolvedValue(['refs/heads/main']);
mockGit.resolveRef = vi.fn().mockResolvedValue('localcommit123');
mockGit.isDescendent = vi.fn().mockResolvedValue(true);
mockGit.currentBranch = vi.fn().mockResolvedValue('main');
mockGit.readCommit = vi.fn().mockResolvedValue({});
// Mock nip19 decode
vi.mocked(nip19.decode).mockReturnValue({
type: 'npub',
data: 'abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab'
});
vi.mocked(nip19.naddrEncode).mockReturnValue('naddr1...');
// Mock Nostr query to return repository and state events
const mockRelay = {
query: vi.fn().mockResolvedValue([
{
id: 'repo123',
pubkey: 'abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab',
kind: 30617,
content: '',
tags: [
['d', 'my-repo'],
['clone', 'https://github.com/user/repo.git'],
],
created_at: Date.now(),
sig: 'signature',
},
{
id: 'state123',
pubkey: 'abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab',
kind: 30618,
content: '',
tags: [
['d', 'my-repo'],
['refs/heads/main', 'remotecommit456'],
['HEAD', 'ref: refs/heads/main'],
],
created_at: Date.now(),
sig: 'signature',
},
]),
};
nostr.group = vi.fn().mockReturnValue(mockRelay);
nostr.relay = vi.fn().mockReturnValue(mockRelay);
nostr.event = vi.fn().mockResolvedValue(undefined);
mockGit.setConfig = vi.fn().mockResolvedValue(undefined);
});
afterEach(() => {
vi.useRealTimers();
});
it('rejects non-fast-forward push without --force flag', async () => {
// Mock isDescendent to return false (not a fast-forward)
mockGit.isDescendent = vi.fn().mockResolvedValue(false);
await expect(
gitInstance.push({
dir: '/test',
remote: 'origin',
ref: 'main',
force: false,
signer: mockSigner,
})
).rejects.toThrow('Updates were rejected');
});
it('allows non-fast-forward push with --force flag', async () => {
// Mock isDescendent to return false (not a fast-forward)
mockGit.isDescendent = vi.fn().mockResolvedValue(false);
// Should not throw with force flag
const pushPromise = gitInstance.push({
dir: '/test',
remote: 'origin',
ref: 'main',
force: true,
signer: mockSigner,
});
// Advance timers to skip the 5 second wait
await vi.advanceTimersByTimeAsync(5000);
await pushPromise;
// Should have attempted to push to the Git remote
expect(mockGit.push).toHaveBeenCalled();
});
it('allows fast-forward push without --force flag', async () => {
// Mock isDescendent to return true (is a fast-forward)
mockGit.isDescendent = vi.fn().mockResolvedValue(true);
// Should not throw
const pushPromise = gitInstance.push({
dir: '/test',
remote: 'origin',
ref: 'main',
force: false,
signer: mockSigner,
});
// Advance timers to skip the 5 second wait
await vi.advanceTimersByTimeAsync(5000);
await pushPromise;
// Should have attempted to push to the Git remote
expect(mockGit.push).toHaveBeenCalled();
});
it('returns early when commits are already up-to-date', async () => {
// Mock resolveRef to return the same commit as remote
mockGit.resolveRef = vi.fn().mockResolvedValue('remotecommit456');
await gitInstance.push({
dir: '/test',
remote: 'origin',
ref: 'main',
force: false,
signer: mockSigner,
});
// Should not have attempted to push (already up-to-date)
expect(mockGit.push).not.toHaveBeenCalled();
});
it('skips fast-forward check when no state event exists', async () => {
// Mock Nostr query to return only repo event (no state)
const mockRelay = {
query: vi.fn().mockResolvedValue([
{
id: 'repo123',
pubkey: 'abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab',
kind: 30617,
content: '',
tags: [
['d', 'my-repo'],
['clone', 'https://github.com/user/repo.git'],
],
created_at: Date.now(),
sig: 'signature',
},
]),
};
nostr.group = vi.fn().mockReturnValue(mockRelay);
nostr.relay = vi.fn().mockReturnValue(mockRelay);
// Should not throw even if not a fast-forward (no state to check against)
const pushPromise = gitInstance.push({
dir: '/test',
remote: 'origin',
ref: 'main',
force: false,
signer: mockSigner,
});
// Advance timers to skip the 5 second wait
await vi.advanceTimersByTimeAsync(5000);
await pushPromise;
// Should have attempted to push
expect(mockGit.push).toHaveBeenCalled();
});
it('skips fast-forward check when state has no matching ref', async () => {
// Mock Nostr query to return state with different ref
const mockRelay = {
query: vi.fn().mockResolvedValue([
{
id: 'repo123',
pubkey: 'abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab',
kind: 30617,
content: '',
tags: [
['d', 'my-repo'],
['clone', 'https://github.com/user/repo.git'],
],
created_at: Date.now(),
sig: 'signature',
},
{
id: 'state123',
pubkey: 'abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab',
kind: 30618,
content: '',
tags: [
['d', 'my-repo'],
['refs/heads/develop', 'othercommit789'],
['HEAD', 'ref: refs/heads/develop'],
],
created_at: Date.now(),
sig: 'signature',
},
]),
};
nostr.group = vi.fn().mockReturnValue(mockRelay);
nostr.relay = vi.fn().mockReturnValue(mockRelay);
// Should not throw (no matching ref in state)
const pushPromise = gitInstance.push({
dir: '/test',
remote: 'origin',
ref: 'main',
force: false,
signer: mockSigner,
});
// Advance timers to skip the 5 second wait
await vi.advanceTimersByTimeAsync(5000);
await pushPromise;
// Should have attempted to push
expect(mockGit.push).toHaveBeenCalled();
});
it('publishes new state event to Nostr relays', async () => {
mockGit.isDescendent = vi.fn().mockResolvedValue(true);
const mockGroupRelay = {
query: vi.fn().mockResolvedValue([
{
id: 'repo123',
pubkey: 'abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab',
kind: 30617,
content: '',
tags: [
['d', 'my-repo'],
['clone', 'https://github.com/user/repo.git'],
],
created_at: Date.now(),
sig: 'signature',
},
{
id: 'state123',
pubkey: 'abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab',
kind: 30618,
content: '',
tags: [
['d', 'my-repo'],
['refs/heads/main', 'remotecommit456'],
['HEAD', 'ref: refs/heads/main'],
],
created_at: Date.now(),
sig: 'signature',
},
]),
event: vi.fn().mockResolvedValue(undefined),
};
nostr.group = vi.fn().mockReturnValue(mockGroupRelay);
const pushPromise = gitInstance.push({
dir: '/test',
remote: 'origin',
ref: 'main',
force: false,
signer: mockSigner,
});
// Advance timers to skip the 5 second wait
await vi.advanceTimersByTimeAsync(5000);
await pushPromise;
// Should have signed a new state event
expect(mockSigner.signEvent).toHaveBeenCalledWith(
expect.objectContaining({
kind: 30618,
tags: expect.arrayContaining([
['d', 'my-repo'],
]),
})
);
// Should have published the state event to Nostr via group
expect(mockGroupRelay.event).toHaveBeenCalled();
});
});
});
+65 -2
View File
@@ -1363,6 +1363,9 @@ export class Git {
private async nostrPush(nostrUrl: string, options: Omit<Parameters<typeof git.push>[0], 'fs' | 'http' | 'corsProxy'> & { signer: NostrSigner }) {
const { signer, ...gitPushOptions } = options;
const dir = options.dir || '.';
const ref = options.ref || 'HEAD';
const remoteRef = options.remoteRef || ref;
const force = options.force || false;
// Parse the Nostr URI
const nostrURI = await this.parseNostrCloneURI(nostrUrl);
@@ -1372,12 +1375,72 @@ export class Git {
console.log(`Pushing to Nostr repository: ${nostrUrl}`);
// Fetch the repository announcement to get relay information and clone URLs
const { repo } = await this.fetchNostrRepo(nostrURI);
// Fetch the repository announcement and state to get relay information and current remote state
const { repo, state } = await this.fetchNostrRepo(nostrURI);
if (!repo) {
throw new Error('Repository announcement not found on Nostr network');
}
// If we have a state event and --force was not used, check if fast-forward is possible.
// we cant let the server do this as we publish the state update first
if (state && !force) {
const stateInfo = this.extractRepositoryState(state);
const remoteRefName = remoteRef.startsWith('refs/') ? remoteRef : `refs/heads/${remoteRef}`;
const remoteCommit = stateInfo.refs[remoteRefName];
if (remoteCommit) {
console.log(`Checking fast-forward: remote ${remoteRefName} is at ${remoteCommit}`);
// Get the local commit we're trying to push
let localCommit: string;
try {
localCommit = await git.resolveRef({
fs: this.fs,
dir,
ref,
});
} catch (error) {
throw new Error(`Failed to resolve local ref ${ref}: ${error}`);
}
console.log(`Local ref ${ref} is at ${localCommit}`);
// If commits are the same, we're already up to date
if (localCommit === remoteCommit) {
console.log('Everything up-to-date');
return;
}
// Check if local commit is a descendant of remote commit (fast-forward possible)
let canFastForward: boolean;
try {
canFastForward = await git.isDescendent({
fs: this.fs,
dir,
oid: localCommit,
ancestor: remoteCommit,
});
} catch (error) {
// If we can't determine ancestry, allow the push to proceed
// (the Git server will do its own validation)
console.warn(`Could not determine if fast-forward is possible: ${error}`);
canFastForward = true;
}
if (!canFastForward) {
throw new Error(
`Updates were rejected because the remote contains work that you do\n` +
`not have locally. This is usually caused by another repository pushing\n` +
`to the same ref. You may want to first integrate the remote changes\n` +
`(e.g., 'git pull ...') before pushing again.\n` +
`See the 'Note about fast-forwards' in 'git push --help' for details.`
);
}
console.log('✓ Fast-forward check passed');
}
}
// Extract relay URLs and clone URLs from the repository announcement
const relayUrls: string[] = [];