酢豚だ by imcool in flickr

初心者ぺちぱーがGitHubでScalaレッスンを始めたぞ。今回はScalaの標準的なビルドツールであるsbtを使ってみる。

sbt is Simple Build Tool

Scalaインストールについて書いた記事で、Homebrewを使ってsbtをインストールする方法を書いたので、インストール方法は割愛する。Homebrew以外のインストール方法については、本家ドキュメントInstalling sbtに詳しい記載があるので、参照のこと。

sbt configuration

Homebrewでsbtをインストールすると、/usr/local/bin/sbtにコマンドが出来上がっている。この中身はこんな感じ。

/usr/local/bin/sbt
#!/bin/sh
test -f ~/.sbtconfig && . ~/.sbtconfig
exec java -Xmx512M ${SBT_OPTS} -jar /usr/local/Cellar/sbt/0.12.2/libexec/sbt-launch.jar "$@"

なので、SBT_OPTS環境変数設定用に、~/.sbtconfigを作っておくといいらしい。というより、設定しておかないと、OutOfMemoryErrorが出て、涙目になると思う。

uncaught exception during compilation: java.lang.OutOfMemoryError
error: java.lang.OutOfMemoryError: PermGen space

Getting-Started/Setupを見ると、SBT_OPTSに設定するJVMのオプションはこんな感じか。

.sbtconfig
export SBT_OPTS="-Xmx1536M -Xss1M -XX:+CMSClassUnloadingEnabled -XX:MaxPermSize=384M"

Build configuration

Getting-Started/HelloGetting-Started/Directory structureの話。

sbtの設定ファイルは.sbt.scalaが使えるらしい。まずはマニュアル通りに書いてみる。

また、Getting-Started/Library Dependenciesを見ると、依存ライブラリの指定はlibraryDependenciesに書くようだ。

build.sbt
name := "hello"
version := "1.0"
scalaVersion := "2.10.1"
libraryDependencies += "org.scalatest" % "scalatest_2.10" % "1.9.1" % "test"
build.properties
sbt.version=0.12.2

sbtプロジェクト用に、ディレクトリを作成する。

$ mkdir -p hello/src/{main,test}/{scala,java,resources}
$ tree
.
└── hello
├── build.properties
├── build.sbt
└── src
├── main
│   ├── java
│   ├── resources
│   └── scala
└── test
├── java
├── resources
└── scala

Hello project

ソースファイルもマニュアル通りに書いてみる。適当なテストコードも追加してみた。

src/main/scala/jp/satooshi/hello/Hello.scala
package jp.satooshi.hello
/**
* へろー!
*/
object Hello {
/**
* へろーするよ!
*
* @param args コマンド引数
*/
def main(args: Array[String]) { println("へろー") }
}
src/test/scala/jp/satooshi/hello/HelloTest.scala
package jp.satooshi.hello
import org.scalatest.FunSuite
class HelloTest extends FunSuite {
test("Hello should run main") {
expectResult()(Hello.main(Array.empty))
}
}

Try to run hello project

Getting-Started/Runningの話。

基本的な設定ができたので、sbtを使ってコンパイルしてみよう。

compileタスク実行
$ sbt
[info] Set current project to hello (in build file:/Users/satoshi/prj/work/scala/hello/)
> compile
[info] Updating {file:/Users/satoshi/prj/work/scala/hello/}default-ea94fa...
[info] Resolving org.scala-lang#scala-reflect;2.10.0 ...
[info] downloading http://repo1.maven.org/maven2/org/scalatest/scalatest_2.10/1.9.1/scalatest_2.10-1.9.1.jar ...
[info] [SUCCESSFUL ] org.scalatest#scalatest_2.10;1.9.1!scalatest_2.10.jar (5810ms)
[info] downloading http://repo1.maven.org/maven2/org/scala-lang/scala-actors/2.10.0/scala-actors-2.10.0.jar ...
[info] [SUCCESSFUL ] org.scala-lang#scala-actors;2.10.0!scala-actors.jar (1110ms)
[info] downloading http://repo1.maven.org/maven2/org/scala-lang/scala-reflect/2.10.0/scala-reflect-2.10.0.jar ...
[info] [SUCCESSFUL ] org.scala-lang#scala-reflect;2.10.0!scala-reflect.jar (6093ms)
[info] Done updating.
[success] Total time: 17 s, completed 2013/03/28 16:13:14

downloadingと表示されているjarファイルは~/.ivy2の下に保存されているようだ。何かまずかったら消してみるといいのかも知れない。

へろーを実行するときはrunタスクだ。

runタスク実行
> run
[info] Updating {file:/Users/satoshi/prj/work/scala/hello/}default-ea94fa...
[info] Resolving org.scala-lang#scala-reflect;2.10.0 ...
[info] Done updating.
[info] Running jp.satooshi.hello.Hello
へろー
[success] Total time: 1 s, completed 2013/03/28 16:13:19

テストを実行するにはtestタスクだ。

testタスク実行
> test
へろー
[info] HelloTest:
[info] - Hello should run main
[info] Passed: : Total 1, Failed 0, Errors 0, Passed 1, Skipped 0
[success] Total time: 1 s, completed 2013/03/28 16:14:44

困ったときはhelpと打ってみよう。sbtのヘルプコマンド。

help
> help
help Displays this help message or prints detailed help on requested commands (run 'help <command>').
about Displays basic information about sbt and the build.
tasks Lists the tasks defined for the current project.
settings Lists the settings defined for the current project.
reload (Re)loads the project in the current directory
projects Lists the names of available projects or temporarily adds/removes extra builds to the session.
project Displays the current project or changes to the provided `project`.
set Evaluates a Setting and applies it to the current project.
session Manipulates session settings. For details, run 'help session'.
inspect Prints the value for 'key', the defining scope, delegates, related definitions, and dependencies.
; <command> (; <command>)* Runs the provided semicolon-separated commands.
~ <command> Executes the specified command whenever source files change.
last Displays output from a previous command or the output from a specific task.
last-grep Shows lines from the last output for 'key' that match 'pattern'.
exit Terminates the build.
show <key> Displays the result of evaluating the setting or task associated with 'key'.
More command help available using 'help <command>' for:
!, -, <, alias, append, apply, eval, iflast, reboot, shell

tasksと打ってみると、現在のプロジェクトで使用可能なタスク一覧が表示される。

tasks
> tasks
This is a list of tasks defined for the current project.
It does not list the scopes the tasks are defined in; use the 'inspect' command for that.
Tasks produce values. Use the 'show' command to run the task and print the resulting value.
clean Deletes files produced by the build, such as generated sources, compiled classes, and task caches.
compile Compiles sources.
console Starts the Scala interpreter with the project classes on the classpath.
console-project Starts the Scala interpreter with the sbt and the build definition on the classpath and useful imports.
console-quick Starts the Scala interpreter with the project dependencies on the classpath.
copy-resources Copies resources to the output directory.
doc Generates API documentation.
package Produces the main artifact, such as a binary jar. This is typically an alias for the task that actually does the packaging.
package-bin Produces a main artifact, such as a binary jar.
package-doc Produces a documentation artifact, such as a jar containing API documentation.
package-src Produces a source artifact, such as a jar containing sources and resources.
publish Publishes artifacts to a repository.
publish-local Publishes artifacts to the local repository.
run Runs a main class, passing along arguments provided on the command line.
run-main Runs the main class selected by the first argument, passing the remaining arguments to the main method.
test Executes all tests.
test-only Executes the tests provided as arguments or all tests if no arguments are provided.
test-quick Executes the tests that either failed before, were not run or whose transitive dependencies changed, among those provided as arguments.
update Resolves and optionally retrieves dependencies, producing a report.
More tasks may be viewed by increasing verbosity. See 'help tasks'.

docタスクというのがあるようなので、試してみよう。

docタスク実行
[info] Updating {file:/Users/satoshi/prj/work/scala/hello/}default-ea94fa...
[info] Resolving org.scala-lang#scala-reflect;2.10.0 ...
[info] Done updating.
[info] Generating Scala API documentation for main sources to /Users/satoshi/prj/work/scala/hello/target/scala-2.10/api...
model contains 2 documentable templates
[info] Scala API documentation generation successful.
[success] Total time: 1 s, completed 2013/03/28 18:14:06

出来上がったのは、こんな感じ。

Conclusion

sbtを使ってプロジェクトの設定とか実行、テストができるようになったよ。やったね!まとめ!

  • build.sbtにプロジェクトビルドの基本設定を書く
  • compile、run、test、docタスクの使い方
  • 困ったときはhelpかtasks

Reference