How to cache Gradle build dependencies to a local Maven repository

I've occasionally found it helpful to cache a copy of a project's dependencies to a local file system. My most recent use case for this called for a local containerized test build without access to an internal network to fetch internal dependencies. An easy workaround was make the project resolve dependencies from a local maven cache that can be mounted as a volume in the container. Building the cache was accomplished using a Gradle task[1] similar to this:

task.register("cacheToMavenLocal", Sync) {
    from new File(gradle.gradleUserHomeDir, 'caches/modules-2/files-2.1')
    into "${rootDir}/local-m2"
    
    // Last copy target wins
    duplicatesStrategy = 'include'
    
    eachFile {
        List<String> parts = it.path.split('/')
        // Construct a maven repo file tree from the path 
        it.path = parts[0].replace('.','/') + 
            '/' + parts[1] + 
            '/' + parts[2] + 
            '/' + parts[4]
    }
    
    includeEmptyDirs false
}

This is a very aggressive way of building a cache since it is copying your entire Gradle cache into the target directory. You can use includes and excludes patterns[2] to copy only specific dependencies or exclude unnecessary ones.

This can be executed like any other Gradle task

./gradlew cacheToMavenLocal

And the resulting files will be copied into the target directory. In my example that would be the local-m2 folder in the project root directory.

To have your project search your local maven cache for dependencies you can point to your local cache like any custom maven repository in the repositories block.

repositories {
    maven {
        url "${rootDir}/local-m2"
    }
}

  1. Gradle Forums. 2021. Need a Gradle task to copy ALL dependencies to a local maven repo. [online] Available at: https://discuss.gradle.org/t/need-a-gradle-task-to-copy-all-dependencies-to-a-local-maven-repo/13397/15 [Accessed 11 November 2021]. ↩︎

  2. Gradle. 2021. Gradle API Documentation: Sync. [online] Available at: https://docs.gradle.org/current/dsl/org.gradle.api.tasks.Sync.html [Accessed 11 November 2021]. ↩︎

Subscribe to Another Dev's Two Cents

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe