Search code examples
javagradlebuild.gradlegradle-plugin

Is a .gradle file in buildSrc folder a plugin for projects?


I am learning gradle from the gradle official website:

https://docs.gradle.org/current/userguide/declaring_dependencies_between_subprojects.html

Here, in one of the example, it has a file in buildSrc folder-

buildSrc/src/main/kotlin/myproject.java-conventions.gradle.kts

plugins {
    id("java")
}

group = "com.example"
version = "1.0"

repositories {
    mavenCentral()
}

dependencies {
    testImplementation("junit:junit:4.13")
}

The structure of the project is:

.
├── buildSrc
│   ...
├── api
│   ├── src
│   │   └──...
│   └── build.gradle.kts
├── services
│   └── person-service
│       ├── src
│       │   └──...
│       └── build.gradle.kts
├── shared
│   ├── src
│   │   └──...
│   └── build.gradle.kts
└── settings.gradle.kts

The module build scripts api/build.gradle.kts and shared/build.gradle.kts are using the plugin 'myproject.java-conventions' as:

plugins {
    id("myproject.java-conventions")
}

I referred the below about how to create custom plugins.

https://www.tutorialspoint.com/gradle/gradle_plugins.htm#:~:text=Plugin%20is%20nothing%20but%20set,are%20handled%20by%20plugins.&text=Extend%20the%20basic%20Gradle%20model,elements%20that%20can%20be%20configured).

I am confused about how just having a .gradle or .gradle.kts file in buildSrc is a plugin that projects are able to use. And, if so, why are they not using that as:

apply plugin: myproject.java-conventions

What is the difference then in apply plugin apply plugin: myproject.java-conventions and

plugins {
    id("myproject.java-conventions")
}

Solution

  • Yes, the myproject.java-conventions.gradle.kts file is a gradle plugin. Specifically, it is a precompiled script plugin. All sub-modules are able to use this plugin because by packaging a plugin in the buildSrc project,

    Gradle will take care of... making it available on the classpath of the build script. The plugin is visible to every build script used by the build.

    The plugins block is simply a newer method of applying plugins. See: What's the difference in applying gradle plugins?