feat: display commit hash in detached HEAD state (#832)

This commit is contained in:
Scott Densmore 2025-06-08 14:59:18 -07:00 committed by GitHub
parent 394312b9c2
commit 9104ac02f7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 38 additions and 5 deletions

View File

@ -88,16 +88,39 @@ describe('useGitBranchName', () => {
expect(result.current).toBeUndefined();
});
it('should return undefined if branch is HEAD (detached state)', async () => {
it('should return short commit hash if branch is HEAD (detached state)', async () => {
(mockExec as MockedFunction<typeof mockExec>).mockImplementation(
(_command, _options, callback) => {
callback?.(null, 'HEAD\n', '');
(command, _options, callback) => {
if (command === 'git rev-parse --abbrev-ref HEAD') {
callback?.(null, 'HEAD\n', '');
} else if (command === 'git rev-parse --short HEAD') {
callback?.(null, 'a1b2c3d\n', '');
}
return new EventEmitter() as ChildProcess;
},
);
const { result, rerender } = renderHook(() => useGitBranchName(CWD));
await act(async () => {
vi.runAllTimers();
rerender();
});
expect(result.current).toBe('a1b2c3d');
});
it('should return undefined if branch is HEAD and getting commit hash fails', async () => {
(mockExec as MockedFunction<typeof mockExec>).mockImplementation(
(command, _options, callback) => {
if (command === 'git rev-parse --abbrev-ref HEAD') {
callback?.(null, 'HEAD\n', '');
} else if (command === 'git rev-parse --short HEAD') {
callback?.(new Error('Git error'), '', 'error output');
}
return new EventEmitter() as ChildProcess;
},
);
const { result, rerender } = renderHook(() => useGitBranchName(CWD));
expect(result.current).toBeUndefined();
await act(async () => {
vi.runAllTimers();
rerender();

View File

@ -27,7 +27,17 @@ export function useGitBranchName(cwd: string): string | undefined {
if (branch && branch !== 'HEAD') {
setBranchName(branch);
} else {
setBranchName(undefined);
exec(
'git rev-parse --short HEAD',
{ cwd },
(error, stdout, _stderr) => {
if (error) {
setBranchName(undefined);
return;
}
setBranchName(stdout.toString().trim());
},
);
}
},
),