Skip to main content

Setting up SBT and an SBT Build

Posted by manning_pubs on April 12, 2013 at 6:15 PM PDT



Setting up SBT and an SBT Build

by Joshua D. Suereth and Matthew Farwell, authors of SBT in Action

The simple build tool (SBT) is a tool for building Java and Scala projects. SBT aims to build well and allow users to customize endlessly, but above all, SBT strives to provide consistency of basic concepts so that, once learned, you don’t have to unlearn them as you dive deeper into the build system. This article, based on chapter 1 of SBT in Action, shows you how to set up SBT and define an SBT build.

SBT is a highly interactive tool, meant to be used during all parts of the development process. It provides interactive help and autocomplete for most services, and it promotes a type of autodiscovery for builds. You can use SBT as a command-line tool, but it shines brightest when you use its shell.

Throughout SBT in Action, readers design an SBT build for a sophisticated website called used-kittens.com that handles the resale of pet kittens. The website attempts to find ideal owners by matching buyer survey questions to known statistics of happy pet owners and behavior characteristics of the kittens. As readers add features to the website, they add new testing and debugging features to the build to ensure that the entire used-kittens.com team works together effectively. In this article, you’ll install SBT and set up a small build project for the used-kittens.com website.

Installing SBT

SBT provides installation packages for most operating system variants at
http://www.scala-sbt.org/release/docs/Getting-Started/Setup.html.

NOTE All examples use SBT version 0.13.0, downloadable at http://scalasbt.artifactoryonline.com/scalasbt/sbt-native-packages/org/s.... You’re free to try the latest version, but we recommend sticking to the one we used.

MS Windows users setup

A fast path to setup is available for Windows users. Download the MSI from http://scalasbt.artifactoryonline.com/scalasbt/sbt-native-packages/org/s..., and then run the installation script. After installation, reboot your machine so that the PATH environment variable is correct.

Linux/Mac users setup

After downloading the zip file, extract it to a safe application location, such as C:\Users\Me\apps or /home/me/apps. You should see the following in the extracted directory:

Everything you need to run SBT is in the sbt/bin directory. This directory consists of the SBT launcher and convenience scripts that provide easier configuration of the Java runtime. To use SBT via the command line, you must place the sbt/bin directory on the path.

To set up your path, complete the following steps:

  1. Locate the local shell setup file for your user:
  2. If you’re using BASH, open ~/.bashrc.

    If you’re using KSH or SH, open ~/.profile.

  3. Add the following lines to your setup file (near the bottom):
  4. SBT_HOME=/path/to/your/zip/extraction
    PATH=$PATH:$SBT_HOME/bin
    export PATH
  5. Close your current terminal window, and then open a new one.
  6. Running SBT

    To run the sbt script, create a directory for an SBT project. We created a directory called tmp in the home directory. Run the sbt command in this new directory. The output should look similar to the following:

    jsuereth@jsuereth-work-i7:~/tmp$ sbt
    [info] Done updating.
    [info] Set current project to default-a005a3 (in build
    file:/home/jsuereth/tmp/)
    >

    This SBT command prompt is where you interact with your build and, optionally, define portions of it.

    Using the SBT shell for interactive development
    SBT is designed to be highly interactive. To take full advantage of its merits, it’s best to use the SBT shell often during development. Even when you use an IDE for writing code, having the SBT shell live can drastically improve the development environment. SBT in Action includes many SBT shell session examples to encourage this type of interactive development and learning.
    We recommend that you start with a lightweight text editor, such as Sublime Text.

    You’re now ready to define your first build.

    Setting up a build

    Every project using SBT should have two files:

    • project/build.properties—Informs SBT which version to use for your build
    • build.sbt—Defines the settings for your build

    Let’s create and fill in these two files. Enter the following line in the project/build.properties file:

    sbt.version=0.13.0

    Enter the following lines in the build.sbt file:

    These files configure the version of SBT used for the build and set the name and version of the project (used-kittens, version 1.0).

    NOTE Because SBT includes default project settings, it requires no build files to run the simplest of builds. Still, it’s good practice to manually create the project/build.properties and build.sbt files.

    Now that the skeleton of the build is in place, let’s take a look at it in SBT. Rerun the sbt command in the root of the project. You should see the following output:

    ~/projects/sbt-in-action/chapter1
    ➜ sbt
    [info] Loading project definition from /home/jsuereth/projects/sbt-in-
    action/chapter1
    [info] Set current project to used-kittens (in build
    file:/home/jsuereth/projects/sbt-in-action/chapter1)
    >

    When starting up, SBT notifies you that it’s using the project named used-kittens rather than default-174241. This is thanks to the name setting you added in build.sbt. Now that SBT is running with a project build file, let’s see what SBT can do.

    To view SBT’s comprehensive help menu, run the help command as shown.

    Make a mental note to return to these options and investigate as needed. For this article, we’ll focus on two command line options:

    • Tasks—A list of tasks you can run on the build
    • Settings—A list of settings you can modify for the project

    Let’s look into each.

    Running tasks

    Tasks are things that the SBT build can do for us, things like compiling a project, creating documentation, or running tests. Out of the box, SBT provides the following tasks as shown.

      >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 ...
    compile          Compiles sources.
    console          Starts the Scala interpreter with the ...
    consoleProject   Starts the Scala interpreter with the sbt ...
    consoleQuick     Starts the Scala interpreter with the ...
    copyResources    Copies resources to the output directory.
    doc              Generates API documentation.
    package          Produces the main artifact, such as a ...
    packageBin       Produces a main artifact, such as a ...
    packageDoc       Produces a documentation artifact, such ...
    packageSrc       Produces a source artifact, such as a ...
    publish          Publishes artifacts to a repository.
    publishLocal     Publishes artifacts to the local repository.
    run              Runs a main class, passing along args ...
    runMain          Runs the main class selected by arg ...
    test             Executes all tests.
    testOnly         Executes the tests provided as arguments ...
    testQuick        Executes the tests that either failed ...
    update           Resolves and optionally retrieves ...

    More tasks may be viewed by increasing verbosity. See 'help
    tasks'.

    You can see SBT offers many tasks right off the bat. Again, note all of the possible tasks you can run, and plan to revisit this list as needed. For now, run the compile task, as shown here.

    The compile command returns immediately because the project is currently empty.

    To watch the compile task do something useful, we’ll create a hello world program. First, you need to know where to put the source code. For that, view the help for settings.

    Working with settings

    Run the settings help on the SBT command line to see if that points you to where source code for the project should go.

    >settings

    This is a list of settings defined for the current project.
    It does not list the scopes the settings are defined in; use the
    'inspect' command for that.

    autoCompilerPlugins            If true, enables automatically ...
    autoScalaLibrary               Adds a dependency on scala-library
    ...
    baseDirectory                  The base directory. Depending on
    ...
    classDirectory                 Directory for compiled classes ...
    crossPaths                     If true, enables cross paths, ...
    fork                           If true, forks a new JVM when ...
    initialCommands                Initial commands to execute ...
    javaHome                       Selects the Java installation used
    ...
    javaSource                     Default Java source directory.
    libraryDependencies            Declares managed dependencies.
    managedResourceDirectories     List of managed resource
    directories.
    maxErrors                      The maximum number of errors, such
    ...
    name                           Project name.
    offline                        Configures sbt to work without ...
    organization                   Organization/group ID.
    publishArtifact                Enables or disables publishing ...
    publishTo                      The resolver to publish to.
    resourceDirectory              Default unmanaged resource ...
    scalaHome                      If Some, defines the local Scala ...
    scalaSource                    Default Scala source directory.
    scalaVersion                   The version of Scala used for
    building.
    sourceDirectories              List of all source directories ...
    sourceDirectory                Default directory containing
    sources.
    target        Main directory for files generated ...
    unmanagedBase                  The default directory for manually
    ...
    unmanagedResourceDirectories   Unmanaged resource directories ...
    unmanagedSourceDirectories     Unmanaged source directories, which
    ...
    version                        The version/revision of the current
    ...

    More settings may be viewed by increasing verbosity. See 'help
    settings'.

    Again, SBT provides several default settings (make another note to return here as needed). For now, the goal is to add some source code. We’re into the Scala language, so let’s look more closely at the scalaSource setting.

    The output tells you that Scala source files belong under the src/main/scala directory under your build directory, and this is where you’ll put the source code for the used-kittens.com website.

    Default project layout
    SBT comes prebaked with many settings and conventions, including an assumed project layout. The default project layout is borrowed from Maven, for familiarity. By default, projects look something like the figure shown here.

    SBT uses a default project layout similar to Maven.

    To add a hello world application to the used-kittens project, create a file in src/main/scala, as shown here.

    src/main/scala/UsedKittenMain.scala
    objectUsedKittenMain extends App {
    println(“Hello, sbt world!”)
    }

    This Scala object extends the scala.App class, allowing it to be used as a main entry point to an application. It does one thing when run: prints the sentence “Hello, sbt world!”. Run SBT’s compile command, as shown here, to test whether the build sees this file.

    > compile
    [info] Compiling 1 Scala source to /home/jsuereth/projects/sbt-in-action/
    chapter1/target/scala-2.10/classes...
    [success] Total time: 1 s, completed Dec 26, 2012 11:03:15 PM

    This time, running compile isn’t quite instantaneous. It takes one second to compile this Scala file. After the Scala code compiles, run the application using the run task in the SBT console.

    > run
    [info] Running UsedKittenMain
    Hello, sbt world!
    [success] Total time: 0 s, completed Dec 26, 2012 11:05:00 PM
    >

    The run task finds the UsedKittenMain application and runs it locally. The output from the application prints directly to the console; the SBT prompt returns when the application is done.

    Summary

    SBT provides a quick and powerful means to get started with a Scala project and rapidly develop, test, and debug your code. Other build tools stop at providing a repeatable build that can be used on a continuous integration server, but SBT goes beyond that and adds a new level of interaction and customization for the developer.


    Here are some other Manning titles you might be interested in:

    Secrets of the JavaScript Ninja

    Secrets of the JavaScript Ninja
    John Resig and Bear Bibeault

    Node.js in Action

    Node.js in Action
    Mike Cantelon, TJ Holowaychuk and Nathan Rajlich

    Ext JS in Action, Second Edition

    Ext JS in Action, Second Edition
    Jesus Garcia, Jacob K. Andresen, and Grgur Grisogono


    AttachmentSize
    sbt001.png16.6 KB
    sbt002.png11.97 KB
    sbt003.png71.08 KB
    sbt004.png38.04 KB
    sbt005.png19.38 KB
    sbt006.png33.61 KB
    sbt007.png4.2 KB
    sbt008.png4.27 KB
    sbt009.png4.11 KB
    Related Topics >>