我正在编写将应用程序部署到服务器的任务.但是,我希望此任务仅在我当前的git分支是主分支时运行.我怎样才能获得当前的git分支?
gradle-git
做法:我知道有一个gradle-git插件getWorkingBranch()
在任务下有一个方法GitBranchList
,但我随时尝试执行
task getBranchName(type: GitBranchList) {
print getWorkingBranch().name
}
Run Code Online (Sandbox Code Playgroud)
我收到"任务尚未执行"错误.我查看了源代码,当没有分支集时它会抛出该错误.这是否意味着这种方法不能完全符合我的想法?我需要在某个地方设置分支?
小智 30
您也可以在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
}
Run Code Online (Sandbox Code Playgroud)
Hie*_*mus 19
不,这并不意味着没有设置分支.这意味着该任务尚未真正执行.你要做的是在配置闭包中调用一个方法,而你可能想在任务执行后调用它.尝试将您的任务更改为:
task getBranchName(type: GitBranchList) << {
print getWorkingBranch().name
}
Run Code Online (Sandbox Code Playgroud)
随着<<
你添加一个doLast,它将在任务执行后执行.
这本质上是 @Song Bi 的答案,但是在 kotlin DSL 中(受到此线程的启发):
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"
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
16241 次 |
最近记录: |