shapeless.labelled.FieldType Scala Examples

The following examples show how to use shapeless.labelled.FieldType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: Cleaner.scala    From cleanframes   with Apache License 2.0 6 votes vote down vote up
package cleanframes

import org.apache.spark.sql.{Column, DataFrame, functions}
import shapeless.labelled.FieldType
import shapeless.{::, HList, HNil, LabelledGeneric, Lazy, Witness}

trait Cleaner[A] {
  def clean(frame: DataFrame, name: Option[String], alias: Option[String]): List[Column]
}

object Cleaner {
  def apply[A](frame: DataFrame, name: Option[String], alias: Option[String])(implicit env: Cleaner[A]): DataFrame = {
    frame.select(
      env.clean(frame, name, alias): _*
    )
  }

  def materialize[A](func: (DataFrame, Option[String], Option[String]) => List[Column]): Cleaner[A] = new Cleaner[A] {
    override def clean(frame: DataFrame, name: Option[String], alias: Option[String]): List[Column] = func(frame, name, alias)
  }

  implicit val hnilCleaner: Cleaner[HNil] = materialize((_, _, _) => Nil)

  implicit def genericObjectCleaner[A, H <: HList](implicit
                                                   gen: LabelledGeneric.Aux[A, H],
                                                   hCleaner: Lazy[Cleaner[H]]): Cleaner[A] =
    materialize((frame, name, alias) => {
      val structColumn = functions.struct(
        hCleaner.value.clean(frame, name, alias): _*
      )

      List(
        alias
          .map(structColumn.as)
          .getOrElse(structColumn)
      )
    })

  implicit def hlistObjectCleaner[K <: Symbol, H, T <: HList](implicit
                                                              witness: Witness.Aux[K],
                                                              hCleaner: Lazy[Cleaner[H]],
                                                              tCleaner: Cleaner[T]): Cleaner[FieldType[K, H] :: T] = {
    val fieldName: String = witness.value.name

    materialize { (frame, name, alias) =>

      val columnName = alias match {
        case None |
             Some(`reserved_root_level_alias`) => fieldName
        case Some(alias) => s"$alias.$fieldName"
      }

      val hColumns = hCleaner.value.clean(frame, Some(columnName), alias = Some(fieldName))
      val tColumns = tCleaner.clean(frame, name, alias)
      hColumns ::: tColumns
    }
  }
} 
Example 2
Source File: RESPParamWrite.scala    From laserdisc   with MIT License 5 votes vote down vote up
package laserdisc.protocol

import shapeless._
import shapeless.labelled.FieldType

import scala.annotation.implicitNotFound

@implicitNotFound(
  """Implicit not found RESPParamWrite[${A}].

Normally you would not need to define one manually, as one will be derived for you automatically iff:
- an instance of Show[${A}] is in scope
- ${A} is a List whose LUB has a RESPParamWrite instance defined
- ${A} is an HList whose elements all have a RESPParamWrite instance defined
"""
) trait RESPParamWrite[A] {
  def write(a: A): Seq[GenBulk]
}

object RESPParamWrite extends RESPParamWriteInstances {
  @inline final def apply[A](implicit instance: RESPParamWrite[A]): RESPParamWrite[A] = instance

  final def const[A](thunk: =>Seq[GenBulk]): RESPParamWrite[A] =
    (_: A) => thunk
  final def instance[A](f: A => Seq[GenBulk]): RESPParamWrite[A] =
    (a: A) => f(a)
}

private[protocol] sealed trait RESPParamWriteInstances extends RESPParamWriteInstances1 {
  implicit final def showRESPParamWrite[A: Show]: RESPParamWrite[A] = RESPParamWrite.instance(a => Seq(Bulk(a)))
  implicit final def pairRESPParamWrite[A, B](
      implicit A: RESPParamWrite[A],
      B: RESPParamWrite[B]
  ): RESPParamWrite[(A, B)] =
    RESPParamWrite.instance {
      case (a, b) => A.write(a) ++ B.write(b)
    }
  implicit final def listRESPParamWrite[A](implicit A: RESPParamWrite[A]): RESPParamWrite[List[A]] =
    RESPParamWrite.instance(_.flatMap(A.write))
  implicit final def taggedRESPParamWrite[K <: Symbol, V](
      implicit K: Witness.Aux[K],
      V: RESPParamWrite[V]
  ): RESPParamWrite[FieldType[K, V]] = RESPParamWrite.instance(Bulk(K.value.name) +: V.write(_))
}

private[protocol] sealed trait RESPParamWriteInstances1 {
  implicit final val nilRESPParamWrite: RESPParamWrite[Nil.type] = RESPParamWrite.const(Seq.empty)
  implicit final val hNilRESPParamWrite: RESPParamWrite[HNil]    = RESPParamWrite.const(Seq.empty)

  implicit final def hConsRESPParamWrite[H, T <: HList](
      implicit H: RESPParamWrite[H],
      T: RESPParamWrite[T]
  ): RESPParamWrite[H :: T] =
    RESPParamWrite.instance {
      case h :: t => H.write(h) ++: T.write(t)
    }
} 
Example 3
Source File: RecordToMap.scala    From circe-generic-extras   with Apache License 2.0 5 votes vote down vote up
package io.circe.generic.extras.util

import scala.collection.immutable.Map
import shapeless.{ ::, HList, HNil, Witness }
import shapeless.labelled.FieldType

abstract class RecordToMap[R <: HList] {
  def apply(r: R): Map[String, Any]
}

object RecordToMap {
  implicit val hnilRecordToMap: RecordToMap[HNil] = new RecordToMap[HNil] {
    def apply(r: HNil): Map[String, Any] = Map.empty
  }

  implicit def hconsRecordToMap[K <: Symbol, V, T <: HList](implicit
    wit: Witness.Aux[K],
    rtmT: RecordToMap[T]
  ): RecordToMap[FieldType[K, V] :: T] = new RecordToMap[FieldType[K, V] :: T] {
    def apply(r: FieldType[K, V] :: T): Map[String, Any] = rtmT(r.tail) + ((wit.value.name, r.head))
  }
} 
Example 4
Source File: EnumerationDecoder.scala    From circe-generic-extras   with Apache License 2.0 5 votes vote down vote up
package io.circe.generic.extras.decoding

import io.circe.{ Decoder, DecodingFailure, HCursor }
import io.circe.generic.extras.Configuration
import scala.annotation.implicitNotFound
import shapeless.{ :+:, CNil, Coproduct, HNil, Inl, Inr, LabelledGeneric, Witness }
import shapeless.labelled.{ FieldType, field }

@implicitNotFound(
  """Could not find EnumerationDecoder for type ${A}.
Some possible causes for this:
- ${A} isn't a case class or sealed trat
- some of ${A}'s members don't have codecs of their own
- missing implicit Configuration"""
)
abstract class EnumerationDecoder[A] extends Decoder[A]

object EnumerationDecoder {
  implicit val decodeEnumerationCNil: EnumerationDecoder[CNil] = new EnumerationDecoder[CNil] {
    def apply(c: HCursor): Decoder.Result[CNil] = Left(DecodingFailure("Enumeration", c.history))
  }

  implicit def decodeEnumerationCCons[K <: Symbol, V, R <: Coproduct](implicit
    witK: Witness.Aux[K],
    gen: LabelledGeneric.Aux[V, HNil],
    decodeR: EnumerationDecoder[R],
    config: Configuration = Configuration.default
  ): EnumerationDecoder[FieldType[K, V] :+: R] = new EnumerationDecoder[FieldType[K, V] :+: R] {
    def apply(c: HCursor): Decoder.Result[FieldType[K, V] :+: R] =
      c.as[String] match {
        case Right(s) if s == config.transformConstructorNames(witK.value.name) =>
          Right(Inl(field[K](gen.from(HNil))))
        case Right(_) =>
          decodeR.apply(c) match {
            case Right(v)  => Right(Inr(v))
            case Left(err) => Left(err)
          }
        case Left(err) => Left(DecodingFailure("Enumeration", c.history))
      }
  }

  implicit def decodeEnumeration[A, Repr <: Coproduct](implicit
    gen: LabelledGeneric.Aux[A, Repr],
    decodeR: EnumerationDecoder[Repr]
  ): EnumerationDecoder[A] =
    new EnumerationDecoder[A] {
      def apply(c: HCursor): Decoder.Result[A] = decodeR(c) match {
        case Right(v)  => Right(gen.from(v))
        case Left(err) => Left(err)
      }
    }
} 
Example 5
Source File: CaseClassDiffy.scala    From ratatool   with Apache License 2.0 5 votes vote down vote up
package com.spotify.ratatool.shapeless

import com.spotify.ratatool.diffy.{BigDiffy, Delta, Diffy, MultiKey}
import com.spotify.ratatool.diffy.BigDiffy.diff
import com.spotify.scio.coders.Coder
import com.spotify.scio.values.SCollection
import shapeless._
import shapeless.labelled.FieldType

import scala.reflect.ClassTag

@SerialVersionUID(42L)
sealed trait MapEncoder[A] extends Serializable {
  def toMap(in: A): Map[String, Any]
}

object MapEncoder {
  def apply[A](implicit encoder: MapEncoder[A]): MapEncoder[A] =
    encoder

  def createEncoder[A](func: A => Map[String, Any]): MapEncoder[A] = new MapEncoder[A] {
    override def toMap(in: A): Map[String, Any] = func(in)
  }

  implicit def stringEncoder[K <: Symbol](implicit witness: Witness.Aux[K]):
  MapEncoder[FieldType[K, String]] = {
    val name = witness.value.name
    createEncoder { v =>
      Map(name -> v.toString)
    }
  }

  implicit def intEncoder[K <: Symbol](implicit witness: Witness.Aux[K]):
  MapEncoder[FieldType[K, Int]] = {
    val name = witness.value.name
    createEncoder { v =>
      Map(name -> v.self)
    }
  }

  implicit def longEncoder[K <: Symbol](implicit witness: Witness.Aux[K]):
  MapEncoder[FieldType[K, Long]] = {
    val name = witness.value.name
    createEncoder { v =>
      Map(name -> v.self)
    }
  }

  implicit def booleanEncoder[K <: Symbol](implicit witness: Witness.Aux[K]):
  MapEncoder[FieldType[K, Boolean]] = {
    val name = witness.value.name
    createEncoder { v =>
      Map(name -> v.self)
    }
  }

  implicit def floatEncoder[K <: Symbol](implicit witness: Witness.Aux[K]):
  MapEncoder[FieldType[K, Float]] = {
    val name = witness.value.name
    createEncoder { v =>
      Map(name -> v.self)
    }
  }

  implicit def doubleEncoder[K <: Symbol](implicit witness: Witness.Aux[K]):
  MapEncoder[FieldType[K, Double]] = {
    val name = witness.value.name
    createEncoder { v =>
      Map(name -> v.self)
    }
  }

  implicit val hnilEncoder: MapEncoder[HNil] =
    createEncoder[HNil](n => Map(HNil.toString -> HNil))

  implicit def seqEncoder[K <: Symbol, V](implicit witness: Witness.Aux[K]):
  MapEncoder[FieldType[K, Seq[V]]] = {
    val name = witness.value.name
    createEncoder { v =>
      Map(name -> v.toIndexedSeq)
    }
  }

  implicit def listEncoder[K <: Symbol, V](implicit witness: Witness.Aux[K]):
  MapEncoder[FieldType[K, List[V]]] = {
    val name = witness.value.name
    createEncoder { v =>
      Map(name -> v.toIndexedSeq)
    }
  }

  
  def diffCaseClass[T : ClassTag : MapEncoder : Coder](lhs: SCollection[T],
                                               rhs: SCollection[T],
                                               keyFn: T => MultiKey,
                                               diffy: CaseClassDiffy[T]): BigDiffy[T] =
    diff(lhs, rhs, diffy, keyFn)
} 
Example 6
Source File: Labels.scala    From enum   with MIT License 5 votes vote down vote up
package enum

import shapeless.labelled.FieldType
import shapeless.{:+:, Witness, CNil, LabelledGeneric, Coproduct}


  val labels: Set[String]
}

object Labels {

  @inline def apply[A](implicit labels: Labels[A]): Labels[A] = labels

  trait Derived[A] extends Labels[A]

  @inline implicit def derived[A](implicit derived: Derived[A]): Labels[A] = derived

  object Derived extends Derived1 {

    implicit val cnil: Derived[CNil] =
      new Derived[CNil] {
        val labels = Set.empty[String]
      }

    implicit def ccons[K <: Symbol, L, R <: Coproduct](implicit
      label: Witness.Aux[K],
      tailLabels: Derived[R]
    ): Derived[FieldType[K, L] :+: R] =
      new Derived[FieldType[K, L] :+: R] {
        val labels = tailLabels.labels + label.value.name
      }
  }

  trait Derived1 {
    implicit def generic[A, Repr <: Coproduct](implicit
      gen: LabelledGeneric.Aux[A, Repr],
      reprLabels: Derived[Repr]
    ): Derived[A] =
      new Derived[A] {
        val labels = reprLabels.labels
      }
  }

} 
Example 7
Source File: DeepHLister.scala    From fluent   with MIT License 5 votes vote down vote up
package fluent.internal

import shapeless.labelled.FieldType
import shapeless.ops.hlist.Prepend
import shapeless.{ ::, DepFn1, HList, HNil, LabelledGeneric, Lazy }


trait DeepHLister[R <: HList] extends DepFn1[R] { type Out <: HList }

trait LowPriorityDeepHLister {
  type Aux[R <: HList, Out0 <: HList] = DeepHLister[R] { type Out = Out0 }

  implicit def headNotCaseClassDeepHLister[H, T <: HList](
    implicit dht: Lazy[DeepHLister[T]]
  ): Aux[H :: T, H :: dht.value.Out] = new DeepHLister[H :: T] {
    type Out = H :: dht.value.Out
    def apply(r: H :: T): Out = r.head :: dht.value(r.tail)
  }
}

object DeepHLister extends LowPriorityDeepHLister {
  def apply[R <: HList](implicit dh: DeepHLister[R]): Aux[R, dh.Out] = dh

  implicit object hnilDeepHLister extends DeepHLister[HNil] {
    type Out = HNil
    def apply(r: HNil): Out = HNil
  }

  implicit def headCaseClassDeepHLister[K, V, R <: HList, T <: HList, OutR <: HList, OutT <: HList, Out0 <: HList](
    implicit
    gen: LabelledGeneric.Aux[V, R],
    dhh: Lazy[DeepHLister.Aux[R, OutR]],
    dht: Lazy[DeepHLister.Aux[T, OutT]],
    prepend: Prepend.Aux[OutR, OutT, Out0]
  ): Aux[FieldType[K, V] :: T, Out0] = new DeepHLister[FieldType[K, V] :: T] {
      type Out = Out0
      def apply(r: FieldType[K, V] :: T): Out = prepend(dhh.value(gen.to(r.head.asInstanceOf[V])), dht.value(r.tail))
  }
} 
Example 8
Source File: CCCassFormatEncoder.scala    From scala-cass   with MIT License 5 votes vote down vote up
package com.weather.scalacass

import shapeless.labelled.FieldType
import shapeless.{ ::, HList, HNil, LabelledGeneric, Lazy, Witness }

abstract class DerivedCCCassFormatEncoder[F] extends CCCassFormatEncoder[F]

object DerivedCCCassFormatEncoder {
  implicit val hNilEncoder: DerivedCCCassFormatEncoder[HNil] = new DerivedCCCassFormatEncoder[HNil] {
    def encodeWithName(f: HNil) = Right(Nil)
    def encodeWithQuery(f: HNil) = Right(Nil)

    val names = Nil
    val types = Nil
  }

  implicit def hConsEncoder[K <: Symbol, H, T <: HList](implicit w: Witness.Aux[K], tdH: Lazy[CassFormatEncoder[H]], tdT: Lazy[DerivedCCCassFormatEncoder[T]]): DerivedCCCassFormatEncoder[FieldType[K, H] :: T] =
    new DerivedCCCassFormatEncoder[FieldType[K, H] :: T] {
      def encodeWithName(f: FieldType[K, H] :: T) = for {
        h <- tdH.value.encode(f.head).right
        t <- tdT.value.encodeWithName(f.tail).right
      } yield (w.value.name.toString, h) :: t
      def encodeWithQuery(f: FieldType[K, H] :: T) = for {
        h <- tdH.value.encode(f.head).right
        t <- tdT.value.encodeWithQuery(f.tail).right
      } yield (tdH.value.withQuery(f.head, w.value.name.toString), h) :: t
      def names = w.value.name.toString :: tdT.value.names
      def types = tdH.value.cassType :: tdT.value.types
    }

  implicit def ccConverter[T, Repr <: HList](implicit gen: LabelledGeneric.Aux[T, Repr], hListDecoder: Lazy[DerivedCCCassFormatEncoder[Repr]]): DerivedCCCassFormatEncoder[T] =
    new DerivedCCCassFormatEncoder[T] {
      def encodeWithName(f: T) = hListDecoder.value.encodeWithName(gen.to(f))
      def encodeWithQuery(f: T) = hListDecoder.value.encodeWithQuery(gen.to(f))
      def names = hListDecoder.value.names
      def types = hListDecoder.value.types
    }
}

trait CCCassFormatEncoder[F] { self =>
  def encodeWithName(f: F): Result[List[(String, AnyRef)]]
  def encodeWithQuery(f: F): Result[List[(String, AnyRef)]]
  def names: List[String]
  def types: List[String]
  def namesAndTypes: List[(String, String)] = names zip types

  final def map[G](fn: G => F): CCCassFormatEncoder[G] = new CCCassFormatEncoder[G] {
    def encodeWithName(f: G): Result[List[(String, AnyRef)]] = self.encodeWithName(fn(f))
    def encodeWithQuery(f: G): Result[List[(String, AnyRef)]] = self.encodeWithQuery(fn(f))
    def names = self.names
    def types = self.types
  }
  final def flatMap[G](fn: G => Result[F]): CCCassFormatEncoder[G] = new CCCassFormatEncoder[G] {
    def encodeWithName(f: G): Result[List[(String, AnyRef)]] = fn(f).right.flatMap(self.encodeWithName)
    def encodeWithQuery(f: G): Result[List[(String, AnyRef)]] = fn(f).right.flatMap(self.encodeWithQuery)
    def names = self.names
    def types = self.types
  }
}

object CCCassFormatEncoder extends ProductCCCassFormatEncoders {
  implicit def derive[T](implicit derived: Lazy[DerivedCCCassFormatEncoder[T]]): CCCassFormatEncoder[T] = derived.value
  def apply[T](implicit instance: CCCassFormatEncoder[T]): CCCassFormatEncoder[T] = instance
} 
Example 9
Source File: CCCassFormatDecoder.scala    From scala-cass   with MIT License 5 votes vote down vote up
package com.weather.scalacass

import com.datastax.driver.core.Row
import shapeless.labelled.{ FieldType, field }
import shapeless.{ ::, HList, HNil, LabelledGeneric, Lazy, Witness }

abstract class DerivedCCCassFormatDecoder[T] extends CCCassFormatDecoder[T]

object DerivedCCCassFormatDecoder {
  implicit val hNilDecoder: DerivedCCCassFormatDecoder[HNil] = new DerivedCCCassFormatDecoder[HNil] {
    def decode(r: Row): Result[HNil] = Right(HNil)
  }

  implicit def hConsDecoder[K <: Symbol, H, T <: HList](implicit w: Witness.Aux[K], tdH: Lazy[CassFormatDecoder[H]], tdT: Lazy[DerivedCCCassFormatDecoder[T]]): DerivedCCCassFormatDecoder[FieldType[K, H] :: T] =
    new DerivedCCCassFormatDecoder[FieldType[K, H] :: T] {
      def decode(r: Row) = for {
        h <- tdH.value.decode(r, w.value.name.toString).right
        t <- tdT.value.decode(r).right
      } yield field[K](h) :: t
    }

  implicit def ccConverter[T, Repr](implicit gen: LabelledGeneric.Aux[T, Repr], hListDecoder: Lazy[DerivedCCCassFormatDecoder[Repr]]): DerivedCCCassFormatDecoder[T] =
    new DerivedCCCassFormatDecoder[T] {
      def decode(r: Row): Result[T] = hListDecoder.value.decode(r).right.map(gen.from)
    }
}

trait CCCassFormatDecoder[T] { self =>
  private[scalacass] def decode(r: Row): Result[T]
  final def map[U](f: T => U): CCCassFormatDecoder[U] = new CCCassFormatDecoder[U] {
    def decode(r: Row): Result[U] = self.decode(r).right.map(f)
  }
  final def flatMap[U](f: T => Result[U]): CCCassFormatDecoder[U] = new CCCassFormatDecoder[U] {
    def decode(r: Row): Result[U] = self.decode(r).right.flatMap(f)
  }

  final def as(r: Row): T = decode(r) match {
    case Right(v)  => v
    case Left(exc) => throw exc
  }
  final def getOrElse(r: Row)(default: => T): T = decode(r).right.getOrElse(default)
  final def attemptAs(r: Row): Result[T] = decode(r)
}

object CCCassFormatDecoder extends ProductCCCassFormatDecoders {
  implicit def derive[T](implicit derived: Lazy[DerivedCCCassFormatDecoder[T]]): CCCassFormatDecoder[T] = derived.value
  def apply[T](implicit decoder: CCCassFormatDecoder[T]) = decoder

  implicit def optionalCodec[T](implicit decoder: CCCassFormatDecoder[T]): CCCassFormatDecoder[Option[T]] =
    new CCCassFormatDecoder[Option[T]] {
      private[scalacass] def decode(r: Row): Result[Option[T]] = decoder.decode(r) match {
        case Left(Recoverable(_)) => Right(None)
        case other                => other.right.map(Option.apply)
      }
    }
} 
Example 10
Source File: EnumerationEncoder.scala    From circe-generic-extras   with Apache License 2.0 5 votes vote down vote up
package io.circe.generic.extras.encoding

import io.circe.{ Encoder, Json }
import io.circe.generic.extras.Configuration
import scala.annotation.implicitNotFound
import shapeless.{ :+:, CNil, Coproduct, HNil, Inl, Inr, LabelledGeneric, Witness }
import shapeless.labelled.FieldType

@implicitNotFound(
  """Could not find EnumerationEncoder for type ${A}.
Some possible causes for this:
- ${A} isn't a case class or sealed trat
- some of ${A}'s members don't have codecs of their own
- missing implicit Configuration"""
)
abstract class EnumerationEncoder[A] extends Encoder[A]

object EnumerationEncoder {
  implicit val encodeEnumerationCNil: EnumerationEncoder[CNil] = new EnumerationEncoder[CNil] {
    def apply(a: CNil): Json = sys.error("Cannot encode CNil")
  }

  implicit def encodeEnumerationCCons[K <: Symbol, V, R <: Coproduct](implicit
    witK: Witness.Aux[K],
    gen: LabelledGeneric.Aux[V, HNil],
    encodeR: EnumerationEncoder[R],
    config: Configuration = Configuration.default
  ): EnumerationEncoder[FieldType[K, V] :+: R] = new EnumerationEncoder[FieldType[K, V] :+: R] {
    def apply(a: FieldType[K, V] :+: R): Json = a match {
      case Inl(l) => Json.fromString(config.transformConstructorNames(witK.value.name))
      case Inr(r) => encodeR(r)
    }
  }

  implicit def encodeEnumeration[A, Repr <: Coproduct](implicit
    gen: LabelledGeneric.Aux[A, Repr],
    encodeR: EnumerationEncoder[Repr]
  ): EnumerationEncoder[A] =
    new EnumerationEncoder[A] {
      def apply(a: A): Json = encodeR(gen.to(a))
    }
} 
Example 11
Source File: HashP.scala    From laserdisc   with MIT License 5 votes vote down vote up
package laserdisc
package protocol

trait HashBaseP {
  import shapeless._
  import shapeless.labelled.FieldType
  import shapeless.nat._1
  import shapeless.ops.hlist.Length
  import shapeless.ops.nat.GTEq.>=

  final def hdel(key: Key, fields: OneOrMoreKeys): Protocol.Aux[NonNegInt] = Protocol("HDEL", key :: fields.value).as[Num, NonNegInt]

  final def hexists(key: Key, field: Key): Protocol.Aux[Boolean] = Protocol("HEXISTS", key :: field :: Nil).as[Num, Boolean]

  final def hget[A: Bulk ==> *](key: Key, field: Key): Protocol.Aux[Option[A]] =
    Protocol("HGET", key :: field :: Nil).opt[GenBulk].as[A]

  final def hgetall[A: Arr ==> *](key: Key): Protocol.Aux[A] = Protocol("HGETALL", key).as[Arr, A]

  final def hincrby(key: Key, field: Key, increment: NonZeroLong): Protocol.Aux[Long] =
    Protocol("HINCRBY", key :: field :: increment :: HNil).as[Num, Long]
  final def hincrby(key: Key, field: Key, increment: NonZeroDouble): Protocol.Aux[Double] =
    Protocol("HINCRBYFLOAT", key :: field :: increment :: HNil).as[Bulk, Double]

  final def hkeys(key: Key): Protocol.Aux[Seq[Key]] = Protocol("HKEYS", key).as[Arr, Seq[Key]]

  final def hlen(key: Key): Protocol.Aux[NonNegInt] = Protocol("HLEN", key).as[Num, NonNegInt]

  final def hmget[L <: HList: Arr ==> *](key: Key, fields: OneOrMoreKeys): Protocol.Aux[L] =
    Protocol("HMGET", key :: fields.value).as[Arr, L]

  final def hmset[L <: HList: RESPParamWrite: LUBConstraint[*, (Key, _)], N <: Nat](key: Key, l: L)(
      implicit ev0: Length.Aux[L, N],
      ev1: N >= _1
  ): Protocol.Aux[OK] = Protocol("HMSET", key :: l).as[Str, OK]
  final def hmset[P <: Product, L <: HList, N <: Nat](key: Key, product: P)(
      implicit gen: LabelledGeneric.Aux[P, L],
      ev0: Length.Aux[L, N],
      ev1: N >= _1,
      ev2: LUBConstraint[L, FieldType[_, _]],
      ev3: RESPParamWrite[L]
  ): Protocol.Aux[OK] = Protocol("HMSET", key :: gen.to(product)).as[Str, OK]

  final def hscan(key: Key, cursor: NonNegLong): Protocol.Aux[ScanKV] = Protocol("HSCAN", key :: cursor :: HNil).as[Arr, ScanKV]
  final def hscan(key: Key, cursor: NonNegLong, pattern: GlobPattern): Protocol.Aux[ScanKV] =
    Protocol("HSCAN", key :: cursor :: "MATCH" :: pattern :: HNil).as[Arr, ScanKV]
  final def hscan(key: Key, cursor: NonNegLong, count: PosInt): Protocol.Aux[ScanKV] =
    Protocol("HSCAN", key :: cursor :: "COUNT" :: count :: HNil).as[Arr, ScanKV]
  final def hscan(key: Key, cursor: NonNegLong, pattern: GlobPattern, count: PosInt): Protocol.Aux[ScanKV] =
    Protocol("HSCAN", key :: cursor :: "MATCH" :: pattern :: "COUNT" :: count :: HNil).as[Arr, ScanKV]

  final def hset[A: Show](key: Key, field: Key, value: A): Protocol.Aux[Boolean] =
    Protocol("HSET", key :: field :: value :: HNil).as[Num, Boolean]

  final def hsetnx[A: Show](key: Key, field: Key, value: A): Protocol.Aux[Boolean] =
    Protocol("HSETNX", key :: field :: value :: HNil).as[Num, Boolean]

  final def hstrlen(key: Key, field: Key): Protocol.Aux[NonNegInt] = Protocol("HSTRLEN", key :: field :: Nil).as[Num, NonNegInt]

  final def hvals[L <: HList: Arr ==> *](key: Key): Protocol.Aux[L] = Protocol("HVALS", key).as[Arr, L]
}

trait HashP extends HashBaseP with HashExtP 
Example 12
Source File: circeDerivation.scala    From typed-schema   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.tschema.utils.json

import io.circe._
import shapeless._
import shapeless.labelled.FieldType

import scala.language.higherKinds
object circeDerivation {
  @deprecated("use standard derivation", since = "0.3.0")
  def deriveObjEncoder[T](implicit enc: Lazy[DerivedCirceEncoder[T]]) = new Encoder.AsObject[T] {
    def encodeObject(a: T): JsonObject = enc.value.encodeObject(a)
  }
}

trait DerivedCirceEncoder[T] extends Encoder.AsObject[T] {
  def encodeObject(a: T): JsonObject
}

trait LowPriorityCirceEncoder {
  implicit def consEncoder[A, S <: Symbol, L <: HList](implicit
      head: Lazy[Encoder[A]],
      tail: DerivedCirceEncoder[L],
      witness: Witness.Aux[S]
  ) = new DerivedCirceEncoder[FieldType[S, A] :: L] {
    def encodeObject(obj: ::[FieldType[S, A], L]): JsonObject =
      tail.encodeObject(obj.tail).add(witness.value.name, head.value.apply(obj.head))
  }
}

object DerivedCirceEncoder extends LowPriorityCirceEncoder {
  implicit val nilEncoder = new DerivedCirceEncoder[HNil] {
    override def encodeObject(a: HNil): JsonObject = JsonObject.empty
  }

  implicit val cnilEncoder = new DerivedCirceEncoder[CNil] {
    override def encodeObject(a: CNil): JsonObject = a.impossible
  }

  implicit def consNullableEncoder[A, S <: Symbol, L <: HList](implicit
      head: Lazy[Encoder[A]],
      tail: DerivedCirceEncoder[L],
      witness: Witness.Aux[S],
      nullable: Nullable[A]
  ) =
    new DerivedCirceEncoder[FieldType[S, A] :: L] {
      def encodeObject(obj: ::[FieldType[S, A], L]): JsonObject = {
        val tailEnc = tail.encodeObject(obj.tail)
        (obj.head: A) match {
          case nullable.zero => tailEnc
          case x             => tailEnc.add(witness.value.name, head.value.apply(x))
        }
      }
    }

  implicit def orEncoder[left, right <: Coproduct](implicit
      left: DerivedCirceEncoder[left],
      right: DerivedCirceEncoder[right]
  ) = new DerivedCirceEncoder[left :+: right] {
    def encodeObject(a: left :+: right): JsonObject = a match {
      case Inl(l: left @unchecked)  => left.encodeObject(l)
      case Inr(r: right @unchecked) => right.encodeObject(r)
    }
  }

  implicit def deriveHListEncoder[T, L <: HList](implicit
      lgen: LabelledGeneric.Aux[T, L],
      enc: DerivedCirceEncoder[L]
  ) = new DerivedCirceEncoder[T] {
    def encodeObject(a: T): JsonObject = enc.encodeObject(lgen.to(a))
  }

  implicit def deriveCoproductEncoder[T, C <: Coproduct](implicit gen: Generic.Aux[T, C], enc: DerivedCirceEncoder[C]) =
    new DerivedCirceEncoder[T] {
      def encodeObject(a: T): JsonObject = enc.encodeObject(gen.to(a))
    }
}

case class Nullable[X](zero: X) extends AnyVal

object Nullable {
  implicit def optionNullable[X] = Nullable[Option[X]](None)
  implicit def vectorNullable[X] = Nullable[Vector[X]](Vector.empty)
  implicit def mapNullable[K, V] = Nullable[Map[K, V]](Map.empty)
} 
Example 13
Source File: ParamDirectives.scala    From typed-schema   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.tschema
package finagle

import cats.Monad
import cats.instances.list._
import cats.syntax.applicative._
import cats.syntax.flatMap._
import com.twitter.finagle.http.{Request, Response}
import ru.tinkoff.tschema.param._
import shapeless._
import shapeless.labelled.{FieldType, field}

trait ParamDirectives[S <: ParamSource] {
  def source: S
  def getByName[F[_]: Routed: Monad, A](name: String, fa: Option[CharSequence] => F[A]): F[A]

  def notFound(name: String): Rejection                 = Rejection.missingParam(name, source)
  def malformed(name: String, error: String): Rejection = Rejection.malformedParam(name, error, source)

  def singleRejection(name: String, error: SingleParamError): Rejection =
    error match {
      case MissingParamError    => notFound(name)
      case ParseParamError(err) => malformed(name, err)
    }

  def errorReject[F[_], A](name: String, error: ParamError)(implicit routed: Routed[F]): F[A] =
    error match {
      case single: SingleParamError => routed.reject(singleRejection(name, single))
      case MultiParamError(vals)    =>
        Routed.rejectMany(vals.map { case (field, err) => singleRejection(field, err) }.toSeq: _*)
    }

  def direct[F[_]: Routed: Monad, A, name, In <: HList](
      name: String,
      result: Param.Result[A],
      in: In,
      k: (FieldType[name, A] :: In) => F[Response]
  ): F[Response] =
    result.fold(errorReject[F, Response](name, _), a => k(field[name](a) :: in))

  def provideOrReject[F[_]: Routed: Monad, A](name: String, result: Param.Result[A]): F[A] =
    result.fold(errorReject[F, A](name, _), _.pure[F])
}

abstract class ParamDirectivesSimple[S <: ParamSource](val source: S) extends ParamDirectives[S] {
  def getFromRequest(name: String)(req: Request): Option[CharSequence]

  def getByName[F[_]: Routed: Monad, A](name: String, f: Option[CharSequence] => F[A]): F[A] =
    Routed.request.flatMap(req => f(getFromRequest(name)(req)))
}

object ParamDirectives {
  def apply[S <: ParamSource](implicit dir: ParamDirectives[S]): ParamDirectives[S] = dir

  type TC[A <: ParamSource]  = ParamDirectives[A]
  type TCS[A <: ParamSource] = ParamDirectivesSimple[A]
  import ParamSource._

  implicit val queryParamDirective: TC[Query] = new TCS[Query](Query) {
    def getFromRequest(name: String)(req: Request): Option[String] = req.params.get(name)
  }

  implicit val cookieParamDirectives: TC[Cookie] = new TCS[Cookie](Cookie) {
    def getFromRequest(name: String)(req: Request): Option[String] = req.cookies.get(name).map(_.value)
  }

  implicit val pathParamDirectives: TC[ParamSource.Path] = new TC[ParamSource.Path] {
    def getByName[F[_]: Routed: Monad, A](name: String, fa: Option[CharSequence] => F[A]): F[A] = Routed.segment(fa)
    def source                                                                                  = ParamSource.Path
  }

  implicit val formDataParamDirectives: TC[Form] = new TCS[Form](Form) {
    def getFromRequest(name: String)(req: Request): Option[String] = req.params.get(name)
  }

  implicit val headerParamDirectives: TC[Header] = new TCS[Header](Header) {
    def getFromRequest(name: String)(req: Request): Option[String] = req.headerMap.get(name)
  }

} 
Example 14
Source File: DebugParams.scala    From typed-schema   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.tschema.example

import io.circe.Encoder
import derevo.tethys.{tethysReader, tethysWriter}
import ru.tinkoff.tschema.swagger.Swagger
import ru.tinkoff.tschema.common.Name
import derevo.circe.{decoder, encoder}
import derevo.derive
import ru.tinkoff.tschema.finagle.CompleteIn
import ru.tinkoff.tschema.finagle.util.message
import shapeless._
import shapeless.labelled.FieldType
import shapeless.ops.hlist.{Mapper, ToList}
import cats.syntax.applicative._
import tethys._
import tethys.jackson._

@derive(tethysWriter, tethysReader, Swagger)
final case class DebugParams[T](value: T, params: Map[String, String])

object DebugParams {
  implicit def routable[In <: HList, T: JsonWriter, L <: HList](
      implicit
      im: Mapper.Aux[InputParamMap.type, In, L],
      tl: ToList[L, (String, String)]
  ): CompleteIn[Http, In, DebugParams[T], T] =
    (res, in) => message.jsonResponse(DebugParams(res, im(in).toList.toMap).asJson).pure[Http]
}

trait InputParamMap[L <: HList] {
  def apply(l: L): Map[String, String]
}

trait LowLevelInputParamMap {
  implicit def simpleCons[L <: HList, A](
      implicit tail: InputParamMap[L]
  ): InputParamMap[A :: L] =
    l => tail(l.tail)
}

object InputParamMap extends Poly1 {
  implicit def consume[K: Name, V] = at[FieldType[K, V]](v => Name[K].string -> v.toString)
} 
Example 15
Source File: DebugParams.scala    From typed-schema   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.tschema
package examples

import akka.http.scaladsl.server.Directives
import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport._
import io.circe.Encoder
import derevo.circe.{decoder, encoder}
import derevo.derive
import ru.tinkoff.tschema.akkaHttp.RoutableIn
import ru.tinkoff.tschema.swagger.Swagger
import shapeless._
import shapeless.labelled.FieldType

@derive(encoder, decoder, Swagger)
final case class DebugParams[T](value: T, params: Map[String, String])

object DebugParams {
  implicit def routable[In <: HList, T: Encoder](implicit im: InputParamMap[In]): RoutableIn[In, T, DebugParams[T]] =
    (in, res) => Directives.complete(DebugParams[T](res, im(in)))
}

trait InputParamMap[L <: HList] {
  def apply(l: L): Map[String, String]
}

trait LowLevelInputParamMap {
  implicit def simpleCons[L <: HList, A](implicit tail: InputParamMap[L]): InputParamMap[A :: L] =
    l => tail(l.tail)
}

object InputParamMap extends LowLevelInputParamMap {
  def apply[L <: HList](implicit im: InputParamMap[L]): InputParamMap[L] = im

  implicit val hnil: InputParamMap[HNil] = _ => Map.empty

  implicit def keyValueCons[L <: HList, K <: Symbol, V](
      implicit witness: Witness.Aux[K],
      tail: InputParamMap[L]
  ): InputParamMap[FieldType[K, V] :: L] =
    l => tail(l.tail) + (witness.value.name -> l.head.toString)
} 
Example 16
Source File: DebugParams.scala    From typed-schema   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.tschema.example

import io.circe.Encoder
import org.manatki.derevo
import org.manatki.derevo.tethysInstances.{tethysReader, tethysWriter}
//import io.circe.syntax._
import org.manatki.derevo.circeDerivation.{decoder, encoder}
import org.manatki.derevo.derive
import org.manatki.derevo.tschemaInstances.swagger
import ru.tinkoff.tschema.common.Name
import ru.tinkoff.tschema.finagle.CompleteIn
import ru.tinkoff.tschema.finagle.util.message
import shapeless._
import shapeless.labelled.FieldType
import shapeless.ops.hlist.{Mapper, ToList}
import cats.syntax.applicative._
import tethys._
import tethys.jackson._

@derive(tethysWriter, tethysReader, swagger)
final case class DebugParams[T](value: T, params: Map[String, String])

object DebugParams {
  implicit def routable[In <: HList, T: JsonWriter, L <: HList](
      implicit
      im: Mapper.Aux[InputParamMap.type, In, L],
      tl: ToList[L, (String, String)]
  ): CompleteIn[Http, In, DebugParams[T], T] =
    (res, in) => message.jsonResponse(DebugParams(res, im(in).toList.toMap).asJson).pure[Http]
}

trait InputParamMap[L <: HList] {
  def apply(l: L): Map[String, String]
}

trait LowLevelInputParamMap {
  implicit def simpleCons[L <: HList, A](
      implicit tail: InputParamMap[L]
  ): InputParamMap[A :: L] =
    l => tail(l.tail)
}

object InputParamMap extends Poly1 {
  implicit def consume[K: Name, V] = at[FieldType[K, V]](v => Name[K].string -> v.toString)
} 
Example 17
Source File: DebugParams.scala    From typed-schema   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.tschema.example

import cats.{Functor, Monad}
import io.circe.Encoder
import derevo.tethys.{tethysReader, tethysWriter}
import ru.tinkoff.tschema.finagle.{LiftHttp, Routed}
import ru.tinkoff.tschema.swagger.Swagger
import ru.tinkoff.tschema.common.Name
import derevo.circe.{decoder, encoder}
import derevo.derive
import ru.tinkoff.tschema.finagle.CompleteIn
import ru.tinkoff.tschema.finagle.util.message
import shapeless._
import shapeless.labelled.FieldType
import shapeless.ops.hlist.{Mapper, ToList}
import cats.syntax.applicative._
import cats.syntax.functor._
import tethys._
import tethys.jackson._

@derive(tethysWriter, tethysReader, Swagger)
final case class DebugParams[T](value: T, params: Map[String, String])

object DebugParams {
  implicit def routable[In <: HList, T: JsonWriter, L <: HList, H[_]: Monad](
      implicit
      im: Mapper.Aux[InputParamMap.type, In, L],
      tl: ToList[L, (String, String)]
  ): CompleteIn[H, In, DebugParams[T], T] =
    (res, in) => message.jsonResponse(DebugParams(res, im(in).toList.toMap).asJson).pure[H]

  implicit def routableF[In <: HList, T: JsonWriter, L <: HList, H[_]: Monad, F[_]](
      implicit
      im:   Mapper.Aux[InputParamMap.type, In, L],
      tl:   ToList[L, (String, String)],
      lift: LiftHttp[H, F]
  ): CompleteIn[H, In, DebugParams[T], F[T]] =
    (fres, in) => lift(fres).map(res => message.jsonResponse(DebugParams(res, im(in).toList.toMap).asJson))
}

trait InputParamMap[L <: HList] {
  def apply(l: L): Map[String, String]
}

trait LowLevelInputParamMap {
  implicit def simpleCons[L <: HList, A](
      implicit tail: InputParamMap[L]
  ): InputParamMap[A :: L] =
    l => tail(l.tail)
}

object InputParamMap extends Poly1 {
  implicit def consume[K: Name, V] = at[FieldType[K, V]](v => Name[K].string -> v.toString)
} 
Example 18
Source File: Patchable.scala    From patchless   with Apache License 2.0 5 votes vote down vote up
package patchless

import shapeless.labelled.{FieldType, field}
import shapeless._

sealed trait Patchable[T] {
  type Updates <: HList
  def apply(t: T, updates: Updates): T
}

object Patchable {
  type Aux[T, U <: HList] = Patchable[T] { type Updates = U }

  def apply[T](implicit patchable: Patchable[T]): Aux[T, patchable.Updates] = patchable

  implicit val hnil: Aux[HNil, HNil] = new Patchable[HNil] {
    final type Updates = HNil
    def apply(t: HNil, updates: HNil): HNil = HNil
  }

  implicit def hcons[K <: Symbol, H, T <: HList, TU <: HList](implicit
    patchTail: Aux[T, TU]
  ): Aux[FieldType[K, H] :: T, FieldType[K, Option[H]] :: TU] = new Patchable[FieldType[K, H] :: T] {
    final type Updates = FieldType[K, Option[H]] :: TU
    def apply(t: FieldType[K, H] :: T, updates: FieldType[K, Option[H]] :: TU) =
      field[K](updates.head.getOrElse(t.head)) :: patchTail(t.tail, updates.tail)
  }

  implicit def generic[T, L <: HList, U <: HList](implicit
    gen: LabelledGeneric.Aux[T, L],
    patchL: Aux[L, U]
  ): Aux[T, U] = new Patchable[T] {
    final type Updates = U
    def apply(t: T, updates: U) = gen.from(patchL(gen.to(t), updates))
  }
} 
Example 19
Source File: package.scala    From finagle-postgres   with Apache License 2.0 5 votes vote down vote up
package com.twitter.finagle.postgres

import scala.collection.immutable.Queue

import com.twitter.finagle.postgres.generic.enumeration.Enums
import com.twitter.finagle.postgres.values.ValueEncoder
import shapeless.ops.hlist.{LeftFolder, LiftAll, Mapper, ToList, ToTraversable, Zip}
import shapeless._
import shapeless.labelled.FieldType

package object generic extends Enums {

  implicit class ToShapelessClientOps(val client: PostgresClient) extends AnyVal {

    def queryAs[T <: Product](query: String, params: Param[_]*)(implicit
      rowDecoder: RowDecoder[T],
      columnNamer: ColumnNamer
    ) = {
      client.prepareAndQuery(query, params: _*)(row => rowDecoder(row)(columnNamer))
    }

  }

  trait QueryParam {
    def params: Seq[Param[_]]
    def placeholders(start: Int): Seq[String]
  }

  implicit class ToQueryParam[T](v: T)(implicit qp: QueryParams[T]) extends QueryParam {
    @inline final def params: Seq[Param[_]] = qp(v)
    @inline final def placeholders(start: Int): Seq[String] = qp.placeholders(v, start)
  }

  object toParam extends Poly1 {
    implicit def cases[T](implicit encoder: ValueEncoder[T]) = at[T](t => Param(t))
  }

  object toLabelledParam extends Poly1 {
    implicit def cases[K <: Symbol, T](implicit name: Witness.Aux[K], encoder: ValueEncoder[T]) = at[FieldType[K, T]] {
      t => name.value.name -> Param(t: T)
    }
  }

  implicit class QueryContext(val str: StringContext) extends AnyVal {
    def sql(queryParams: QueryParam*) = {
      val parts = if(str.parts.last == "") str.parts.dropRight(1) else str.parts
      val diff = queryParams.length - parts.length
      val pad = if(diff > 0) Seq.fill(diff)("") else Seq.empty
      Query(
        parts ++ pad,
        queryParams,
        identity)
    }
  }

} 
Example 20
Source File: GraphQLFields.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.navigator.graphqless

import sangria.schema.{Context, Field}
import shapeless.{::, HList, HNil, LabelledGeneric, Lazy, Witness}
import shapeless.labelled.FieldType
import shapeless.ops.record.Selector

trait GraphQLFields[T, Repr] {
  def fields[Ctx]: List[Field[Ctx, T]]
}

object GraphQLFields {
  def apply[T, Repr](implicit graphQLFields: GraphQLFields[T, Repr]): GraphQLFields[T, Repr] =
    graphQLFields
}

@SuppressWarnings(Array("org.wartremover.warts.Any"))
trait DerivedGraphQLFields {

  def mkField[Ctx, C, Repr <: HList, K <: Symbol, V](
      implicit
      kw: Witness.Aux[K],
      vField: Lazy[GraphQLOutputType[V]],
      gen: LabelledGeneric.Aux[C, Repr],
      selector: Selector.Aux[Repr, K, V]
  ): Field[Ctx, C] =
    Field(
      name = kw.value.name,
      fieldType = vField.value.outputType[Ctx],
      resolve = (context: Context[Ctx, C]) => selector(gen.to(context.value)))

  implicit def singleFieldGraphQLField[C, Repr <: HList, K <: Symbol, V](
      implicit kw: Witness.Aux[K],
      vField: Lazy[GraphQLOutputType[V]],
      gen: LabelledGeneric.Aux[C, Repr],
      selector: Selector.Aux[Repr, K, V]
  ): GraphQLFields[C, FieldType[K, V] :: HNil] = new GraphQLFields[C, FieldType[K, V] :: HNil] {

    override def fields[Ctx]: List[Field[Ctx, C]] =
      List(mkField[Ctx, C, Repr, K, V])
  }

  implicit def productGraphQLField[C, Repr <: HList, K <: Symbol, V, T <: HList](
      implicit
      kw: Witness.Aux[K],
      vField: Lazy[GraphQLOutputType[V]],
      tGraphQLField: Lazy[GraphQLFields[C, T]],
      gen: LabelledGeneric.Aux[C, Repr],
      selector: Selector.Aux[Repr, K, V]
  ): GraphQLFields[C, FieldType[K, V] :: T] = new GraphQLFields[C, FieldType[K, V] :: T] {
    override def fields[Ctx]: List[Field[Ctx, C]] = {
      val head = mkField[Ctx, C, Repr, K, V]
      val tail = tGraphQLField.value.fields[Ctx]
      head +: tail
    }
  }
}

object DerivedGraphQLFields extends DerivedGraphQLFields 
Example 21
Source File: ParquetRecordDecoder.scala    From parquet4s   with MIT License 5 votes vote down vote up
package com.github.mjakubowski84.parquet4s

import shapeless.labelled.{FieldType, field}
import shapeless.{::, HList, HNil, LabelledGeneric, Lazy, Witness}

import scala.language.higherKinds
import scala.util.control.NonFatal


  def decode(record: RowParquetRecord, configuration: ValueCodecConfiguration): T

}

object ParquetRecordDecoder {

  object DecodingException {
    def apply(msg: String, cause: Throwable): DecodingException = {
      val decodingException = DecodingException(msg)
      decodingException.initCause(cause)
      decodingException
    }
  }

  case class DecodingException(msg: String) extends RuntimeException(msg)

  def apply[T](implicit ev: ParquetRecordDecoder[T]): ParquetRecordDecoder[T] = ev

  def decode[T](record: RowParquetRecord, configuration: ValueCodecConfiguration = ValueCodecConfiguration.default)
               (implicit ev: ParquetRecordDecoder[T]): T = ev.decode(record, configuration)

  implicit val nilDecoder: ParquetRecordDecoder[HNil] = new ParquetRecordDecoder[HNil] {
    override def decode(record: RowParquetRecord, configuration: ValueCodecConfiguration): HNil.type = HNil
  }

  implicit def headValueDecoder[FieldName <: Symbol, Head, Tail <: HList](implicit
                                                                          witness: Witness.Aux[FieldName],
                                                                          headDecoder: ValueCodec[Head],
                                                                          tailDecoder: ParquetRecordDecoder[Tail]
                                                                         ): ParquetRecordDecoder[FieldType[FieldName, Head] :: Tail] =
    new ParquetRecordDecoder[FieldType[FieldName, Head] :: Tail] {
      override def decode(record: RowParquetRecord, configuration: ValueCodecConfiguration): FieldType[FieldName, Head] :: Tail = {
        val fieldName = witness.value.name
        val decodedFieldValue = try {
          record.get[Head](fieldName, configuration)
        } catch {
          case NonFatal(cause) =>
            throw DecodingException(s"Failed to decode field $fieldName of record: $record", cause)
        }
        field[FieldName](decodedFieldValue) :: tailDecoder.decode(record, configuration)
      }
    }

  implicit def genericDecoder[A, R](implicit
                                    gen: LabelledGeneric.Aux[A, R],
                                    decoder: Lazy[ParquetRecordDecoder[R]]
                                   ): ParquetRecordDecoder[A] =
    new ParquetRecordDecoder[A] {
      override def decode(record: RowParquetRecord, configuration: ValueCodecConfiguration): A =
        gen.from(decoder.value.decode(record, configuration))
    }

} 
Example 22
Source File: ParquetRecordEncoder.scala    From parquet4s   with MIT License 5 votes vote down vote up
package com.github.mjakubowski84.parquet4s

import shapeless.labelled.FieldType
import shapeless.{::, HList, HNil, LabelledGeneric, Lazy, Witness}

import scala.language.higherKinds
import scala.util.control.NonFatal



  def encode(entity: T, configuration: ValueCodecConfiguration): RowParquetRecord

}

object ParquetRecordEncoder {

  object EncodingException {
    def apply(msg: String, cause: Throwable): EncodingException = {
      val encodingException = EncodingException(msg)
      encodingException.initCause(cause)
      encodingException
    }
  }

  case class EncodingException(msg: String) extends RuntimeException(msg)

  def apply[T](implicit ev: ParquetRecordEncoder[T]): ParquetRecordEncoder[T] = ev

  def encode[T](entity: T, configuration: ValueCodecConfiguration = ValueCodecConfiguration.default)
               (implicit ev: ParquetRecordEncoder[T]): RowParquetRecord = ev.encode(entity, configuration)

  implicit val nilDEncoder: ParquetRecordEncoder[HNil] = new ParquetRecordEncoder[HNil] {
    override def encode(nil: HNil, configuration: ValueCodecConfiguration): RowParquetRecord = RowParquetRecord()
  }

  implicit def headValueEncoder[FieldName <: Symbol, Head, Tail <: HList](implicit
                                                                          witness: Witness.Aux[FieldName],
                                                                          headEncoder: ValueCodec[Head],
                                                                          tailEncoder: ParquetRecordEncoder[Tail]
                                                                         ): ParquetRecordEncoder[FieldType[FieldName, Head] :: Tail] =
    new ParquetRecordEncoder[FieldType[FieldName, Head] :: Tail] {
      override def encode(entity: FieldType[FieldName, Head] :: Tail, configuration: ValueCodecConfiguration): RowParquetRecord = {
        val fieldName = witness.value.name
        val fieldValue = try {
          headEncoder.encode(entity.head, configuration)
        } catch {
          case NonFatal(cause) =>
            throw EncodingException(s"Failed to encode field $fieldName: ${entity.head}, due to ${cause.getMessage}", cause)
        }
        tailEncoder.encode(entity.tail, configuration).prepend(fieldName, fieldValue)
      }
    }

  implicit def genericEncoder[A, R](implicit
                                    gen: LabelledGeneric.Aux[A, R],
                                    encoder: Lazy[ParquetRecordEncoder[R]]
                                   ): ParquetRecordEncoder[A] =
    new ParquetRecordEncoder[A] {
      override def encode(entity: A, configuration: ValueCodecConfiguration): RowParquetRecord =
        encoder.value.encode(gen.to(entity), configuration)
    }

} 
Example 23
Source File: HListInstances.scala    From docless   with MIT License 5 votes vote down vote up
package com.timeout.docless.schema.derive

import com.timeout.docless.schema._
import JsonSchema._
import shapeless._
import io.circe._
import io.circe.syntax._
import shapeless.labelled.FieldType
import reflect.runtime.{universe => ru}

trait HListInstances {
  implicit val hNilSchema: JsonSchema[HNil] = inlineInstance(
    JsonObject.fromMap(Map.empty)
  )

  implicit def hlistSchema[K <: Symbol, H, T <: HList](
      implicit witness: Witness.Aux[K],
      lazyHSchema: Lazy[JsonSchema[H]],
      lazyTSchema: Lazy[JsonSchema[T]]
  ): JsonSchema[FieldType[K, H] :: T] = instanceAndRelated {
    val fieldName = witness.value.name
    val hSchema   = lazyHSchema.value
    val tSchema   = lazyTSchema.value
    val (hValue, related) =
      if (hSchema.inline)
        hSchema.asJson -> tSchema.relatedDefinitions
      else
        hSchema.asJsonRef -> (tSchema.relatedDefinitions + hSchema
          .NamedDefinition(fieldName))

    val hField  = fieldName -> hValue
    val tFields = tSchema.jsonObject.toList

    JsonObject.fromIterable(hField :: tFields) -> related
  }

  implicit def genericSchema[A, R <: HList](
      implicit gen: LabelledGeneric.Aux[A, R],
      rSchema: JsonSchema[R],
      fields: Required.Fields[R],
      tag: ru.WeakTypeTag[A]
  ): JsonSchema[A] =
    instanceAndRelated[A] {
      JsonObject.fromMap(
        Map(
          "type"       -> Json.fromString("object"),
          "required"   -> fields.asJson,
          "properties" -> rSchema.jsonObject.asJson
        )
      ) -> rSchema.relatedDefinitions
    }

} 
Example 24
Source File: Required.scala    From docless   with MIT License 5 votes vote down vote up
package com.timeout.docless.schema

import io.circe._
import shapeless._
import shapeless.labelled.FieldType

trait Required[A] {
  def isRequired: Boolean = true
}

object Required {
  implicit def optIsRequired[A]: Required[Option[A]] =
    new Required[Option[A]] {
      override def isRequired = false
    }

  implicit def otherRequired[A]: Required[A] = new Required[A] {
    override def isRequired = true
  }

  def isRequired[A](implicit ev: Required[A]): Boolean = ev.isRequired

  trait Fields[A] {
    def get: List[String]
    def asJson: Json = Json.arr(get.map(Json.fromString): _*)
  }

  object Fields {
    def instance[A](fs: List[String]): Fields[A] = new Fields[A] {
      override def get: List[String] = fs
    }

    implicit val hnilFields: Fields[HNil] = instance(Nil)

    implicit def hlistFields[K <: Symbol, H, T <: HList](
        implicit witness: Witness.Aux[K],
        req: Lazy[Required[H]],
        tFields: Fields[T]
    ): Fields[FieldType[K, H] :: T] = instance {
      if (req.value.isRequired)
        witness.value.name :: tFields.get
      else
        tFields.get
    }

    implicit val genericCNil: Fields[CNil] = instance(Nil)

    implicit def genericCoproduct[H, T <: Coproduct](
        implicit hFields: Lazy[Fields[H]],
        tFields: Fields[T]
    ): Fields[H :+: T] = instance((hFields.value.get ++ tFields.get).distinct)

    implicit def genericOutIsCooprod[A, R <: Coproduct](
        implicit gen: Generic.Aux[A, R],
        fields: Fields[R]
    ): Fields[A] = instance(fields.get)

    implicit def genericFields[A, R](implicit gen: LabelledGeneric.Aux[A, R],
                                     rfs: Fields[R]): Fields[A] =
      instance(rfs.get)

    def apply[L](implicit ev: Fields[L]): List[String] = ev.get
  }
} 
Example 25
Source File: DerivedValidator.scala    From octopus   with Apache License 2.0 5 votes vote down vote up
package octopus

import shapeless.labelled.FieldType
import shapeless.{:+:, ::, CNil, Coproduct, HList, HNil, Inl, Inr, LabelledGeneric, Lazy, Witness}

class DerivedValidator[T](val v: Validator[T]) extends AnyVal

object DerivedValidator extends LowPriorityValidatorDerivation {
  def apply[T](v: Validator[T]): DerivedValidator[T] = new DerivedValidator[T](v)
}

trait LowPriorityValidatorDerivation extends Serializable{

  implicit val hnilValidator: DerivedValidator[HNil] = DerivedValidator(Validator[HNil])

  implicit def hconsValidator[L <: Symbol, H, T <: HList](implicit label: Witness.Aux[L],
                                                          hv: Lazy[Validator[H]],
                                                          tv: DerivedValidator[T]): DerivedValidator[FieldType[L, H] :: T] = DerivedValidator {
    (hlist: FieldType[L, H] :: T) =>
      hv.value.validate(hlist.head).map(FieldLabel(label.value) :: _) ++ tv.v.validate(hlist.tail)
  }

  // $COVERAGE-OFF$
  implicit val cnilValidator: DerivedValidator[CNil] = DerivedValidator {
    (_: CNil) => null
  }
  // $COVERAGE-ON$

  implicit def coproductValidator[L <: Symbol, H, T <: Coproduct](implicit hv: Lazy[Validator[H]],
                                                                  tv: DerivedValidator[T]): DerivedValidator[FieldType[L, H] :+: T] = DerivedValidator {
    case Inl(head) => hv.value.validate(head)
    case Inr(tail) => tv.v.validate(tail)
  }

  implicit def genValidator[T, Repr](implicit gen: LabelledGeneric.Aux[T, Repr],
                                     dv: Lazy[DerivedValidator[Repr]]): DerivedValidator[T] = DerivedValidator {
    (obj: T) => dv.value.v.validate(gen.to(obj))
  }
} 
Example 26
Source File: DerivedAsyncValidator.scala    From octopus   with Apache License 2.0 5 votes vote down vote up
package octopus

import shapeless.labelled.FieldType
import shapeless.{::, HList, HNil, LabelledGeneric, Lazy, Witness}

class DerivedAsyncValidator[M[_], T](val av: AsyncValidatorM[M, T]) extends AnyVal

object DerivedAsyncValidator {

  def apply[M[_]: AppError, T](av: AsyncValidatorM[M, T]): DerivedAsyncValidator[M, T] = new DerivedAsyncValidator[M, T](av)

  implicit def hnilValidator[M[_]: AppError]: DerivedAsyncValidator[M, HNil] = DerivedAsyncValidator(AsyncValidatorM[M, HNil])

  implicit def hconsValidator[M[_]: AppError, L <: Symbol, H, T <: HList]
  (
    implicit
    label: Witness.Aux[L],
    hv: Lazy[AsyncValidatorM[M, H]],
    tv: DerivedAsyncValidator[M, T]
  ): DerivedAsyncValidator[M, FieldType[L, H] :: T] =
    DerivedAsyncValidator {
      AsyncValidatorM.instance { (hlist: FieldType[L, H] :: T) =>
        AppError[M].map2(
          AppError[M].map(hv.value.validate(hlist.head)){ errors =>
            errors.map(FieldLabel(label.value) :: _)
          },
          tv.av.validate(hlist.tail))(_ ++ _)
      }
    }

  implicit def genValidator[M[_]: AppError, T, Repr](
    implicit
    gen: LabelledGeneric.Aux[T, Repr],
    dav: Lazy[DerivedAsyncValidator[M, Repr]]
  ): DerivedAsyncValidator[M, T] =
    DerivedAsyncValidator {
      AsyncValidatorM.instance { (obj: T) =>
        dav.value.av.validate(gen.to(obj))
      }
    }
} 
Example 27
Source File: RowDecoder.scala    From finagle-postgres   with Apache License 2.0 5 votes vote down vote up
package com.twitter.finagle.postgres.generic

import com.twitter.finagle.postgres.Row
import com.twitter.finagle.postgres.values.ValueDecoder
import shapeless._
import shapeless.labelled.{FieldType, field}

trait RowDecoder[T] {
  @inline def apply(row: Row)(implicit columnNamer: ColumnNamer): T
}

object RowDecoder extends RowDecoder0 {

  def apply[T : RowDecoder] = implicitly[RowDecoder[T]]

  // Recursive base case for decoding rows
  implicit object hnil extends RowDecoder[HNil] {
    @inline final def apply(row: Row)(implicit columnNamer: ColumnNamer) = HNil
  }

  // Optional (nullable) values
  class HConsOption[K <: Symbol, H, T <: HList](implicit
    colName: Witness.Aux[K],
    decodeHead: ValueDecoder[H],
    decodeTail: RowDecoder[T]
  ) extends RowDecoder[FieldType[K, Option[H]] :: T] {
    @inline final def apply(row: Row)(implicit columnNamer: ColumnNamer): FieldType[K, Option[H]] :: T = {
      field[K](row.getOption[H](columnNamer(colName.value.name))) :: decodeTail(row)(columnNamer)
    }
  }

  implicit def hconsOption[K <: Symbol, H, T <: HList](implicit
    colName: Witness.Aux[K],
    decodeHead: ValueDecoder[H],
    decodeTail: RowDecoder[T]
  ): RowDecoder[FieldType[K, Option[H]] :: T] = new HConsOption

  // Decoders for tuples of case classes - for JOINs.
  // This could be arity-abstracted, but would probably end up messier and cause implicit issues
  // So instead we'll just start with making a two-table join workable and go from there.
  implicit def joined[A <: Product, B <: Product, AL <: HList, BL <: HList](implicit
    prodA: GenericProduct[A, AL],
    prodB: GenericProduct[B, BL]
  ): RowDecoder[(A, B)] = new RowDecoder[(A, B)] {
    @inline final def apply(row: Row)(implicit columnNamer: ColumnNamer): (A, B) = {
      (prodA.apply(row)(columnNamer andThen ((s: String) => s"""_1.$s""")),
        prodB.apply(row)(columnNamer andThen ((s: String) => s"""_2.$s""")))
    }
  }


}

trait RowDecoder0 {

  // Generic decoder for any case class which has a LabelledGeneric
  class GenericProduct[T <: Product, L <: HList](implicit
    gen: LabelledGeneric.Aux[T, L],
    decodeL: RowDecoder[L]
  ) extends RowDecoder[T] {
    @inline final def apply(row: Row)(implicit columnNamer: ColumnNamer): T = gen.from(decodeL(row)(columnNamer))
  }

  implicit def genericProduct[T <: Product, L <: HList](implicit
    gen: LabelledGeneric.Aux[T, L],
    decodeL: RowDecoder[L]
  ): GenericProduct[T, L] = new GenericProduct[T, L]

  // Non-optional values (prioritized here underneath optional values)
  class HCons[K <: Symbol, H, T <: HList](implicit
    colName: Witness.Aux[K],
    decodeHead: ValueDecoder[H],
    decodeTail: RowDecoder[T]
  ) extends RowDecoder[FieldType[K, H] :: T] {
    @inline final def apply(row: Row)(implicit columnNamer: ColumnNamer): FieldType[K, H] :: T = {
      field[K](row.get[H](columnNamer(colName.value.name))) :: decodeTail(row)(columnNamer)
    }
  }

  implicit def hcons[K <: Symbol, H, T <: HList](implicit
    colName: Witness.Aux[K],
    decodeHead: ValueDecoder[H],
    decodeTail: RowDecoder[T]
  ): RowDecoder[FieldType[K, H] :: T] = new HCons

} 
Example 28
Source File: EnumerationCodec.scala    From circe-generic-extras   with Apache License 2.0 5 votes vote down vote up
package io.circe.generic.extras.codec

import io.circe.{ Codec, Decoder, DecodingFailure, HCursor, Json }
import io.circe.generic.extras.Configuration
import scala.annotation.implicitNotFound
import shapeless.{ :+:, CNil, Coproduct, HNil, Inl, Inr, LabelledGeneric, Witness }
import shapeless.labelled.{ FieldType, field }

@implicitNotFound(
  """Could not find EnumerationCodec for type ${A}.
Some possible causes for this:
- ${A} isn't a case class or sealed trat
- some of ${A}'s members don't have codecs of their own
- missing implicit Configuration"""
)
abstract class EnumerationCodec[A] extends Codec[A]

object EnumerationCodec {
  implicit val codecForEnumerationCNil: EnumerationCodec[CNil] = new EnumerationCodec[CNil] {
    def apply(c: HCursor): Decoder.Result[CNil] = Left(DecodingFailure("Enumeration", c.history))
    def apply(a: CNil): Json = sys.error("Cannot encode CNil")
  }

  implicit def codecForEnumerationCCons[K <: Symbol, V, R <: Coproduct](implicit
    witK: Witness.Aux[K],
    gen: LabelledGeneric.Aux[V, HNil],
    codecForR: EnumerationCodec[R],
    config: Configuration = Configuration.default
  ): EnumerationCodec[FieldType[K, V] :+: R] = new EnumerationCodec[FieldType[K, V] :+: R] {
    def apply(c: HCursor): Decoder.Result[FieldType[K, V] :+: R] =
      c.as[String] match {
        case Right(s) if s == config.transformConstructorNames(witK.value.name) =>
          Right(Inl(field[K](gen.from(HNil))))
        case Right(_) =>
          codecForR.apply(c) match {
            case Right(v)  => Right(Inr(v))
            case Left(err) => Left(err)
          }
        case Left(err) => Left(DecodingFailure("Enumeration", c.history))
      }
    def apply(a: FieldType[K, V] :+: R): Json = a match {
      case Inl(l) => Json.fromString(config.transformConstructorNames(witK.value.name))
      case Inr(r) => codecForR(r)
    }
  }

  implicit def codecForEnumeration[A, R <: Coproduct](implicit
    gen: LabelledGeneric.Aux[A, R],
    codecForR: EnumerationCodec[R]
  ): EnumerationCodec[A] =
    new EnumerationCodec[A] {
      def apply(c: HCursor): Decoder.Result[A] = codecForR(c) match {
        case Right(v)  => Right(gen.from(v))
        case Left(err) => Left(err)
      }
      def apply(a: A): Json = codecForR(gen.to(a))
    }
} 
Example 29
Source File: ToMappable.scala    From shapeless-datatype   with Apache License 2.0 5 votes vote down vote up
package shapeless.datatype.mappable

import shapeless._
import shapeless.labelled.FieldType

import scala.language.higherKinds

trait ToMappable[L <: HList, M] extends Serializable {
  def apply(l: L): M
}

trait LowPriorityToMappable1 {
  implicit def hconsToMappable1[K <: Symbol, V, T <: HList, M](implicit
    wit: Witness.Aux[K],
    mt: MappableType[M, V],
    toT: Lazy[ToMappable[T, M]]
  ): ToMappable[FieldType[K, V] :: T, M] = new ToMappable[FieldType[K, V] :: T, M] {
    override def apply(l: FieldType[K, V] :: T): M =
      mt.put(wit.value.name, l.head, toT.value(l.tail))
  }
}

trait LowPriorityToMappableOption1 extends LowPriorityToMappable1 {
  implicit def hconsToMappableOption1[K <: Symbol, V, T <: HList, M](implicit
    wit: Witness.Aux[K],
    mt: MappableType[M, V],
    toT: Lazy[ToMappable[T, M]]
  ): ToMappable[FieldType[K, Option[V]] :: T, M] = new ToMappable[FieldType[K, Option[V]] :: T, M] {
    override def apply(l: FieldType[K, Option[V]] :: T): M =
      mt.put(wit.value.name, l.head, toT.value(l.tail))
  }
}

trait LowPriorityToMappableSeq1 extends LowPriorityToMappableOption1 {
  implicit def hconsToMappableSeq1[K <: Symbol, V, T <: HList, M, S[_]](implicit
    wit: Witness.Aux[K],
    mt: MappableType[M, V],
    toT: Lazy[ToMappable[T, M]],
    toSeq: S[V] => Seq[V]
  ): ToMappable[FieldType[K, S[V]] :: T, M] = new ToMappable[FieldType[K, S[V]] :: T, M] {
    override def apply(l: FieldType[K, S[V]] :: T): M =
      mt.put(wit.value.name, toSeq(l.head), toT.value(l.tail))
  }
}

trait LowPriorityToMappable0 extends LowPriorityToMappableSeq1 {
  implicit def hconsToMappable0[K <: Symbol, V, H <: HList, T <: HList, M: CanNest](implicit
    wit: Witness.Aux[K],
    gen: LabelledGeneric.Aux[V, H],
    mbt: BaseMappableType[M],
    toH: Lazy[ToMappable[H, M]],
    toT: Lazy[ToMappable[T, M]]
  ): ToMappable[FieldType[K, V] :: T, M] = new ToMappable[FieldType[K, V] :: T, M] {
    override def apply(l: FieldType[K, V] :: T): M =
      mbt.put(wit.value.name, toH.value(gen.to(l.head)), toT.value(l.tail))
  }
}

trait LowPriorityToMappableOption0 extends LowPriorityToMappable0 {
  implicit def hconsToMappableOption0[K <: Symbol, V, H <: HList, T <: HList, M: CanNest](implicit
    wit: Witness.Aux[K],
    gen: LabelledGeneric.Aux[V, H],
    mbt: BaseMappableType[M],
    toH: Lazy[ToMappable[H, M]],
    toT: Lazy[ToMappable[T, M]]
  ): ToMappable[FieldType[K, Option[V]] :: T, M] = new ToMappable[FieldType[K, Option[V]] :: T, M] {
    override def apply(l: FieldType[K, Option[V]] :: T): M =
      mbt.put(wit.value.name, l.head.map(h => toH.value(gen.to(h))), toT.value(l.tail))
  }
}

trait LowPriorityToMappableSeq0 extends LowPriorityToMappableOption0 {
  implicit def hconsToMappableSeq0[K <: Symbol, V, H <: HList, T <: HList, M: CanNest, S[_]](
    implicit
    wit: Witness.Aux[K],
    gen: LabelledGeneric.Aux[V, H],
    mbt: BaseMappableType[M],
    toH: Lazy[ToMappable[H, M]],
    toT: Lazy[ToMappable[T, M]],
    toSeq: S[V] => Seq[V]
  ): ToMappable[FieldType[K, S[V]] :: T, M] = new ToMappable[FieldType[K, S[V]] :: T, M] {
    override def apply(l: FieldType[K, S[V]] :: T): M =
      mbt.put(wit.value.name, toSeq(l.head).map(h => toH.value(gen.to(h))), toT.value(l.tail))
  }
}

object ToMappable extends LowPriorityToMappableSeq0 {
  implicit def hnilToMappable[M](implicit mbt: BaseMappableType[M]): ToMappable[HNil, M] =
    new ToMappable[HNil, M] {
      override def apply(l: HNil): M = mbt.base
    }
} 
Example 30
Source File: ApiTransformerSpec.scala    From typedapi   with MIT License 5 votes vote down vote up
package typedapi.shared

import typedapi.Json
import shapeless._
import shapeless.labelled.FieldType

// compilation-only test
final class ApiTransformerSpec extends TypeLevelFoldLeftLowPrio with ApiTransformer {

  case class Foo()

  def testCompile[H <: HList, Out](implicit folder: TypeLevelFoldLeft.Aux[H, Unit, Out]): TypeLevelFoldLeft.Aux[H, Unit, Out] = 
    folder

  val pathW = Witness("test")
  val fooW  = Witness('foo)
  val barW  = Witness('bar)

  testCompile[GetElement[Json, Foo] :: HNil, (HNil, HNil, HNil, GetCall, FieldType[Json, Foo])]
  testCompile[PutElement[Json, Foo] :: HNil, (HNil, HNil, HNil, PutCall, FieldType[Json, Foo])]
  testCompile[PutWithBodyElement[Json, Foo, Json, Foo] :: HNil, (HNil, FieldType[Json, BodyField.T] :: HNil, Foo :: HNil, PutWithBodyCall, FieldType[Json, Foo])]
  testCompile[PostElement[Json, Foo] :: HNil, (HNil, HNil, HNil, PostCall, FieldType[Json, Foo])]
  testCompile[PostWithBodyElement[Json, Foo, Json, Foo] :: HNil, (HNil, FieldType[Json, BodyField.T] :: HNil, Foo :: HNil, PostWithBodyCall, FieldType[Json, Foo])]
  testCompile[DeleteElement[Json, Foo] :: HNil, (HNil, HNil, HNil, DeleteCall, FieldType[Json, Foo])]
  testCompile[GetElement[Json, Foo] :: PathElement[pathW.T] :: HNil, (pathW.T :: HNil, HNil, HNil, GetCall, FieldType[Json, Foo])]
  testCompile[GetElement[Json, Foo] :: SegmentParam[fooW.T, String] :: HNil, (SegmentInput :: HNil, fooW.T :: HNil, String :: HNil, GetCall, FieldType[Json, Foo])]
  testCompile[GetElement[Json, Foo] :: QueryParam[fooW.T, String] :: HNil, (QueryInput :: HNil, fooW.T :: HNil, String :: HNil, GetCall, FieldType[Json, Foo])]
  testCompile[GetElement[Json, Foo] :: QueryParam[fooW.T, List[String]] :: HNil, (QueryInput :: HNil, fooW.T :: HNil, List[String] :: HNil, GetCall, FieldType[Json, Foo])]
  testCompile[GetElement[Json, Foo] :: HeaderParam[fooW.T, String] :: HNil, (HeaderInput :: HNil, fooW.T :: HNil, String :: HNil, GetCall, FieldType[Json, Foo])]
  testCompile[GetElement[Json, Foo] :: FixedHeaderElement[fooW.T, barW.T] :: HNil, (FixedHeader[fooW.T, barW.T] :: HNil, HNil, HNil, GetCall, FieldType[Json, Foo])]
  testCompile[GetElement[Json, Foo] :: ClientHeaderParam[fooW.T, String] :: HNil, (ClientHeaderInput :: HNil, fooW.T :: HNil, String :: HNil, GetCall, FieldType[Json, Foo])]
  testCompile[GetElement[Json, Foo] :: ClientHeaderElement[fooW.T, barW.T] :: HNil, (ClientHeader[fooW.T, barW.T] :: HNil, HNil, HNil, GetCall, FieldType[Json, Foo])]
  testCompile[GetElement[Json, Foo] :: ClientHeaderCollParam[Int] :: HNil, (ClientHeaderCollInput :: HNil, HNil, Map[String, Int] :: HNil, GetCall, FieldType[Json, Foo])]
  testCompile[GetElement[Json, Foo] :: ServerHeaderMatchParam[fooW.T, String] :: HNil, (ServerHeaderMatchInput :: HNil, fooW.T :: HNil, Map[String, String] :: HNil, GetCall, FieldType[Json, Foo])]
  testCompile[GetElement[Json, Foo] :: ServerHeaderSendElement[fooW.T, barW.T] :: HNil, (ServerHeaderSend[fooW.T, barW.T] :: HNil, HNil, HNil, GetCall, FieldType[Json, Foo])]

  testCompile[
    GetElement[Json, Foo] :: HeaderParam[fooW.T, Boolean] :: QueryParam[fooW.T, Int] :: SegmentParam[fooW.T, String] :: PathElement[pathW.T] :: HNil, 
    (pathW.T :: SegmentInput :: QueryInput :: HeaderInput :: HNil, fooW.T :: fooW.T :: fooW.T :: HNil, String :: Int :: Boolean :: HNil, GetCall, FieldType[Json, Foo])
  ]
} 
Example 31
Source File: package.scala    From typedapi   with MIT License 5 votes vote down vote up
package typedapi

import typedapi.shared._
import shapeless._
import shapeless.labelled.FieldType
import shapeless.ops.hlist.Tupler
import shapeless.ops.function.FnFromProduct

package object client extends TypeLevelFoldLeftLowPrio 
                      with TypeLevelFoldLeftListLowPrio
                      with WitnessToStringLowPrio
                      with ApiTransformer {

  def deriveUriString(cm: ClientManager[_], uri: List[String]): String = cm.base + "/" + uri.mkString("/")

  def derive[H <: HList, FH <: HList, El <: HList, KIn <: HList, VIn <: HList, M <: MethodType, MT <: MediaType, Out, D <: HList]
    (apiList: ApiTypeCarrier[H])
    (implicit filter: FilterServerElements.Aux[H, FH],
              folder: Lazy[TypeLevelFoldLeft.Aux[FH, Unit, (El, KIn, VIn, M, FieldType[MT, Out])]],
              builder: RequestDataBuilder.Aux[El, KIn, VIn, M, FieldType[MT, Out], D],
              inToFn: FnFromProduct[VIn => ExecutableDerivation[El, KIn, VIn, M, MT, Out, D]]): inToFn.Out =
    inToFn.apply(input => new ExecutableDerivation[El, KIn, VIn, M, MT, Out, D](builder, input))

  def deriveAll[H <: HList, FH <: HList, In <: HList, Fold <: HList, B <: HList, Ex <: HList]
    (apiLists: CompositionCons[H])
    (implicit filter: FilterServerElementsList.Aux[H, FH],
              folders: TypeLevelFoldLeftList.Aux[FH, Fold],
              builderList: RequestDataBuilderList.Aux[Fold, B],
              executables: ExecutablesFromHList.Aux[B, Ex],
              tupler: Tupler[Ex]): tupler.Out =
    executables(builderList.builders).tupled
} 
Example 32
Source File: Endpoint.scala    From typedapi   with MIT License 5 votes vote down vote up
package typedapi.server

import typedapi.shared._
import shapeless._
import shapeless.labelled.FieldType
import shapeless.ops.function._

import scala.language.higherKinds


    def from(fn: Fn): Endpoint[El, KIn, VIn, M, ROut, F, Out] =
      new Endpoint[El, KIn, VIn, M, ROut, F, Out](method, extractor, headers) {
        private val fin = fnToVIn(fn)

        def apply(in: VIn): F[Result[Out]] = fin(in)
      }
  }

  def apply[H <: HList, FH <: HList, El <: HList, KIn <: HList, VIn <: HList, ROut, Fn, M <: MethodType, MT <: MediaType, Out]
    (apiList: ApiTypeCarrier[H])
    (implicit filter: FilterClientElements.Aux[H, FH],
              folder: Lazy[TypeLevelFoldLeft.Aux[FH, Unit, (El, KIn, VIn, M, FieldType[MT, Out])]],
              extractor: RouteExtractor.Aux[El, KIn, VIn, M, HNil, ROut],
              methodShow: MethodToString[M],
              serverHeaders: ServerHeaderExtractor[El],
              inToFn: Lazy[FnFromProduct.Aux[VIn => F[Result[Out]], Fn]],
              fnToVIn: Lazy[FnToProduct.Aux[Fn, VIn => F[Result[Out]]]]): Derivation[El, KIn, VIn, M, ROut, Fn, Out] =
    new Derivation[El, KIn, VIn, M, ROut, Fn, Out](extractor, methodShow.show, serverHeaders(Map.empty), fnToVIn.value)
} 
Example 33
Source File: MapShapedReader.scala    From pureconfig   with Mozilla Public License 2.0 5 votes vote down vote up
package pureconfig.generic

import pureconfig._
import pureconfig.error.KeyNotFound
import pureconfig.generic.ProductHint.UseOrDefault
import shapeless._
import shapeless.labelled.{ FieldType, field }


private[generic] trait MapShapedReader[Original, Repr, DefaultRepr] {
  def from(cur: ConfigObjectCursor, default: DefaultRepr, usedFields: Set[String]): ConfigReader.Result[Repr]
}

object MapShapedReader {

  implicit def labelledHNilReader[Original](
    implicit
    hint: ProductHint[Original]): MapShapedReader[Original, HNil, HNil] =
    new MapShapedReader[Original, HNil, HNil] {
      def from(cur: ConfigObjectCursor, default: HNil, usedFields: Set[String]): ConfigReader.Result[HNil] =
        hint.bottom(cur, usedFields).fold[ConfigReader.Result[HNil]](Right(HNil))(Left.apply)
    }

  final implicit def labelledHConsReader[Original, K <: Symbol, H, T <: HList, D <: HList](
    implicit
    key: Witness.Aux[K],
    hConfigReader: Derivation[Lazy[ConfigReader[H]]],
    tConfigReader: Lazy[MapShapedReader[Original, T, D]],
    hint: ProductHint[Original]): MapShapedReader[Original, FieldType[K, H] :: T, Option[H] :: D] =
    new MapShapedReader[Original, FieldType[K, H] :: T, Option[H] :: D] {
      def from(cur: ConfigObjectCursor, default: Option[H] :: D, usedFields: Set[String]): ConfigReader.Result[FieldType[K, H] :: T] = {
        val fieldName = key.value.name
        val fieldAction = hint.from(cur, fieldName)
        lazy val reader = hConfigReader.value.value
        val headResult = (fieldAction, default.head) match {
          case (UseOrDefault(cursor, _), Some(defaultValue)) if cursor.isUndefined =>
            Right(defaultValue)
          case (action, _) if !action.cursor.isUndefined || reader.isInstanceOf[ReadsMissingKeys] =>
            reader.from(action.cursor)
          case _ =>
            cur.failed[H](KeyNotFound.forKeys(fieldAction.field, cur.keys))
        }
        val tailResult = tConfigReader.value.from(cur, default.tail, usedFields + fieldAction.field)
        ConfigReader.Result.zipWith(headResult, tailResult)((head, tail) => field[K](head) :: tail)
      }
    }
} 
Example 34
Source File: MapShapedWriter.scala    From pureconfig   with Mozilla Public License 2.0 5 votes vote down vote up
package pureconfig.generic

import scala.collection.JavaConverters._

import com.typesafe.config.{ ConfigFactory, ConfigObject, ConfigValue }
import pureconfig._
import shapeless._
import shapeless.labelled.FieldType


private[generic] trait MapShapedWriter[Original, Repr] extends ConfigWriter[Repr]

object MapShapedWriter {

  implicit def labelledHNilWriter[Original]: MapShapedWriter[Original, HNil] = new MapShapedWriter[Original, HNil] {
    override def to(t: HNil): ConfigValue = ConfigFactory.parseMap(Map().asJava).root()
  }

  final implicit def labelledHConsWriter[Original, K <: Symbol, H, T <: HList](
    implicit
    key: Witness.Aux[K],
    hConfigWriter: Derivation[Lazy[ConfigWriter[H]]],
    tConfigWriter: Lazy[MapShapedWriter[Original, T]],
    hint: ProductHint[Original]): MapShapedWriter[Original, FieldType[K, H] :: T] =
    new MapShapedWriter[Original, FieldType[K, H] :: T] {
      override def to(t: FieldType[K, H] :: T): ConfigValue = {
        val rem = tConfigWriter.value.to(t.tail)
        val valueOpt = hConfigWriter.value.value match {
          case tc: WritesMissingKeys[H @unchecked] =>
            tc.toOpt(t.head)
          case w =>
            Some(w.to(t.head))
        }
        val kv = hint.to(valueOpt, key.value.name)

        // TODO check that all keys are unique
        kv.fold(rem) {
          case (k, v) =>
            rem.asInstanceOf[ConfigObject].withValue(k, v)
        }
      }
    }
} 
Example 35
Source File: SelectorByValue.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless
package ml
package internals

import shapeless.labelled.FieldType
import shapeless.{::, DepFn1, HList, Witness}


trait SelectorByValue[L <: HList, Value] extends DepFn1[L] with Serializable { type Out <: Symbol }

object SelectorByValue {
  type Aux[L <: HList, Value, Out0 <: Symbol] = SelectorByValue[L, Value] { type Out = Out0 }

  implicit def select[K <: Symbol, T <: HList, Value](implicit wk: Witness.Aux[K]): Aux[FieldType[K, Value] :: T, Value, K] = {
    new SelectorByValue[FieldType[K, Value] :: T, Value] {
      type Out = K
      def apply(l: FieldType[K, Value] :: T): Out = wk.value
    }
  }

  implicit def recurse[H, T <: HList, Value](implicit st: SelectorByValue[T, Value]): Aux[H :: T, Value, st.Out] = {
    new SelectorByValue[H :: T, Value] {
      type Out = st.Out
      def apply(l: H :: T): Out = st(l.tail)
    }
  }
}