As Rudiger suggested, the answer is straightforward.
Instead of using repo.getBranch()
to get the branch name, use repo.getFullBranch()
to get it.
The full-branch version returns a string "refs/heads/[branchname]" if we're on a branch, or a raw SHA-1 if we are not.
Confirmed, tested, and pushed.
Thanks!