可选的摇篮依赖Maven的库

可选的摇篮依赖Maven的库

问题描述:

我工作的一个Android库,并想用仅在使用我的图书馆项目包括的依赖以及依赖。类似于毕加索,提供的 OkHttp

I'm working on an Android library and would like to use a dependency only if the project using my library includes that dependency as well. Similar to what Picasso does with OkHttp.

我已经考虑到了这个主code。通过检查ClassNotFoundExceptions,但它仍然在包括它部署到Maven的中央的依赖关系。我如何产生一些诸如Maven的<可选>真< /可选> 标签

I already took care of this on the main code by checking for ClassNotFoundExceptions but it still includes the dependencies upon deploying it to Maven Central. How do I generate something such as Maven's <optional>true</optional> tag?

我使用 gradle这个-MVN推部署通过我的摇篮文物。

I'm using gradle-mvn-push to deploy my artifacts via Gradle.

投票摇篮 - 1749

在此同时,您可以使用 pom.withXml 办法修改生成的POM文件,例如添加&LT;可选&GT; 标签或更改&LT;&范围GT; 值:

In the mean time you can use pom.withXml approach to modify the generated pom file, for example to add <optional> tags or change <scope>values:

apply plugin: 'java'
apply plugin: 'maven-publish'

configurations {
  optional
  compile.extendsFrom optional
}

dependencies {
  compile 'com.some.group:artifact:1.0';
  optional 'com.another.group:optional-artifact:1.0'
}

publishing {
  publications {
    maven( MavenPublication ) {
      from components.java

      pom.withXml {
        asNode().dependencies.dependency.findAll { xmlDep ->
          // mark optional dependencies
          if ( project.configurations.optional.allDependencies.findAll { dep ->
            xmlDep.groupId.text() == dep.group && xmlDep.artifactId.text() == dep.name
          } ) {
            def xmlOptional = xmlDep.optional[ 0 ];
            if ( !xmlOptional ) {
              xmlOptional = xmlDep.appendNode( 'optional' )
            }
            xmlOptional.value = 'true';
          }

          // fix maven-publish issue when all maven dependencies are placed into runtime scope
          if ( project.configurations.compile.allDependencies.findAll { dep ->
            xmlDep.groupId.text() == dep.group && xmlDep.artifactId.text() == dep.name
          } ) {
            def xmlScope = xmlDep.scope[ 0 ];
            if ( !xmlScope ) {
              xmlScope = xmlDep.appendNode( 'scope' )
            }
            xmlScope.value = 'compile';
          }
        }
      }
    }
  }
}