| 1 | /** |
| 2 | * How far a branch has moved from the default branch, worked out from the |
| 3 | * two histories alone: commits it has that the default branch does not |
| 4 | * (ahead), and commits the default branch gained since they last agreed |
| 5 | * (behind). Each history is read only so far back, so a count that ran |
| 6 | * past it is a lower bound, said with `aheadMore` and `behindMore`. |
| 7 | */ |
| 8 | export type Drift = { ahead: number; behind: number; aheadMore: boolean; behindMore: boolean }; |
| 9 | |
| 10 | /** `branch` and `main` are commit hashes, newest first; `limit` is how many each was asked for. */ |
| 11 | export function drift(branch: string[], main: string[], limit: number): Drift { |
| 12 | const onMain = new Set(main); |
| 13 | let ahead = branch.findIndex((hash) => onMain.has(hash)); |
| 14 | if (ahead === -1) { |
| 15 | // No shared commit within reach: everything read is ahead, and how far |
| 16 | // behind it is cannot be told. |
| 17 | return { ahead: branch.length, behind: 0, aheadMore: branch.length >= limit, behindMore: true }; |
| 18 | } |
| 19 | const base = branch[ahead]; |
| 20 | const behind = main.indexOf(base); |
| 21 | return { ahead, behind, aheadMore: false, behindMore: false }; |
| 22 | } |
| 23 | |
| 24 | /** `12`, `50+` when the count ran past what was read, or `?` when nothing was counted before it did. */ |
| 25 | export function count(value: number, more: boolean): string { |
| 26 | if (more && value === 0) return "?"; |
| 27 | return more ? `${value}+` : String(value); |
| 28 | } |