Setting up Artifactory in gradle global - gradle

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"
}
}
}
}

Related

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'
}

Setting POM version for upload archive in Gradle build

I am using Gradle to build my own Android Libraries. I put this libraries into a gradle multi project.
Root Project
Lib A
Lib B
and so on.
I am trying to upload the created aar files into my local maven repo (.m2 directory)
I am using the following commands in my gradle file of the Root Project
uploadArchives {
repositories {
mavenDeployer {
repository(url: mavenLocal().url)
pom.groupId = rootProject.group
pom.artifactId = project.name
pom.version = project.version
}
}
}
everything works fine except the settings for the project.version. Where can I define the value for every single subproject?
Regards
Michael
Try checking out Gradle-Fury at https://github.com/gradle-fury/gradle-fury
Essentially, set the pom.version and various other settings in gradle.properties, add a few apply from throughout the build.gradle files and you're set. Definitely works with direct publication to sonatype oss/central.
These settings can be overridden on a per module basis by adding a gradle.properties file in each module that you need to override the parent's settings from.
declaimer: i'm one of the authors

How to provide correct settings for gradle?

Using Jenkins for CI, I need to use hidden credentials for Gradle or maven publishing. My credentials are applied in Jenkins rather than in source code. Maven settings are in a settings.xml, but I would like to define properties in Jenkins. What would I use in a command-line to do this? I imagine
gradle -Dsomething.username=blah -Dsomething.password=secret
There may be a better way but this is how we do it: we define target maven repository in build.gradle using custom project properties and then provide those properties via command line:
uploadArchives {
repositories {
mavenDeployer {
repository(url: "https://your-repo-server.company.com/your-built-artifacts") {
authentication(userName: project.getProperties()['nexusUploadUsername'], password: project.getProperties()['nexusUploadPassword'])
}
}
}
}
gradle -PnexusUploadUsername=blah -PnexusUploadPassword=secret
You can also take one step further and configure them as Jenkins build parameters or environment variables in order to prevent people from seeing them in logs (do not forget to set that 'Mask passwords' checkbox): gradle -PnexusUploadUsername=$JENKINS_NEXUS_USER -PnexusUploadPassword=$JENKINS_NEXUS_PASSWORD.

How to specify module name when publishing to Artifactory from Jenkins

I'm using the gradle artifactory publish plugin documented here: http://www.jfrog.com/confluence/display/RTF/Gradle+1.6+Publishing+Artifactory+Plugin
I'm using the standard config exactly as laid out in the documentation.
When I run the gradle publishArtifactory task from the command line I get output like this. I.e. It deploys to my correct module name.
Deploying artifact: http://<my server>/artifactory/libs-snapshot-local/<my actual module name>/web/0.1-SNAPSHOT/web-0.1-SNAPSHOT.war
When I configure Jenkins to run the gradle publishArtifactory task using the same gradle build file I get output like this. I.e. It uses the Jenkins build for the module name.
Deploying artifact: http://artifactory01.bcinfra.net:8081/artifactory/libs-snapshot-local/<the name of the jenkins build>/web/0.1-SNAPSHOT/web-0.1-SNAPSHOT.war
Any ideas on how to prevent the artifactory plugin from using the Jenkins build name for the module name?
The module name used for uploading is derived from the gradle project name. The default value for a gradle project name is taken from the project folder name. I suspect that on your jenkins job you check out your code into a folder named like your build job. That's why per default this folder name is used as project name.
The cleanest solution is to explicitly set your project name in gradle.
Therefore you need a settings.gradle file in your project root folder that contains the project name:
rootProject.name = "web"
You can also let Gradle single-handedly do the publishing to Artifactory, without the need for the Artifactory plugin in Jenkins.
This way, you can set the names of the artifacts using artifactId "your artifact name" without changing the project's name as suggested by Rene Groeschke.
Here's my publish.gradle that demonstrates this:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath "org.jfrog.buildinfo:build-info-extractor-gradle:3.0.1"
}
}
// Because this is a helper script that's sourced in from a build.gradle, we can't use the ID of external plugins
// We either use the full class name of the plugin without quotes or an init script: http://www.gradle.org/docs/current/userguide/init_scripts.html
apply plugin: org.jfrog.gradle.plugin.artifactory.ArtifactoryPublicationsPlugin
// Pack the sources into a jar
task sourceJar(type: Jar) {
from sourceSets.main.allSource; classifier = "sources"
}
// Pack the Javadoc into a jar
task javadocJar(type: Jar) {
from javadoc.outputs.files; classifier = "javadoc"
}
apply plugin: "maven-publish"
publishing {
publications {
mavenJava(MavenPublication){
from components.java
// Set the base name of the artifacts
artifactId "your artifact name"
artifact jar
artifact sourceJar
artifact javadocJar
}
}
}
artifactory {
contextUrl = "http://localhost:8081/artifactory"
publish {
// Publish these artifacts
defaults{ publications ("mavenJava") }
repository {
repoKey = "libs-release-local"
// Provide credentials like this:
//-Partifactory.publish.password=yourPassword
//-Partifactory.publish.username=yourUsername
}
}
resolve {
repository {
repoKey = "libs-release"
}
}
}
You can use this script in your build.gradle via apply from: "path/to/publish.gradle" and call it like this:
./gradlew artifactoryPublish -Partifactory.publish.username="yourUsername" -Partifactory.publish.password="yourPassword"

Resources