Scripting Library in Scala: Ammonite
Ammonite is a handy library that enables scripting for Scala. See how to use it in your REPL, add it to an existing project, or use it as a standalone shell.
Join the DZone community and get the full member experience.
Join For FreeAmmonite is a Scala library that lets us use the Scala language for scripting. The advantage of using Ammonite is that we don't have to switch over to Python or Bash for scripting requirements of our projects. This liberates us from the need to work in multiple languages.
Ammonite can be used in the REPL as scripts, or as a library in existing projects, or, alternatively, as a standalone system shell.
Ammonite REPL
This is an improved Scala REPL. It has more features than the standard REPL and is loaded with lots of ergonomic improvements like Pretty Printing, Syntax Highlighting, etc. and supports adaptable configurations — that is, configurations can be put in the predef.sc file.
To get started with Ammonite as a Scala shell, download the standalone Ammonite 1.0.2 executable for Scala 2.12.
sudo curl -L -o /usr/local/bin/amm https://git.io/v5Tct && sudo chmod +x /usr/local/bin/amm &&
You can also set the Path in your bashrc:
#Set Ammonite Home
export AMMONITE_HOME="path/amm"
Ammonite as a Library for Existing Projects
Add the following library dependency to your build.sbt:
libraryDependencies += "com.lihaoyi" % "ammonite" % "1.0.2" % "test"
cross CrossVersion.full
sourceGenerators in Test += Def.task {
val file = (sourceManaged in Test).value / "amm.scala"
IO.write(file, ""
"object amm extends App { ammonite.Main().run() }"
"")
Seq(file)
}.taskValue
One can also try the latest features in the unstable release:
libraryDependencies += "com.lihaoyi" % "ammonite" % "1.0.2-3-79f3f8b" % "test" cross CrossVersion.full
Scala Scripts
Before we explore further into the details, let us understand What are Scala Scripts?
In simple terms, these are lightweight files that contain Scala code that can be run from the command line directly.
Another question that pops up is Why Scala Scripts when we have SBT projects?
Scala Scripts allows to run code without setting up of the project or build file. And Scala Scripts are very useful for small pieces of code as they support much easier and quicker deployment in comparison to SBT project.
Deploying a script file is as easy as copying the file to the location and running it, it requires no project/ folder or .jar files etc or compilation. The Scala Scripts are being auto-compiled the first time they are executed. The subsequent runs are faster as they get cached.This also saves us the trouble of setting up heavyweight SBT projects.
Writing Scala Scripts
Now, let us get started by writing a Scala script. Any file followed by the .sc extension is a Scala script, and it can be executed from the terminal.
Example: Deploy.sc
Let us create a Scala script that will allow us to set up git project in the current directory and add files to the git repository, as well as make a commit, then display the list of git branches.
- Create a file GitCommands.sc
- Add the following code to it:
import ammonite.ops._, ImplicitWd._
%git 'init
%git('add, "-A")
%git('commit, "-am", "First Commit")
%git 'branch
val log = %%('git, 'log, "--pretty=oneline").out.lines
- Save the above file
- Execute the file with the command amm GitCommands.sc:
In the above example, we see the script in action. Now, let us explore a few more uses in detail.
- File Commands: Use Scala Script to create a directory in the system and show the content of the directory. Create a file named FileCommands.sc and copy the content given below :
import ammonite.ops._ println("Starting contents") ls! cwd foreach println mkdir(cwd/"my-folder") println("Contents after creating folder") ls! cwd foreach println write(cwd/"my-folder"/"soo.txt", "Hello Hello") println("Written file contents") println(read! cwd/"my-folder"/"soo.txt")
Now execute the above file with the command amm FileCommands.sc:
- Scala Code in scripting Style: Create a file named Bar.sc and copy the following into it. It creates a Scala variable:
val myMessage="Hello World, You are at Knoldus"
Create another Scala script file that will use the above variable named Foo.sc and copy the following code :import $file.Bar println("Hello World") println(Bar.myMessage)
In the above Scala script, we have imported another Scala script file named Bar.sc
- HTML embedded in Scala code: Create a file named Lib.sc and copy the following content in the file:
import $ivy.`com.lihaoyi::scalatags:0.6.0`, scalatags.Text.all._ println(a("Hello", href := "http://www.google.com").render)
In the above Scala script, we have imported a dependency from the ivy to embed HTML in scala code. Run the above script with amm Lib.sc:
- Complex Scala Code: In the last example, let us use Ammonite to start a finagle server. Create a file named FinagleServer.sc and copy the following code:
import $ivy.`com.twitter::finagle-http:6.36.0 `import com.twitter.finagle._, com.twitter.util._ val service = new Service[http.Request, http.Response] { def apply(req: http.Request): Future[http.Response] = { val response = http.Response(req.version, http.Status.Ok) response.contentString = "Hello, Welcome to Knoldus Server!" Future.value(response) } } val server = Http.serve(":8080", service) Await.ready(server)
- Execute the above file with the command amm FinagleServer.sc:
It will start the finagle server at 8080.
Published at DZone with permission of Pallavi Singh, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments