はじめての sbt-plugin

sbtでコマンドを定義する - tototoshiの日記にてコマンドの定義の仕方を書きました。
今度はこれの延長で sbt-plugin を作ってみます。
sbt-plugin にすることで再利用しやすくなりますね。

作るもの

hello コマンドを追加する sbt-hello-plugin を作ります。


build.sbt

sbt-plugin は sbt プロジェクトとして作成します。


build.sbt には最低限以下の設定をすればOK

sbtPlugin := true

name:= "hello-plugin"

organization := "com.github.tototoshi"

src/main/scala/com/github/tototoshi/sbt/Hello.scala

心臓部です。

import sbt._
import Keys._

object HelloPlugin extends Plugin {
  override lazy val settings = Seq(
    commands ++= Seq(
      hello
    )
  )

  // コマンドの定義
  lazy val hello = Command.command("hello") { state =>
    println("hello")
    state
  }
}


Plugin トレイトを extends すれば良いようです。

trait Plugin
{
	def settings: Seq[Project.Setting[_]] = Nil
}


そんなわけで、あとは publish-local すればすぐに使えます。


つまり、意外と簡単ですね、ってことです。(なげやり


sbt-plugin の使いかた

project/plugin.sbt を作って一行書きます。

addSbtPlugin("com.github.tototoshi" % "hello-plugin" % "0.1")


sbt-plugin が他のライブラリに依存している場合、 plugin.sbt に libraryDependencies を追加します。

addSbtPlugin("com.github.tototoshi" % "hello-plugin" % "0.1")

libraryDependencies ++= Seq(
  "なにかの" % "ライブラリ" % "1.0",
)

参考

sbt-sh はとても単純なので参考にしやすいと思います。