我们有一个自定义插件,我们想在其中构建用于部署的特殊tar文件。我们想在某些依赖项上剥离版本号。
插件的代码:
void addTarTask(Project project) {
Tar tar = project.tasks.create("tar", Tar)
tar.classifier = "bin"
project.afterEvaluate {
tar.into("${project.name}-${project.version}"){
into('lib'){
from project.tasks.jar
from project.configurations.runtime
}
//snip more custom requirements
}
}
}
我尝试了一些使用正则表达式从文件中删除版本的操作,如下所示:
into('lib'){
from project.tasks.jar
from project.configurations.runtime {
rename '(.*)-[0-9]+\\..*.jar', '$1.jar' // not sure regex is okay - it is just to demo
}
}
是否有可能无法获得类型依赖/ Artifact 对象,因此我可以跳过正则表达式并使代码更简洁。类似于(pseducode):
if(${artifact.extension} == "so") {
return ${artifact.name}.${artifact.extension}
} else {
// just return normal file
}
任何帮助表示赞赏:-)
最佳答案
您所引用的runtime
Configuration具有dependencies
属性,该属性是一个包含DependencySet对象的Dependency。
这意味着您可以遍历依赖项以获取其名称。
您可以使用它来编写特定的重命名规则。还有一些注意事项。
我生成了一个示例项目来举例说明:
gradle init --type java-library
然后将build.gradle编辑为:
apply plugin: 'java'
repositories {
jcenter()
}
dependencies {
compile 'org.slf4j:slf4j-api:1.7.21'
testCompile 'junit:junit:4.12'
}
task log << {
configurations.runtime.allDependencies.each { println it }
println ""
configurations.testCompile.allDependencies.each { println it }
}
task copy(type: Copy) {
from configurations.runtime
into "$buildDir/lib"
configurations.runtime.allDependencies.each {
rename "-${it.version}", ""
}
}
结果如下:
[:~/tmp] % ./gradlew log copy
:log
DefaultExternalModuleDependency{group='org.slf4j', name='slf4j-api', version='1.7.21', configuration='default'}
DefaultExternalModuleDependency{group='junit', name='junit', version='4.12', configuration='default'}
DefaultExternalModuleDependency{group='org.slf4j', name='slf4j-api', version='1.7.21', configuration='default'}
[...]
[:~/tmp] % ./gradlew dependencies
[...]
testCompile - Dependencies for source set 'test'.
+--- org.slf4j:slf4j-api:1.7.21
\--- junit:junit:4.12
\--- org.hamcrest:hamcrest-core:1.3
[...]
[:~/tmp] % ls build/lib
slf4j-api.jar
请注意,
hamcrest
依赖项由gradle dependencies
显示,但未打印。这是因为在配置时尚未解决依赖性,因此gradle尚不知道传递性依赖性。换句话说,您可以在插件中实现类似于上面的复制任务的操作,但是它仅适用于直接在构建脚本中指定的依赖项。当然,如果您必须重命名某些依赖关系,则也可以显式指定传递依赖关系,它仍然可以使用。由于遵循了extendsFrom
规则,因此testCompile配置可以正确打印slf4j和junit。
关于gradle - 从Gradle自定义插件中的某些依赖中剥离版本号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40024088/