'Create task for dependency lock in Gradle >5.0

I want to create a task which to execute

dependencies --update-locks ':'

I had a configuration:

dependencyLocking {
    lockAllConfigurations()
}

I try with

task lockDependencies {
    dependsOn = ['dependencies','--update-locks *:*']
} 

But have:

  • What went wrong: Could not determine the dependencies of task ':lockDependencies'.

    Task with path '--update-locks :' not found in root project



Solution 1:[1]

You cannot pass Gradle command line parameters as a task dependency, that's what your error above is about.

The state of writing locks, either with --write-locks or --update-locks, is something that happens really early in the build lifecycle.

You can somewhat control it from a task with the following: * Create a placeholder task in your build script * In the settings.gradle(.kts) query the requested tasks from the command line, and if it is there, mutate the start parameters:

if (startParameter.taskNames.contains('placeHolder')) {
    startParameter.setWriteDependencyLocks(true)
}

Note that this is not an option if you are trying to lock the classpath of the build itself, which is one of the motivations behind using a command line flag.

Note also that this just allows replacing a flag, like --update-locks *:* with a task invocation like updateLocks but will not work if that task is wired as a dependency of other tasks, as it needs to be requested explicitly. And doing the start parameter mutation after the task graph is computed is too late in the lifecycle.

Solution 2:[2]

The best way to do this in my opinion is to add inside the build.gradle file the following code:

dependencyLocking {
    lockAllConfigurations()
}
task commitLockDependencies {
    'git add /gradle/dependency-locks '.execute()
}
init {
    dependsOn('commitLockDependencies')
}

And then inside the settings.gradle the following line:

startParameter.setWriteDependencyLocks(true)

Working with gradle 7.1.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Louis Jacomet
Solution 2 Gaetano Piazzolla