(
workDir: string,
options: GitStatusCacheOptions = {},
)
| 64 | const AHEAD_BEHIND_RE = /\[(?:ahead (\d+))?(?:, )?(?:behind (\d+))?\]/; |
| 65 | |
| 66 | export function createGitStatusCache( |
| 67 | workDir: string, |
| 68 | options: GitStatusCacheOptions = {}, |
| 69 | ): GitStatusCache { |
| 70 | const isRepo = detectGitRepo(workDir); |
| 71 | let branch: BranchState = { value: null, fetchedAt: 0 }; |
| 72 | let status: StatusState = { |
| 73 | dirty: false, |
| 74 | ahead: 0, |
| 75 | behind: 0, |
| 76 | diffAdded: 0, |
| 77 | diffDeleted: 0, |
| 78 | fetchedAt: 0, |
| 79 | }; |
| 80 | let pullRequest: PullRequestState = { |
| 81 | value: null, |
| 82 | branch: null, |
| 83 | fetchedAt: 0, |
| 84 | pendingBranch: null, |
| 85 | requestId: 0, |
| 86 | }; |
| 87 | |
| 88 | return { |
| 89 | getStatus: () => { |
| 90 | if (!isRepo) return null; |
| 91 | |
| 92 | const now = Date.now(); |
| 93 | if (now - branch.fetchedAt >= BRANCH_TTL_MS) { |
| 94 | branch = { value: readBranch(workDir), fetchedAt: now }; |
| 95 | } |
| 96 | if (branch.value === null) return null; |
| 97 | |
| 98 | if (now - status.fetchedAt >= STATUS_TTL_MS) { |
| 99 | status = { ...readStatus(workDir), fetchedAt: now }; |
| 100 | } |
| 101 | refreshPullRequestIfNeeded(branch.value, now); |
| 102 | |
| 103 | return { |
| 104 | branch: branch.value, |
| 105 | dirty: status.dirty, |
| 106 | ahead: status.ahead, |
| 107 | behind: status.behind, |
| 108 | diffAdded: status.diffAdded, |
| 109 | diffDeleted: status.diffDeleted, |
| 110 | pullRequest: pullRequest.branch === branch.value ? pullRequest.value : null, |
| 111 | }; |
| 112 | }, |
| 113 | }; |
| 114 | |
| 115 | function refreshPullRequestIfNeeded(branchName: string, now: number): void { |
| 116 | if (pullRequest.pendingBranch === branchName) return; |
| 117 | const fetchedAt = pullRequest.branch === branchName ? pullRequest.fetchedAt : 0; |
| 118 | if (now - fetchedAt < PULL_REQUEST_TTL_MS) return; |
| 119 | |
| 120 | const requestId = pullRequest.requestId + 1; |
| 121 | pullRequest = { |
| 122 | value: pullRequest.branch === branchName ? pullRequest.value : null, |
| 123 | branch: branchName, |
no test coverage detected