dtell
dtell

Reputation: 2568

Git alias for git status lists files relative to repository root

I have a bunch of shorthand aliases for git commands. One of them is git stat as an abbreviation for git status.

I declare the alias in my global git configuration (living in ~/.gitconfig) as

[alias]
stat = !"git status"

This works fine but an annoying problem occurs: When I'm inside of a git repository git stat always shows me paths relative to the repository root rather than to the current directory.

An example:

repo
├── .git
└── folder
    └── file
$ cd repo/folder
$ touch fileB
$ git stat
Untracked files:
  (use "git add <file>..." to include in what will be committed)
    folder/fileB
$ git status
Untracked files:
  (use "git add <file>..." to include in what will be committed)
    fileB

As you can see git stat lists fileB relative to repo while git status lists it relative to repo/folder.

How can I achieve my alias to behave as the original command?

Upvotes: 0

Views: 223

Answers (2)

torek
torek

Reputation: 487755

You're running into the fact that aliased shell commands are run from the top level of the working tree. This is documented, but it's cleverly hidden in the git config documentation, since there is no better place to put it:

If the alias expansion is prefixed with an exclamation point, it will be treated as a shell command. For example, defining alias.new = !gitk --all --not ORIG_HEAD, the invocation git new is equivalent to running the shell command gitk --all --not ORIG_HEAD. Note that shell commands will be executed from the top-level directory of a repository, which may not necessarily be the current directory. GIT_PREFIX is set as returned by running git rev-parse --show-prefix from the original current directory. See git-rev- parse[1].

You can use $GIT_PREFIX to locate the target directory. In this particular case, though, LeGEC's answer, pointing to using a simple alias, is the way to go.

Upvotes: 3

LeGEC
LeGEC

Reputation: 51780

You registered your alias as an external shell command (starting with !), which will be run from the repo's root.

If you want a shortcut for known git commands, set a simple alias rule :

git config --global alias.stat status

This also works with options to git commands :

git config --global alias.stat "status -sb"

You will gain the bonus ability to autocomplete all known options to this command (since git now "understands" what the alias is).

Upvotes: 3

Related Questions