src/Pure/General/csv.scala
author wenzelm
Fri, 01 Apr 2022 17:06:10 +0200
changeset 75393 87ebf5a50283
parent 73340 0ffcad1f6130
child 75606 0f7cb6cd08fe
permissions -rw-r--r--
clarified formatting, for the sake of scala3;

/*  Title:      Pure/General/csv.scala
    Author:     Makarius

Support for CSV: RFC 4180.
*/

package isabelle


object CSV {
  def print_field(field: Any): String = {
    val str = field.toString
    if (str.exists("\",\r\n".contains(_))) {
      (for (c <- str) yield { if (c == '"') "\"\"" else c.toString }).mkString("\"", "", "\"")
    }
    else str
  }

  sealed case class Record(fields: Any*) {
    override def toString: String = fields.iterator.map(print_field).mkString(",")
  }

  sealed case class File(name: String, header: List[String], records: List[Record]) {
    override def toString: String = (Record(header:_*) :: records).mkString("\r\n")

    def file_name: String = name + ".csv"
    def write(dir: Path): Unit = isabelle.File.write(dir + Path.explode(file_name), toString)
  }
}