Home > database >  If subproject has dependency add another
If subproject has dependency add another

Time:12-04

I have a multi-module project and I want to add another dependency automatically if a submodule contains a specific dependency.

So far I've added this on my root build.gradle.kts

subprojects {
    apply {
        plugin("java")
    }

    project.configurations.implementation.get().allDependencies.forEach {
        println(it.name)
    }
}

But it prints nothing. How can I get all dependencies implemented by a subproject and then another if it contains one already?

Thanks

CodePudding user response:

Please try to use afterEvaluate, dependencies are not available at the level you are asking for

subprojects {
    apply {
        plugin("java")
    }

    afterEvaluate {
        project.configurations.implementation.get().getDependencies().forEach {
            println(it.name)
            // Check if the dependency is the one you're looking for
            // and add another dependency if needed
        }
    }
}

CodePudding user response:

You can use the getDependencies() method of the Configuration class to get a list of all the dependencies for a given configuration. Then, you can iterate over the list and check if a specific dependency is present using the contains() method.

Here is an example:

subprojects {
apply {
    plugin("java")
}

val implementationDependencies = project.configurations.implementation.get().getDependencies()
implementationDependencies.forEach {
    println(it.name)

    // Check if a specific dependency is present
    if (it.name == "your-dependency-name") {
        // Add another dependency if the specific one is present
        project.dependencies {
            implementation("org.another.dependency:1.0.0")
        }
    }
}

}

Note that this code will only check dependencies that are part of the implementation configuration. If you want to check dependencies in other configurations, you can replace implementation with the appropriate configuration name.

CodePudding user response:

Here's one way you could achieve what you're looking for:

subprojects {
    apply {
        plugin("java")
    }

    project.configurations.implementation.get().allDependencies.forEach {
        if (it.name == "specific-dependency") {
            // Add another dependency here
            dependencies {
                implementation("com.example:another-dependency:1.0.0")
            }
        }
    }
}

This code iterates over all the dependencies in the 'implementation' configuration for each subproject, and if it finds a dependency with the name 'specific-dependency', it adds 'another-dependency' to the 'implementation' configuration for that subproject.

  • Related