diff --git a/__tests__/git.test.ts b/__tests__/git.test.ts index 24546006..99fac933 100644 --- a/__tests__/git.test.ts +++ b/__tests__/git.test.ts @@ -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 => { + 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 => { + 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 => { const fullCmd = `${cmd} ${args?.join(' ')}`; diff --git a/src/git.ts b/src/git.ts index 7845300b..2cf7491a 100644 --- a/src/git.ts +++ b/src/git.ts @@ -123,13 +123,14 @@ export class Git { private static async getDetachedRef(): Promise { const res = await Git.exec(['show', '-s', '--pretty=%D']); - const refMatch = res.match(/^HEAD, (.*)$/); + // Can be "HEAD, " or "grafted, HEAD, " + 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(); // Tag refs are formatted as "tag: " if (ref.startsWith('tag: ')) {