Search code examples
gitgit-plumbing

How do I programmatically compare files at two revisions in git?


I want to compare two versions of a file (which exist at different paths) at different commits in git. I don't want the diff, I simply want to know if the contents and modes are the same. The documentation for diff-files doesn't indicate any meaning for return values. I don't see something similar to cmp(1) in git. Is there another plumbing tool to do this or does diff-files have return values that express this?


Solution

  • git ls-tree <commit> -- <path> outputs

    <mode> SP <type> SP <object> TAB <file>

    <mode> is the file mode. <object> is the sha1 that indicates the content.

    Compare the modes and objects.

    <object> here can be named in another way

    <commit>:<path>

    So git rev-parse <commit>:<path> can output the sha1 of the blob or the tree. Comparing the two sha1, we can see if the contents are the same or not.