Skip to content

Commit e659417

Browse files
committed
feat(repo): handle detached HEAD state
1 parent 516da8a commit e659417

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

src/index.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,17 @@
11
import process from "node:process";
2-
import { getConfig, getDefaultTargetBranch, getMergedBranches, isGitRepo } from "./repo.js";
2+
import { getConfig, getDefaultTargetBranch, getMergedBranches, isDetachedHead, isGitRepo } from "./repo.js";
33
import { outputMergedBranches } from "./output.js";
44

55
function main(): void {
66
if (!isGitRepo()) {
77
console.error("Not a git repository.");
88
process.exit(1);
99
}
10+
if (isDetachedHead()) {
11+
console.error("HEAD is detached (e.g., after checkout of a commit). Please switch to a branch.");
12+
process.exit(1);
13+
}
14+
1015
const targetBranch = getDefaultTargetBranch();
1116
if (!targetBranch) {
1217
console.error("No 'master' or 'main' branch found.");

src/repo.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,16 @@ export function isGitRepo(): boolean {
1111
}
1212
}
1313

14-
export function isBranchExists(branch: string): boolean {
14+
export function isDetachedHead(): boolean {
15+
try {
16+
const output = execSync("git symbolic-ref --quiet --short HEAD", { encoding: "utf-8" }).trim();
17+
return output === "";
18+
} catch {
19+
return true;
20+
}
21+
}
22+
23+
function isBranchExists(branch: string): boolean {
1524
try {
1625
execSync(`git show-ref --verify --quiet refs/heads/${branch}`);
1726
return true;

0 commit comments

Comments
 (0)