当前位置: 首页>>代码示例>>Scala>>正文


Scala Xor类代码示例

本文整理汇总了Scala中cats.data.Xor的典型用法代码示例。如果您正苦于以下问题:Scala Xor类的具体用法?Scala Xor怎么用?Scala Xor使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Xor类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: RawApiExtensionImpl

//设置package包名称以及导入依赖的类
package im.actor.server.api.rpc

import akka.actor._
import cats.data.Xor
import im.actor.api.rpc.collections.ApiRawValue
import im.actor.api.rpc.FutureResultRpc
import im.actor.api.rpc.raw.RawApiService
import im.actor.api.rpc.{ AuthorizedClientData, ClientData, CommonRpcErrors, RpcError }

import scala.collection.concurrent.TrieMap
import scala.concurrent.Future

sealed trait RawApiExtension extends Extension

private[rpc] final class RawApiExtensionImpl(system: ExtendedActorSystem) extends RawApiExtension {
  import FutureResultRpc._
  import system.dispatcher

  private val services = TrieMap.empty[String, RawApiService]

  def register(name: String, clazz: Class[_ <: RawApiService]): Unit = {
    val service = system.dynamicAccess.createInstanceFor[RawApiService](clazz, List(classOf[ActorSystem] ? system)).get
    register(name, service)
  }

  def register(name: String, service: RawApiService): Unit = services.putIfAbsent(name, service)

  def register(serviceSeq: Seq[(String, RawApiService)]): Unit = services ++= serviceSeq

  def handle(service: String, method: String, params: Option[ApiRawValue], clientData: ClientData): Future[RpcError Xor ApiRawValue] =
    (for {
      serviceHandler ? fromOption(CommonRpcErrors.UnsupportedRequest)(services.get(service))
      response ? fromOption(CommonRpcErrors.UnsupportedRequest)(serviceHandler.handleRequests(clientData)(params).lift(method))
      result ? fromFutureXor(response)
    } yield result).value
}

object RawApiExtension extends ExtensionId[RawApiExtensionImpl] with ExtensionIdProvider {
  override def createExtension(system: ExtendedActorSystem) = new RawApiExtensionImpl(system)

  override def lookup(): ExtensionId[_ <: Extension] = RawApiExtension
} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:43,代码来源:RawApiExtension.scala

示例2: ExecutionContextBackboneCoordinator

//设置package包名称以及导入依赖的类
package ie.zalando.pipeline.backbone.concurrent

import scala.concurrent.{ ExecutionContext, Future }
import scala.util.Try
import scala.util.control.NonFatal

import org.slf4j.LoggerFactory

import cats.data.Xor
import ie.zalando.pipeline.backbone.Backbone
import ie.zalando.pipeline.backbone.Phases.{ LocalReleasePhase, TransformationPipelineFailure }

class ExecutionContextBackboneCoordinator[DA](backbone: Backbone[DA], executionContext: ExecutionContext) {

  import ExecutionContextBackboneCoordinator._

  val localInitPhases = backbone.initializeTopLevelContexts

  def process(datum: DA): Future[Xor[TransformationPipelineFailure, DA]] = {
    Future {
      val (dataPhases, releasePhases) = backbone.initializeInLocalContext(-1, localInitPhases).unzip
      try {
        backbone.transformDatum(backbone.createStateMonad(dataPhases), datum)
      } finally {
        releasePhases.foreach((phase: LocalReleasePhase) => {
          Try({ phase.releaseLocalResources() }).recover { case NonFatal(ex) => log.warn(s"Release phase $phase failed:", ex) }
        })
      }
    }(executionContext)
  }

}

object ExecutionContextBackboneCoordinator {
  val log = LoggerFactory.getLogger(classOf[ExecutorServiceBackboneCoordinator[_]])
} 
开发者ID:retnuh,项目名称:pipeline-backbone,代码行数:37,代码来源:ExecutionContextBackboneCoordinator.scala

示例3: ExecutorServiceBackboneCoordinator

//设置package包名称以及导入依赖的类
package ie.zalando.pipeline.backbone.concurrent

import java.util.concurrent.{ Callable, Future, ExecutorService }

import scala.util.Try
import scala.util.control.NonFatal

import org.slf4j.LoggerFactory

import cats.data.Xor
import ie.zalando.pipeline.backbone.Backbone
import ie.zalando.pipeline.backbone.Phases.{ LocalReleasePhase, TransformationPipelineFailure }

class ExecutorServiceBackboneCoordinator[DA](backbone: Backbone[DA], executor: ExecutorService) {
  import ExecutorServiceBackboneCoordinator._

  val localInitPhases = backbone.initializeTopLevelContexts

  private class BackboneCallable(datum: DA) extends Callable[Xor[TransformationPipelineFailure, DA]] {
    override def call(): Xor[TransformationPipelineFailure, DA] = {
      val (dataPhases, releasePhases) = backbone.initializeInLocalContext(-1, localInitPhases).unzip
      try {
        backbone.transformDatum(backbone.createStateMonad(dataPhases), datum)
      } finally {
        releasePhases.foreach((phase: LocalReleasePhase) => {
          Try({ phase.releaseLocalResources() }).recover { case NonFatal(ex) => log.warn(s"Release phase $phase failed:", ex) }
        })
      }
    }
  }

  def process(datum: DA): Future[Xor[TransformationPipelineFailure, DA]] = {
    executor.submit(new BackboneCallable(datum))
  }

}

object ExecutorServiceBackboneCoordinator {
  val log = LoggerFactory.getLogger(classOf[ExecutorServiceBackboneCoordinator[_]])
} 
开发者ID:retnuh,项目名称:pipeline-backbone,代码行数:41,代码来源:ExecutorServiceBackboneCoordinator.scala

示例4: StreamConsumer

//设置package包名称以及导入依赖的类
package consumers

import akka.Done
import akka.actor.ActorSystem
import akka.kafka.scaladsl.Consumer
import akka.kafka.{ConsumerSettings, Subscriptions}
import akka.stream.scaladsl.Sink
import akka.stream.{ActorMaterializer, ActorMaterializerSettings}
import cats.data.Xor
import com.typesafe.config.ConfigFactory
import org.apache.kafka.clients.consumer.{ConsumerConfig, ConsumerRecord}
import org.apache.kafka.clients.consumer.internals.PartitionAssignor.Subscription
import org.apache.kafka.common.serialization.{ByteArrayDeserializer, StringDeserializer}
import io.circe._
import io.circe.generic.auto._
import cats.data.Xor.{Left, Right}
import model.Employee

import scala.concurrent.Future

object StreamConsumer  extends App{
  implicit val actorSystem = ActorSystem("consumer-actors", ConfigFactory.load())
  implicit val materializer = ActorMaterializer(ActorMaterializerSettings(actorSystem))

  lazy val consumerSettings = ConsumerSettings(actorSystem, new ByteArrayDeserializer, new StringDeserializer)
    .withBootstrapServers("localhost:9092")
    .withGroupId("group13")
    .withProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest")//"latest")
    .withProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true")
    .withProperty(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000")

  lazy val subscription = Subscriptions.topics("raw-data-1")
  lazy val db = new Processor()
  Consumer.plainSource(consumerSettings, subscription)
      .mapAsync(4){
        db.processMessage
      }
    .runWith(Sink.ignore)

}

class Processor {
  def processMessage(record: ConsumerRecord[Array[Byte], String]): Future[Done] ={
    println(s"DB.save: ${record.value()}")

    Option(record.value()).foreach{ jsonString =>
      val mayBeEmp: Xor[Error, Employee] = jawn.decode[Employee](jsonString)
      mayBeEmp match {
        case Left(error) => println(error)
        case Right(emp) => println(s"employee name: ${emp.name}")
      }
    }
    Future.successful(Done)  }
} 
开发者ID:ajit-scala,项目名称:kafka-consumers,代码行数:55,代码来源:StreamConsumer.scala

示例5: circe

//设置package包名称以及导入依赖的类
package org.mdoc.common.model

import cats.data.Xor
import io.circe.{ Decoder, DecodingFailure, Encoder }
import scodec.bits.ByteVector

object circe {

  implicit val byteVectorDecoder: Decoder[ByteVector] =
    Decoder.instance { cursor =>
      Decoder[String].apply(cursor).flatMap { str =>
        ByteVector.fromBase64Descriptive(str) match {
          case Right(bytes) => Xor.right(bytes)
          case Left(err) => Xor.left(DecodingFailure(err, cursor.history))
        }
      }
    }

  implicit val byteVectorEncoder: Encoder[ByteVector] =
    Encoder[String].contramap(_.toBase64)
} 
开发者ID:m-doc,项目名称:common-model,代码行数:22,代码来源:circe.scala

示例6: CirceSpec

//设置package包名称以及导入依赖的类
package org.mdoc.common.model

import cats.data.Xor
import io.circe.{ Decoder, Encoder, Json }
import org.mdoc.common.model.circe._
import org.scalacheck.Prop._
import org.scalacheck.Properties
import scodec.bits.ByteVector

object CirceSpec extends Properties("circe") {

  property("Decoder[ByteVector] success") = secure {
    Decoder[ByteVector].decodeJson(Json.string("SGVsbG8=")) ?=
      Xor.right(ByteVector("Hello".getBytes))
  }

  property("Decoder[ByteVector] failure") = secure {
    Decoder[ByteVector].decodeJson(Json.string("???")).isLeft
  }

  property("Encoder[ByteVector]") = secure {
    Encoder[ByteVector].apply(ByteVector("Hello".getBytes)) ?=
      Json.string("SGVsbG8=")
  }
} 
开发者ID:m-doc,项目名称:common-model,代码行数:26,代码来源:CirceSpec.scala

示例7: RenderingInputSpec

//设置package包名称以及导入依赖的类
package org.mdoc.common.model

import cats.data.Xor
import io.circe.generic.auto._
import io.circe.parse._
import io.circe.syntax._
import org.mdoc.common.model.Format.{ Html, Pdf }
import org.mdoc.common.model.RenderingEngine.LibreOffice
import org.mdoc.common.model.circe._
import org.scalacheck.Prop._
import org.scalacheck.Properties
import scodec.bits.ByteVector

object RenderingInputSpec extends Properties("RenderingInput") {

  {
    val json = """
      {"id":{"self":"42"},"config":{"outputFormat":{"Pdf":{}},"engine":{"LibreOffice":{}}},"doc":{"format":{"Html":{}},"body":"SGVsbG8sIFdvcmxkIQ=="}}
    """.trim

    val config = RenderingConfig(Pdf, LibreOffice)
    val doc = Document(Html, ByteVector("Hello, World!".getBytes))
    val input = RenderingInput(JobId("42"), config, doc)

    property("JSON decode") = secure {
      decode[RenderingInput](json) ?= Xor.right(input)
    }

    property("JSON encode") = secure {
      input.asJson.noSpaces ?= json
    }
  }
} 
开发者ID:m-doc,项目名称:common-model,代码行数:34,代码来源:RenderingInputSpec.scala

示例8: RulesExecutor

//设置package包名称以及导入依赖的类
package uk.gov.hmrc.decisionservice.service

import cats.data.Xor
import org.drools.KnowledgeBase
import org.drools.builder.{KnowledgeBuilderFactory, ResourceType}
import org.drools.io.ResourceFactory
import org.slf4j.LoggerFactory
import play.api.i18n.Messages
import uk.gov.hmrc.decisionservice.model.{DecisionServiceError, KnowledgeBaseError, RulesFileError}

import scala.collection.JavaConversions._


object RulesExecutor {
  val logger = LoggerFactory.getLogger(RulesExecutor.getClass())
  val LoggerVariable: String = "logger"
  val DroolsDialect: String = "JANINO"
  val DroolsDialectMvelStrict: String = "false"

  def using[R <: { def dispose(): Unit }, B](resource: R)(f: R => B): B = try { f(resource) } finally { resource.dispose() }

  def analyze(model: List[Any], kb: String):Xor[DecisionServiceError,List[AnyRef]] = {
    analyze(model, kb, createKb(kb))
  }

  def analyze(model: List[Any], kb: String, maybeKnowledgeBase:Xor[DecisionServiceError,KnowledgeBase]):Xor[DecisionServiceError,List[AnyRef]] = {
    maybeKnowledgeBase match {
      case Xor.Right(knowledgeBase) =>
        val results = using(knowledgeBase.newStatefulKnowledgeSession()) { session =>
          session.setGlobal(LoggerVariable, LoggerFactory.getLogger(kb))
          model.foreach(session.insert(_))
          session.fireAllRules()
          session.getObjects()
        }
        Xor.right(results.toList)
      case [email protected](ee) => e
    }
  }

  def createKb(kb: String): Xor[DecisionServiceError,KnowledgeBase] = {
    try {
      System.setProperty("drools.dialect.java.compiler", DroolsDialect)
      val config = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration()
      config.setProperty("drools.dialect.mvel.strict", DroolsDialectMvelStrict)
      val res = ResourceFactory.newClassPathResource(kb)
      val knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(config)
      knowledgeBuilder.add(res, ResourceType.DTABLE)
      val errors = knowledgeBuilder.getErrors()
      errors.size() match {
        case n if n > 0 =>
          for (error <- errors) logger.error(error.getMessage())
          Xor.left(KnowledgeBaseError(Messages("rules.executor.knowledge.base.error") + s" $errors"))
        case _ =>
          Xor.right(knowledgeBuilder.newKnowledgeBase())
      }
    } catch {
      case e:Throwable => Xor.left(RulesFileError(e.getMessage))
    }
  }
} 
开发者ID:Baisysoft,项目名称:off-payroll-decision-service,代码行数:61,代码来源:RulesExecutor.scala

示例9: validate

//设置package包名称以及导入依赖的类
package im.actor.server.activation.common

import java.time.temporal.ChronoUnit._
import java.time.{ LocalDateTime, ZoneOffset }

import akka.http.scaladsl.util.FastFuture
import cats.data.Xor
import im.actor.server.db.ActorPostgresDriver.api._
import im.actor.server.model.AuthCode
import im.actor.server.persist.AuthCodeRepo

import scala.concurrent.{ ExecutionContext, Future }

trait CommonAuthCodes {
  self: ActivationProvider ?

  protected val activationConfig: ActivationConfig
  protected val db: Database
  protected implicit val ec: ExecutionContext

  override def validate(txHash: String, code: String): Future[ValidationResponse] = {
    val action = for {
      optCode ? AuthCodeRepo.findByTransactionHash(txHash)
      result ? optCode map {
        case s if isExpired(s, activationConfig.expiration.toMillis) ?
          for (_ ? AuthCodeRepo.deleteByTransactionHash(txHash)) yield ExpiredCode
        case s if s.code != code ?
          if (s.attempts + 1 >= activationConfig.attempts) {
            for (_ ? AuthCodeRepo.deleteByTransactionHash(txHash)) yield ExpiredCode
          } else {
            for (_ ? AuthCodeRepo.incrementAttempts(txHash, s.attempts)) yield InvalidCode
          }
        case _ ? DBIO.successful(Validated)
      } getOrElse DBIO.successful(InvalidHash)
    } yield result
    db.run(action)
  }

  protected def deleteAuthCode(txHash: String): Future[Unit] = db.run(AuthCodeRepo.deleteByTransactionHash(txHash).map(_ ? ()))

  protected def createAuthCodeIfNeeded(resp: CodeFailure Xor Unit, txHash: String, code: String): Future[Int] = resp match {
    case Xor.Left(_)  ? FastFuture.successful(0)
    case Xor.Right(_) ? db.run(AuthCodeRepo.createOrUpdate(txHash, code))
  }

  protected def isExpired(code: AuthCode, expiration: Long): Boolean =
    code.createdAt.plus(expiration, MILLIS).isBefore(LocalDateTime.now(ZoneOffset.UTC))

} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:50,代码来源:CommonAuthCodes.scala

示例10: ExtHistoryMessageModel

//设置package包名称以及导入依赖的类
package im.actor.api.rpc

import cats.data.Xor
import com.google.protobuf.CodedInputStream
import im.actor.api.rpc.Refs.ApiMessageAttributes
import im.actor.api.rpc.messaging.{ ApiMessage, ApiMessageContainer, ApiMessageReaction, ApiMessageState }
import im.actor.server.model.{ HistoryMessage, MessageReaction }
import org.joda.time.DateTime

trait HistoryImplicits {

  implicit class ExtHistoryMessageModel(model: HistoryMessage) {
    def asStruct(
      lastReceivedAt: DateTime,
      lastReadAt:     DateTime,
      reactions:      Seq[MessageReaction],
      attributes:     Option[ApiMessageAttributes] = None
    ): Xor[String, ApiMessageContainer] = {
      val in = CodedInputStream.newInstance(model.messageContentData)
      try {
        Xor.fromEither(ApiMessage.parseFrom(in)) map { messageContent ?
          val state = if (model.userId == model.senderUserId) {
            if (model.date.getMillis <= lastReadAt.getMillis)
              Some(ApiMessageState.Read)
            else if (model.date.getMillis <= lastReceivedAt.getMillis)
              Some(ApiMessageState.Received)
            else
              Some(ApiMessageState.Sent)
          } else None // for incoming

          ApiMessageContainer(
            senderUserId = model.senderUserId,
            randomId = model.randomId,
            date = model.date.getMillis,
            message = messageContent,
            state = state,
            reactions = reactions.toVector map (r ? ApiMessageReaction(r.userIds.toVector, r.code)),
            attribute = attributes,
            quotedMessage = None
          )
        }
      } catch {
        case e: Exception ? Xor.Left(e.getMessage)
      }
    }
  }

} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:49,代码来源:HistoryImplicits.scala

示例11: ArrayStyleRawApiService

//设置package包名称以及导入依赖的类
package im.actor.api.rpc.raw

import akka.actor.ActorSystem
import cats.data.Xor
import im.actor.api.rpc.collections._
import im.actor.api.rpc.{ ClientData, RpcError }

import scala.concurrent.Future

// todo: find a better name. It is not array style already. Arrays just could be parsed to case classes for convinience
abstract class ArrayStyleRawApiService(system: ActorSystem) extends RawApiService(system) with RawValueParserTypeclassInstances {
  import im.actor.api.rpc.FutureResultRpc._
  import system.dispatcher

  type Request

  final override def handleRequests: Handler = implicit client ? params ? new PartialFunction[String, Future[Response]] {
    override def isDefinedAt(name: String): Boolean = validateRequests(None).isDefinedAt(name)

    override def apply(name: String): Future[Response] = {
      (for {
        request ? fromXor(validateRequests(params)(name))
        result ? fromFutureXor(processRequests(client)(request))
      } yield result).value
    }
  }

  protected def validateRequests: Option[ApiRawValue] ? PartialFunction[String, RpcError Xor Request]

  protected def processRequests: ClientData ? PartialFunction[Request, Future[Response]]

  /**
   * Parse content of `optParams` to type T,
   * Returns `RawApiRpcErrors.InvalidParams` if `optParams` is empty
   * Returns `RawApiRpcErrors.InvalidParams` if it wasn't able to parse `optParams` to type T
   * @param optParams data that will be parsed. Should be non empty
   * @tparam T type to parse to
   */
  final protected def parseParams[T: RawValueParser](optParams: Option[ApiRawValue]): RpcError Xor T =
    for {
      params ? Xor.fromOption(optParams, RawApiRpcErrors.InvalidParams)
      result ? Xor.fromOption(RawValueParser.parse[T](params), RawApiRpcErrors.InvalidParams)
    } yield result

} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:46,代码来源:ArrayStyleRawApiService.scala

示例12: matchesEmail

//设置package包名称以及导入依赖的类
package im.actor.server.api.rpc.service.auth

import cats.MonadCombine
import cats.data.{ NonEmptyList, Xor }
import cats.syntax.all._
import im.actor.api.rpc._
import im.actor.util.misc.StringUtils
import org.apache.commons.validator.routines.EmailValidator

private[auth] trait Helpers extends PublicKeyHelpers {

  private def matchesEmail(s: String): NonEmptyList[String] Xor String =
    if (EmailValidator.getInstance().isValid(s)) s.right else NonEmptyList.of("Should be valid email address").left

  def validEmail(email: String): NonEmptyList[String] Xor String =
    StringUtils.nonEmptyString(email).flatMap(e ? matchesEmail(e.toLowerCase))

  private implicit val listMonadCombine = new MonadCombine[List] {
    def pure[A](x: A): List[A] = List(x)
    def flatMap[A, B](fa: List[A])(f: (A) ? List[B]): List[B] = fa flatMap f
    def empty[A]: List[A] = List.empty[A]
    def combineK[A](x: List[A], y: List[A]): List[A] = x ::: y
    def tailRecM[A, B](a: A)(f: (A) ? List[Either[A, B]]): List[B] = defaultTailRecM(a)(f)
  }

  def validationFailed(errorName: String, errors: NonEmptyList[String]): RpcError =
    RpcError(400, errorName, errors.toList.mkString(", "), false, None)
} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:29,代码来源:Helpers.scala

示例13: FileRpcErrors

//设置package包名称以及导入依赖的类
package im.actor.api.rpc

import cats.data.Xor
import im.actor.server.acl.ACLUtils

import scala.concurrent.ExecutionContext
import akka.actor.ActorSystem
import slick.dbio.DBIO
import im.actor.api.rpc.files.ApiFileLocation
import im.actor.server.persist.files.FileRepo

object FileRpcErrors {
  val FileNotFound = RpcError(404, "FILE_NOT_FOUND", "File not found.", false, None)
  val FileTooLarge = RpcError(400, "FILE_TOO_LARGE", "File is too large.", false, None)
  val LocationInvalid = RpcError(400, "LOCATION_INVALID", "", false, None)
  val UnsupportedSignatureAlgorithm = RpcError(400, "SIGNATURE_ALGO_NOT_SUPPORTED", "", false, None)
}

object FileHelpers {

  def withFileLocation[R <: RpcResponse](fileLocation: ApiFileLocation, maxSize: Long)(f: ? DBIO[RpcError Xor R])(implicit ec: ExecutionContext, s: ActorSystem) = {
    FileRepo.find(fileLocation.fileId) flatMap {
      case Some(file) ?
        if (!file.isUploaded) {
          DBIO.successful(Error(FileRpcErrors.LocationInvalid))
        } else if (file.size > maxSize) {
          DBIO.successful(Error(FileRpcErrors.FileTooLarge))
        } else if (ACLUtils.fileAccessHash(file.id, file.accessSalt) != fileLocation.accessHash) {
          DBIO.successful(Error(FileRpcErrors.LocationInvalid))
        } else {
          f
        }
      case None ? DBIO.successful(Error(FileRpcErrors.FileNotFound))
    }
  }

} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:38,代码来源:FileHelpers.scala

示例14: registerUserRoute

//设置package包名称以及导入依赖的类
package io.scalac.wtf.domain

import akka.http.scaladsl.server.Directives._
import cats.data.{Reader, Xor}
import spray.json.{JsObject, JsString}

import UserService.createUser
import spray.json.DefaultJsonProtocol._
import cats.implicits._
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._

trait UserRoutes {
  implicit val userFormat = jsonFormat2(NewUser)

  def registerUserRoute = Reader((config: Config) => {
    implicit val ec = config.ec
    path("register") {
      post {
        entity(as[NewUser]) { userRequest =>
          val user = User(email = userRequest.email, password = userRequest.password)
          val result = config.db.run(createUser(user))

          complete {
            result.map {
              case Xor.Left(errors) => JsString(errors.unwrap.mkString(" "))
              case Xor.Right(_) => JsObject.empty
            }
          }
        }
      }
    }
  })
} 
开发者ID:ScalaConsultants,项目名称:whisky-tango-foxtrot,代码行数:34,代码来源:UserRoutes.scala

示例15: Helper

//设置package包名称以及导入依赖的类
package io.taig.sbt.changelog

import cats.data.Xor
import cats.syntax.xor._
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.api.errors.NoHeadException
import org.eclipse.jgit.lib.AnyObjectId
import org.eclipse.jgit.revwalk.RevWalk

import scala.collection.JavaConversions._
import scala.language.reflectiveCalls

object Helper {
    
    def commits( range: Option[Range] )( implicit g: Git ): RevWalk = {
        val walk = new RevWalk( g.getRepository )

        range.getOrElse( HEAD.right ) match {
            case Xor.Left( ( since, until ) ) ?
                walk.markStart( walk.lookupCommit( until ) )
                walk.markUninteresting( walk.lookupCommit( since ) )
            case Xor.Right( start ) ?
                walk.markStart( walk.lookupCommit( start ) )
        }

        walk
    }

    def parseRange( range: String )( implicit g: Git ): Option[( String, String ) Xor String] = {
        range.split( "\\.\\." ) match {
            case Array( since, until ) ? Some( ( since, until ).left )
            case Array( start )        ? Some( start.right )
            case _                     ? None
        }
    }

    def resolveDefaultRange( tags: List[String] )( implicit g: Git ): Range = {
        recentTags match {
            case head :: _ ? ( resolve( head ), HEAD ).left
            case _         ? HEAD.right
        }
    }

    def HEAD( implicit g: Git ) = resolve( "HEAD" )

    def resolve( id: String )( implicit g: Git ) = {
        g.getRepository.resolve( id )
    }

    def using[T <: { def close() }, U]( resource: T )( block: T ? U ): U = {
        try {
            block( resource )
        } finally {
            if ( resource != null ) resource.close()
        }
    }
} 
开发者ID:Taig,项目名称:sbt-git-changelog,代码行数:58,代码来源:Helper.scala


注:本文中的cats.data.Xor类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。