From 2c6fb5a8e865290ade760c15001773af88c4078c Mon Sep 17 00:00:00 2001 From: Rob Norris Date: Fri, 12 Aug 2022 09:55:22 -0500 Subject: [PATCH] convenience methods --- modules/core/src/main/scala/cursor.scala | 8 ++++++++ modules/core/src/main/scala/package.scala | 22 ++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/modules/core/src/main/scala/cursor.scala b/modules/core/src/main/scala/cursor.scala index cedda111..80f4e643 100644 --- a/modules/core/src/main/scala/cursor.scala +++ b/modules/core/src/main/scala/cursor.scala @@ -9,6 +9,7 @@ import scala.reflect.{classTag, ClassTag} import cats.data.Ior import cats.implicits._ import io.circe.Json +import org.tpolecat.typename.{ TypeName, typeName } import Cursor.{ cast, Context, Env } import QueryInterpreter.{ mkErrorResult, mkOneError } @@ -305,6 +306,13 @@ object Cursor { def add[T](items: (String, T)*): Env def add(env: Env): Env def get[T: ClassTag](name: String): Option[T] + + def getR[A: ClassTag: TypeName](name: String): Result[A] = + get[A](name) match { + case None => Result.failure(s"Key '$name' of type ${typeName[A]} was not found in $this") + case Some(value) => Result(value) + } + } object Env { diff --git a/modules/core/src/main/scala/package.scala b/modules/core/src/main/scala/package.scala index ca8369da..a38b9512 100644 --- a/modules/core/src/main/scala/package.scala +++ b/modules/core/src/main/scala/package.scala @@ -6,6 +6,7 @@ package edu.gemini import cats.data.IorNec import cats.data.Ior import cats.data.NonEmptyChain +import cats.syntax.all._ package object grackle { /** @@ -29,6 +30,27 @@ package object grackle { def failure[A](p: Problem): Result[A] = Ior.left(NonEmptyChain(p)) + def fromOption[A](oa: Option[A], ifNone: => Problem): Result[A] = + oa match { + case Some(a) => Result(a) + case None => Result.failure(ifNone) + } + + def fromEither[A](ea: Either[Problem, A]): Result[A] = + ea.fold(Result.failure(_), Result.apply) + + def warning[A](warning: Problem, value: A): Result[A] = + Result.failure[A](warning).putRight(value) + + def fromOption[A](oa: Option[A], ifNone: => String)(implicit ev: DummyImplicit): Result[A] = + fromOption(oa, Problem(ifNone)) + + def fromEither[A](ea: Either[String, A])(implicit ev: DummyImplicit): Result[A] = + fromEither(ea.leftMap(Problem(_))) + + def warning[A](warning: String, value: A): Result[A] = + this.warning(Problem(warning), value) + } }