Skip to content

Commit 9104ac0

Browse files
feat: display commit hash in detached HEAD state (google-gemini#832)
1 parent 394312b commit 9104ac0

2 files changed

Lines changed: 38 additions & 5 deletions

File tree

packages/cli/src/ui/hooks/useGitBranchName.test.ts

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -88,16 +88,39 @@ describe('useGitBranchName', () => {
8888
expect(result.current).toBeUndefined();
8989
});
9090

91-
it('should return undefined if branch is HEAD (detached state)', async () => {
91+
it('should return short commit hash if branch is HEAD (detached state)', async () => {
9292
(mockExec as MockedFunction<typeof mockExec>).mockImplementation(
93-
(_command, _options, callback) => {
94-
callback?.(null, 'HEAD\n', '');
93+
(command, _options, callback) => {
94+
if (command === 'git rev-parse --abbrev-ref HEAD') {
95+
callback?.(null, 'HEAD\n', '');
96+
} else if (command === 'git rev-parse --short HEAD') {
97+
callback?.(null, 'a1b2c3d\n', '');
98+
}
99+
return new EventEmitter() as ChildProcess;
100+
},
101+
);
102+
103+
const { result, rerender } = renderHook(() => useGitBranchName(CWD));
104+
await act(async () => {
105+
vi.runAllTimers();
106+
rerender();
107+
});
108+
expect(result.current).toBe('a1b2c3d');
109+
});
110+
111+
it('should return undefined if branch is HEAD and getting commit hash fails', async () => {
112+
(mockExec as MockedFunction<typeof mockExec>).mockImplementation(
113+
(command, _options, callback) => {
114+
if (command === 'git rev-parse --abbrev-ref HEAD') {
115+
callback?.(null, 'HEAD\n', '');
116+
} else if (command === 'git rev-parse --short HEAD') {
117+
callback?.(new Error('Git error'), '', 'error output');
118+
}
95119
return new EventEmitter() as ChildProcess;
96120
},
97121
);
98122

99123
const { result, rerender } = renderHook(() => useGitBranchName(CWD));
100-
expect(result.current).toBeUndefined();
101124
await act(async () => {
102125
vi.runAllTimers();
103126
rerender();

packages/cli/src/ui/hooks/useGitBranchName.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,17 @@ export function useGitBranchName(cwd: string): string | undefined {
2727
if (branch && branch !== 'HEAD') {
2828
setBranchName(branch);
2929
} else {
30-
setBranchName(undefined);
30+
exec(
31+
'git rev-parse --short HEAD',
32+
{ cwd },
33+
(error, stdout, _stderr) => {
34+
if (error) {
35+
setBranchName(undefined);
36+
return;
37+
}
38+
setBranchName(stdout.toString().trim());
39+
},
40+
);
3141
}
3242
},
3343
),

0 commit comments

Comments
 (0)