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_helper
whatever.
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)
git rev-parse --show-toplevel
gets you the repo root dir directly.Thanks, Bez. When I looked into this a while back, I found
--git-dir
, but not--show-toplevel
. I'll revise the OP.A classic example of developers writing complex solutions for simple problems.
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.vs
There's no
/dev/null
on Windows. But I think Open3.popen3 would work.