Using gradle project variable in buildscript scope - gradle

There is a similar question here Access project extra properties in buildscript closure
but i found a "workaround" which does not look like the optimum
I have a multi gradle project - im declaring the repository in the main gradle file
using
subprojects {
repostiories {
maven {..}
}
}
now i also have to set these for the build script because im using a plugin !
so again buildscript { repositories ...
Now instead of pasting the URLs twice i wanted to use a property - as i figured project.ext properties are not set during the buildscript stage thus i put them
in my gradle.settings file
i couldnt set rootProject.ext.xx settings so i had to use
gradle.ext {
mavenURLs = [ companyURL1, companyURL2 ... etc]
}
Now i could use gradle.ext.mavenURLs in my build.gradle file
Is there a better way ?
Is there a way to set the buildscript and dependency repositories for all project in one block without repeating once for buildscript and once for the dependency ?

def repoClosure = { RepositoryHandler repoHandler ->
repoHandler.mavenLocal()
repoHandler.mavenCentral()
['http://mycompany/repo1', 'http://mycompany/repo2'].each { mavenURL ->
repoHandler.maven {
url mavenURL
credentials {
username 'foo'
password 'bar'
}
}
}
}
project.with {
allprojects {
repoClosure(buildscript.repositories)
repoClosure(repositories)
}
}

Simply create my-repositories.gradle file, with content like:
def repoClosure = {
maven {
url uri("${rootProject.rootDir}/offline-repository")
}
google()
mavenCentral()
['http://mycompany/repo1', 'http://mycompany/repo2'].each { mavenURL ->
maven {
url mavenURL
credentials {
username 'my-name'
password 'my-password'
}
}
}
}
project.with {
allprojects {
buildscript {
ext.myVariable = "Just an example!"
repositories(repoClosure)
}
repositories(repoClosure)
}
}
Then in your build.gradle apply it, like:
buildscript {
apply from: './my-repositories.gradle'
ext {
kotlin_version = '1.5.30'
}
dependencies {
classpath 'com.android.tools.build:gradle:7.0.4'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
// ...

Related

Define the generator code location using gradle to build xtext and xtend

I'm trying to create a first project using xText and xTend building with gradle.
I created the grammar following the guidance in the xText documentation and also created the xtend generators.
In eclipse the code generates to src-gen folder as expected.
When I created the gradle script, also following the http://xtext.github.io/xtext-gradle-plugin/xtext-builder.html to build my code instead of generating the code in 'src-gen' folder it generates in 'build' folder.
Is there any way to change this folder from build to src-gen in the gradle? I tried a lot of things and I got always errors.
Complete code of grade script:
apply plugin: 'org.xtext.builder'
dependencies {
xtextLanguages 'com.example.mylang:mylang:1.0.0-SNAPSHOT'
}
xtext {
languages {
mylang{
setup = 'com.example.MyLangStandaloneSetup'
generator.outlet.producesJava = true
}
}
sourceSets {
main {
srcDir 'src/main/xtext'
xtendOutputDir 'src-gen'
}
}
}
you can configure that in the source set
sourceSets {
main.xtendOutputDir = 'xtend-gen'
}
e.g.
plugins {
id "org.xtext.xtend" version "1.0.21"
}
apply plugin: 'java'
apply plugin: 'org.xtext.xtend'
sourceSets {
main.java.srcDirs = ['src','xtend-gen']
main.xtendOutputDir = 'xtend-gen'
}
repositories {
jcenter()
}
dependencies {
// This dependency is exported to consumers, that is to say found on their compile classpath.
compile 'org.eclipse.xtext:org.eclipse.xtext.xbase.lib:2.13.0'
}
or for the xtxt builder plugin
buildscript {
repositories {
mavenLocal()
jcenter()
}
dependencies {
classpath 'org.xtext:xtext-gradle-plugin:1.0.21'
}
}
plugins {
id "org.xtext.builder" version "1.0.21"
}
repositories {
mavenLocal()
jcenter()
}
dependencies {
xtextLanguages 'org.xtext.example.mydslfoo:org.xtext.example.mydslfoo:1.0.0-SNAPSHOT'
}
xtext {
version '2.13.0'
languages {
mydslfoo {
setup = 'org.xtext.example.mydslfoo.MyDslFooStandaloneSetup'
generator {
outlets {
HEROES {
}
}
}
}
}
sourceSets {
main {
srcDir 'src'
output {
dir(xtext.languages.mydslfoo.generator.outlet, 'src-gen')
}
}
}
}

How are gradle extra properties set in the Kotlin DSL?

I'm trying to organize my build files as I would in groovy, by having values in a separate file to reuse. But I cannot understand the syntax to do the same thing in the kotlin DSL.
Here's what I'm using in root build.gradle.kts:
applyFrom("config.gradle.kts")
buildscript {
repositories {
google()
jcenter()
}
dependencies {
val test = project.extra["minSdkVer"]
classpath("com.android.tools.build:gradle:3.0.0-alpha4")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.1.2-5")
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
mavenCentral()
}
}
and here's whats in the config.gradle.kts that is being referenced:
mapOf(
Pair("minSdkVer", 22),
Pair("targetSdkVer", 25),
Pair("compiledSdkVer", 25),
Pair("buildToolsVer", "26-rc4")
).entries.forEach {
project.extra.set(it.key, it.value)
}
But there's an error:
Cannot get property 'minSdkVer' on extra properties extension as it
does not exist
A correct fix: Gradle collects and applies the buildscript { ... } blocks from your script strictly before executing anything else from it. So, to make your properties from config.gradle.kts available inside the buildscript, you should move applyFrom("config.gradle.kts") to your buildscript { ... } block:
buildscript {
applyFrom("config.gradle.kts")
/* ... */
}
Another possible mistake is using an extra property as extra["minSdkVer"] in a scope of another ExtensionAware, like a task in this example:
val myTask = task("printMinSdkVer") {
doLast {
println("Extra property value: ${extra["minSdkVer"]}")
}
}
In this case, extra.get(...) uses not the project.extra but the extra of the task.
To fix that, specify that you work with the project. Direct usage:
println(project.extra["minSdkVer"])
And for delegation.
val minSdkVer by project.extra

Gradle remove specific dependency configuration from generated pom

I need to ignore some dependencies defined in the configuration "configurations.nonDistributable" when using gradles plugin maven-publish to generate pom files, I haven't found a reliable way of doing this, except for manually parsing the XML to remove them. Am I missing something, does gradle allow for an easier way of doing this?
build.gradle example:
configurations{
nonDistributable
}
dependencies {
nonDistributable ('org.seleniumhq.selenium:selenium-java:2.52.0'){
exclude group:'com.google.guava' // included in elasticsearch
}
nonDistributable ('com.assertthat:selenium-shutterbug:0.3') {
transitive = false
}
nonDistributable 'mysql:mysql-connector-java:5.1.40'
nonDistributable fileTree(dir: 'non-distributable-libs', include: '*.jar')
}
// generate subprojects pom
subprojects {
apply plugin: 'maven-publish'
model {
tasks.generatePomFileForMavenJavaPublication {
destination = file("$buildDir/../../$distDir/build/pom/$project.name-pom.xml")
}
}
afterEvaluate { project ->
publishing {
publications {
mavenJava(MavenPublication) {
from components.java
}
}
}
}
}
// generate root project pom
model {
tasks.generatePomFileForMavenJavaPublication {
destination = file("$buildDir/../$distDir/build/pom/$project.name-pom.xml")
}
}
afterEvaluate { project ->
publishing {
publications {
mavenJava(MavenPublication) {
from components.java
}
}
}
}
You can create your own publication pom. It would look something like this:
customMaven(MavenPublication) {
artifactId 'myArtifactId'
pom.withXml {
def dependencies = asNode().appendNode('dependencies')
configurations.specialConfiguration.getResolvedConfiguration().getFirstLevelModuleDependencies().each {
def dependency = dependencies.appendNode('dependency')
dependency.appendNode('groupId', it.moduleGroup)
dependency.appendNode('artifactId', it.moduleName)
dependency.appendNode('version', it.moduleVersion)
}
}
}
Then you can create a special configuration that extends from only those configurations that you want to include.
I am using this to create a special pom that contains all testRuntime dependencies to be used for integration tests separated from the main project.

Gradle Custom buildScriptRepository methods

I would like to make a custom buildScript repository method so I can easily reference our internal maven repo. Right now I'm required to declare a maven block everywhere we use our plugin.
Here is the current setup
buildscript {
repositories {
jcenter()
maven { url 'http://myNexus:8081/nexus/content/repositories/My-Release' }
}
dependencies {
classpath 'com.example.plugin:my-plugin:1+'
}
}
What I would like to do is something like this
buildscript {
repositories {
jcenter()
myReleaseRepo()
}
dependencies {
classpath 'com.example.plugin:my-plugin:1+'
}
}
How can I make a method available to create a repository anywhere we may use the plugin in the future?
Another solution is to add custom methods on RepositoryHandler using some Groovy goodness. Just chuck this in ~/.gradle/init.gradle
RepositoryHandler.metaClass.myReleaseRepo = {
delegate.maven {
name 'myReleaseRepo'
url 'http://myNexus:8081/nexus/content/repositories/My-Release'
}
}
After that, you can use it just as you described:
buildscript {
repositories {
myReleaseRepo()
}
}
Metaclasses in Groovy are just great. The delegate in this case is pretty much like the javascript this. This code is essentially using the RepositoryHandler instance (delegate keyword) and just calling repositoryHandlerInstance.maven(name, url).
It is possible to add a repo to an init script which would then apply to all gradle invocations that use the init script - without having to individually declare your maven repo in each build.gradle.
Solution 1:
Partial solution, does not do exactly what you're asking for. In init.gradle:
allprojects{
buildscript{
repositories{
maven{ url 'http://myNexus:8081/nexus/content/repositories/My-Release' }
}
}
}
Then your build.gradle can skip buildscript repo declaration entirely:
buildscript {
dependencies {
classpath 'com.example.plugin:my-plugin:1+'
}
}
Solution 2:
In fact, you can even move your buildscript classpath declaration to init and have the plugin apply to all projects that use the init script:
beefier init.gradle
allprojects{
buildscript{
repositories{
maven{ url 'http://myNexus:8081/nexus/content/repositories/My-Release' }
}
dependencies {
classpath 'com.example.plugin:my-plugin:1+'
}
}
}
gives you a lighter build.gradle
apply plugin: 'my-plugin'
I tried to, but apparently you cannot move the apply line to init.gradle as well. see this defect.
Solution 3:
I retract what I said in the comment above, I figured out how to do exactly what you're asking for. Apparently you can create extensions for the buildscript block using the initscript. However I still prefer solution2, because it gives you a cleaner build.gradle.
To create a buildscript extension, in your init.gradle:
class customRepos {
def buildscript
customRepos(buildscript) {
this.buildscript = buildscript
}
void addMyRepo() {
buildscript.repositories {
maven{ url 'http://myNexus:8081/nexus/content/repositories/My-Release' }
}
}
}
allprojects {
extensions.create('myRepo', customRepos, buildscript)
}
which then allows you to do this in your build.gradle
buildscript{
myRepo.addMyRepo()
dependencies {
classpath 'com.example.plugin:my-plugin:1+'
}
}
apply plugin: 'my-plugin'

Gradle global variable not in scope within buildscript

I have something like this in my top level build.gradle (Gradle 2.2)
ext.repo = "https://my-artifactory-repo"
buildscript {
repositories {
maven {
credentials {
username foo
password bar
}
url repo //doesn't work
}
}
dependencies {
classpath 'com.android.tools.build:gradle:0.14.1'
}
}
allprojects {
repositories {
maven {
credentials {
username foo
password bar
}
url repo //works
}
}
}
This is the error
Could not find property 'repo' on org.gradle.api.internal.artifacts.repositories.DefaultMavenArtifactRepository_Decorated#718afa64.
So it works in allprojects but not buildscript.
You can define your variable as an extra property with ext in the buildscript {...}. This variable is then also accessible in the scope of allprojects {...}:
buildscript {
ext {
repo = "https://my-artifactory-repo"
}
repositories {
maven {
url repo // works
}
}
}
allprojects {
repositories {
maven {
url repo // works
}
}
}
This is happening because the buildscript {...} configuration closure is always evaluated first, so the property is not yet defined. A workaround would be to define the property outside of the build script, either by placing it in a gradle.properties file or via the command line.

Resources