Skip to content

Instantly share code, notes, and snippets.

@solidsnack
Created August 8, 2013 23:41
Show Gist options
  • Select an option

  • Save solidsnack/6189862 to your computer and use it in GitHub Desktop.

Select an option

Save solidsnack/6189862 to your computer and use it in GitHub Desktop.
Tar as the JSON of UNIX
import org.kamranzafar.jtar._
import java.io.{ByteArrayInputStream, ByteArrayOutputStream}
import scala.collection.mutable.ArrayBuffer
import com.google.common.base.Charsets
object Tar {
def toTar(entries: Map[String,String]): Array[Byte] = {
val bytesOut = new ByteArrayOutputStream()
val archive = new TarOutputStream(bytesOut)
val mTime: Long = System.currentTimeMillis() / 1000
val paired = for ((name, data) <- entries) yield {
val bytes: Array[Byte] = data.getBytes(Charsets.UTF_8)
(TarHeader.createHeader(name, bytes.length, mTime, false), bytes)
}
for ((header, bytes) <- paired) {
val entry = new TarEntry(header)
entry.setGroupId(0)
entry.setUserId(0)
archive.putNextEntry(entry)
archive.write(bytes)
}
archive.close()
bytesOut.toByteArray
}
def unTar(tar: Array[Byte]): Map[String,String] = {
val asTar = new TarInputStream(new ByteArrayInputStream(tar))
var entry: TarEntry = null
val entries: ArrayBuffer[(String, String)] = new ArrayBuffer()
while ({ entry = asTar.getNextEntry ; entry != null }) {
val name = entry.getName
if (name.last != '/') {
val data = new Array[Byte](entry.getSize.toInt)
asTar.read(data)
entries.append((name, new String(data, Charsets.UTF_8)))
}
}
entries.toMap
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment