How to know which branch a "git log" commit belongs to?

Solution 1:

I think that what you're looking for is the very useful command:

git branch -a --contains <SHA1sum-of-commit>

... which will tell you every branch (both local and remote-tracking) that contains that commit.

Unfortunately, I don't think there's a git log option that just outputs this for every commit. Using --all --source is close, but will only display one of the branches for each commit. However, if you click on a commit in gitk --all, you'll see that it lists every branch that that commit is on.

There's one part of your question that isn't very well defined, however - you ask:

What I want is to get the most recent branch that the commit in log belongs to

It isn't clear to me what you mean by this - the "most recent branch" might be (a) the most recently created ref (b) the most recently modified ref (c) the branch with the most recent commit on it, etc. etc. There's probably a better way of defining what you want in terms of the commit graph.

Solution 2:

With git log you already get all the commits from the current branch you are on.

If you want to see commits from merged branches you can use

$ git log --pretty=oneline --graph

To create a log tree and see what merged branches a commit stems from.

--graph will make the commit tree and --pretty=oneline will make a one line visualization for every commit

To add branches (as refs) to the log:

$ git log --all --source --pretty=oneline --graph

To display branches with commits:

$ git show-branch

Solution 3:

Have you tried the "--decorate" option to git log?

I have this alias in my .gitconfig:

[alias]
        k = log --graph --oneline --abbrev-commit  --decorate

It shows a similar graph as the one shown by gitk, with the branch names "decorated" besides the most recent commit in the branch.