'Find out which branch has the most recent version of a certain file

Say I have a file in a repo and I want to find out which branch has the most recent version of the file, let's say the filepath is 'foo'.

Let's assume the status/index/worktree of the repo is clean.

How can I go through all the branches local and remote and find out which commit on which branch holds the most recent change to 'foo'?

git


Solution 1:[1]

If you have a recent enough version of git to support all this functionality:

  • Get the commit ID of the last (reachable) commit to touch a file using

    git log --all --format=format:%H -n 1 -- path/to/file
    

    Here --all means to search the history of all refs (branches, tags, etc.), --format=format:%H means show only the commit ID, and -n 1 means display only the first commit found. git log orders commits from newest to oldest, by default, so the first one will be the latest.

  • Then find all branches which contain that commit using

    git branch --all --contains commitID
    

    You can omit --all if you want to see only local branches.

To combine these into one command that lists the branch names, assuming there is a commit that modifies the specified file:

git branch --all --contains "$(git log --all --format=format:%H -n 1 -- path/to/file)"

This procedure does not require the index and working tree to be clean, although it will only detect changes to the file that have been committed.

Solution 2:[2]

The "source" flag to git-log adds the ref name. When I tried, it shows the branch name, so you don't need the second step. For example,

git log --all --source -n 1 -- pathname

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David Z
Solution 2 MikeG