如何在 gradle 中获取当前的 git 分支?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15061277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get the current git branch in gradle?
提问by neptune
I'm writing a task to deploy my application to the server. However, I'd like for this task to run only if my current git branch is the master branch. How can I get the current git branch?
我正在编写一个任务来将我的应用程序部署到服务器。但是,我希望此任务仅在我当前的 git 分支是主分支时运行。如何获取当前的 git 分支?
gradle-git
approach:
gradle-git
方法:
I know there is a gradle-git pluginthat has a method getWorkingBranch()
under the task GitBranchList
, but anytime I try to execute
我知道有一个gradle-git 插件getWorkingBranch()
在任务下有一个方法GitBranchList
,但任何时候我尝试执行
task getBranchName(type: GitBranchList) {
print getWorkingBranch().name
}
I get a "Task has not executed yet" error. I looked at the sourceand it throws that error when there is no branch set. Does that mean this method doesn't do quite what I think it does? That I need to set the branch somewhere?
我收到“任务尚未执行”错误。我查看了源代码,当没有设置分支时,它会抛出该错误。这是否意味着这种方法不像我认为的那样做?我需要在某处设置分支吗?
回答by Song Bi
You also are able to get git branch name
without the plug-in.
您也可以在git branch name
没有插件的情况下获得。
def gitBranch() {
def branch = ""
def proc = "git rev-parse --abbrev-ref HEAD".execute()
proc.in.eachLine { line -> branch = line }
proc.err.eachLine { line -> println line }
proc.waitFor()
branch
}
Refer to: Gradle & GIT : How to map your branch to a deployment profile
回答by Hiery Nomus
No this doesn't mean that the branch is not set. It means that the task hasn't really executed yet. What you're trying to do is calling a method in the configuration closure, whereas you probably want to call it after task execution. Try to change your task to:
不,这并不意味着没有设置分支。这意味着任务还没有真正执行。您要做的是在配置闭包中调用一个方法,而您可能希望在任务执行后调用它。尝试将您的任务更改为:
task getBranchName(type: GitBranchList) << {
print getWorkingBranch().name
}
With the <<
you're adding a doLast, which will be executed after the task has been executed.
随着<<
您添加一个 doLast,它将在任务执行后执行。