From 2c9b1a3ffc3d5e282ffe5b83a86314e99445bbc6 Mon Sep 17 00:00:00 2001 From: Sam Atkins Date: Thu, 20 Jun 2024 14:31:09 +0100 Subject: [PATCH] feat(git): Handle detached HEAD in `git status` and `git branch --list` --- packages/git/src/subcommands/branch.js | 5 +++++ packages/git/src/subcommands/status.js | 15 +++++++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/packages/git/src/subcommands/branch.js b/packages/git/src/subcommands/branch.js index 257db2998..1b1baf020 100644 --- a/packages/git/src/subcommands/branch.js +++ b/packages/git/src/subcommands/branch.js @@ -269,6 +269,11 @@ const BRANCH = { throw SHOW_USAGE; } + if (!current_branch) { + const oid = await git.resolveRef({ fs, dir, gitdir, ref: 'HEAD' }); + stdout(`* ${chalk.greenBright(`(HEAD detached at ${shorten_hash(oid)})`)}`); + } + for (const branch of branches) { if (branch === current_branch) { stdout(chalk.greenBright(`* ${branch}`)); diff --git a/packages/git/src/subcommands/status.js b/packages/git/src/subcommands/status.js index 8ab2283d4..882860a72 100644 --- a/packages/git/src/subcommands/status.js +++ b/packages/git/src/subcommands/status.js @@ -18,7 +18,8 @@ */ import git from 'isomorphic-git'; import path from 'path-browserify'; -import { find_repo_root } from '../git-helpers.js'; +import { find_repo_root, shorten_hash } from '../git-helpers.js'; +import chalk from 'chalk'; export default { name: 'status', @@ -107,7 +108,17 @@ export default { dir, gitdir, }); - stdout(`On branch ${current_branch}\n`); + if (current_branch) { + stdout(`On branch ${current_branch}`); + // Check if the branch actually exists. If not, this is a fresh repo that's never been committed to. + const actual_current_branch = await git.currentBranch({ fs, dir, gitdir, test: true }); + if (!actual_current_branch) { + stdout('\nNo commits yet\n'); + } + } else { + const oid = await git.resolveRef({ fs, dir, gitdir, ref: 'HEAD' }); + stdout(`${chalk.redBright('HEAD detached at')} ${shorten_hash(oid)}`); + } if (staged.length) { stdout('Changes to be committed:');