I do something very similar on my project - packaging up build info into a properties file that can be read from the classpath in your Java application.
Here's how I accomplish that in a Gradle script:
tasks.withType(Jar).all { Jar jar ->
jar.doFirst {
String jarType = jar.extension
if(jar.classifier) jarType = jar.classifier
String fileName = "project.properties"
ant.propertyfile(file: "${jar.temporaryDir}/${fileName}") {
entry(key: "PROJECT_GROUP", value: project.group)
entry(key: "PROJECT_ARTIFACT", value: project.archivesBaseName)
entry(key: "PROJECT_VERSION", value: project.version)
entry(key: "PROJECT_BUILD_DATE", value: new Date())
entry(key: "BUILD_NUMBER", value: hasProperty("teamcity") ? teamcity["build.number"] : "local")
}
String intoPath = "your/package/name/here/${project.name}/${jarType}"
jar.from(jar.temporaryDir) {
include fileName
if(jar instanceof War) intoPath = "WEB-INF/classes/${intoPath}"
into(intoPath)
}
println "\tCreated ${intoPath}/${fileName}"
}
}
Here, I'm adding functionality to every Jar
task (including War
) that creates a properties file for that archive and includes it on the classpath under your/package/name/here/${project.name}/${jarType}/project.properties
.
This is the beauty of Gradle. It makes customizations like this very simple - no plugin required.
Then, to read the properties in my app, I inject or hardcode the expected path to the file and load the properties like this:
public Properties lookupClassPathResource(String pathToResource) {
Properties p = null;
org.springframework.core.io.Resource r = new org.springframework.core.io.ClassPathResource(pathToResource);
if(r.exists()) {
try {
p = org.springframework.core.io.support.PropertiesLoaderUtils.loadProperties(r);
} catch (IOException e) {
//log or wrap/rethrow exception
}
}
return p;
}
And fun times are had by all!
EDIT: Apparently the question/answer linked in the OP (about accessing build.number
) is a little out-of-date. Instead of doing System.getProperty("build.number")
, you can use the teamcity
properties that TeamCity implicitly adds to your project via a Gradle init script. The code above has been modified to reflect this. Also see this question for other examples.