Rock-solid shell scripting with Ammonite

Post on 23-Jan-2018

6,304 views 0 download

transcript

http://www.lihaoyi.com/Ammonite/

Rock-solid shell scripting with Ammonite

Maxim Novak

@maximnovakmaximn@wix.com https://github.com/maximn

01

List files

List files (recursively)

List all *.scala files

List the 3 largest *.scala files

Challenge… let’s ask Google

List the 3 largest *.scala files

Can’t really understand it

Seems to work…

http://toonclips.com/design/5803

http://www.clipartpanda.com/categories/man-thinking-drawing

(Lack of) Error handling

http://www.clipartpanda.com/categories/man-thinking-drawing

(Lack of) Error handling

Success

http://www.clipartpanda.com/categories/man-thinking-drawing

(Lack of) Error handling

Failed

Bash scripts are hard to understand, hard to maintain, and very fragile

Bash scripts are hard to understand, hard to maintain, and very fragile

We need something better

Why not ?

02

List files

import java.io.File

val file = new File(".")if (file.exists && file.isDirectory) {file.listFiles.toSeq

} else {Nil

}

Write text to file

import java.nio.file.{Paths, Files}import java.nio.charset.StandardCharsets

val file = Paths.get("hi.txt")val content ="hello".getBytes(StandardCharsets.UTF_8)Files.write(file, content)

http://humandefect.deviantart.com/art/Uh-Oh-542255224

Verbose…

What you really want is

What you really want isthe power of Scala

with the semantics of a shell

Welcome Ammonite!

03

List files

http://toonclips.com/design/9164

Structured data, yes!

ls! wd is an alias for ls(wd)

List files (recursively)

List all *.scala files

List 3 largest *.scala files

Change directory

Write text to file

Running an executable

It’s easy breezy.

It’s easy breezy. And it’s safe.

Type safety

Main.scala:296: type mismatch;

found : ammonite.ops.Path

required: ammonite.ops.RelPath

relative/absolute

^

Compilation Failed

Type safety

Error handling

java.nio.file.NoSuchFileException: /Users/max/noSuchPath

sun.nio.fs.UnixException.translateToIOException(UnitExce

sun.nio.fs.UnixException.rethrowAsIOException(UnitExcept

sun.nio.fs.UnixException.rethrowAsIOException(UnitExcept

sun.nio.fs.UnixFileAttributeViews$Basic.readAttributes(U

It’s easy breezy. And it’s safe. Also, you can load any JVM library to the shell.

Loading an external library

JVM ecosystem at your fingertips

Power and safety of Scala

Shell semantics

https://pixabay.com/en/shells-massage-therapy-sand-beach-792912/http://youandworld.am/news/5790.html

Ammonite blurs the line between “system shell” and a “programming language”

http://www.lihaoyi.com/Ammonite/

Thank YouMaxim Novak

@maximnovakmaximn@wix.com https://github.com/maximn