Scripting Library in Scala – Ammonite

Table of contents
Reading Time: 4 minutes

Ammonite is a Scala library that lets us use Scala language for Scripting. It allows us to write scripts in Scala. The advantage of using Ammonite is that we don’t have to switch over to Python or Bash for scripting requirements of the projects.This liberates the developer from the need of working 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
It 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 support configurability that is Configurations can be put in the predef.sc file.

To Get Started with the 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 Library into Existing Project

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 scripts. Any file followed by .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 for us in the current directory and add the files to the git repository and make a commit and 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

Screenshot from 2017-09-27 12-57-34

In the above example, we see usage Scala Script for Git Commands. 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 command :

    amm FileCommands.sc

    Screenshot2

  • 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

    Screenshot3

  • 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

    Screenshot4.png

  • 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 command :

    amm FinagleServer.sc

    It will start the finagle server at 8080.

    Screenshot6


    knoldus-advt-sticker


     

    References :

  • http://ammonite.io/#ScalaScripts
  • https://github.com/lihaoyi/ammonite

Written by 

Pallavi is a Software Consultant, with more than 3 years of experience. She is very dedicated, hardworking and adaptive. She is Technology agnostic and knows languages like Scala and Java. Her areas of interests include microservices, Akka, Kafka, Play, Lagom, Graphql, Couchbase etc. Her hobbies include art & craft and photography.

1 thought on “Scripting Library in Scala – Ammonite4 min read

Comments are closed.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading