I implement a Gradle plugin - defining some required constants in a Groovy class
like
class MyConstants { public final static String blurbId = "xyz" }
Now I want to access this constant “blurbId” from Gradle build…
Tried JavaExec, but in vain, as I have no main method to call…
How can I assign this Groovy constant to a Gradle variable (in ext-block?)
Gernot, you are right about the classpath. You still need to tell Gradle about the classpath in the buildscript even if you don’t have an apply plugin.
buildscript {
dependencies {
// the classic way
classpath 'group:module:version'
// OR you can do
classpath fileTree ( dir: '/path/to/Jars' include:'*.jar' )
}
Ah now I see what you’re trying. ProductVersion is part of your project you’re building which is a gradle plugin and not part of a gradle plugin you use for building your project.
This is currently not out of the box supported, because the classes of the project itself are not part of the build classpath. You have different options here I guess
use regex to get the versionId out of your ProductVersion class
reverse the way the version is handled. you can declare the version in your build script and then prepocess your ProductVersion java file to get this version information backed into this file.
alternatively use a method in ProductVersion to resolve the version from a property file instead of having a field for this. From the user perspective this would look the same as your current user api as you can take advantage from groovy’s property syntax.
personally I would go with option3. A solution could look like this:
//your ProductVersion class
class ProductVersion {
public static String getVersionId() {
try{
final URL resource = ProductVersion.class.getClassLoader().getResource("htmlsanitycheckversion.properties");
Properties props = new Properties()
props.load(resource.openConnection().inputStream)
return props.getProperty("version");
} catch (IOException E) {
}
return "[unknown]";
}
}
You would need an additional properties file where you store the version information:
# a file src/main/resources/htmlsanitycheckversion.properties
version=@version@
Now you just need to ensure this version information is updated during the build:
// in your build.gradle file
processResources {
inputs.property "version", project.version
filter(org.apache.tools.ant.filters.ReplaceTokens, tokens: [version: project.version])
}
Now you still have the contract of ProductVersion.versionId, but the version information is owned by the build process, which is imo the better place for this information.
well you can have the version information declared in your build.gradle
file or in a gradle.properties file. it is up to you. people tend to put
this into the gradle.properties file (next to your build.gradle file)
these days as it is easier to maintain (and to automate)