sbtティップス

Scalaビルドツールsbt(simple build tool)のティップス

Scala導入ティップスの記事でも紹介したsbtについて、別途ここで纏めます。

sbtリファレンス
https://www.scala-sbt.org/1.x/docs/

参考ブログ: sbt

SDKMANによるインストール
https://sdkman.io/install

SDKMANのインストールについてもScala導入ティップスの記事を参照して下さい。

インストールするsbtのバージョンを確認します。

$sdk list sbt

================================================================================
Available Sbt Versions
================================================================================
     1.4.4               1.3.4               1.1.2                              
     1.4.3               1.3.3               1.1.1                              
     1.4.2               1.3.1               1.1.0                              
     1.4.1               1.3.0             * 1.0.4                              
     1.4.0               1.2.8               1.0.3                              
     1.4.0-RC2           1.2.7               1.0.2                              
   * 1.3.13              1.2.6               1.0.1                              
     1.3.12              1.2.5               1.0.0                              
     1.3.11              1.2.4           > * 0.13.18                            
     1.3.10              1.2.3               0.13.17                            
     1.3.9               1.2.1                                                  
     1.3.8               1.2.0                                                  
     1.3.7               1.1.6                                                  
     1.3.6               1.1.5                                                  
     1.3.5               1.1.4                                                  

================================================================================
+ - local version
* - installed
> - currently in use

複数バージョンのインストールが可能です。バージョンの切り換えは、バージョンを指定して defaultコマンド で行います。

$sdk default sbt 1.3.13

sdkヘルプ一覧

Usage: sdk <command> [candidate] [version]
       sdk offline <enable|disable>

   commands:
       install   or i    <candidate> [version] [local-path]
       uninstall or rm   <candidate> <version>
       list      or ls   [candidate]
       use       or u    <candidate> <version>
       default   or d    <candidate> [version]
       home      or h    <candidate> <version>
       env       or e    [init]
       current   or c    [candidate]
       upgrade   or ug   [candidate]
       version   or v
       broadcast or b
       help
       offline           [enable|disable]
       selfupdate        [force]
       update
       flush             [archives|tmp|broadcast|version]

   candidate  :  the SDK to install: groovy, scala, grails, gradle, kotlin, etc.
                 use list command for comprehensive list of candidates
                 eg: $ sdk list
   version    :  where optional, defaults to latest stable if not provided
                 eg: $ sdk install groovy
   local-path :  optional path to an existing local installation
                 eg: $ sdk install groovy 2.4.13-local /opt/groovy-2.4.13

sbtシェルからscalaシェルへ

$ sbt console
scala> 

またはsbtにてsbtシェル起動後consoleコマンドを入力

$ sbt
[info] welcome to sbt 1.3.13 (AdoptOpenJDK Java 11.0.9.1)
[info] loading global plugins from /home/takanobu/.sbt/1.0/plugins
[info] loading settings for project chapter-cluster-build from plugins.sbt ...
[info] loading project definition from /home/takanobu/IdeaProjects/akka-in-action/chapter-cluster/project
[info] loading settings for project chapter-cluster from scala.sbt,build.sbt ...
[info] set current project to words-cluster (in build file:/home/takanobu/IdeaProjects/akka-in-action/chapter-cluster/)
[info] sbt server started at local:///home/takanobu/.sbt/1.0/server/540c81ed307cf8174db4/sock

sbt:words-cluster> console

[info] Compiling 6 Scala sources to /home/takanobu/IdeaProjects/akka-in-action/chapter-cluster/target/scala-2.13/classes ...
[info] Non-compiled module 'compiler-bridge_2.13' for Scala 2.13.4. Compiling...
[info]   Compilation completed in 18.928s.
[info] Starting scala interpreter...
Welcome to Scala 2.13.4 (OpenJDK 64-Bit Server VM, Java 11.0.9.1).
Type in expressions for evaluation. Or try :help.

scala>

github等に公開されているプログラムをIntelliJにて検証する際に、sbtのバージョンを変更しなければならない場合があります。

その場合、SDKMANにより指定バージョンをインストール、
以下 Launcher(sbt-launcher.jar) の項目で、 Custom を選択、SDKMANでインストールした sbt バージョンの sbt-launcher-.jar へのパス

/home/<user_name>/.sdkman/candidates/sbt/1.3.13/bin/sbt-launch.jar

を指定します。

run, runMain

以下サンプルコードによるsbtコマンドの使用例

Cluster Client with gRPC transport

run

Scalaコンソールにて"run"実行コマンド入力、複数のファイルにまたがり、オブジェクトで定義したメイン関数を尋ねてくるので希望の数値を入力して選択

sbt:akka-grpc-quickstart-scala> run

Multiple main classes detected. Select one to run:
 [1] com.example.helloworld.GreeterClient
 [2] com.example.helloworld.GreeterServer

Enter number: 1
[info] running com.example.helloworld.GreeterClient 
......

runMain

予めメイン関数を含むオブジェクトを指定して起動

sbt:akka-grpc-quickstart-scala> runMain com.example.helloworld.GreeterServer

[info] running com.example.helloworld.GreeterServer 
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
(gRPC server bound to {}:{},127.0.0.1,8080)

sbtプラグイン: sbt-revolver

sbtシェルのバックグラウンドでアプリを動作 reStart 。動作停止 reStop 、ステータス確認 reStatus などを同シェルで出来るようになります。

プロジェクトディレクトリに project/plugins.sbt を作成し、以下のフォーマットでプラグインとそのバージョンを指定。
https://www.scala-sbt.org/1.x/docs/Using-Plugins.html

sbt-revolver

addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")

追加コマンド

reStart — starts your application in a forked JVM. The optionally specified (JVM) arguments are appended to the ones configured via the reStartArgs/ reStart::javaOptions setting (see the “Configuration” section below). If the application is already running it is first stopped before being restarted.

reStop stops application. This is done by simply force-killing the forked JVM. Note, that this means that shutdown hooks are not run (see #20).

reStatus shows an informational message about the current running state of the application.

Community Plugins

Plugins available for sbt 1.0 (including RC-x)

Code formatter plugins

Documentation plugins

  • tut: documentation and tutorial generator.
  • Laika: Transform Markdown or reStructuredText
    into HTML or PDF with Templating.
  • sbt-site: site generator.
  • sbt-microsites: generate
    and publish microsites using Jekyll.
  • sbt-unidoc: create unified API
    documentation across subprojects.
  • sbt-ghpages: publish generated
    sites to GitHub pages.
  • sbt-class-diagram: generate
    class diagrams from Scala source code.
  • sbt-api-mappings:
    generate Scaladoc apiMappings for common Scala libraries.
  • literator:
    generate literate-style markdown docs from your sources.
  • sbt-example:
    generate ScalaTest test suites from examples in Scaladoc.
  • sbt-delombok:
    delombok Java sources files that contain Lombok annotations to make Javadoc contain Lombok-generated classes and methods.
  • sbt-alldocs: collect all the docs for a project and dependencies into a single folder.
  • sbt-apidoc: A port of apidocjs to sbt, to document REST Api.
  • sbt-github-pages
    (docs): publish a website to GitHub Pages with minimal effort - works well with GitHub Actions.
  • sbt-docusaur
    (docs): build a website using Docusaurus and publish to GitHub Pages with minimal effort - works well with GitHub Actions.

One jar plugins

Release plugins

Deployment integration plugins

  • sbt-heroku: deploy applications
    directly to Heroku.
  • sbt-docker-compose:
    launch Docker images using docker compose.
  • sbt-appengine
    deploy your webapp to Google App Engine.
  • sbt-marathon: deploy applications
    on Apache Mesos using the Marathon
    framework.
  • sbt-riotctl: deploy
    applications as systemd services directly to a Raspberry Pi, ensuring
    dependencies (e.g. wiringpi) are met.

Utility and system plugins

IDE integration plugins

Test plugins

  • scripted: integration testing for sbt plugins.
  • sbt-jmh: run Java Microbenchmark Harness
    (JMH) benchmarks from sbt.
  • sbt-doctest: generate and run
    tests from Scaladoc comments.
  • gatling-sbt: performance and
    load-testing using Gatling.
  • sbt-multi-jvm: run tests using
    multiple JVMs.
  • sbt-scalaprops: scalaprops
    property-based testing integration.
  • sbt-testng: TestNG framework
    integration.
  • sbt-jcstress: Java Concurrency
    Stress Test (jcstress) integration.
  • sbt-stryker4s: Test your tests with mutation testing.
  • sbt-cached-ci: Incremental sbt builds for CI environments.

Library dependency plugins

Web and frontend development plugins

Database plugins

Framework-specific plugins

  • sbt-newrelic: NewRelic support for
    artefacts built with sbt-native-packager.
  • sbt-spark: Spark application
    configurator.
  • sbt-api-builder: support for
    ApiBuilder from within sbt’s shell.

Code generator plugins

Static code analysis plugins

Code coverage plugins

Create new project plugins

  • sbt-fresh: create an opinionated fresh
    sbt project.

In-house plugins

Verification plugins

Language support plugins

  • sbt-frege: build Frege
    code with sbt.
  • sbt-cc: compile C and C++ source files with sbt.

Resolvers

sbt追加レポジトリ

resolvers += name at location

Ex)

resolvers += "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots"

sbtコマンドリファレンス

プロジェクトディレクトリ内でコマンド実行

$ sbt compile
...
$ sbt run
...
$ sbt package
...

compile
Compiles the main sources (in the src/main/scala directory). test:compile compiles test sources (in the src/test/scala/ directory).

console
Starts the Scala interpreter with a classpath including the compiled sources, all jars in the lib directory, and managed libraries. To return to sbt, type :quit, Ctrl+D (Unix), or Ctrl+Z (Windows). Similarly, test:console starts the interpreter with the test classes and classpath.

package
Creates a jar file containing the files in src/main/resources and the classes compiled from src/main/scala. test:package creates a jar containing the files in src/test/resources and the class compiled from src/test/scala.

packageSrc
Creates a jar file containing all main source files and resources. The packaged paths are relative to src/main/scala and src/main/resources. Similarly, test:packageSrc operates on test source files and resources.

run <argument>
Runs the main class for the project in the same virtual machine as sbt. The main class is passed the arguments provided. Please see Running Project Code for details on the use of System.exit and multithreading (including GUIs) in code run by this action. test:run runs a main class in the test code.

runMain <main-class> <argument>
Runs the specified main class for the project in the same virtual machine as sbt. The main class is passed the arguments provided. Please see Running Project Code for details on the use of System.exit and multithreading (including GUIs) in code run by this action. test:runMain runs the specified main class in the test code.

sbtプラグイン:sbt-assembly

https://www.scala-sbt.org/1.x/docs/Plugins.html#Plugins

project/plugin.sbt に以下追加

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

sbt-assemblyによる Jarファイル作成のため build.sbt に以下追加

...
...
...

// Assembly settings
mainClass in assembly := Some("aia.cluster.words.Main")

assemblyJarName in assembly := "words-node.jar"

Jarファイル作成

$ sbt assembly

Jarファイルの実行

$ java -DPORT=2551 -Dconfig.resource=/seed.conf -jar target/scala-2.13/words-node.jar