Skip to content

Instantly share code, notes, and snippets.

@ykon
Last active February 3, 2019 12:12
Show Gist options
  • Save ykon/2e8a65fb1fffe85bac8fce38d6718034 to your computer and use it in GitHub Desktop.
Save ykon/2e8a65fb1fffe85bac8fce38d6718034 to your computer and use it in GitHub Desktop.
import java.nio.file._
object mail_header {
def read_file(path: String): Option[String] = {
val p = Paths.get(path)
if (Files.exists(p)) Some(new String(Files.readAllBytes(p))) else None
}
def split_header_body(text: String): Option[(String, String)] = {
text.split("\r\n\r\n", 2) match {
case Array(header, body) => Some(header, body)
case _ => None
}
}
def unfold_header(header: String): String =
header.replaceAll("\r\n[ \t]+", " ")
def split_field(line: String): Option[(String, String)] = {
val pat = """(\S+): *(.+)?""".r
pat.findFirstMatchIn(line) match {
case Some(m) => Some(m.group(1), Option(m.group(2)).getOrElse(""))
case None => None
}
}
def parse_header(header: String): List[(String, String)] =
header.lines.flatMap(split_field).toList
def tuple_to_hash(header: List[(String, String)]): Map[String, List[String]] =
header.groupBy(_._1).map { case (k, v) => (k.toLowerCase(), v.map(_._2)) }
def main(args: Array[String]): Unit = {
val text = read_file("data.txt").getOrElse(sys.error("File not found"))
val (header, _) = split_header_body(text).getOrElse(sys.error("Invalid mail-header"))
val unfolded_header = unfold_header(header)
val tupled_header = parse_header(unfolded_header)
val mail_header = tuple_to_hash(tupled_header)
println(mail_header)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment