Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

remoteRefs.ts

67 lines1.8 KB

1export function parseRemoteNamesInGitOrder(stdout: string): ReadonlyArray<string> {
2 return stdout
3 .split("\n")
4 .map((line) => line.trim())
5 .filter((line) => line.length > 0);
6}
7​
8export function parseRemoteNames(stdout: string): ReadonlyArray<string> {
9 return parseRemoteNamesInGitOrder(stdout).toSorted((a, b) => b.length - a.length);
11​
12export function parseRemoteRefWithRemoteNames(
13 ref: string,
14 remoteNames: ReadonlyArray<string>,
15): { remoteRef: string; remoteName: string; branchName: string } | null {
16 const trimmedRef = ref.trim();
17 if (trimmedRef.length === 0) {
18 return null;
19 }
20​
21 for (const remoteName of remoteNames) {
22 const remotePrefix = `${remoteName}/`;
23 if (!trimmedRef.startsWith(remotePrefix)) {
24 continue;
25 }
26 const branchName = trimmedRef.slice(remotePrefix.length).trim();
27 if (branchName.length === 0) {
28 return null;
29 }
30 return {
31 remoteRef: trimmedRef,
32 remoteName,
33 branchName,
34 };
35 }
36​
37 return null;
39​
40export function extractBranchNameFromRemoteRef(
41 ref: string,
42 options?: {
43 remoteName?: string | null;
44 remoteNames?: ReadonlyArray<string>;
45 },
46): string {
47 const normalized = ref.trim();
48 if (normalized.length === 0) {
49 return "";
50 }
51​
52 if (normalized.startsWith("refs/remotes/")) {
53 return extractBranchNameFromRemoteRef(normalized.slice("refs/remotes/".length), options);
54 }
55​
56 const remoteNames = options?.remoteName ? [options.remoteName] : (options?.remoteNames ?? []);
57 const parsedRemoteRef = parseRemoteRefWithRemoteNames(normalized, remoteNames);
58 if (parsedRemoteRef) {
59 return parsedRemoteRef.branchName;
60 }
61​
62 const firstSlash = normalized.indexOf("/");
63 if (firstSlash === -1) {
64 return normalized;
65 }
66 return normalized.slice(firstSlash + 1).trim();