0

I've read the man page of git-rev-parse, but still have no idea of what does this command do. Let's say I have a git project that has a structure like this:

MyProject
├── Folder1
├── Folder2
├── .git

If I run

git-rev-parse HEAD

then I can get a SHA_1 that is the same as my last commit. Pretty straightforward.

However, if I run

git-rev-parse HEAD: Folder1

then I get another SHA_2 that is different with any SHA that I've ever committed. My question is: what does this "git-rev-parse HEAD: Folder1" mean and what is this SHA_2?

P. Tsin
  • 435
  • 4
  • 14
  • There must not be a space character between `HEAD:Folder1`, otherwise you will just get the commit hash and the filename (`Folder1`) again – knittl May 31 '21 at 15:11

2 Answers2

5

Take a look at the docs:

<rev>:<path>, e.g. HEAD:README, master:./README

A suffix : followed by a path names the blob or tree at the given path in the tree-ish object named by the part before the colon. A path starting with ./ or ../ is relative to the current working directory. The given path will be converted to be relative to the working tree’s root directory. This is most useful to address a blob or tree from a commit or tree that has the same tree structure as the working tree.

This means that it does not get the hash of a commit/tag/branch/... but it gets the hash of a directory/file in a commit/tag/branch/....

So, git-rev-parse HEAD:Folder1 means getting the SHA hash of the tree object of the directory Folder1 in the ref HEAD (checked out state).

dan1st
  • 12,568
  • 8
  • 34
  • 67
1

commit:path/to/file describes a file (a "BLOB") at a specific commit. For example in the git.git repository:

$ git rev-parse v2.31.1:git.c
9bc077a025cba4c5b3628b0eabb4d3aac0f35c63
$ git cat-file -t 9bc077a025cba4c5b3628b0eabb4d3aac0f35c63
blob
$ git cat-file -p 9bc077a025cba4c5b3628b0eabb4d3aac0f35c63 | head
#include "builtin.h"
#include "config.h"
#include "exec-cmd.h"
#include "help.h"
#include "run-command.h"
#include "alias.h"
#include "shallow.h"

#define RUN_SETUP       (1<<0)
#define RUN_SETUP_GENTLY    (1<<1)

You can find an explanation under the Specifying Revisions section of the rev-parse man page:

   <rev>:<path>, e.g. HEAD:README, master:./README
       A suffix : followed by a path names the blob or tree at the given
       path in the tree-ish object named by the part before the colon. A
       path starting with ./ or ../ is relative to the current working
       directory. The given path will be converted to be relative to the
       working tree’s root directory. This is most useful to address a blob
       or tree from a commit or tree that has the same tree structure as the
       working tree.

Of course, path/to/file might be a directory in which case the output hash will point to a tree object instead.

knittl
  • 246,190
  • 53
  • 318
  • 364