mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 08:23:34 +00:00
Preserve HEAD from past repo state / set refs to match repo state on clone
This commit is contained in:
2 files changed
+303
-25
No files matched your search
@@ -918,6 +918,261 @@ describe('Git', () => {
|
||||
expect(mainRefTag![1]).toMatch(/^[0-9a-f]{40}$/);
|
||||
}
|
||||
});
|
||||
|
||||
it('should preserve existing HEAD from state event when pushing', async () => {
|
||||
// Create a mock Git HTTP server
|
||||
const mockServer = new MockGitHttpServer();
|
||||
const mockRepo = createMockRepository();
|
||||
mockServer.addRepository('https://git.example.com/user/repo', mockRepo);
|
||||
|
||||
// Create Nostr repository events with HEAD pointing to develop
|
||||
const repoEvent: NostrEvent = {
|
||||
id: 'repo-event-id',
|
||||
pubkey: testPubkey,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
kind: 30617,
|
||||
tags: [
|
||||
['d', 'my-repo'],
|
||||
['clone', 'https://git.example.com/user/repo.git'],
|
||||
],
|
||||
content: '',
|
||||
sig: 'test-sig',
|
||||
};
|
||||
|
||||
// State event has HEAD pointing to develop, not main
|
||||
// Use the actual commit SHA from the mock repository
|
||||
const stateEvent: NostrEvent = {
|
||||
id: 'state-event-id',
|
||||
pubkey: testPubkey,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
kind: 30618,
|
||||
tags: [
|
||||
['d', 'my-repo'],
|
||||
['HEAD', 'ref: refs/heads/develop'], // Different from local HEAD
|
||||
['refs/heads/main', '2e538da98e06b91e70268817b0fa3f01aeeb003e'],
|
||||
['refs/heads/develop', '2e538da98e06b91e70268817b0fa3f01aeeb003e'], // Use same commit as main for simplicity
|
||||
],
|
||||
content: '',
|
||||
sig: 'test-sig',
|
||||
};
|
||||
|
||||
vi.mocked(nostr.group).mockReturnValue({
|
||||
query: vi.fn(async () => [repoEvent, stateEvent]),
|
||||
} as unknown as ReturnType<NPool['group']>);
|
||||
|
||||
const gitWithMock = new Git({
|
||||
fs,
|
||||
nostr,
|
||||
signer,
|
||||
systemAuthor: { name: 'Test User', email: '[email protected]' },
|
||||
relayList: [{ url: new URL('wss://relay.example.com'), read: true, write: true }],
|
||||
fetch: mockServer.fetch,
|
||||
});
|
||||
|
||||
// Clone the repository
|
||||
// The NIP-34 state event says HEAD points to develop, so that's what we should get
|
||||
await gitWithMock.clone({
|
||||
url: `nostr://${testNpub}/my-repo`,
|
||||
dir: '/preserve-head-repo',
|
||||
singleBranch: true,
|
||||
depth: 1,
|
||||
});
|
||||
|
||||
// Verify local HEAD matches the NIP-34 state event (develop, not main)
|
||||
const localHead = await gitWithMock.resolveRef({
|
||||
dir: '/preserve-head-repo',
|
||||
ref: 'HEAD',
|
||||
depth: 2,
|
||||
});
|
||||
expect(localHead).toBe('refs/heads/develop');
|
||||
|
||||
// Now switch to main branch locally (simulating user changing branches)
|
||||
await gitWithMock.checkout({ dir: '/preserve-head-repo', ref: 'main' });
|
||||
|
||||
// Verify we're now on main
|
||||
const newLocalHead = await gitWithMock.resolveRef({
|
||||
dir: '/preserve-head-repo',
|
||||
ref: 'HEAD',
|
||||
depth: 2,
|
||||
});
|
||||
expect(newLocalHead).toBe('refs/heads/main');
|
||||
|
||||
// Make a local change and commit
|
||||
await fs.mkdir('/preserve-head-repo/.shakespeare');
|
||||
await fs.writeFile('/preserve-head-repo/.shakespeare/git.json', JSON.stringify({ name: 'Test', email: '[email protected]' }));
|
||||
await fs.writeFile('/preserve-head-repo/test.txt', 'test content');
|
||||
await gitWithMock.add({ dir: '/preserve-head-repo', filepath: 'test.txt' });
|
||||
await gitWithMock.commit({ dir: '/preserve-head-repo', message: 'Test commit' });
|
||||
|
||||
// Clear the mock to track new calls
|
||||
vi.mocked(nostr.event).mockClear();
|
||||
|
||||
// Push to Nostr
|
||||
try {
|
||||
await gitWithMock.push({ dir: '/preserve-head-repo', remote: 'origin' });
|
||||
} catch {
|
||||
// Expected to fail on actual git push
|
||||
}
|
||||
|
||||
// Find the published state event
|
||||
const eventCalls = vi.mocked(nostr.event).mock.calls;
|
||||
const publishedStateEvent = eventCalls.find(([event]) => event.kind === 30618)?.[0];
|
||||
expect(publishedStateEvent).toBeDefined();
|
||||
|
||||
if (publishedStateEvent) {
|
||||
// HEAD should be preserved from the original state event (develop), not use local HEAD (main)
|
||||
const headTag = publishedStateEvent.tags.find(([name]: string[]) => name === 'HEAD');
|
||||
expect(headTag).toBeDefined();
|
||||
expect(headTag![1]).toBe('ref: refs/heads/develop');
|
||||
}
|
||||
});
|
||||
|
||||
it('should use local HEAD when no state event exists', async () => {
|
||||
// Create only repo event, no state event
|
||||
const repoEvent: NostrEvent = {
|
||||
id: 'repo-event-id',
|
||||
pubkey: testPubkey,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
kind: 30617,
|
||||
tags: [
|
||||
['d', 'new-repo'],
|
||||
['clone', 'https://git.example.com/user/repo.git'],
|
||||
],
|
||||
content: '',
|
||||
sig: 'test-sig',
|
||||
};
|
||||
|
||||
// No state event initially
|
||||
vi.mocked(nostr.group).mockReturnValue({
|
||||
query: vi.fn(async () => [repoEvent]),
|
||||
} as unknown as ReturnType<NPool['group']>);
|
||||
|
||||
const gitWithMock = new Git({
|
||||
fs,
|
||||
nostr,
|
||||
signer,
|
||||
systemAuthor: { name: 'Test User', email: '[email protected]' },
|
||||
relayList: [{ url: new URL('wss://relay.example.com'), read: true, write: true }],
|
||||
});
|
||||
|
||||
// Initialize a local repository instead of cloning
|
||||
await gitWithMock.init({ dir: '/new-repo', defaultBranch: 'main' });
|
||||
await gitWithMock.addRemote({ dir: '/new-repo', remote: 'origin', url: `nostr://${testNpub}/new-repo` });
|
||||
|
||||
// Make a commit
|
||||
await fs.mkdir('/new-repo/.shakespeare');
|
||||
await fs.writeFile('/new-repo/.shakespeare/git.json', JSON.stringify({ name: 'Test', email: '[email protected]' }));
|
||||
await fs.writeFile('/new-repo/test.txt', 'test');
|
||||
await gitWithMock.add({ dir: '/new-repo', filepath: 'test.txt' });
|
||||
await gitWithMock.commit({ dir: '/new-repo', message: 'Test' });
|
||||
|
||||
// Clear the mock to track new calls
|
||||
vi.mocked(nostr.event).mockClear();
|
||||
|
||||
// Push to Nostr
|
||||
try {
|
||||
await gitWithMock.push({ dir: '/new-repo', remote: 'origin' });
|
||||
} catch {
|
||||
// Expected to fail on actual git push
|
||||
}
|
||||
|
||||
// Find the published state event
|
||||
const eventCalls = vi.mocked(nostr.event).mock.calls;
|
||||
const publishedStateEvent = eventCalls.find(([event]) => event.kind === 30618)?.[0];
|
||||
expect(publishedStateEvent).toBeDefined();
|
||||
|
||||
if (publishedStateEvent) {
|
||||
// HEAD should use local HEAD since no state event existed
|
||||
const headTag = publishedStateEvent.tags.find(([name]: string[]) => name === 'HEAD');
|
||||
expect(headTag).toBeDefined();
|
||||
expect(headTag![1]).toBe('ref: refs/heads/main');
|
||||
}
|
||||
});
|
||||
|
||||
it('should use local HEAD when state event exists but has no HEAD tag', async () => {
|
||||
// Create a mock Git HTTP server
|
||||
const mockServer = new MockGitHttpServer();
|
||||
const mockRepo = createMockRepository();
|
||||
mockServer.addRepository('https://git.example.com/user/repo', mockRepo);
|
||||
|
||||
// Create repo and state event, but state has no HEAD tag
|
||||
const repoEvent: NostrEvent = {
|
||||
id: 'repo-event-id',
|
||||
pubkey: testPubkey,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
kind: 30617,
|
||||
tags: [
|
||||
['d', 'no-head-repo'],
|
||||
['clone', 'https://git.example.com/user/repo.git'],
|
||||
],
|
||||
content: '',
|
||||
sig: 'test-sig',
|
||||
};
|
||||
|
||||
// State event without HEAD tag
|
||||
const stateEvent: NostrEvent = {
|
||||
id: 'state-event-id',
|
||||
pubkey: testPubkey,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
kind: 30618,
|
||||
tags: [
|
||||
['d', 'no-head-repo'],
|
||||
['refs/heads/main', '2e538da98e06b91e70268817b0fa3f01aeeb003e'],
|
||||
],
|
||||
content: '',
|
||||
sig: 'test-sig',
|
||||
};
|
||||
|
||||
vi.mocked(nostr.group).mockReturnValue({
|
||||
query: vi.fn(async () => [repoEvent, stateEvent]),
|
||||
} as unknown as ReturnType<NPool['group']>);
|
||||
|
||||
const gitWithMock = new Git({
|
||||
fs,
|
||||
nostr,
|
||||
signer,
|
||||
systemAuthor: { name: 'Test User', email: '[email protected]' },
|
||||
relayList: [{ url: new URL('wss://relay.example.com'), read: true, write: true }],
|
||||
fetch: mockServer.fetch,
|
||||
});
|
||||
|
||||
// Clone the repository
|
||||
await gitWithMock.clone({
|
||||
url: `nostr://${testNpub}/no-head-repo`,
|
||||
dir: '/no-head-repo',
|
||||
singleBranch: true,
|
||||
depth: 1,
|
||||
});
|
||||
|
||||
// Make a local change
|
||||
await fs.mkdir('/no-head-repo/.shakespeare');
|
||||
await fs.writeFile('/no-head-repo/.shakespeare/git.json', JSON.stringify({ name: 'Test', email: '[email protected]' }));
|
||||
await fs.writeFile('/no-head-repo/test.txt', 'test');
|
||||
await gitWithMock.add({ dir: '/no-head-repo', filepath: 'test.txt' });
|
||||
await gitWithMock.commit({ dir: '/no-head-repo', message: 'Test' });
|
||||
|
||||
// Clear the mock to track new calls
|
||||
vi.mocked(nostr.event).mockClear();
|
||||
|
||||
// Push to Nostr
|
||||
try {
|
||||
await gitWithMock.push({ dir: '/no-head-repo', remote: 'origin' });
|
||||
} catch {
|
||||
// Expected to fail on actual git push
|
||||
}
|
||||
|
||||
// Find the published state event
|
||||
const eventCalls = vi.mocked(nostr.event).mock.calls;
|
||||
const publishedStateEvent = eventCalls.find(([event]) => event.kind === 30618)?.[0];
|
||||
expect(publishedStateEvent).toBeDefined();
|
||||
|
||||
if (publishedStateEvent) {
|
||||
// HEAD should use local HEAD since state event had no HEAD tag
|
||||
const headTag = publishedStateEvent.tags.find(([name]: string[]) => name === 'HEAD');
|
||||
expect(headTag).toBeDefined();
|
||||
expect(headTag![1]).toBe('ref: refs/heads/main');
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
+48
-25
@@ -729,19 +729,33 @@ export class Git {
|
||||
remote,
|
||||
});
|
||||
|
||||
// The clone already set up local refs correctly, but we need to ensure
|
||||
// HEAD matches the Nostr state if it's a symbolic ref
|
||||
const headTag = state.tags.find(([name]) => name === 'HEAD');
|
||||
if (headTag && headTag[1].startsWith('ref: ')) {
|
||||
const headTarget = headTag[1].substring(5);
|
||||
await git.writeRef({
|
||||
fs: this.fs,
|
||||
dir: options.dir,
|
||||
ref: 'HEAD',
|
||||
value: headTarget,
|
||||
symbolic: true,
|
||||
force: true,
|
||||
});
|
||||
// The NIP-34 state event is the source of truth for repository state
|
||||
// Set local refs to match the state event
|
||||
for (const [name, val] of state.tags) {
|
||||
if (name === 'HEAD') {
|
||||
// Handle HEAD specially - it can be symbolic or direct
|
||||
const symbolic = val.startsWith('ref: ');
|
||||
const value = symbolic ? val.substring(5) : val;
|
||||
await git.writeRef({
|
||||
fs: this.fs,
|
||||
dir: options.dir,
|
||||
ref: 'HEAD',
|
||||
value,
|
||||
symbolic,
|
||||
force: true,
|
||||
});
|
||||
} else if (name.startsWith('refs/heads/')) {
|
||||
// Set local branch refs to match state event
|
||||
await git.writeRef({
|
||||
fs: this.fs,
|
||||
dir: options.dir,
|
||||
ref: name,
|
||||
value: val,
|
||||
force: true,
|
||||
});
|
||||
}
|
||||
// Note: We don't set refs/tags/ here as those are typically immutable
|
||||
// and should come from the clone/fetch operations
|
||||
}
|
||||
}
|
||||
|
||||
@@ -876,7 +890,7 @@ export class Git {
|
||||
const dir = options.dir || '.';
|
||||
|
||||
// Fetch the current repo events from Nostr
|
||||
const { repo } = await this.fetchRepoEvents(nostrURI);
|
||||
const { repo, state } = await this.fetchRepoEvents(nostrURI);
|
||||
|
||||
if (!repo) {
|
||||
throw new Error('Repository not found on Nostr network');
|
||||
@@ -893,18 +907,27 @@ export class Git {
|
||||
];
|
||||
|
||||
// Add HEAD ref
|
||||
const headRef = await git.resolveRef({
|
||||
fs: this.fs,
|
||||
dir,
|
||||
ref: 'HEAD',
|
||||
depth: 2,
|
||||
});
|
||||
|
||||
// Check if HEAD is a symbolic ref
|
||||
if (headRef.startsWith('refs/')) {
|
||||
stateTags.push(['HEAD', `ref: ${headRef}`]);
|
||||
// If a HEAD is already defined in the state event, preserve it unchanged
|
||||
// Otherwise, use the local repository's HEAD
|
||||
const existingHeadTag = state?.tags.find(([name]) => name === 'HEAD');
|
||||
if (existingHeadTag) {
|
||||
// Preserve the existing HEAD from the state event
|
||||
stateTags.push(existingHeadTag);
|
||||
} else {
|
||||
stateTags.push(['HEAD', headRef]);
|
||||
// No existing HEAD, use local HEAD
|
||||
const headRef = await git.resolveRef({
|
||||
fs: this.fs,
|
||||
dir,
|
||||
ref: 'HEAD',
|
||||
depth: 2,
|
||||
});
|
||||
|
||||
// Check if HEAD is a symbolic ref
|
||||
if (headRef.startsWith('refs/')) {
|
||||
stateTags.push(['HEAD', `ref: ${headRef}`]);
|
||||
} else {
|
||||
stateTags.push(['HEAD', headRef]);
|
||||
}
|
||||
}
|
||||
|
||||
// Collect all branch refs
|
||||
|
||||
Reference in new issue
Block a user