How to add gradle dependency automatically

2019-06-08 20:48发布

问题:

I'm wondering if there is any gradle task or any other util that will add dependency so e.g.

dependencies {
   ... // so far dependencies    
   compile 'com.new.dependency:x.y"
}

in your build.gradle file instead you manually type it.

I'm trying to write IntelliJ plugin that will automatically add a library to any project. So far I need to analyze/parse document content and it's tedious.

For example when you go to project setting in IntelliJ and add library the code is automatically added.

回答1:

You can specify collections as your dependencies, like:

dependencies {
   compile ['org.slf4j:slf4j-api:1.7.5','org.apache.commons:commons-lang3:3.1']
}

Which means you can use anything that can produce a list. If your plugin maintained a file like:

compile.dependencies:

org.slf4j:slf4j-api:1.7.5
org.apache.commons:commons-lang3:3.1

Then you could include the dependencies into the project like:

dependencies {   
    compile file('compile.dependencies').readLines()
}

Users of your plugin would have to know to add these lines to their build.gradle. Or, better, you could bundle the configuration into an include file, like:

subprojects() {
  dependencies {   
     if (file('compile.dependencies').exists()) {
       compile file('compile.dependencies').readLines()
     }

     if (file('runtime.dependencies').exists()) {
      runtime file('runtime.dependencies').readLines()
     }
  }
}

Then your users would only have to use "apply from:" to include the config.



回答2:

There's no such tool, nor utility. There's a possibility to add dependencies to project using tooling API but the changes introduced will not be serialized to configuration (build.gradle) file.