6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Gradle で sources jar を集める

6
Last updated at Posted at 2015-07-15

はじめに

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

  • gradle 9.2.1 で動作確認しています。
  • Configuration Cache が有効の場合でも動作します。
  • 本記事の初版 (2015年) は、Gradle 2.5 向けでした。9.2.1 向けへの変更差分は大きいです。気になる方は編集履歴を参照してください。

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

dependencies 部分を任意に変更して使用してください。

build.gradle
plugins {
    id 'java'
}

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(17)
    }
}

repositories {
    mavenCentral()
}

dependencies {
    // これは例です。任意に変更してください。
    implementation 'software.amazon.awssdk:s3:2.41.5'
}

// 集約タスク
def collectSourcesJarTask = tasks.register('collectSourcesJar') {
}

// configuration ごとにタスクを登録
configurations.matching { it.canBeResolved }.all { Configuration conf ->
    def taskName = "collect${conf.name.capitalize()}SourcesJar"

    def t = tasks.register(taskName, Sync) {
        into(layout.buildDirectory.dir("dependencies/${conf.name}-sources"))

        from(conf.incoming.artifactView {
            withVariantReselection()
            attributes {
                attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage, Usage.JAVA_RUNTIME))
                attribute(Category.CATEGORY_ATTRIBUTE, project.objects.named(Category, Category.DOCUMENTATION))
                attribute(Bundling.BUNDLING_ATTRIBUTE, project.objects.named(Bundling, Bundling.EXTERNAL))
                attribute(DocsType.DOCS_TYPE_ATTRIBUTE, project.objects.named(DocsType, DocsType.SOURCES))
            }
        }.files)

        duplicatesStrategy = DuplicatesStrategy.FAIL
    }

    // 集約タスクへぶら下げる
    collectSourcesJarTask.configure { it.dependsOn(t) }
}

実行方法

./gradlew collectSourcesJar

実行すると、dependencies に記述した artifact の sources jar を、Configuration ごとのディレクトリに集めます。

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

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

build.gradle

// ...

// 集約タスク
def collectJarsTask = tasks.register('collectJars') {
}

// configuration ごとにタスクを登録
configurations.matching { it.canBeResolved }.all { Configuration conf ->
    def taskName = "collect${conf.name.capitalize()}Jars"

    def t = tasks.register(taskName, Sync) {
        into(layout.buildDirectory.dir("dependencies/${conf.name}-jars"))
        from(conf)

        duplicatesStrategy = DuplicatesStrategy.FAIL
    }

    // 集約タスクへぶら下げる
    collectJarsTask.configure { it.dependsOn(t) }
}

実行方法:

./gradlew collectJars
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?