我正在编写一个任务,将我的应用程序部署到服务器。但是,我希望只有当我当前的git分支是主分支时,才运行这个任务。如何获取当前的git分支?
gradle-git方法:
我知道有一个gradle-git plugin在任务GitBranchList下有一个getWorkingBranch()方法,但是每当我尝试执行
task getBranchName(type: GitBranchList) {
print getWorkingBranch().name
}我得到一个“任务还没有执行”的错误。我查看了source,当没有分支集时,它会抛出这个错误。这是不是意味着这个方法并不像我想的那样呢?我需要把树枝放在什么地方?
发布于 2013-02-25 16:21:53
不,这并不意味着没有设置分支。这意味着任务还没有真正执行。您要做的是在配置闭包中调用一个方法,而您可能希望在任务执行后调用它。尝试将您的任务更改为:
task getBranchName(type: GitBranchList) << {
print getWorkingBranch().name
}使用<<,您将添加一个doLast,它将在任务执行后执行。
发布于 2016-04-21 13:05:07
您也可以在没有插件的情况下获得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
}请参阅:Gradle & GIT : How to map your branch to a deployment profile
发布于 2021-08-11 13:59:42
这里本质上是@Song Bi的答案,但在kotlin DSL中(灵感来自这个线程here):
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import java.io.ByteArrayOutputStream
/**
* Utility function to retrieve the name of the current git branch.
* Will not work if build tool detaches head after checkout, which some do!
*/
fun gitBranch(): String {
return try {
val byteOut = ByteArrayOutputStream()
project.exec {
commandLine = "git rev-parse --abbrev-ref HEAD".split(" ")
standardOutput = byteOut
}
String(byteOut.toByteArray()).trim().also {
if (it == "HEAD")
logger.warn("Unable to determine current branch: Project is checked out with detached head!")
}
} catch (e: Exception) {
logger.warn("Unable to determine current branch: ${e.message}")
"Unknown Branch"
}
}https://stackoverflow.com/questions/15061277
复制相似问题