Renaming Your Gradle Build Files

In a multi-module project, searching for the right build.gradle can be tricky. After all, everything is called build.gradle so using our trusty Open File doesn’t help much. One neat trick to organize your code is to rename your build.gradle file to something meaningful like app.gradle, my-feature.gradle, and so on.

Renamed Build.gradle files

How does it work

When you declare a module in your settings.gradle, the build system will look for a file named build.gradle in a folder corresponding to the module’s name. In other words, if you declare an :app module, gradle will expect the build file to be located at app/build.gradle.

Turns out that we can ignore this convention from our settings.gradle with the project.buildFileName property.

Adding the following snippet to your settings.gradle will rename each module’ s build.gradle file to its module’s name. e.g. app.gradle. The root build.gradle itself won’t be renamed.

// Add this at the end of settings.gradle
rootProject.children.each { subproject -> 
     subproject.buildFileName = "${subproject.name}.gradle" 
}

If you are using nested modules, you will need to add a bit of recursion to the mix to rename each submodule in the hierarchy. Replace the code above with the following:

// Add this at the end of settings.gradle
void rename_build_file_to_module_name(project) {
  project.buildFileName = "${project.name}.gradle"
  project.children.each { child -> rename_build_file_to_module_name(child) }
}

// Will rename every module's build.gradle file to use its name instead of `build`.
// E.g. `app/build.gradle` will become `app/app.gradle`
// The root build.gradle file will remain untouched
rootProject.children.each { subproject -> rename_build_file_to_module_name(subproject) }

That’s all there is to it, we now have a new convention to look for files named after the module.

Renaming the files

Now that gradle knows where to find the files… you actually need to rename the files on disk! You can go at it manually or run the following script at the root of your project.

#!/usr/bin/env bash
if [[ ! -f settings.gradle ]] ; then
    echo 'Make sure to run this at the root of your project'
    exit 1
fi

find . -iname build.gradle -not -path ./build.gradle  | while read build_file; do
    moduledir=$(dirname $build_file)
    modulename=$(basename $moduledir)
    new_build_file="$moduledir/$modulename.gradle"
    echo "Renaming'$build_file' to $new_build_file"
    mv $build_file $new_build_file
done

The source code for this post is available here