gpt4 book ai didi

plugins - 如何在自定义 gradle 插件中迭代 gradle 依赖项?

转载 作者:行者123 更新时间:2023-12-02 10:08:27 24 4
gpt4 key购买 nike

我已遵循本指南:

http://www.gradle.org/docs/current/userguide/custom_plugins.html

使用以下结构/文件创建一个独立的 gradle 插件:

  my-gradle-plugin
> src
> main
> java
> com
> mygroup
> MyGradlePlugin.groovy
> build.gradle
> settings.gradle

build.gradle:

apply plugin: 'groovy'

dependencies {
compile gradleApi()
groovy localGroovy()
}

apply plugin: 'maven'
repositories {
mavenCentral()
}

group = 'com.mygroup'
version = '1.0.0-SNAPSHOT'

MyGradlePlugin.groovy:

package com.mygroup

import org.gradle.api.*

class MyGradlePlugin implements Plugin<Project> {

void apply(Project project) {
print " project.name " + project.name + "\n"
print " project.dependencies " + project.dependencies + "\n"
// How do we iterate each dependency and print artifactId, group, version??
// project.dependencies.each {
// compile(it) {
// print it.next()
// print it.name
// }
// }
project.configurations.each {
print it.dump()

}
}
}

在另一个项目中我使用/应用这个插件:

apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'eclipse'

repositories {
mavenLocal()
}

buildscript {
repositories {
mavenLocal()
}
dependencies {
classpath group: 'com.mygroup', name: 'my-gradle-plugin', version: '1.0.0-SNAPSHOT'
}
}



dependencies {
compile group: 'commons-codec', name: 'commons-codec', version: '1.4'
compile group: 'commons-beanutils', name: 'commons-beanutils', version: '1.7.0'
}

install.doLast {
apply plugin: 'my-gradle-plugin'

}

但是如何从 MyGradlePlugin.groovy 中的 apply 方法迭代公共(public)依赖项并打印它们的坐标(artifactId、groupId、version)?

最佳答案

我知道这是一个老问题,但由于没有选定的答案,我将举一个我用过的例子。这是基于 gradle 文档第 49.8.2.2 节中的示例。

我使用它来执行自定义依赖项解析,但您可以在依赖项迭代中执行您想要的任何操作。请注意,这是有效的,因为它传递了一个在配置阶段之后执行的闭包。

插件代码:

package com.overtherainbow

import org.gradle.api.Project
import org.gradle.api.Plugin
import org.gradle.api.artifacts.DependencyResolveDetails

class DefaultVersionPlugin implements Plugin<Project> {

// This is where dependency versions are defined
def defaultVersionsMap = [
'javax.servlet:servlet-api' : '2.5',
'log4j:log4j' : '1.2.16']

void apply(Project project) {
project.configurations.all {
resolutionStrategy.eachDependency {
DependencyResolveDetails details -> resolveDependencyVersion(project, details)
}
}
}

def resolveDependencyVersion(Project project, DependencyResolveDetails details) {
if (details.requested.version == 'default') {
def version = resolveDefaultVersion(project, details.requested.group, details.requested.name)
details.useVersion version
}
}

def resolveDefaultVersion(Project project, String group, String name) {
project.logger.debug("Resolving default dependency for $group:$name")
println "Resolving default dependency for $group:$name"
defaultVersionsMap["$group:$name"]
}
}

关于plugins - 如何在自定义 gradle 插件中迭代 gradle 依赖项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13202522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com