0

I am writing a Git post-receive hook, and within the hook script, I need the absolute path of the project directory (i.e. the directory of the repository). What is a reliable way to do this that works for both non-bare and bare repositories?

From my understanding, if the repository is bare (which I can check using git rev-parse --is-bare-repository), the absolute path can be obtained using pwd. If the repository is not bare, how can I reliably obtain the absolute path of the repository? Is it dirname "$(pwd)"? Is this method reliable?

Flux
  • 9,805
  • 5
  • 46
  • 92
  • Does this answer your question? [Is there a way to get the git root directory in one command?](https://stackoverflow.com/questions/957928/is-there-a-way-to-get-the-git-root-directory-in-one-command) – iBug Mar 23 '21 at 06:48
  • The top answer of the linked question *is reliable*. – iBug Mar 23 '21 at 06:49
  • @iBug No. All those answers assume that the repository in question is not bare. – Flux Mar 23 '21 at 06:51
  • @iBug In a bare repository, `git rev-parse --show-toplevel` in a post-receive hook will fail with exit code 128 and error message: `fatal: this operation must be run in a work tree`. – Flux Mar 23 '21 at 06:53
  • 1
    In a post-receive hook (or in a hook in general) `$GIT_DIR` points to the *repository* location. If you want the *working tree* location, don't use `$GIT_DIR`, but if you want the *repository* location, do use `$GIT_DIR`. To turn it into an absolute path, consider using `realpath`, though there are portability issues here. – torek Mar 23 '21 at 06:53
  • You can use conditional statements in your script to handle different cases for bare repos and non-bare repos. – iBug Mar 23 '21 at 06:56
  • @iBug Yes, but is my proposed `dirname "$(pwd)"` method reliable? – Flux Mar 23 '21 at 06:57
  • @torek "In a post-receive hook (or in a hook in general) `$GIT_DIR` points to the repository location." Are you sure about this? In a non-bare repository, `$GIT_DIR` seems to point to the `.git/` directory of the repository. – Flux Mar 23 '21 at 07:02
  • 1
    Yes, "repository location" always refer to the `.git` directory, otherwise there wouldn't be a separate "working tree location". – iBug Mar 23 '21 at 07:03
  • Yes, as @iBug says, "repository location" means where the `HEAD` file, `objects/` directory, and so on reside. "Working tree" means where the user's work-tree resides. In a question like this it's important to keep in mind that there need not be any correlation between the two (when Git is invoked with `--git-dir` and `--work-tree` both, for instance). – torek Mar 23 '21 at 07:12

0 Answers0