forkandwait
forkandwait

Reputation: 5157

Git alias gives pathspec error

I am trying to diagnose a problem with an alias that lets a user checkout the most recent commit of a file in order to clobber their most recent changes. I don't want to reset hard, just checkout the older version into a new round of committing.

It is also important not to branch the entire repo to HEAD^ if a file name is not passed in mistakenly, hence the -u switch for sh (to choke if $1 is not filled with something).

We are all working in the same repository if that matters, and I am the only user who isn't a complete newbie, but I am not a git master by any means.

We are using MsysGit 1.8.4 on Windows 7.

Here is the alias:

[alias]
    back1=!sh -uc 'git checkout HEAD^ $1 ' -

However, this sometimes gives an error like

$ git back0 format_tests.sas
error: pathspec 'format_tests.sas' did not match any file(s) known to git.

However if I run

$ git checkout HEAD^ format_tests.sas

directly from the command line, it works fine. It also seems to test fine on another git repository.

I feel like it might be a quoting problem, but I have no idea at this point.

The reason I don't use the method presented below is that if I run the command without a file, I get something like the following, which is NOT OK in our newbie environment (why I used a shell command with the "-u" switch in the first place):

testgit.git/ (j=0,r=0)$ git back1
Warning: you are leaving 1 commit behind, not connected to
any of your branches:

  a77dfed hlksdj;

If you want to keep them by creating a new branch, this may be a good time
to do so with:

 git branch new_branch_name a77dfed

HEAD is now at 954f639... blakjsd

Thanks for the interest and help!

Upvotes: 0

Views: 476

Answers (1)

ssmith
ssmith

Reputation: 734

Your alias doesn't need to be run through the shell, you should be able to do this:

[alias]
    back=checkout HEAD^ --

Git will automatically append the alias' arguments, meaning this:

$ git back afile bfile cfile

will turn into this:

$ git checkout HEAD^ -- afile bfile cfile

Bonus: Note the use of the double hyphen "--", this tells checkout that the remaining arguments are all files, otherwise it may mistakenly interpret a file as an existing branch or other ref.

To address the poster's requirement of using a shell command alias, the catch is that the subshell will have it's working directory set to the repository's root directory. Here's what git help config has to say:

alias.*
    [...] 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.

The good news is the GIT_PREFIX variable that you can use in your command like so:

back1=!sh -uc 'git checkout HEAD^ -- "$GIT_PREFIX/$1"' -

Upvotes: 2

Related Questions