Wednesday, March 17, 2010

Scala Unix file permissions DSL

Scala native DSL capabilities are astonishing. I just created some Scala object to mimic Unix file permission representation and "chmod" interaction, and I'm rather pleased of the result

Only user", "group" and "other" permission are managed - so no setuid, setgid or sticky bit.

Perm objects

They are simple immutable permission objects with a nice toString and an octal representation:
scala> val p:Perm = wx
scala> w.toString // "-wx"
scala> w.octal // 3
You can combine permission to obtain new permissions:
scala> w+r  // rw-
scala> rwx-w // r-w

FilePerms objects

They keep a group of three mutable permissions. You can create a new File permission object from octal values:
scala> val perms = FilePerms(777)

Or from Perm object:
scala> val perms = FilePerms(rw,rw,r)
Like Perm, they have nice string and octal representation:
scala> val perms = FilePerms(777)
scala> perms.toString //rwxrwxrwx
scala> perms.octal // 777

Missing values are initialized to "no permission":
scala> val perms = FilePerms(77) //rwxrwx---
scala> val perms = FilePerms(rw) //rw-------

And of course, you can change permissions:
scala> val perms = FilePerms(77) //rwxrwx---
scala> perms.g-wx  // rwxr----
scala> perms.ugo+x // rwxr-x--x
scala> perms.a-wx  // r--r-----
The binding of theses objects with Java IO with the goal to actually set file permissions is let as an exercise for the reader ;)
It's available on gist here: http://gist.github.com/335791. To test it, simply copy the file content, fire a Scala REPL, start an object declaration, past the content of the file, close you object, import its content, and play:
scala> object p { [enter]
  | [here, past the content of the file]
  .....
  | }
defined module p

scala> import p._
import p._

scala> FilePerms(644)
res0: Option[p.FilePerms] = Some(rw-r--r--)

Enjoy !


PS: if you have an idea about how to mimic chown, I would appreciate. For now, all I get is:
chmod( ug(_)+rw, filePerms)
Not really nice.

  © Blogger template 'Minimalist G' by Ourblogtemplates.com 2008

Back to TOP