Some gradle snippets

Building a jar that includes only parts of a project

Suppose you have a package "api" that you want to build separately. You can define a following task:


    task apiJar(type: Jar, group: "build", description: 'Assembles the API') {
        setClassifier("api")
        from sourceSets.main.allSource
        from sourceSets.main.output
        include 'alexiy/bla/bla/bla/api/**'
    }
        

Publication configuration

You must set the project version and maven group - setVersion(), setGroup(). Then you must configure maven publications:


    publishing {
        publications {
            //"projectName" is arbitrary, used to reference the publication in the script
            projectName(MavenPublication) {
                //this is the artifact ID. Defaults to archive base name if not set
                artifactId 'some-artifact'
                // add all jars to be included for publishing
                artifact(jar) {
                    builtBy remapJar
                }
                artifact(sourcesJar) {
                    builtBy remapSourcesJar
                }
                artifact apiJar
                artifact makeApiSource
            }
        }
    }
    

Inheriting dependencies of an arbitrary project

Suppose we have a main project and 2 subprojects.


            main-project
            |--subproject-alpha
            |--subproject-beta
        

Main project contains dependencies that we want to use in both subprojects, and we also want to use main project's code. We can achieve that without using plugins by adding following code to the subprojects' build scripts:


    dependencies {
            //depend on the root project
        implementation project(':')
            //depend on all of the root project's dependencies
        rootProject.configurations.each { configuration->
            configuration.dependencies.each { dependency->
                dependencies.add(configuration.name,dependency)
            }
        }
    }
         

We can also add dependencies of specific configurations only. Here is how to add dependencies of test configurations:


    rootProject.configurations.testImplementation.dependencies.each { dep->
        dependencies.add('testImplementation',dep)
    }
         
As you can see, we're achieving this mostly by using Groovy code.