How do I preconfigure Gradle Plugin Repository? - gradle

I want to use new fancy plugin { id: ''} syntax in Gradle with my custom in-house plugins that are stored in company's Artifacotry. In order to do this I can set maven repository for Gradle Plugin Repostiory in settings.gradle only.
I want to set this globally in my custom Gradle package that would be downloaded using Gradle wrapper. I can define globally dependencies repository and buildscript dependendencies repository in $GRADLE/init.d/repositories.gradle script, but I can not do it for Gradle Plugin Registry because it is required to be placed in settings.gradle.
How can I achieve this?

You can accomplish this using the settingsEvaluated method from the Gradle API.
Put the following in an init script.
def ENTERPRISE_REPOSITORY_URL = "https://repo.gradle.org/gradle/repo"
settingsEvaluated { setting ->
setting.pluginManagement.repositories {
// Remove all repositories not pointing to the enterprise repository url
all { ArtifactRepository repo ->
if (!(repo instanceof MavenArtifactRepository) ||
repo.url.toString() != ENTERPRISE_REPOSITORY_URL) {
project.logger.lifecycle "Repository ${repo.url} removed. Only
$ENTERPRISE_REPOSITORY_URL is allowed"
remove repo
}
}
// add the enterprise repository
maven {
name "STANDARD_ENTERPRISE_REPO"
url ENTERPRISE_REPOSITORY_URL
}
}
}

Related

how to set archiveBaseName for local .m2 repository

I'm trying to upgrade a dependency to a project that will ultimately become a dependency to my project. I've made the upgrade and I want to test it locally before I put it out on the repo to be used. I'm learning Gradle and a few Google searches showed me how to add the project to the settings.gradle file. But the dependency project uses aliases for their dependencies (see build.gradle below).
settings.gradle
include ':TransportImpl'
Changed to:
include ':TransportImpl', ':jeromq'
project(':jeromq').projectDir = new File("../zeromq/jeromq")
build.gradle
//project.ext.set("JEROMQ", 'THIRD-PARTY:jeromq:0.4.2')
project.ext.set("JEROMQ", ':jeromq')
If I uncomment the original line (shown commented above), because that apk is in the repo it gets recognized. I'm guessing that this only works for external libraries.
Other things I have tried:
//project.ext.set("JEROMQ", 'C:/Users/username/.m2/repository/THIRD_PARTY/jeromq/0.5.1-SNAPSHOT/jeromq-0.5.1-SNAPSHOT-jeromq.jar')
//project.ext.set("JEROMQ", 'C:\\Users\\username\\.m2\\repository\\THIRD_PARTY\\jeromq\\0.5.1\\jeromq-0.5.1-jeromq.jar')
//implementation filetree(dir: 'C:\\Users\\username\\.m2\\repository\\THIRD_PARTY\\jeromq\\0.5.1', include:['jeromq-0.5.1-jeromq.jar'])
Can anyone give me a tip on how I can assign a variable that points to the local repository and use that variable to set an archiveBaseName?
New Information:
gradle.build for our jeromq project
apply plugin : 'maven'
apply plugin : 'maven-publish'
// Top-level build file where you can add configuration options common to all sub-projects/modules.
ext {
// Nexus paths
nexusUrl='https://nexus.path'
Releases='/Private_Releases'
nexusUsername = project.findProperty("nexusUsername") ?: (System.getenv("NEXUS_USERNAME") ?: "user_name"
nexusPassword = project.findProperty("nexusPassword") ?: (System.getenv("NEXUS_PASSWORD") ?: "password")
// Project versions
jeromqVersion = "0.5.1-SNAPSHOT"
}
allprojects {
// Read only repositories for dependencies; this should never be used to publish
repositories {
mavenCentral()
jcenter()
}
}
The project that uses it as a dependency finds it using the following from its build.gradle file:
// Create aliases for dependencies
project.ext.set("EASY_MOCK", 'Test:easymock:3.5.1')
project.ext.set("OBJENESIS", 'Test:objenesis:2.6')
// **************** HERE ***************************
// THIRD-PARTY is configured to look on the nexus server
project.ext.set("JEROMQ", 'THIRD-PARTY:jeromq:0.4.2') ... or 0.5.1 or 0.5.1-SNAPSHOT ...
allprojects {
// Read only repositories for dependencies; this should never be used to publish
repositories {
mavenCentral()
mavenLocal()
// maven {
// // trying to add my local repo,
// // BUT this still does not change where THIRD-PARTY is pointing to
// url 'file://C:/Users/me/.m2/repository/THIRD_PARTY/jeromq/0.5.1-SNAPSHOT/jeromq-0.5.1-SNAPSHOT-jeromq.jar'
// }
maven {
name 'ReleasesName'
url "$nexusUrl$ReleasesName
}
}
maven {
name 'ReleasesNameSnapshots'
url "$nexusUrl$ReleasesNameSnapshots"
credentials {
username "${rootProject.ext.nexusReadOnlyUsername}"
password "${rootProject.ext.nexusReadOnlyPassword}"
}
}
jcenter {
url "https://jcenter.bintray.com/"
}
}
The only reason I need the alias for that dependency is because it is used in other places.
I'm not entirely sure what you are asking, but I think what you are trying is completely off.
The build you are trying to include is a Maven build, not a Gradle build, so it is unlikely you can simply treat it as it were a Gradle build.
And even if it were a Gradle build, including it like you did would not be the right way. How you tried it is for including multiple projects of a multi-project build, not including external libraries.
If it were a Gradle build, you would use a composite build, which effectively replaces a declared binary dependency by the build output of a "sub-build". But afair this only works cleanly with a Gradle build.
Why don't you simply mvn install your modified jeromq version, add mavenLocal() to your dependencies and depend on that just installed version? That would be the usual way for locally testing new Maven built dependencies.

Gradle repositories in Gradle settings instead of build?

In Maven, you can store the list of repositories in settings.xml, which means each developer can have his own settings (when you are inside a company, you will use the local Nexus as a mirror, but when outside, you will use Maven Central).
How do you do that with Gradle ?
You can use a gradle init script for that. these init scripts can live in the ~/.gradle/init.d/ folder. Having on (e.g. default-repos.gradle) with adding default repositories can look like this:
allprojects {
repositories {
maven {
url = 'http://nexus.local.org'
}
}
}

Setting up Artifactory in gradle global

currently I have a project which is deploying artifacts in our artifactory. For that Project everything is setted up perfect and it works.
I just wonderd if there is a possibility to set up the whole artifactory configuration global in gradle, so that I don't have to write the artifactory {...} stuff for each project.
You can maintain a file lets say build_dependency.gradle and define the task for all project
allprojects
{
//task common for all the project
}
subprojects
{
//task for subprojects
}
or specify the type of project e.g ext.warProject = 1 in dependency file and refer it in build_dependency.gradle as
if(project.hasProperty('warProject '))
{
//task here
}
and use this file in build.gradle like apply from: "$rootDir/path_to_file/build_dependency.gradle"
"$rootDir/path_to_dependenccy_file"`
You could simply write your own Gradle plugin that would be responsible for:
applying the artifactory plugin and other related plugin(s) like maven-publish
provide default values for the artifactory extension properties , like contextUrl, repoKey, credentials, etc...
Then your different projects will just have to apply your custom plugin, and provide only the project-specific configuration (configuration of the artefact to be published, for example, in publishing extension)
EDIT there are other ways to implement that, but it depends on what you mean by "global in gradle":
global to your own computer? then you could create a User InitScript that would contain the artifactory plugin configuration part
global to your team/company ? then you could need to implement a custom plugin, and maybe include this plugin into a custom gradle wrapper distribution (see example here
EDIT2 If you just want to set the artifactory plugin configuration of different sub-project of a same multi-project build, then the simpliest solution would be to define this configuration in the subprojects block of the root project build script:
subprojects {
apply plugin: "com.jfrog.artifactory"
artifactory {
publish {
contextUrl = '<repo url>'
repository {
repoKey = "<repo name>"
username = "user"
password = "pass"
}
}
}
}

Gradle - globally define plugins repository proxy-cache for all projects

I need to globally set the plugin repositories for all Gradle projects. There is a way of doing that by adding the below section in settings.gradle file:
pluginManagement {
repositories {
maven {
url 'https://artifactory.mycompany.org/artifactory/gradle-plugins/'
credentials {
username = 'some-user'
password = 'some-password'
}
}
}
}
However, when I put this file in ~/.gradle/settings.gradle, it doesn't seem to be working. I don't want to add such settings.gradle file in each project due to corporate reasons.
Is there a way of telling Gradle globally where to fetch all of the plugins?

Boilerplate project configuration in Gradle with Gradle Kotlin DSL

I'm currently trying to improve the way our projects share their configuration. We have lots of different multi-module gradle projects for all of our libraries and microservices (i.e. many git repos).
My main goals are:
To not have my Nexus repository config duplicated in every project (also, I can safely assume that the URL won't change)
To make my custom Gradle plugins (published to Nexus) available to every project with minimal boilerplate / duplication (they should be available to every project, and the only thing the project cares about is the version it's using)
No magic - it should be obvious to developers how everything is configured
My current solution is a custom gradle distribution with an init script that:
adds mavenLocal() and our Nexus repository to the project repos (very similar to the Gradle init script documentation example, except it adds repos as well as validating them)
configures an extension that allows our gradle plugins to be added to the buildscript classpath (using this workaround). It also adds our Nexus repo as a buildscript repo as that's where the plugins are hosted. We have quite a few plugins (built upon Netflix's excellent nebula plugins) for various boilerplate: standard project setup (kotlin setup, test setup, etc), releasing, publishing, documentation, etc and it means our project build.gradle files are pretty much just for dependencies.
Here is the init script (sanitised):
/**
* Gradle extension applied to all projects to allow automatic configuration of Corporate plugins.
*/
class CorporatePlugins {
public static final String NEXUS_URL = "https://example.com/repository/maven-public"
public static final String CORPORATE_PLUGINS = "com.example:corporate-gradle-plugins"
def buildscript
CorporatePlugins(buildscript) {
this.buildscript = buildscript
}
void version(String corporatePluginsVersion) {
buildscript.repositories {
maven {
url NEXUS_URL
}
}
buildscript.dependencies {
classpath "$CORPORATE_PLUGINS:$corporatePluginsVersion"
}
}
}
allprojects {
extensions.create('corporatePlugins', CorporatePlugins, buildscript)
}
apply plugin: CorporateInitPlugin
class CorporateInitPlugin implements Plugin<Gradle> {
void apply(Gradle gradle) {
gradle.allprojects { project ->
project.repositories {
all { ArtifactRepository repo ->
if (!(repo instanceof MavenArtifactRepository)) {
project.logger.warn "Non-maven repository ${repo.name} detected in project ${project.name}. What are you doing???"
} else if(repo.url.toString() == CorporatePlugins.NEXUS_URL || repo.name == "MavenLocal") {
// Nexus and local maven are good!
} else if (repo.name.startsWith("MavenLocal") && repo.url.toString().startsWith("file:")){
// Duplicate local maven - remove it!
project.logger.warn("Duplicate mavenLocal() repo detected in project ${project.name} - the corporate gradle distribution has already configured it, so you should remove this!")
remove repo
} else {
project.logger.warn "External repository ${repo.url} detected in project ${project.name}. You should only be using Nexus!"
}
}
mavenLocal()
// define Nexus repo for downloads
maven {
name "CorporateNexus"
url CorporatePlugins.NEXUS_URL
}
}
}
}
}
Then I configure each new project by adding the following to the root build.gradle file:
buildscript {
// makes our plugins (and any others in Nexus) available to all build scripts in the project
allprojects {
corporatePlugins.version "1.2.3"
}
}
allprojects {
// apply plugins relevant to all projects (other plugins are applied where required)
apply plugin: 'corporate.project'
group = 'com.example'
// allows quickly updating the wrapper for our custom distribution
task wrapper(type: Wrapper) {
distributionUrl = 'https://com.example/repository/maven-public/com/example/corporate-gradle/3.5/corporate-gradle-3.5.zip'
}
}
While this approach works, allows reproducible builds (unlike our previous setup which applied a build script from a URL - which at the time wasn't cacheable), and allows working offline, it does make it a little magical and I was wondering if I could do things better.
This was all triggered by reading a comment on Github by Gradle dev Stefan Oehme stating that a build should work without relying on an init script, i.e. init scripts should just be decorative and do things like the documented example - preventing unauthorised repos, etc.
My idea was to write some extension functions that would allow me to add our Nexus repo and plugins to a build in a way that looked like they were built into gradle (similar to the extension functions gradleScriptKotlin() and kotlin-dsl() provided by the Gradle Kotlin DSL.
So I created my extension functions in a kotlin gradle project:
package com.example
import org.gradle.api.artifacts.dsl.DependencyHandler
import org.gradle.api.artifacts.dsl.RepositoryHandler
import org.gradle.api.artifacts.repositories.MavenArtifactRepository
fun RepositoryHandler.corporateNexus(): MavenArtifactRepository {
return maven {
with(it) {
name = "Nexus"
setUrl("https://example.com/repository/maven-public")
}
}
}
fun DependencyHandler.corporatePlugins(version: String) : Any {
return "com.example:corporate-gradle-plugins:$version"
}
With the plan to use them in my project's build.gradle.kts as follows:
import com.example.corporateNexus
import com.example.corporatePlugins
buildscript {
repositories {
corporateNexus()
}
dependencies {
classpath(corporatePlugins(version = "1.2.3"))
}
}
However, Gradle was unable to see my functions when used in the buildscript block (unable to compile script). Using them in the normal project repos/dependencies worked fine though (they are visible and work as expected).
If this worked, I was hoping to bundle the jar into my custom distribution , meaning my init script could just do simple validation instead of hiding away the magical plugin and repo configuration. The extension functions wouldn't need to change, so it wouldn't require releasing a new Gradle distribution when plugins change.
What I tried:
adding my jar to the test project's buildscript classpath (i.e. buildscript.dependencies) - doesn't work (maybe this doesn't work by design as it doesn't seem right to be adding a dependency to buildscript that's referred to in the same block)
putting the functions in buildSrc (which works for normal project deps/repos but not buildscript, but is not a real solution as it just moves the boilerplate)
dropping the jar in the lib folder of the distribution
So my question really boils down to:
Is what I'm trying to achieve possible (is it possible to make custom classes/functions visible to the buildScript block)?
Is there a better approach to configuring a corporate Nexus repo and making custom plugins (published to Nexus) available across lots of separate projects (i.e. totally different codebases) with minimal boilerplate configuration?
If you want to benefit from all the Gradle Kotlin DSL goodness you should strive to apply all plugins using the plugins {} block. See https://github.com/gradle/kotlin-dsl/blob/master/doc/getting-started/Configuring-Plugins.md
You can manage plugin repositories and resolution strategies (e.g. their version) in your settings files. Starting with Gradle 4.4 this file can be written using the Kotlin DSL, aka settings.gradle.kts. See https://docs.gradle.org/4.4-rc-1/release-notes.html.
With this in mind you could then have a centralized Settings script plugin that sets things up and apply it in your builds settings.gradle.kts files:
// corporate-settings.gradle.kts
pluginManagement {
repositories {
maven {
name = "Corporate Nexus"
url = uri("https://example.com/repository/maven-public")
}
gradlePluginPortal()
}
}
and:
// settings.gradle.kts
apply(from = "https://url.to/corporate-settings.gradle.kts")
Then in your project build scripts you can simply request plugins from your corporate repository:
// build.gradle.kts
plugins {
id("my-corporate-plugin") version "1.2.3"
}
If you want your project build scripts in a multi-project build to not repeat the plugin version you can do so with Gradle 4.3 by declaring versions in your root project. Note that you also could set the versions in settings.gradle.kts using pluginManagement.resolutionStrategy if having all builds use the same plugins version is what you need.
Also note that for all this to work, your plugins must be published with their plugin marker artifact. This is easily done by using the java-gradle-plugin plugin.
I promised #eskatos that I would come back and give feedback on his answer - so here it is!
My final solution consists of:
Gradle 4.7 wrapper per project (pointed at a mirror of http://services.gradle.org/distributions setup in Nexus as a raw proxy repository, i.e. it's vanilla Gradle but downloaded via Nexus)
Custom Gradle plugins published to our Nexus repo along with plugin markers (generated by the Java Gradle Plugin Development Plugin)
Mirroring the Gradle Plugin Portal in our Nexus repo (i.e. a proxy repo pointing at https://plugins.gradle.org/m2)
A settings.gradle.kts file per project that configures our maven repo and gradle plugin portal mirror (both in Nexus) as plugin management repositories.
The settings.gradle.kts file contains the following:
pluginManagement {
repositories {
// local maven to facilitate easy testing of our plugins
mavenLocal()
// our plugins and their markers are now available via Nexus
maven {
name = "CorporateNexus"
url = uri("https://nexus.example.com/repository/maven-public")
}
// all external gradle plugins are now mirrored via Nexus
maven {
name = "Gradle Plugin Portal"
url = uri("https://nexus.example.com/repository/gradle-plugin-portal")
}
}
}
This means that all plugins and their dependencies are now proxied via Nexus, and Gradle will find our plugins by id as the plugin markers are published to Nexus as well. Having mavenLocal in there as well facilitates easy testing of our plugin changes locally.
Each project's root build.gradle.kts file then applies the plugins as follows:
plugins {
// plugin markers for our custom plugins allow us to apply our
// plugins by id as if they were hosted in gradle plugin portal
val corporatePluginsVersion = "1.2.3"
id("corporate-project") version corporatePluginsVersion
// 'apply false` means this plugin can be applied in a subproject
// without having to specify the version again
id("corporate-publishing") version corporatePluginsVersion apply false
// and so on...
}
And configures the gradle wrapper to use our mirrored distribution, which when combined with the above means that everything (gradle, plugins, dependencies) all come via Nexus):
tasks {
"wrapper"(Wrapper::class) {
distributionUrl = "https://nexus.example.com/repository/gradle-distributions/gradle-4.7-bin.zip"
}
}
I was hoping to avoid the boilerplate in the settings files using #eskatos's suggestion of applying a script from a remote URL in settings.gradle.kts. i.e.
apply { from("https://nexus.example.com/repository/maven-public/com/example/gradle/corporate-settings/1.2.3/corporate-settings-1.2.3.kts" }
I even managed to generate a templated script (published alongside our plugins) that:
configured the plugin repos (as in the above settings script)
used a resolution strategy to apply the version of the plugins associated with the script if the requested plugin id was one of our plugins and the version wasn't supplied (so you can just apply them by id)
However, even though it removed the boilerplate, it meant our builds were reliant on having a connection to our Nexus repo, as it seems that even though scripts applied from a URL are cached, Gradle does a HEAD request anyway to check for changes. It also made it annoying to test plugin changes locally, as I had to point it manually at the script in my local maven directory. With my current config, I can simply publish the plugins to maven local and update the version in my project.
I'm quite happy with the current setup - I think it's far more obvious to developers now how the plugins are applied. And it's made it far easier to upgrade Gradle and our plugins independently now that there's no dependency between the two (and no custom gradle distribution required).
I've been doing something like this in my build
buildscript {
project.apply {
from("${rootProject.projectDir}/sharedValues.gradle.kts")
}
val configureRepository: (Any) -> Unit by extra
configureRepository.invoke(repositories)
}
In my sharedValues.gradle.kts file I have code like this:
/**
* This method configures the repository handler to add all of the maven repos that your company relies upon.
* When trying to pull this method out of the [ExtraPropertiesExtension] use the following code:
*
* For Kotlin:
* ```kotlin
* val configureRepository : (Any) -> Unit by extra
* configureRepository.invoke(repositories)
* ```
* Any other casting will cause a compiler error.
*
* For Groovy:
* ```groovy
* def configureRepository = project.configureRepository
* configureRepository.invoke(repositories)
* ```
*
* #param repoHandler The RepositoryHandler to be configured with the company repositories.
*/
fun repositoryConfigurer(repoHandler : RepositoryHandler) {
repoHandler.apply {
// Do stuff here
}
}
var configureRepository : (RepositoryHandler) -> Unit by extra
configureRepository = this::repositoryConfigurer
I follow a similar patter for configuring the resolution strategy for plugins.
The nice thing about this pattern is that anything you configure in sharedValues.gradle.kts can also be used from your buildSrc project meaning that you can reuse repository declarations.
Updated:
You can apply another script from a URL, for example doing this:
apply {
// This was actually a plugin that I used at one point.
from("http://dl.bintray.com/shemnon/javafx-gradle/8.1.1/javafx.plugin")
}
Simply host your script that you want all your builds to share on some http server (would highly recommend using HTTPS so your build can't be targeted by a man in the middle attack).
The downside of this is that I don't think that scripts applied from urls aren't cached so they will be re-downloaded every time you run your build.
This may have been fixed by now, I'm not certain.
A solution offered to me by Stefan Oehme when I was having a similar problem was to vendor my own custom distribution of Gradle. According to him this is a common thing to do at large companies.
Simply create a custom fork of the gradle repo, add your companies special sauce to every project using this custom version of gradle.
I encountered a similar problem when common config is replicated in each and every project. Solved it by a custom gradle distribution with the common settings defined in init script.
Created a gradle plugin for preparing such custom distributions - custom-gradle-dist. It works perfectly for my projects, e.g. a build.gradle for a library project looks like this (this is a complete file):
dependencies {
compile 'org.springframework.kafka:spring-kafka'
}

Resources