Set dependency constraints in a plugin

i try to set some dependency constraints in a plugin. The following code does not work. On which configuration do i have to add the constraints and how to force a download of the new constraints?

  public void apply(Project project) {
    Logger logger = project.getLogger();

    project.getConfigurations().all(configuration -> {
      if (!configuration.getDependencies().isEmpty()) { //which configuration should be used??
        final DependencyHandler dependencyHandler = project.getDependencies();
        dependencyHandler.constraints(
            constraintHandler -> {
              final DependencyConstraint dependencyConstraint = constraintHandler.create("org.yaml:snakeyaml:2.0");
              dependencyConstraint.because("test");
              if (dependencyConstraint instanceof DependencyConstraintInternal) {
                ((DependencyConstraintInternal) dependencyConstraint).setForce(true);
                logger.warn("Forced constraint {}", dependencyConstraint.getName());
              } else {
                logger.warn("Unable to force constraint {}", dependencyConstraint.getName());
              }
              configuration.getDependencyConstraints().add(dependencyConstraint);
            }
        );
      }
    });

I didn’t analyze your code in-depth, but my first guess would be, that the problem is your check for isEmpty() as your configuration closure is afair executed as soon as the configuration is created and before dependencies are added to it.

You might instead try to use Configuration#withDependencies { ... } which mainly was introduced to supply last-minute dependencies, eventually based on other dependencies. So this might also be the extension point you are after for your logic.

Besides that your code in general looks suspicious by using internal classes and so on.
Maybe you just set the constraint explicitly where you need it. :slight_smile:

I found the solution. i was using the wrong methods. This is working for me:

project.getConfigurations().all(configuration -> 
  configuration.getResolutionStrategy().eachDependency(details -> {
    ModuleVersionSelector selector = details.getRequested();
    String key = selector.getGroup() + ":" + selector.getName();
    if (libToUpdate.containsKey(key)) {
      MinimalExternalModuleDependency modules = libToUpdate.get(key);
         details.useVersion(modules.getVersion());
    }
  })
);

Thx for your help