How to execute git command from build.gradle?

2019-06-15 16:24发布

问题:

Could you guys clarify why

def getBuildSuffix() {
  return 'git rev-list HEAD | wc -l | tr -d " "'.execute().text.trim()
}

returns nothing to me taking into consideration there is data when you run git command from a command line:

prototype (master) $ git rev-list HEAD | wc -l | tr -d " "
72

May be I'm just executing a git command from my build.gradle in a wrong way?

回答1:

Pipe is a shell feature so you need to go like:

['sh', '-c', 'git rev-list HEAD | wc -l | tr -d " "'].execute().text.trim()


回答2:

You have to do your own piping or call by shell (see answer from @topr). see the error:

def p1 = 'git rev-list HEAD | wc -l | tr -d " "'.execute()
p1.waitFor()
println p1.exitValue()
//-> 128
println p1.errorStream.text
//-> fatal: ambiguous argument '|': unknown revision or path not in the working tree.
//-> Use '--' to separate paths from revisions, like this:
//-> 'git <command> [<revision>...] -- [<file>...]'
println p1.text 
//-> nothing

Use groovy e.g.:

println 'git rev-list HEAD'.execute().text.split().size()


回答3:

If you're doing this for Android you need Integer.parseInt(), like so:

Integer.parseInt(['sh','-c','git rev-list --all --count'] .execute().text.trim())



标签: groovy gradle