LoginSignup
6
7

More than 5 years have passed since last update.

Gradleでsources jarを集める

Last updated at Posted at 2015-07-15

はじめに

Gradleでdependenciesに記述した(通常の)jarファイルを集めることは比較的簡単ですが、それらのsources jarを集めようとしたところ意外と手間取ったのでメモしておきます。

sources jarをダウンロードする方法

sources jarを集めるには、こんなやり方でOKでした。

build.gradle
import org.gradle.api.artifacts.query.ArtifactResolutionQuery
import org.gradle.internal.component.external.model.DefaultModuleComponentIdentifier
import org.gradle.jvm.JvmLibrary
import org.gradle.language.base.artifact.SourcesArtifact

// ....

task collectSourcesJar << {
    DependencyHandler dependencyHandler = project.dependencies
    project.configurations.each { Configuration configration ->
        // scope毎に全部欲しい場合はLenientConfiguration#getArtifactsの引数をorg.gradle.api.specs.Specs#satisfyAllに変える
        def componentIdentifiers = configration.resolvedConfiguration.lenientConfiguration.getArtifacts { Dependency dependency ->
            configration.dependencies.contains(dependency)
        }.collect { ResolvedArtifact artifact ->
            ModuleVersionIdentifier id = artifact.moduleVersion.id
            DefaultModuleComponentIdentifier.newId(id)
        }
        ArtifactResolutionQuery query = dependencyHandler.createArtifactResolutionQuery()
        query.forComponents(componentIdentifiers)
        query.withArtifacts(JvmLibrary, SourcesArtifact)
        def sourcesJars = []
        ArtifactResolutionResult resolutionResult = query.execute()
        resolutionResult.resolvedComponents.each { ComponentArtifactsResult componentArtifactsResult ->
            componentArtifactsResult.getArtifacts(SourcesArtifact).each { ArtifactResult artifactResult ->
                if (artifactResult instanceof ResolvedArtifactResult) {
                    sourcesJars << artifactResult.file
                }
            }
        }

        // build/dependencies/compile-sources/ などに出力する
        project.copy {
            from sourcesJars
            into "${project.buildDir}/dependencies/${configration.name}-sources"
        }
    }
}

使い方

taskを実行してください。

./gradlew collectSourcesJar

実行すると、dependenciesに記述したartifactのsources jarをダウンロードし、スコープごとのディレクトリに集めます。

NOTE

  • gradle 2.5で動作確認しています。
  • DefaultModuleComponentIdentifier クラスを使用しているのがイマイチなのですが、gradle 2.5ではこうしないと動いてくれませんでした。
    • 原因は org.gradle.api.internal.artifacts.ivyservice.resolveengine.result.ComponentIdentifierSerializer がinstanceofしている箇所だと思うのですが。。。
    • gradle 2.4では、org.gradle.api.artifacts.component.ModuleComponentIdentifierをimplementsしたクラスで動きます。

通常のjarをダウンロードする方法

ちなみに、通常のjarファイルを集める方法は例えばこんなふうです。

build.gradle
project.copy {
    from project.configurations.compile
    into "${project.buildDir}/dependencies/compile"
}
6
7
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7