Git config alias escaping

断了今生、忘了曾经 提交于 2019-11-28 10:20:58
alexK

EDIT This solution doesn't work in all cases. Here is a correct solution which works in all cases.

I'm using bash as a command-line and the following alias worked for me:

unwip = "!f() { git filter-branch --msg-filter 'sed -e "s/[ci skip/]$/g"' $1..HEAD ; }; f"

The only downside is that you're specifying the interpreter and always using sh. In my case I'm relying on user's shell. Though I don't believe it will be a problem in any of major shells as we're doing just basic stuff.

Generic solution

Getting a git alias to pass the parser correctly can be a mind-boggling set of \\\\" noise, so I created two aliases:

# Quote / unquote a sh command, converting it to / from a git alias string
quote-string = "!read -r l; printf \\\"!; printf %s \"$l\" | sed 's/\\([\\\"]\\)/\\\\\\1/g'; printf \" #\\\"\\n\" #"
quote-string-undo = "!read -r l; printf %s \"$l\" | sed 's/\\\\\\([\\\"]\\)/\\1/g'; printf \"\\n\" #"

This allows you to convert anything you could type into sh+, eg:

$ echo '\"'

\"

Into a quoted string fit for an alias:

$ git quote-string
echo '\"'

"!echo '\\\"' #"

To quote a multi-line string, I wrote a longer script, which I suggest you run as:

git quote-string |sponge

Answering OP's specific issue

Using git quote-string on the OP's command, I get:

"!git filter-branch -f --msg-filter \"sed -e \\\"s/\\[ci skip\\]$//g\\\"\" master..HEAD #"

So, to use the OP's preferred alias name, under [alias] in ~/.gitconfig, add:

unwip = "!git filter-branch -f --msg-filter \"sed -e \\\"s/\\[ci skip\\]$//g\\\"\" master..HEAD #"

Debugging

Sometimes it's nice to see what is going on under the hood. Try this alias:

debug  = "!set -x; GIT_TRACE=2 GIT_CURL_VERBOSE=2 GIT_TRACE_PERFORMANCE=2 GIT_TRACE_PACK_ACCESS=2 GIT_TRACE_PACKET=2 GIT_TRACE_PACKFILE=2 GIT_TRACE_SETUP=2 GIT_TRACE_SHALLOW=2 git"

Just insert debug between git and whatever would usually follow, eg for the OP's question:

git debug unwip


+ git uses /bin/sh to execute aliases beginning with !*. To work around this, create a command line like: bash -c 'echo \\\"' and then pass this to git quote-string.

* See the "Debugging" heading for proof

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!