如何在gradle中的项目构造函数中指定配置?

时间:2015-02-23 21:48:26

标签: gradle

我正在尝试解决类似于此处解决的问题的问题:https://github.com/pniederw/elastic-deps/blob/master/build.gradle

基本上,我有一个gradle项目映射到预构建的工件,存储在一个名为PrebuiltArtifactMap.groovy的文件中(我从我的非gradle构建系统生成),并且我希望将项目依赖项解析为工件依赖项。 map有一个合适的条目,否则将其作为项目依赖项。

只要我使用我依赖的项目的默认配置,它就可以正常工作,但是当我想使用指定的配置时,我似乎无法使其工作。

我想写这个:

def smartProject(String projectPath, String configuration=null) {
    return PrebuiltArtifactMap.resolveProjectDep(project, projectPath, configuration)
}

class PrebuiltArtifactMap
{
    static Map<String, String> projectToCoordinate = null;


    static Object resolveDep(String mapKey, String itemKey) {
        def map = projectToCoordinate[mapKey]
        if (map == null) {
            throw new GradleException("Prebuilt $mapKey doesn't exist.")
        }
        def artifact = map[itemKey]
        return artifact
    }

    static Object resolveProjectDep(Project dependentProject,
                                    String projectPath,
                                    String configuration=null) {
        // Attempt to locate gradle project in PrebuiltArtifactMap.groovy,
        // and resolve it into an artifact dependency if present.
        if (projectToCoordinate == null) {
            if (configuration == null) {
                return dependentProject.project(projectPath)
            } else {
                // *** THIS HERE doesn't work!!
                return dependentProject.project(path: projectPath,
                                                configuration: configuration)
            }
        } else {
            def artifact = resolveDep('ProjectMap', projectPath)
            if (artifact == null) {
                throw new GradleException("Prebuilt ProjectMap doesn't define an artifact for $projectPath.")
            }
            println "Resolving ${projectPath} to ${artifact}"
            if (artifact == 'LOCAL') {
                if (configuration == null) {
                    return dependentProject.project(projectPath)
                } else {
                    return dependentProject.project(path: projectPath, configuration: configuration)
                }
            }
            return artifact
        }
    }
}

({
   def mapFile = file("PrebuiltArtifactMap.groovy")
   if (mapFile.exists()) {
       PrebuiltArtifactMap.projectToCoordinate = evaluate(mapFile)
   }
})()

标记为***的部分此处不起作用!!失败,因为Project对象没有这样的方法。

我想要做的是替换表单

的声明
dependencies {
    myconfig project(":path:to:project", configuration: "archives")
}

用这个:

dependencies {
    myconfig smartProject(":path:to:project", "archives")
}

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

您要找的是DependencyHandler上的project方法,它返回Dependency。您可以通过方法getDependencies()DependencyHandler实例访问Project

在你的情况下看起来像这样:

dependentProject.dependencies.project(path: projectPath, configuration: configuration)