| | |
| | |
| | |
| | |
| | |
| |
|
| | import { useState, useEffect, useCallback } from 'react'; |
| | import { exec } from 'node:child_process'; |
| | import fs from 'node:fs'; |
| | import fsPromises from 'node:fs/promises'; |
| | import path from 'node:path'; |
| |
|
| | export function useGitBranchName(cwd: string): string | undefined { |
| | const [branchName, setBranchName] = useState<string | undefined>(undefined); |
| |
|
| | const fetchBranchName = useCallback( |
| | () => |
| | exec( |
| | 'git rev-parse --abbrev-ref HEAD', |
| | { cwd }, |
| | (error, stdout, _stderr) => { |
| | if (error) { |
| | setBranchName(undefined); |
| | return; |
| | } |
| | const branch = stdout.toString().trim(); |
| | if (branch && branch !== 'HEAD') { |
| | setBranchName(branch); |
| | } else { |
| | exec( |
| | 'git rev-parse --short HEAD', |
| | { cwd }, |
| | (error, stdout, _stderr) => { |
| | if (error) { |
| | setBranchName(undefined); |
| | return; |
| | } |
| | setBranchName(stdout.toString().trim()); |
| | }, |
| | ); |
| | } |
| | }, |
| | ), |
| | [cwd, setBranchName], |
| | ); |
| |
|
| | useEffect(() => { |
| | fetchBranchName(); |
| |
|
| | const gitLogsHeadPath = path.join(cwd, '.git', 'logs', 'HEAD'); |
| | let watcher: fs.FSWatcher | undefined; |
| |
|
| | const setupWatcher = async () => { |
| | try { |
| | |
| | await fsPromises.access(gitLogsHeadPath, fs.constants.F_OK); |
| | watcher = fs.watch(gitLogsHeadPath, (eventType: string) => { |
| | |
| | if (eventType === 'change' || eventType === 'rename') { |
| | |
| | fetchBranchName(); |
| | } |
| | }); |
| | } catch (_watchError) { |
| | |
| | |
| | |
| | } |
| | }; |
| |
|
| | setupWatcher(); |
| |
|
| | return () => { |
| | watcher?.close(); |
| | }; |
| | }, [cwd, fetchBranchName]); |
| |
|
| | return branchName; |
| | } |
| |
|