0

If all I have to go on is a reference, i.e. refs/heads/my-branch, how can I convert that to the actual branch name, i.e. my-branch, without first checking out the repository?

I've tried git rev-parse --abbrev-ref refs/heads/my-branch which works, however this only will work if i've checked out the repository in the first place, which I haven't done.

Basically i'm recieving refs/heads/my-branch from CI, and then I need to go clone that repository at that branch. But I can't do git clone myrepo -b refs/heads/my-branch, because that's invalid, it wants the actual branch name.

How can I work around this?

John Bergqvist
  • 852
  • 13
  • 38
  • Does this answer your question? [Is it possible to get branch names without clone or pull from git?](https://stackoverflow.com/questions/25765237/is-it-possible-to-get-branch-names-without-clone-or-pull-from-git) – xandermonkey Jun 30 '20 at 14:32
  • 1
    Why not just textually cut `refs/heads/` ? – phd Jun 30 '20 at 15:50
  • Why aren't you using the checkout action (https://github.com/actions/checkout)? It will checkout the ref that triggered your workflow. – riQQ Jun 30 '20 at 16:03
  • See [this answer](https://stackoverflow.com/a/58178121/11934042) which also works for branch names. – peterevans Jun 30 '20 at 22:56

1 Answers1

0

The way Git stores local branches is as a reference starting with refs/heads. That prefix indicates a local branch. So you can simply trim off that prefix if it exists and get the branch name.

Note that there are other references that your CI system may use, such as tags (e.g., refs/tags/v1.0), so you'll want to verify that your reference matches the pattern you expect.

If you're trying to do this in GitHub Actions, you'd be better off using the actions/checkout action, since that both automatically checks out the right ref and avoids cloning unrelated refs, which means that your workflow is both simpler and faster.

bk2204
  • 64,793
  • 6
  • 84
  • 100