DEV Community

Burdette Lamar
Burdette Lamar

Posted on • Updated on

How to Get the Git Directory

Here's a code snippet that shows how to get the git directory for a git project:

def git_clone_dir_path
  git_dir = `git rev-parse --show-toplevel`.chomp
  $?.success? ? git_dir : nil
end

p git_clone_dir_path

[Simplified per reply below. Thanks, Bez!]

This works in any directory in the project.

I use this for a test that involves a project-specific path. On my machine, a test might generate an actual-value path such as C:/Users/Burdette/Documents/GitHub/markdown_helperwhatever.

If I put use that path as the expected value, it

On your machine's clone, that path would be different.

So in my expected values, I put git_dir/whatever. The test can then substitute in the local git directory.

That lets the test work on any machine.

Top comments (6)

Collapse
 
bezhermoso profile image
Bez Hermoso

git rev-parse --show-toplevel gets you the repo root dir directly.

Collapse
 
burdettelamar profile image
Burdette Lamar

Thanks, Bez. When I looked into this a while back, I found --git-dir, but not --show-toplevel. I'll revise the OP.

Collapse
 
bgadrian profile image
Adrian B.G.

A classic example of developers writing complex solutions for simple problems.

Collapse
 
phallstrom profile image
Philip Hallstrom

I'd tweak that command to git rev-parse --show-toplevel 2> /dev/null so that if you're not in a git repo it doesn't spit a warning to the console.

ruby foo.rb
fatal: Not a git repository (or any of the parent directories): .git
nil

vs

ruby foo.rb
nil
Collapse
 
burdettelamar profile image
Burdette Lamar

There's no /dev/null on Windows. But I think Open3.popen3 would work.

Collapse
 
vlasales profile image
Vlastimil Pospichal • Edited
$ git config --global alias.pwd '!pwd'
$ git pwd