AWK statement inside a git alias

2019-07-22 13:14发布

问题:

I'm trying to create a git alias to print all pull requests from the log, in a specific format. However I'm having issues with AWK to remove double spaces.

This is the output from git log using this command: git log --merges --grep="pull request" --pretty=format:"[%h] %s %b" [SHA]..HEAD

[5c420cb] Merge pull request #001 from repo_name/branch_name Pull request title

Piping with the following AWK command I was able to print it as I wanted: awk '{$2=$3=$4=$6=$7=""; gsub(/ +/," ",$0); $2=$2 ":"; print}'

[5c420cb] #001: Pull request title

However, glueing everything in the git alias

[alias]
    release = !"git log --merges --grep=\"pull request\" --pretty=format:\"[%h] %s %b\" $1..HEAD | awk '{$2=$3=$4=$6=$7=\\\"\\\";gsub(/ +/,\\\" \\\",$0);$2=$2 \\\":\\\";print}'"

AWK prints that the [SHA] is not a file:

$ git release SHA
awk: can't open file SHA
 source line number 1

What could be wrong? I'm open to use other tools like sed, cut or even a bash function inside the alias.

I'm under OS X Mavericks.

回答1:

When git calls your alias it sticks your arguments on the end of the command and runs it.

With your alias that turns in to (manually dequoted so ignore quoting errors):

git log --merges --grep="pull request" --pretty=format:"[%h] %s %b" $1..HEAD | awk '{$2=$3=$4=$6=$7=\\"\\";gsub(/ +/,\\" \\",$0);$2=$2 \\":\\";print}' SHA

At which point $1 expands to nothing, git sees ..HEAD (which is perfectly reasonable).

awk sees an argument of SHA which doesn't exist and triggers the error (and causes it to ignore stdin).

You need to wrap the pipeline in a "shell script".

release = "!bash -c 'git log --merges --grep=\"pull request\" --pretty=format:\"[%h] %s %b\" $1..HEAD | awk \"{\\$2=\\$3=\\$4=\\$6=\\$7=\\\"\\\";gsub(/ +/,\\\" \\\",\\$0);\\$2=\\$2 \\\":\\\";print}\"' -"

It might be possible to do that in a way that has less horrible quoting but that's the format that's worked for me so I've stuck with it.

The - argument there at the end is to fill the $0 argument to that shell so positional arguments work the way people expect them to.