What is the purpose of gradle's buildSrc folder?

Jeff Storey picture Jeff Storey · Dec 14, 2012 · Viewed 8.7k times · Source

In gradle, what is the purpose of using a buildSrc file as a top level, as opposed to just a typical java project layout (src/main/java)?

If I have a layout of

src
   main
      java

or

buildSrc
    src
       main
          java

What would be the difference (or the reason for doing this)? Is it more useful in multi module projects? Even for a multi module project, couldn't I do something like

proj1
  src


proj2
  src

And then just have a top level build.gradle (at the same level as proj1 and proj2) that defines common settings across the projects?

Answer

Peter Niederwieser picture Peter Niederwieser · Dec 14, 2012

buildSrc is a separate build whose purpose is to build any tasks, plugins, or other classes which are intended to be used in build scripts of the main build, but don't have to be shared across builds.(*) It wouldn't be possible to build such classes as part of the main build, because they have to exist before the main build's build scripts can even be compiled/evaluated, and Gradle compiles/evaluates all build scripts before it does any work (configuration vs. execution phase).

Compared to putting all build code into build scripts, buildSrc gives you a way to develop build code more like regular code, as classes that you can test, import into your IDE, etc. It is one way to keep build scripts simple and DRY even for more complicated builds.

buildSrc is more often seen in multi-project builds simply because larger builds are more likely to implement their own custom tasks and plugins.

Over time, buildSrc will grow into a more general capability of executing multiple dependent builds in a single Gradle invocation.

(*) Sharing classes across builds is possible but more involved. In particular, you'll need to publish the classes to a repository, and consuming builds have to explicitly import them from there, similar to when sharing production libraries between builds.