プラグインの基本

プラグインとは何か

プラグインは、新しいセッティングやタスクを追加することでビルド定義を拡張する。例えば、プラグインを使って githubWorkflowGenerate というタスクを追加して、GitHub Actions のための YAML を自動生成することができる。

Scaladex を使ったプラグイン・バージョンの検索

Scaladex を用いてプラグインを検索して、そのプラグインの最新バージョンを探すことができる。

プラグインの宣言

ビルドが hello というディレクトリにあるとして、sbt-github-actions をビルド定義に追加したい場合、hello/project/plugins.sbt というファイルを作成して、プラグインの ModuleID を addSbtPlugin(...) に渡すことで、プラグイン依存性を宣言する:

// In project/plugins.sbt

addSbtPlugin("com.github.sbt" % "sbt-github-actions" % "0.28.0")

ビルドに sbt-assembly を追加する場合、以下を追加する:

// In project/plugins.sbt

addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "2.3.1")

ソース依存性プラグインレシピには git リポジトリにホスティングされたプラグインを直接使う実験的技法が書かれてる。

プラグインは、通常サブプロジェクトに追加されるセッティングやタスクを提供することでその機能を実現する。次のセクションでその仕組みをもう少し詳しくみていく。

auto plugin の有効化と無効化

プラグインは、自身が持つセッティング群がビルド定義に自動的に追加されるよう宣言することができ、 その場合、プラグインの利用者は何もしなくてもいい。

auto plugin 機能は、セッティング群とその依存関係がサブプロジェクトに自動的、かつ安全に設定されることを保証する。auto plugin の多くはデフォルトのセッティング群を自動的に追加するが、中には明示的な有効化を必要とするものもある。

明示的な有効化が必要な auto plugin を使っている場合は、以下を build.sbt に追加する必要がある:

lazy val util = (project in file("util"))
  .enablePlugins(FooPlugin, BarPlugin)
  .settings(
    name := "hello-util"
  )

enablePlugins メソッドを使って、そのサブプロジェクトで使用したい auto plugin を明示的に定義できる。

逆に disablePlugins メソッドを使ってプラグインを除外することもできる。例えば、util から IvyPlugin のセッティングを除外したいとすると、build.sbt を以下のように変更する:

lazy val util = (project in file("util"))
  .enablePlugins(FooPlugin, BarPlugin)
  .disablePlugins(plugins.IvyPlugin)
  .settings(
    name := "hello-util"
  )

明示的な有効化が必要か否かは、それぞれの auto plugin がドキュメントで明記しておくべきだ。あるプロジェクトでどんな auto plugin が有効化されているか気になったら、 sbt シェルから plugins コマンドを実行してみよう。

sbt:hello> plugins
In build /tmp/hello/:
  Enabled plugins in hello:
    sbt.plugins.CorePlugin
    sbt.plugins.DependencyTreePlugin
    sbt.plugins.Giter8TemplatePlugin
    sbt.plugins.IvyPlugin
    sbt.plugins.JUnitXmlReportPlugin
    sbt.plugins.JvmPlugin
    sbt.plugins.SemanticdbPlugin
Plugins that are loaded to the build but not enabled in any subprojects:
  sbt.ScriptedPlugin
  sbt.plugins.SbtPlugin

ここでは、plugins の表示によって sbt のデフォルトのプラグインが全て有効化されていることが分かる。 sbt のデフォルトセッティングは 7つのプラグインによって提供される:

  1. CorePlugin: タスクの並列実行などのコア機能。
  2. DependencyTreePlugin: 依存性のツリー表示タスク。
  3. Giter8TemplatePlugin: sbt new 機能の提供。
  4. IvyPlugin: モジュールの依存性解決と公開機能。
  5. JUnitXmlReportPlugin: junit-xml の生成。
  6. JvmPlugin: Java/Scala サブプロジェクトのコンパイル、テスト、実行、パッケージ化の機構。
  7. SemanticdbPlugin: SemanticDB の生成。

利用可能なプラグイン

Scaladex の他にプラグインのリストがある。