- Installing and running SBT on Windows 10
- How to set up sbt on Windows to select a specific JDK (among available JDKs)?
- 1 Answer 1
- Введение в sbt
- Предисловие
- 1. Установка sbt
- 2. Hello, World
- В качестве заключения
- sbt tool window
- Toolbar
- sbt Getting started with sbt
- Remarks
- Versions
- Import SBT Project into Eclipse
- Install on Mac OSX
- MacPorts
- Homebrew
- Sources
- Verification
- Install SBT on Linux
- RPM-based Linux Distributions
- Install SBT on Windows
- Install
- Verify Installation
Installing and running SBT on Windows 10
Jun 14, 2018 · 3 min read
As I mentioned in yesterday’s post, I’m working on a workshop for Scala days (Join us if you can! ) that includes setting up an Akka cluster on a set of three Raspberry Pis. The workshop organizers have very kindly shared a pre-built image with me.
Up until now I’ve been working with the image on Windows 10 via Windows Subsystem for Linux, but I need to connect to the project in Eclipse to make updates, and it’s just not easy transferring files back and forth between the two systems.
Instead, I ’ m using Eclipse for Windows and the Windows version of the Scala Simple Build Tool (SBT). Here’s what I had to do to make that happen, in a few minutes with 2 easy steps:
- Download and install the .msi from the SBT download page
- ADD sbt\bin to the PATH.
Two handy tips for this:
For easy and error-free copying of the path, go to the sbt\bin directory, right click and choose “copy address as text”:
Then to easily add the environment variable, open the windows menu then type environment, and pick the first option:
That takes you directly to the advanced system properties dialog:
Then just pick Environment Variables, and paste the copied path in to your PATH.
One more tip: If you need to use a common.credentials file with a provided SBT script, it usually goes in
If that doesn’t work, run the script and it will tell you where it expects to find credentials via error messages.
Now you should be able to run SBT from the command line.
Optionally, to get the project working in Eclipse, add this line to your project/plugins.sbt (substitute the current version of sbteclipse from the GitHub site, mine was 5.2.4) :
Then from the project’s bae folder type
This will run for a while the first time, and generate .project and .classpath files that eclipse will use to import the project.
In Eclipse, choose File>Import>General> Existing Projects into Workspace, and choose the project’s base folder, then Next.
How to set up sbt on Windows to select a specific JDK (among available JDKs)?
Is there a way to tell SBT which (locally) installed JDK to use?
I am quite certain I could change PATH and JAVA_HOME but I’d rather not change those settings since they apply for the whole system (Windows in that case).
I am more looking for a command line parameter of some sort.
1 Answer 1
If you’re looking to specify a JDK for running SBT (rather than a JDK to use for running your code and/or tests from within SBT), you can make use of the JAVA_HOMES environment variable, plus a .java-version file in your project.
This is described in SBT‘s sbt.bat file (typically installed to C:\Program Files (x86)\sbt\bin ) as a «poor man’s jenv «, which isn’t currently available on Windows.
(If you’re looking for a similar solution for Linux or MacOS, you can either use jEnv , or specify the Java home directory via the -java-home SBT command line option—which also, sadly, isn’t currently implemented on Windows.)
The JAVA_HOMES environment variable (not to be confused with JAVA_HOME ) is used by SBT to identify a directory that contains one or more JDK installations. For example, if you’re using AdoptOpenJDK‘s JDK distributions (recommended on Windows, if Oracle‘s new licensing restrictions are a problem for you), then this would typically be defined as C:\Program Files\AdoptOpenJDK .
Let’s say that you have two such JDK installations in the JAVA_HOMES directory: one in a subdirectory named jdk-8.0.212.03-hotspot ; another in the jdk-11.0.3.7-hotspot subdirectory. You can select which JDK you want to use, on a project-by-project basis, by creating a file called .java-version in the root directory of each SBT project. To use the JDK in the jdk-8.0.212.03-hotspot subdirectory, this file should then contain:
When you run the sbt command, if you have JAVA_HOMES defined, SBT will look for a .java-version file in the project’s root directory. If it finds it, it creates a local version of JAVA_HOME that is defined as JAVA_HOMES plus the last line of .java-version . It also adds this JAVA_HOME ‘s bin directory to the path. (It also creates a JDK_HOME process-local environment variable with the same value.)
This should do what you want. Although it’s not a command line-based solution, it doesn’t adversely affect other users, and allows each SBT project to be configured individually. If you do not have permission to create a system-wide environment variable, you should still be able to create a user-specific JAVA_HOMES environment variable. Note that when using this solution, the JDK that SBT uses is then not necessarily the one identified by your system-wide (or user-specific) JAVA_HOME environment variable. (If you have not defined JAVA_HOMES , then SBT will expect you to have defined a valid JAVA_HOME variable.)
One word of caution: if you commit .java-version to source control, you must ensure that everyone defines a valid JAVA_HOMES environment variable, and has a JDK with the exact same name installed in that directory.
Введение в sbt
Предисловие
sbt, используя небольшое число концепций, предлагает гибкие решения сборки проектов.
Это руководство расскажет о некоторых моментах, которые необходимы для создания и поддержки решений по сборке с помощью sbt.
Данное руководство, очень рекомендовано к прочтению. Но, если вам некогда читать все, то самую важную информацию вы можете прочитать в разделах “Параметры .sbt сборки”, “Области сборок”, “Дополнительные параметры сборок”. Но, мы не обещаем, что эта хорошая идея поможет вам пропустить все страницы данного руководства.
Лучше всего читать этот документ последовательно, опираясь на пройденный ранее материал.
Спасибо, что используете sbt! Желаем вам получить от этого максимум удовольствия!
1. Установка sbt
Для создания sbt проекта вам нужно сделать следующие шаги:
- Установить sbt и создать скрипт запуска
- Создать простой проект “Hello world”
- Создать директорию проекта с исходными файлами внутри
- Описать параметры сборки
- Прочитать как запустить sbt
- Продолжить чтение руководства о параметрах sbt сборки
В конечном счете, установка сводится к запуску JAR файла и shell скрипта. Но, мы опишем несколько путей для разных платформ, которые могут сделать установку менее утомительной.
Если у вас появились проблемы с запуском sbt, смотрите раздел “Примечания к установке”.
1.a. Установка под Mac
С помощью Macports
$ port install sbt
Homebrew
$ brew install sbt
1.b. Установка под Windows
Просто скачайте инсталятор msi и запустите его.
1.c. Установка под Linux
Официально поддерживаемые дистрибутивы:
RPM пакет
DEB пакет
В дальнейшем я расскажу о том, как можно скачать и настроить sbt вручную. А пока что, самое интересное.
2. Hello, World
Создаем директорию проекта с исходным кодом
Одним из корректных вариантов sbt проекта, может быть директория, содержащая один файл с исходным кодом. Попробуйте создать директорию hello с файлом hw.scala, со следующим содержимым:
Теперь, в самой директории запустите sbt и наберите команду run в интерактивной консоле. В Linux или OS X это выглядить примерно так:
При создании проекта, sbt работает в соответствии со следующими правилами:
- Исходник лежит в корневой директории
- Исходники лежат в директории src/main/scala или src/main/java
- Тесты лежат в src/test/scala или src/test/java
- Файлы ресурсов в src/main/resources или src/test/resources
- Файлы jar в директории lib
По умолчанию, sbt соберет проект той версией scala, с помощью которой sbt был запущен сам.
Кроме запуска консоли, проект можно сразу запустить на выполнение командой sbt run.
Параметры сборки
Большинство проектов, все же нуждаются в более сложной настройке процесса сборки. В sbt основные параметры сборки хранятся в файле build.sbt в корневой директории проекта.
Например, если для нашего проекта hello создать файл настроек, то выглядеть бы он мог примерно так:
Обратите внимание на пустые строки. Это не просто так, они на самом деле требуются чтобы отделять строки в файле конфигурации и без них sbt выдаст ошибку. Подробнее мы вернемся к этому файлу в последующих разделах.
Установка версии sbt
Вы можете принудительно скачать и установить нужную версию sbt если пропишете в файле hello/project/build.properties следующую строчку:
sbt.version=0.13.5
Теперь, при запуске будет использоваться версия sbt 0.13.5. Если ее нет, то скрип скачает и установит ее в системе.
Хранить версию sbt следует именно в файле project/build.properties для избежания возможных колизий.
В качестве заключения
Для эксперимента, я решил ограничиться только этими самыми первыми разделами, и если реакция будет более-менее положительной, надеюсь продолжить переводить и остальные.
sbt tool window
The sbt tool window is enabled automatically when you create or open your sbt project. Click sbt on the right sidebar to open the tool window. The tool window displays the sbt linked projects, their tasks, dependencies, and all changes made to the underlying build.sbt file.
If you removed the sbt tool window from the sidebar, select View | Tool Windows | sbt from the main menu to reopen it.
Item | Description | |||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Item | Description | ||||||
---|---|---|---|---|---|---|---|
Click this button to refresh all registered sbt projects after changes have been made to an sbt script. | |||||||
Click this button to link an sbt project. | |||||||
Click this button to detach an external sbt project. | |||||||
Use these buttons to expand or collapse all the nodes. | |||||||
Click this button to import a module or a data to your sbt project. It might be useful for the multi-module projects. | |||||||
Use this icon to access the following settings: Auto-Reload Setting : select this option to configure the reloading process of your sbt project in the Build Tools settings dialog. sbt Settings : select this option to configure the settings of the current sbt project in the sbt settings dialog. sbt Getting started with sbtRemarksThe Simple Build Tool (SBT for short) can be used to build Scala (or Java) project code. This includes managing code, dependencies, and resources that must be built, tested, and/or compiled to a .jar or other artifact. Custom tasks can be created to manage all of these processes. A note on the name; SBT is sometimes referred to as the ‘Scala Build Tool’. While this was not the original intent, it has come to be commonly used as well. SBT may be used to build any project on the JVM. .sbt files, or ‘SBT build definitions’ are specially interpreted files, written in Scala, that are used by SBT to define a build. .scala build definitions may also be written and imported into an .sbt file. Versions prior to 13.6 required that any .sbt file has each statement separated by a blank line. Without the blank line, the .sbt file will break. A universal package exists in ZIP and TGZ formats. Versions
Import SBT Project into EclipseThis assumes you have installed both Eclipse and SBT. Install the SBT plugin for Eclipse from the Eclipse marketplace. In the command line switch directory to the root directory of the project. Execute sbt, which will load the project. Compile the project to ensure dependencies are obtainable. Run the eclipse task: Go into Eclipse and select the menu option: File > New > Project From Existing Sources In the wizard, navigate to your project directory and select it. Eclipse will handle the rest. Install on Mac OSXFull official instructions can be found here. MacPortsInstall MacPorts. Then, in the terminal execute: HomebrewInstall Homebrew. Then, in the terminal execute: SourcesDownload sbt All platforms (tgz) installation from SBT. Then, execute following Inside your $HOME make sure to update /.profile — by adding following lines VerificationIn the terminal execute: You should expect output similar to: If you get no output sbt is not installed. Install SBT on LinuxFull instructions can be found here. Set the Java Environment variable. RPM-based Linux DistributionsDownload SBT repository definitions and add it to YUM: Install SBT according to the definitions previously added to YUM: Install SBT on WindowsInstallMSI installers can be found here. This is the latest stable version. Download and execute to install. Verify InstallationUse the WindowsKey + R , type cmd . Alternatively, navigate to the .sbt (for example, in C:\Users\Hopper ) and type cmd in the address bar. Type sbt about to get version information, verifying it is installed. You should see something like this: |