2

I have a list of commit id and filenames from a git repository. what I need is to get the file path of each file in the list based on the commit id. But I don't know how to do that using git command.

Suppose I have a commit id and filename: [cb85815bc1, GuiCommonElements.java]. Now I need the full path of the file in that commit id. So, the output should be like path/path/path/GuiCommonElements.java.

I tried many commands but didn't give me such results.

git show cb85815bc1 --grep='GuiCommonElements.java'
git log cb85815bc1 --grep='GuiCommonElements.java' --name-only

Any help would be appreciated.

2
  • What if that commit has four different file paths, all of which either end with or contain that path component? E.g., what if commit cb85815bc1 contains d1/GuiCommonElements.java, d2/GuiCommonElements.java, lib/old/GuiCommonElements.java, and lib/new/GuiCommonElements.java? Commented May 22, 2019 at 1:31
  • @torek All paths should be retrieved Commented May 22, 2019 at 1:34

1 Answer 1

4

git show (or git log -p, which does something extremely similar but operates on more than one commit) will diff the commit against its parent(s). Adding --name-only reduces the diff output to show only changed-file-names, rather than changed-file-names plus the instruction-set.

What you probably want here is to use git ls-tree, which shows the names of files contained within a commit. If you are not at the top level of the repository, git ls-tree defaults to showing only things in the current directory, so you probably want to add -r --full-tree. You then want to look for things that contain, or end with, your selected name:

git ls-tree -r --full-tree cb85815bc1 | grep GuiCommonElements.java

This is slightly flawed as grep itself takes regular expression arguments and shows lines that match, so not only will it show files like:

lib/old/GuiCommonElements.java
lib/new/GuiCommonElements.java

but also:

other/ThisIsNotGuiCommonElements.java

(because that contains GuiCommonElements.java) and:

other/GuiCommonElementsXJava

(because . matches one of any character, including X). But it's probably good enough, and if you like, you can shore it up a bit.

The git ls-tree documentation claims that it takes <path>... arguments that are "patterns to match", but glob patterns seem not to work here: If globs worked, '**/GuiCommonElements.java' would do the trick, but in my test just now they didn't.

Sign up to request clarification or add additional context in comments.

1 Comment

error: pathspec 'test' did not match any file(s) known to git

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.