CoreDefinition.scala 1.61 KB
Newer Older
1
package chisel.packaging
Jens Korinth's avatar
Jens Korinth committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import scala.io.Source
import play.api.libs.json._
import play.api.libs.functional.syntax._

/**
 * Basic definition of a core for IP-XACT packaging.
 **/
case class CoreDefinition(name: String, vendor: String, library: String, version: String, root: String) {
  import CoreDefinition._
  def write(filename: String) : Boolean = try {
    val fw = new java.io.FileWriter(filename)
    fw.append(Json.toJson(this).toString)
    fw.flush()
    fw.close()
    true
  } catch { case ex: Exception => println("ERROR: " + ex); false }
}

/**
 * Contains methods for reading a core definition from Json.
 **/
object CoreDefinition {
  implicit val coreDefinitionWrites : Writes[CoreDefinition] = (
      (JsPath \ "name").write[String] ~
      (JsPath \ "vendor").write[String] ~
      (JsPath \ "library").write[String] ~
      (JsPath \ "version").write[String] ~
      (JsPath \ "root").write[String]
    )(unlift(CoreDefinition.unapply))

  implicit val coreDefinitionReads : Reads[CoreDefinition] = (
      (JsPath \ "name").read[String] ~
      (JsPath \ "vendor").read[String] ~
      (JsPath \ "library").read[String] ~
      (JsPath \ "version").read[String] ~
      (JsPath \ "root").read[String]
    )(CoreDefinition.apply _)

  def read(filename: String) : Option[CoreDefinition] = try {
    val contents = Source.fromFile(filename).getLines.mkString("\n")
    val json = Json.parse(contents)
    json.validate[CoreDefinition] match {
      case s: JsSuccess[CoreDefinition] => Some(s.get)
      case e: JsError => { println("ERROR: " + e); None }
    }
  } catch { case ex: Exception => println("ERROR: " + ex); None }
}