How to get a Date
object representing the time of start of the build 开发者_开发技巧process in Gradle?
Some background
In a plugin I am writing, I need to store the date and time of the build in the constructed archive (it's mainly used to display the date along with build number in the title bar of the application, to make QA life easier).
I want to have the same date for multiple subprojects that are being built, so ideally I would like to just use the start of build. As a workaround, I hold the date in a static field, but it hurts my eyes. I've seen in the source that there are multiple org.gradle.util.Clock
instances that hold such information, but I cannot find a way to retrieve one from a plugin.
Your plugin could just set/get a dynamic property on the root project:
def root = project.rootProject
if (!root.hasProperty("startTime")) {
root.startTime = new Date()
}
// do whatever necessary with root.startTime
I've managed to retrieve the build time clock with following code:
Clock clock = project.gradle.services.get(BuildRequestMetaData.class).buildTimeClock
Date startDate = new Date(clock.getStartTime())
Still, it's far from being ideal, since it uses Gradle internal API: getServices()
method is defined in org.gradle.api.internal.GradleInternal
interface.
I could not get either of the above methods to quite produce what the OP (and I) was looking for, so I came up with this build.gradle
:
import java.text.SimpleDateFormat
import java.util.Date
apply plugin: 'java'
def getCurrentTimestamp ()
{
Date today = new Date ()
SimpleDateFormat df = new SimpleDateFormat ("MM-dd-yyyy_hh-mm")
return df.format (today)
}
task tar (type: Tar) {
from 'src/'
baseName 'sillyProject'
classifier getCurrentTimestamp ()
extension 'tar'
}
repositories {
mavenCentral()
}
dependencies {
// etc.
This produces the tar archive (i.e., when you run $ gradle tar
) under $projectDir/build/distributions/sillyProject-<currentTimestamp>.tar
. Hope this helps someone.
精彩评论