Move git sync operations directly into GitSyncProvider

This commit is contained in:
Alex Gleason committed 2025-12-29 17:57:16 -06:00
1 parent b7081ea64a
commit 02cc069ff8
4 files changed
+196 -138

No files matched your search

+149 -3
View File
@@ -1,8 +1,15 @@
import { useState, useCallback, ReactNode } from 'react';
import { GitSyncContext, GitOperation, GitSyncState } from '@/contexts/GitSyncContext';
import { useState, useCallback, ReactNode, useRef } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { GitSyncContext, GitOperation, GitSyncState, FetchResult } from '@/contexts/GitSyncContext';
import { useGit } from '@/hooks/useGit';
export function GitSyncProvider({ children }: { children: ReactNode }) {
const [syncStates, setSyncStates] = useState<Map<string, GitSyncState>>(new Map());
const queryClient = useQueryClient();
const { git } = useGit();
// Track active operations to prevent concurrent operations on the same directory
const activeOperations = useRef<Map<string, Promise<unknown>>>(new Map());
const startOperation = useCallback((dir: string, operation: GitOperation) => {
setSyncStates(prev => {
@@ -68,8 +75,147 @@ export function GitSyncProvider({ children }: { children: ReactNode }) {
return syncStates.get(dir)?.error;
}, [syncStates]);
// Helper to invalidate git status queries
const invalidateGitStatus = useCallback((dir: string) => {
const projectId = dir.split('/').pop();
if (projectId) {
queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
}
}, [queryClient]);
// Helper to ensure only one operation runs at a time per directory
const withOperationLock = useCallback(async <T,>(
dir: string,
operation: GitOperation,
fn: () => Promise<T>
): Promise<T> => {
// Check if there's already an active operation for this directory
const existingOp = activeOperations.current.get(dir);
if (existingOp) {
// Wait for the existing operation to complete first
await existingOp.catch(() => {
// Ignore errors from previous operation
});
}
// Start the new operation
startOperation(dir, operation);
setError(dir, null);
const promise = fn()
.then(result => {
endOperation(dir);
activeOperations.current.delete(dir);
return result;
})
.catch(err => {
const error = err instanceof Error ? err : new Error(`${operation} failed`);
endOperation(dir, error);
setError(dir, error);
activeOperations.current.delete(dir);
throw error;
});
activeOperations.current.set(dir, promise);
return promise;
}, [startOperation, endOperation, setError]);
// Git operation: fetch
const fetch = useCallback(async (dir: string, remote = 'origin'): Promise<FetchResult> => {
return withOperationLock(dir, 'fetch', async () => {
const fetchResult = await git.fetch({ dir, remote });
invalidateGitStatus(dir);
return fetchResult;
});
}, [git, withOperationLock, invalidateGitStatus]);
// Git operation: pull
const pull = useCallback(async (dir: string, ref: string, _remote = 'origin'): Promise<void> => {
return withOperationLock(dir, 'pull', async () => {
await git.pull({ dir, ref, singleBranch: true });
invalidateGitStatus(dir);
});
}, [git, withOperationLock, invalidateGitStatus]);
// Git operation: push
const push = useCallback(async (dir: string, ref: string, remote = 'origin', force = false): Promise<void> => {
return withOperationLock(dir, 'push', async () => {
await git.push({ dir, remote, ref, force });
invalidateGitStatus(dir);
});
}, [git, withOperationLock, invalidateGitStatus]);
// Git operation: sync (pull then push)
const sync = useCallback(async (dir: string, ref: string, remote = 'origin'): Promise<void> => {
return withOperationLock(dir, 'pull', async () => {
// Pull first
await git.pull({ dir, ref, singleBranch: true });
// Then push (update operation type)
startOperation(dir, 'push');
await git.push({ dir, remote, ref });
invalidateGitStatus(dir);
});
}, [git, withOperationLock, invalidateGitStatus, startOperation]);
// Git operation: force pull
const forcePull = useCallback(async (dir: string, ref: string, remote = 'origin'): Promise<void> => {
return withOperationLock(dir, 'pull', async () => {
// Step 1: Fetch latest changes from remote
await git.fetch({
dir,
remote,
ref,
singleBranch: true,
});
// Step 2: Get the remote commit SHA
const remoteRef = `refs/remotes/${remote}/${ref}`;
const remoteSha = await git.resolveRef({ dir, ref: remoteRef });
// Step 3: Force update the current branch to point to remote
await git.writeRef({
dir,
ref: `refs/heads/${ref}`,
value: remoteSha,
force: true,
});
// Step 4: Force checkout all files (overwrite local changes)
await git.checkout({
dir,
ref,
force: true,
});
invalidateGitStatus(dir);
});
}, [git, withOperationLock, invalidateGitStatus]);
// Git operation: force push
const forcePush = useCallback(async (dir: string, ref: string, remote = 'origin'): Promise<void> => {
return withOperationLock(dir, 'push', async () => {
await git.push({ dir, remote, ref, force: true });
invalidateGitStatus(dir);
});
}, [git, withOperationLock, invalidateGitStatus]);
return (
<GitSyncContext.Provider value={{ syncStates, startOperation, endOperation, setError, getState, getError }}>
<GitSyncContext.Provider value={{
syncStates,
getState,
getError,
fetch,
pull,
push,
sync,
forcePull,
forcePush,
startOperation,
endOperation,
setError,
}}>
{children}
</GitSyncContext.Provider>
);
+16 -88
View File
@@ -45,7 +45,7 @@ export function SyncStep({ projectId, remoteUrl }: SyncStepProps) {
const { git } = useGit();
const { projectsPath } = useFSPaths();
const { config } = useAppContext();
const { getState, getError, startOperation, endOperation, setError: setGlobalError } = useGitSyncState();
const gitSync = useGitSyncState();
const dir = `${projectsPath}/${projectId}`;
const ref = gitStatus?.currentBranch || 'main';
@@ -54,30 +54,26 @@ export function SyncStep({ projectId, remoteUrl }: SyncStepProps) {
const { autosync, isLoading: isLoadingAutosync, setAutosync } = useGitAutosync(dir);
// Get unified sync state and error
const syncState = getState(dir);
const syncState = gitSync.getState(dir);
const isSyncing = syncState?.isActive || false;
const currentOperation = syncState?.operation || null;
const error = getError(dir) || null;
// Helper to set error for this directory
const setError = useCallback((err: Error | null) => {
setGlobalError(dir, err);
}, [dir, setGlobalError]);
const error = gitSync.getError(dir) || null;
const hasRemoteChanges = gitStatus?.remoteBranchExists && ((gitStatus?.ahead ?? 0) > 0 || (gitStatus?.behind ?? 0) > 0);
const commitsAhead = gitStatus?.ahead ?? 0;
const commitsBehind = gitStatus?.behind ?? 0;
// Generic git operation handler
// Helper to set error for this directory
const setError = useCallback((err: Error | null) => {
gitSync.setError(dir, err);
}, [dir, gitSync]);
// Generic git operation handler with success feedback
const executeGitOperation = useCallback(async (
operation: 'pull' | 'push' | 'force-pull' | 'force-push',
action: () => Promise<void>
) => {
if (!remoteUrl) return;
const gitOp = operation === 'force-pull' ? 'pull' : operation === 'force-push' ? 'push' : operation;
startOperation(dir, gitOp);
setError(null);
setSyncSuccess(false);
@@ -87,98 +83,30 @@ export function SyncStep({ projectId, remoteUrl }: SyncStepProps) {
// Show success feedback
setSyncSuccess(true);
setTimeout(() => setSyncSuccess(false), 2500);
// Clear error on success
endOperation(dir);
} catch (err) {
console.warn(err);
const message = err instanceof Error ? err : new Error(`Failed to ${operation}`);
endOperation(dir, message);
setError(message);
// Error is already set by the provider
}
// Invalidate git status to refresh UI
queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
}, [projectId, queryClient, remoteUrl, dir, startOperation, endOperation, setError]);
}, [remoteUrl, setError]);
const handleSync = async () => {
if (!remoteUrl) return;
setError(null);
setSyncSuccess(false);
try {
// Pull first to get latest changes
startOperation(dir, 'pull');
await git.pull({ dir, ref, singleBranch: true });
endOperation(dir);
// Then push local changes
startOperation(dir, 'push');
await git.push({ dir, remote: 'origin', ref });
endOperation(dir);
// Show success feedback
setSyncSuccess(true);
setTimeout(() => setSyncSuccess(false), 2500);
} catch (err) {
console.warn(err);
const message = err instanceof Error ? err : new Error('Failed to sync');
endOperation(dir, message);
setError(message);
}
// Invalidate git status to refresh UI
queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
await executeGitOperation(() => gitSync.sync(dir, ref));
};
const handlePull = async () => {
await executeGitOperation('pull', async () => {
await git.pull({ dir, ref, singleBranch: true });
});
await executeGitOperation(() => gitSync.pull(dir, ref));
};
const handlePush = async () => {
await executeGitOperation('push', async () => {
await git.push({ dir, remote: 'origin', ref });
});
await executeGitOperation(() => gitSync.push(dir, ref));
};
const handleForcePull = async () => {
await executeGitOperation('force-pull', async () => {
// Step 1: Fetch latest changes from remote
await git.fetch({
dir,
remote: 'origin',
ref,
singleBranch: true,
});
// Step 2: Get the remote commit SHA
const remoteRef = `refs/remotes/origin/${ref}`;
const remoteSha = await git.resolveRef({ dir, ref: remoteRef });
// Step 3: Force update the current branch to point to remote
await git.writeRef({
dir,
ref: `refs/heads/${ref}`,
value: remoteSha,
force: true,
});
// Step 4: Force checkout all files (overwrite local changes)
await git.checkout({
dir,
ref,
force: true,
});
});
await executeGitOperation(() => gitSync.forcePull(dir, ref));
};
const handleForcePush = async () => {
await executeGitOperation('force-push', async () => {
await git.push({ dir, remote: 'origin', ref, force: true });
});
await executeGitOperation(() => gitSync.forcePush(dir, ref));
};
// Temporary feedback state helper