Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(git): handle detached ref in shallow clone context #217

Merged
merged 1 commit into from
Dec 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions __tests__/git.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,52 @@ describe('ref', () => {
expect(ref).toEqual('refs/tags/8.0.0');
});

it('returns mocked detached tag ref (shallow clone)', async () => {
jest.spyOn(Exec, 'getExecOutput').mockImplementation((cmd, args): Promise<ExecOutput> => {
const fullCmd = `${cmd} ${args?.join(' ')}`;
let result = '';
switch (fullCmd) {
case 'git branch --show-current':
result = '';
break;
case 'git show -s --pretty=%D':
result = 'grafted, HEAD, tag: 8.0.0';
break;
}
return Promise.resolve({
stdout: result,
stderr: '',
exitCode: 0
});
});

const ref = await Git.ref();

expect(ref).toEqual('refs/tags/8.0.0');
});

it('should throws an error when detached HEAD ref is not supported', async () => {
jest.spyOn(Exec, 'getExecOutput').mockImplementation((cmd, args): Promise<ExecOutput> => {
const fullCmd = `${cmd} ${args?.join(' ')}`;
let result = '';
switch (fullCmd) {
case 'git branch --show-current':
result = '';
break;
case 'git show -s --pretty=%D':
result = 'wrong, HEAD, tag: 8.0.0';
break;
}
return Promise.resolve({
stdout: result,
stderr: '',
exitCode: 0
});
});

await expect(Git.ref()).rejects.toThrow('Cannot find detached HEAD ref in "wrong, HEAD, tag: 8.0.0"');
});

it('returns mocked detached branch ref', async () => {
jest.spyOn(Exec, 'getExecOutput').mockImplementation((cmd, args): Promise<ExecOutput> => {
const fullCmd = `${cmd} ${args?.join(' ')}`;
Expand Down
7 changes: 4 additions & 3 deletions src/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,13 +123,14 @@ export class Git {
private static async getDetachedRef(): Promise<string> {
const res = await Git.exec(['show', '-s', '--pretty=%D']);

const refMatch = res.match(/^HEAD, (.*)$/);
// Can be "HEAD, <tagname>" or "grafted, HEAD, <tagname>"
const refMatch = res.match(/^(grafted, )?HEAD, (.*)$/);

if (!refMatch) {
if (!refMatch || !refMatch[2]) {
throw new Error(`Cannot find detached HEAD ref in "${res}"`);
}

const ref = refMatch[1].trim();
const ref = refMatch[2].trim();
crazy-max marked this conversation as resolved.
Show resolved Hide resolved

// Tag refs are formatted as "tag: <tagname>"
if (ref.startsWith('tag: ')) {
Expand Down