Open History to see the last commit
1import type { GitBranch } from "@t3tools/contracts";
2
3export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
4 const firstSeparatorIndex = branchName.indexOf("/");
5 if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {
6 return branchName;
7 }
8 return branchName.slice(firstSeparatorIndex + 1);
9}
10
11function deriveLocalBranchNameCandidatesFromRemoteRef(
12 branchName: string,
13 remoteName?: string,
14): ReadonlyArray<string> {
15 const candidates = new Set<string>();
16 const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
17 if (firstSlashCandidate.length > 0) {
18 candidates.add(firstSlashCandidate);
19 }
20
21 if (remoteName) {
22 const remotePrefix = `${remoteName}/`;
23 if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
24 candidates.add(branchName.slice(remotePrefix.length));
25 }
26 }
27
28 return [...candidates];
29}
30
31export function dedupeRemoteBranchesWithLocalMatches(
32 branches: ReadonlyArray<GitBranch>,
33): ReadonlyArray<GitBranch> {
34 const localBranchNames = new Set(
35 branches.filter((branch) => !branch.isRemote).map((branch) => branch.name),
36 );
37
38 return branches.filter((branch) => {
39 if (!branch.isRemote) {
40 return true;
41 }
42
43 const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
44 branch.name,
45 branch.remoteName,
46 );
47 return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
48 });
49}