(activeWorkspace: WorkspaceInfo | null)
| 24 | |
| 25 | const REFRESH_INTERVAL_MS = 3000; |
| 26 | export function useGitStatus(activeWorkspace: WorkspaceInfo | null) { |
| 27 | const [status, setStatus] = useState<GitStatusState>(emptyStatus); |
| 28 | const requestIdRef = useRef(0); |
| 29 | const workspaceIdRef = useRef<string | null>(activeWorkspace?.id ?? null); |
| 30 | const cachedStatusRef = useRef<Map<string, GitStatusState>>(new Map()); |
| 31 | const workspaceId = activeWorkspace?.id ?? null; |
| 32 | |
| 33 | const resolveBranchName = useCallback( |
| 34 | (incoming: string | undefined, cached: GitStatusState | undefined) => { |
| 35 | const trimmed = incoming?.trim(); |
| 36 | if (trimmed && trimmed !== "unknown") { |
| 37 | return trimmed; |
| 38 | } |
| 39 | const cachedBranch = cached?.branchName?.trim(); |
| 40 | return cachedBranch && cachedBranch !== "unknown" |
| 41 | ? cachedBranch |
| 42 | : trimmed ?? ""; |
| 43 | }, |
| 44 | [], |
| 45 | ); |
| 46 | |
| 47 | const refresh = useCallback(() => { |
| 48 | if (!workspaceId) { |
| 49 | setStatus(emptyStatus); |
| 50 | return; |
| 51 | } |
| 52 | const requestId = requestIdRef.current + 1; |
| 53 | requestIdRef.current = requestId; |
| 54 | return getGitStatus(workspaceId) |
| 55 | .then((data) => { |
| 56 | if ( |
| 57 | requestIdRef.current !== requestId || |
| 58 | workspaceIdRef.current !== workspaceId |
| 59 | ) { |
| 60 | return; |
| 61 | } |
| 62 | const cached = cachedStatusRef.current.get(workspaceId); |
| 63 | const resolvedBranchName = resolveBranchName(data.branchName, cached); |
| 64 | const nextStatus = { |
| 65 | ...data, |
| 66 | branchName: resolvedBranchName, |
| 67 | error: null, |
| 68 | }; |
| 69 | setStatus(nextStatus); |
| 70 | cachedStatusRef.current.set(workspaceId, nextStatus); |
| 71 | }) |
| 72 | .catch((err) => { |
| 73 | console.error("Failed to load git status", err); |
| 74 | if ( |
| 75 | requestIdRef.current !== requestId || |
| 76 | workspaceIdRef.current !== workspaceId |
| 77 | ) { |
| 78 | return; |
| 79 | } |
| 80 | const message = err instanceof Error ? err.message : String(err); |
| 81 | const cached = cachedStatusRef.current.get(workspaceId); |
| 82 | const nextStatus = cached |
| 83 | ? { ...cached, error: message } |
no test coverage detected