fix: Extract the name from the remote ref correctly

Correctly extract the name of the remote branch, supporting branch names with nested paths

Also: Add tests
This commit is contained in:
estib 2024-09-16 16:05:12 +02:00
parent 4c00fce37b
commit a9c58aa35a
2 changed files with 55 additions and 2 deletions

View File

@ -0,0 +1,42 @@
import * as BranchUtils from './branch';
import { expect, test, describe } from 'vitest';
describe.concurrent('getBranchNameFromRef', () => {
test('When provided a ref with a remote prefix, it returns the branch name', () => {
const ref = 'refs/remotes/origin/main';
expect(BranchUtils.getBranchNameFromRef(ref)).toBe('main');
});
test('When provided a ref without a remote prefix, it returns the branch name', () => {
const ref = 'main';
expect(BranchUtils.getBranchNameFromRef(ref)).toBe('main');
});
test('When provided a ref with a remote prefix and multiple separators, it returns the branch name', () => {
const ref = 'refs/remotes/origin/feature/cool-thing';
expect(BranchUtils.getBranchNameFromRef(ref)).toBe('feature/cool-thing');
});
});
describe.concurrent('getBranchRemoteFromRef', () => {
test('When provided a ref with a remote prefix, it returns the remote name', () => {
const ref = 'refs/remotes/origin/main';
expect(BranchUtils.getBranchRemoteFromRef(ref)).toBe('origin');
});
test('When provided a ref without a remote prefix, it returns undefined', () => {
const ref = 'main';
expect(BranchUtils.getBranchRemoteFromRef(ref)).toBeUndefined();
});
test('When provided a ref with a remote prefix and multiple separators, it returns the remote name', () => {
const ref = 'refs/remotes/origin/feature/cool-thing';
expect(BranchUtils.getBranchRemoteFromRef(ref)).toBe('origin');
});
});

View File

@ -2,13 +2,24 @@ import { entries, type UnknowObject } from './object';
const PREFERRED_REMOTE = 'origin';
const BRANCH_SEPARATOR = '/';
const REF_REMOTES_PREFIX = 'refs/remotes/';
export function getBranchNameFromRef(ref: string): string | undefined {
return ref.split(BRANCH_SEPARATOR).pop();
if (ref.startsWith(REF_REMOTES_PREFIX)) {
ref = ref.slice(REF_REMOTES_PREFIX.length);
}
const parts = ref.split(BRANCH_SEPARATOR);
return parts.length > 1 ? parts.slice(1).join(BRANCH_SEPARATOR) : ref;
}
export function getBranchRemoteFromRef(ref: string): string | undefined {
return ref.split(BRANCH_SEPARATOR)[0];
if (ref.startsWith(REF_REMOTES_PREFIX)) {
ref = ref.slice(REF_REMOTES_PREFIX.length);
}
const parts = ref.split(BRANCH_SEPARATOR);
return parts.length > 1 ? parts[0] : undefined;
}
const BRANCH_RANKING_EXACT: UnknowObject<number> = {