From a99287563090938d84a150345217068967d7e66a Mon Sep 17 00:00:00 2001 From: sleefd Date: Fri, 8 Dec 2023 18:40:46 +0800 Subject: [PATCH] ansi color log --- src/main/scala/sbtcurl/CurlPlugin.scala | 37 ++++++++++++++++++------- 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/src/main/scala/sbtcurl/CurlPlugin.scala b/src/main/scala/sbtcurl/CurlPlugin.scala index 466e2ae..a8ed340 100644 --- a/src/main/scala/sbtcurl/CurlPlugin.scala +++ b/src/main/scala/sbtcurl/CurlPlugin.scala @@ -2,6 +2,7 @@ package sbtcurl import sbt._ import sbt.Keys._ +import sbtcurl.Curl.AnsiLogger import scala.io.Source import scala.sys.process._ @@ -21,7 +22,7 @@ object CurlPlugin extends AutoPlugin { lazy val curlSettings: Seq[Def.Setting[_]] = Seq( curl := { val input = Def.spaceDelimited().parsed.mkString(" ") - implicit val log: Logger = streams.value.log + implicit val log: AnsiLogger = streams.value.log log.info(Curl(input)) }, ) @@ -42,11 +43,11 @@ object CurlPlugin extends AutoPlugin { }, curlTest := { val someFile = curlTestScript.value - implicit val log: Logger = streams.value.log + implicit val log: AnsiLogger = streams.value.log if (someFile.isDefined) { - Curl(someFile.get).foreach(println) + Curl(someFile.get).foreach(log.info) } else { - log.error("No any curl script file found!") + log.colorError("No any curl script file found!") } } ) @@ -58,16 +59,32 @@ object CurlPlugin extends AutoPlugin { } object Curl { - def apply(cmd: String)(implicit logger: Logger): String = { - var curl = cmd - if(!cmd.startsWith("curl")) { - curl = s"curl $cmd" + private val ANSI_RESET = "\u001B[0m" + + private val ANSI_GREEN = "\u001B[32m" + + private val ANSI_RED = "\u001B[31m" + + implicit class AnsiLogger(log: Logger) { + def colorInfo(msg: => String, ansi: String = ANSI_GREEN): Unit = + log.info(s"${ansi}$msg${ANSI_RESET}") + + def colorError(msg: => String, ansi: String = ANSI_RED): Unit = + log.error(s"${ansi}$msg${ANSI_RESET}") + + def info(msg: String): Unit = log.info(msg) + } + + def apply(cmd: String)(implicit logger: AnsiLogger): String = { + val curl = cmd match { + case s if s.startsWith("curl") => cmd + case _ => s"curl $cmd" } - logger.info(curl) + logger.colorInfo(curl) curl.!! } - def apply(file: File)(implicit logger: Logger): Seq[String] = { + def apply(file: File)(implicit logger: AnsiLogger): Seq[String] = { val source = Source.fromFile(file) try { val (list, _) = source