Search code examples
gitinotifyinotifywait

Most efficient way to get the path of a git repo which tracks a file


I am watching an arbitrary folder with inotifywait. When a file changes, I want to determine which git repo (if any) is relevant to that file.

I see this answer: How to tell if a file is git tracked (by shell exit code)?

The difference here is - I don't really care if git is tracking the file or not, I just want to know - if git were to track that file, which git existing git repo would it be for. That is my question.

Is the best way to do this simply:

#!/usr/bin/env bash

cd "$(dirname "$changed_file")" && git rev-parse --show-toplevel 

? is that about right? will that git rev-parse --show-toplevel command always given the relevant repo for that file?


Solution

  • if git were to track that file, which git existing git repo would it be for.

    git rev-parse --show-toplevel will show you the top of the work tree for the repo that would track a file you git add from there, yes, but Git doesn't impose any requirements on where a repository's parts are kept. There's a search path for the ones you don't call out explicitly, and git rev-parse --show-toplevel is showing you the work tree it found, if you didnt' tell it, or the one you told it to use. Say git help to see the main options for getting explicit with it, and pointers to further docs if you need them.