Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

convenience methods #251

Merged
merged 1 commit into from
Aug 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions modules/core/src/main/scala/cursor.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down Expand Up @@ -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 {
Expand Down
22 changes: 22 additions & 0 deletions modules/core/src/main/scala/package.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
/**
Expand All @@ -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)

}

}