How to add to a plugin task the dependencies comming from build.grade script?

284 views Asked by At

I Have a task from my plugin that need mysql or postgres drivers. currently I hardcoded into FooPlugin::apply method this:

configuration.dependencies.add(project.dependencies.create('mysql:mysql-connector-java:5.1.34'))

But I would like to let users, to choose their drivers. So for this I would like to grab all dependencies from gradle build script (build.gradle) which applying my plugin to inject these dependencies to the task dynamically.

Resolved: add a piece of code

I tried this:

class FooPlugin implements Plugin<Project>{

    @Override
    void apply(Project project) {
        project.afterEvaluate {
            def configuration = project.configurations.create('bar')
            configuration.extendsFrom(project.configurations.findByName('compile'))
            …
        }
    }
}

If you do not put into project.afterEvaluate block below error is raised:

Cannot change dependencies of configuration ':bar' after it has been resolved.
1

There are 1 answers

1
JBirdVegas On

I'm not sure exactly what your trying to accomplish so I'm going to guess at a couple things.

Looks like your trying to add a dependency or react based on a dependency added. I think you can accomplish either through the resolutionStrategy

project.configurations {
    compile.resolutionStrategy {
        // adds a dependency to a project, always.
        force 'commons-io:commons-io:2.5'
        // loop through all the dependencies to modify before resolution
        eachDependency { DependencyResolveDetails details ->
            // here you can change details about a dependency or respond however needed
            if (details.requested.group == 'mysql' && details.requested.name == 'mysql-connector-java') {
                // for example we can force a specific version
                details.useVersion '5.1.34'
            }
            // you could also add a if block for postgres if needed
        }
    }
}