使用grgit在构建时获取Gradle子项目

时间:2017-07-18 18:23:31

标签: gradle gradle-dependencies grgit

如何让gradle克隆git存储库(到当前存储库的子存储库)并将其构建为子项目?

目前我有以下内容:

settings.gradle:

include 'contrib/dependency/foolib'

build.gradle(缩短):

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.2'
        classpath 'org.ajoberstar:gradle-git:0.7.0'
    }
}

apply plugin: 'com.android.application'

import org.ajoberstar.grgit.*

task clone << {
    File dir = new File('contrib/dependency')
    if(!dir.exists()) {
        def grgit = Grgit.clone(dir: dir, uri: 'https://github.com/someone/dependency.git', refToCheckout: 'dev')
    }
    def grgit = Grgit.open(dir)
    grgit.checkout(branch: 'dev')
    grgit.pull(rebase: false)
}


project.afterEvaluate {
    preBuild.dependsOn clone
}


repositories {
    mavenCentral()
}

dependencies {
    compile project(':contrib/dependency/foolib')
}

android {
    // nothing out of the ordinary here, omitting
}

子项目有自己的build.gradle,它可以自行构建。

我逐渐构建并测试了脚本,首先使用克隆操作(效果很好)。当我第一次以完整的最终形式运行脚本时,子回购已经/仍然存在,这要归功于之前的克隆操作,并且构建顺利完成。

然而,当我通过简单地删除contrib来模拟新构建时,我收到了一个错误:

Cannot evaluate module contrib/dependency/foolib : Configuration with name 'default' not found.

显然,这是由仍然要导入的子项目引用引起的。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我最终使用git子模块解决了它,正如@nickb建议的那样。

build.gradle(缩短):

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.2'
    }
}

apply plugin: 'com.android.application'

repositories {
    mavenCentral()
}

dependencies {
    compile project(':contrib/dependency/foolib')
}

android {
    // nothing out of the ordinary here, omitting
}

(基本上,我刚删除了所有的grgit东西,但保留了子项目作为依赖项。)

然后在我的项目目录中我做了:

git submodule add https://github.com/someone/dependency.git contrib/dependency
cd contrib/dependency

# then either (to switch to a different branch):
git checkout -b mybranch origin/mybranch

# or (to check out a particular ref on the current branch):
git checkout deadc0de

# or both of the above (to check out a particular ref on a different branch)

(要稍后更新子模块,您可能需要先检查git fetchgit pull,然后再查看所需的参考号。)

但请注意,使用git中的子模块并非没有陷阱,这很容易破坏您在子模块中所做的更改,或者无意中恢复到过时的版本。为了避免这些:

  • 不要提交子模块(始终提交上游,然后从上游提取)
  • 每次HEAD更改(拉,合并,结帐等)时务必运行git submodule update

关于git子模块陷阱的一篇好文章:https://codingkilledthecat.wordpress.com/2012/04/28/why-your-company-shouldnt-use-git-submodules/

相关问题