6

When an external command is run via Git alias, it is run from the rood directory of the repository (where the .git/ is usually located). It can be checked with:

$ cd /some/path/inside/repo
$ echo $(git -c alias.root='!pwd' root)

Now, is there a way to get the exact path where the alias was run from?`


In case of XY problem, here's what I'm doing: I want an alias that launches shell function which, in its turn, runs several Git commands, like ls-files. It should work only in the path where it was called, so it should know it.

It works well if I just run the function, because it doesn't change paths and runs exactly where it was called. But I want a little more native behaviour. What I have now is

git-add-specificname -opt -opt2 --long-option -- path1 path2

What I want is

git add-specificname -opt -opt2 --long-option -- path1 path2

Aliasing parameters in Git is not allowed, so no chance for git add specificname...

Nick Volynkin
  • 14,023
  • 6
  • 43
  • 67

1 Answers1

10

You need to add cd ${GIT_PREFIX:-.} in your alias.

(Git 1.7.6+:

Processes spawned by "[alias] <name> = !process" in the configuration can inspect GIT_PREFIX environment variable to learn where in the working tree the original command was invoked.

git config:

'GIT_PREFIX' is set as returned by running 'git rev-parse --show-prefix' from the original current directory.

)

If GIT_PREFIX is not defined (because you are executing the alias from the root folder of the repo), it will be replaced by '.'.

You can see that variable used in t/t1020-subdirectory.sh

test_expect_success 'GIT_PREFIX for !alias' '
    printf "dir/" >expect &&
    (
        git config alias.test-alias-directory "!sh -c \"printf \$GIT_PREFIX\"" &&
        cd dir &&
        git test-alias-directory >../actual
    ) &&
    test_cmp expect actual
'
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • I'd been expecting a brilliant answer from you exactly. :) – Nick Volynkin Jul 30 '15 at 11:44
  • @NickVolynkin I just saw a similar answer (for a slightly different question): http://stackoverflow.com/a/21929373/6309 – VonC Jul 30 '15 at 11:47
  • 1
    One more detail: what does the `:-.` syntax do? – Nick Volynkin Jul 30 '15 at 12:27
  • 1
    @NickVolynkin That what I meant with "If GIT_PREFIX is not defined (because you are executing the alias from the root folder of the repo), it will be replaced by '.'.". When you execute an alias from the root folder, GIT_PREFIX is *not* defined. Hence the need to use '.' (current folder) – VonC Jul 30 '15 at 12:28
  • Oh, a substitution. Can't get used to shell's fancy syntax. )) – Nick Volynkin Jul 30 '15 at 12:31