Created
January 15, 2016 08:59
-
-
Save makiftutuncu/c76e814cb6a6ac7f4a3d to your computer and use it in GitHub Desktop.
A small script to parse Play's routes file and genenrate Json string output
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.io._ | |
case class Route(httpMethod: String, url: String, endpoint: Endpoint) { | |
def toJson = s"""{"httpMethod":"$httpMethod","url":"$url","endpoint":$endpoint}""" | |
override def toString = toJson | |
} | |
case class Endpoint(controllerPackage: String, controller: String, method: String, parameters: List[String]) { | |
def toJson = s"""{"controllerPackage":"$controllerPackage","controller":"$controller","method":"$method","parameters":${parameters.map(p => "\"" + p + "\"").mkString("[",",","]")}}""" | |
override def toString = toJson | |
} | |
val source = Source.fromFile("routes") | |
val lines = source.getLines.toList | |
source.close() | |
val routeLineRegex = """^(\w+?)\s+(.+?)\s+(.+)$""".r | |
val endpointRegex = """^([\w.]+)\.(\w+)\.(\w+)$""".r | |
val endpointWithParanthesisRegex = """^([\w.]+)\.(\w+)\.(\w+)(?:\((.+)\))$""".r | |
val tempRoutes: List[Option[Route]] = lines.map { | |
line => | |
if (line.startsWith("#")) { | |
None | |
} else { | |
routeLineRegex.findFirstMatchIn(line).flatMap { | |
lineMatch => | |
val (httpMethod: String, url: String, endpointString: String) = (lineMatch.group(1), lineMatch.group(2), lineMatch.group(3)) | |
val matchAsOpt = if (endpointString.contains("(")) { | |
endpointWithParanthesisRegex.findFirstMatchIn(endpointString) | |
} else { | |
endpointRegex.findFirstMatchIn(endpointString) | |
} | |
matchAsOpt.map { | |
endpointMatch => | |
val (controllerPackage: String, controller: String, method: String, parametersString: String) = if (endpointMatch.groupCount > 3) { | |
(endpointMatch.group(1), endpointMatch.group(2), endpointMatch.group(3), endpointMatch.group(4)) | |
} else { | |
(endpointMatch.group(1), endpointMatch.group(2), endpointMatch.group(3), "") | |
} | |
val parameters: List[String] = parametersString.split(",").toList.map { | |
parameterString => | |
if (parameterString.contains(":")) { | |
parameterString.split(":").head.trim | |
} else { | |
parameterString.trim | |
} | |
} | |
val endpoint = Endpoint(controllerPackage, controller, method, parameters) | |
val route = Route(httpMethod, url, endpoint) | |
route | |
} | |
} | |
} | |
} | |
val routes: List[Route] = tempRoutes.collect { | |
case Some(route) => route | |
} | |
println(routes.mkString("[",",","]")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment