Configure maven-publish via Java binary plugin

plugins

(Christian Bellina) #1

I’m writing a binary plugin to centralize the publishing configuration for our org’s projects.

In essence, I want to have one place where all our maven publication and repository information is kept so that developers don’t have to add this information to every one of their build scripts.

I’m writing the plugin in Java per the documentation’s recommendation to use a static language. However, I can’t figure out a straightforward way to set up the maven-publish configuration programmatically via Java.

I’m relatively new to Gradle and Groovy.

This is what I have:

Task defaultMavenPublishTask = project.getProject()
                                         .getTasksByName("publish", false)
                                         .stream()
                                         .findFirst()
                                         .orElseThrow(() -> new RuntimeException());

// TODO how do I configure the maven publish task (i.e. add configurations and repository info) using Java?

myPublishTask.dependsOn(defaultMavenPublishTask);

(Chris Doré) #2

When using the maven-publish plugin, you do not typically need to configure any of the tasks directly. You configure the publications and repositories and from that model the maven-publish plugin creates the required tasks.

Here’s a quick example of a plugin that adds a repository (note, I didn’t test this):

class RepoPlugin implements org.gradle.api.Plugin<org.gradle.api.Project>
{
    @Override
    void apply( org.gradle.api.Project project )
    {
        project.getPluginManager().apply( "maven-publish" );

        project.extensions.configure( org.gradle.api.publish.PublishingExtension, new Action<org.gradle.api.publish.PublishingExtension>() {
            @Override
            void execute( org.gradle.api.publish.PublishingExtension publishingExtension )
            {
                publishingExtension.getRepositories().maven( new Action<org.gradle.api.artifacts.repositories.MavenArtifactRepository>() {
                    @Override
                    void execute( org.gradle.api.artifacts.repositories.MavenArtifactRepository repo )
                    {
                        repo.setUrl( "http://my.server/myrepo" );
                    }
                } );
            }
        } );
    }
}

The Gradle Javadoc should help explain how to set other attributes you may need, like credentials. If you wish to also add publications, take a look at the return value of publishingExtension.getPublications().


(Christian Bellina) #3

Thanks Chris, that’s just what I needed.