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