How to refer to a file in another git branch?

Viewed 58

I have a situation like this,

* 23e53d6 (master)  ---> a_config_file (original)
* f4e4dd2 ...
* 6308fc5 ...
|  
| * e52ec6b (hacky) ---> a_config_file (altered)
|/  
* 23e53d6 ...

and I would like to reference a_config_file on the hacky branch, while being on any branch and without copying it, to be used for a command, such as:

$ awesome_tool --config=hacky-branch-version-of-a-config-file <...>

Is this even possible? Some solutions I looked into:

  • I know about git restore --source=hacky a_config_file but that copies that version of the file into the current working dir, overwriting the current one so it shows up in git status

  • There is also git show e52ec6b:a_config_file but I can't use standard input or process substitution with the CLI tool of my choice so I would have to save the output (file, mkfifo, etc.) and invoke that - which is basically the previous item


I'm aware of the following questions, but these don't seem to provide a solution to this question:

Please let me know if I overlooked something!)

1 Answers

I think the governing limitations here are:

  • your tool of choice:

    I can't use standard input or process substitution with the CLI tool of my choice

    If the tool can only work with a real file on disk, then you need to create that file on disk.

  • As Joachim Sauer pointed out, "Non-checked out files are not stored anywhere in a directly-useful format".

    The data for the file obviously exists somewhere in git's database, but it's likely to be compressed into a "packfile", so not usable directly.

However, your conclusion that any file created would show up in git status is false, because you have full control over its name and location.

Approach 1: create the file outside the project directory

One approach would be to create a file outside the current directory, e.g. in /tmp. If you have access to the system's mktemp command, or an equivalent, you can safely automate that without choosing a file name. For instance, in a shell script:

OLDCONFIG="$(mktemp)"
git show e52ec6b:a_config_file > "$OLDCONFIG"
awesome_tool --config="$OLDCONFIG" <...>
rm -f "$OLDCONFIG"

Approach 2: use .gitignore

Alternatively, you could create a file in the current directory with a fixed name, and list that name in .gitignore. That way you don't even need a scripting language with variables, just fixed commands. For instance, add a_config_file.old to your .gitignore file, and then use this:

git show e52ec6b:a_config_file > a_config_file.old
awesome_tool --config=a_config_file.old <...>
rm -f a_config_file.old
Related