本文整理汇总了Scala中sbt.complete.Parser类的典型用法代码示例。如果您正苦于以下问题:Scala Parser类的具体用法?Scala Parser怎么用?Scala Parser使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Parser类的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: CleanShadedPlugin
//设置package包名称以及导入依赖的类
// https://github.com/sbt/sbt-dirty-money/blob/master/src/main/scala/sbtdirtymoney/DirtyMoneyPlugin.scala
import sbt._, Keys._
object CleanShadedPlugin extends AutoPlugin {
override def requires = plugins.IvyPlugin
override def trigger = allRequirements
object autoImport {
val cleanCacheIvyDirectory: SettingKey[File] = settingKey[File]("")
val cleanCache: InputKey[Unit] = inputKey[Unit]("")
val cleanCacheFiles: InputKey[Seq[File]] = inputKey[Seq[File]]("")
val cleanLocal: InputKey[Unit] = inputKey[Unit]("")
val cleanLocalFiles: InputKey[Seq[File]] = inputKey[Seq[File]]("")
}
import autoImport._
object CleanShaded {
import sbt.complete.Parser
import sbt.complete.DefaultParsers._
final case class ModuleParam(organization: String, name: Option[String])
def parseParam: Parser[Option[ModuleParam]] =
((parseOrg ~ parseName.?) map {
case o ~ n => ModuleParam(o, n)
}).?
private def parseOrg: Parser[String] =
(Space ~> token(StringBasic.examples("\"organization\"")))
private def parseName: Parser[String] =
(Space ~> token(token("%") ~> Space ~> StringBasic.examples("\"name\"")))
def query(base: File, param: Option[ModuleParam], org: String, name: String): Seq[File] =
(param match {
case None => base ** ("*" + org + "*") ** ("*" + name + "*")
case Some(ModuleParam("*", None)) => base ** "*"
case Some(ModuleParam(o, None | Some("*"))) => base ** ("*" + o + "*") ** "*"
case Some(ModuleParam(o, Some(n))) => base ** ("*" + o + "*") ** ("*" + n + "*")
}).get
}
override def projectSettings = Seq(
cleanCacheIvyDirectory := ivyPaths.value.ivyHome getOrElse (Path.userHome / ".ivy2"),
cleanCache := IO.delete(cleanCacheFiles.evaluated),
cleanLocal := IO.delete(cleanLocalFiles.evaluated),
cleanCacheFiles := {
val base = cleanCacheIvyDirectory.value / "cache"
val param = CleanShaded.parseParam.parsed
CleanShaded.query(base, param, organization.value, moduleName.value)
},
cleanLocalFiles := {
val base = cleanCacheIvyDirectory.value / "local"
val param = CleanShaded.parseParam.parsed
CleanShaded.query(base, param, organization.value, moduleName.value)
}
)
}
示例2: CommandRunner
//设置package包名称以及导入依赖的类
package x7c1.chaff.publish
import sbt.State
object CommandRunner {
def runCommand(command: String): State => State = { st: State =>
import sbt.complete.Parser
@annotation.tailrec
def runCommand(command: String, state: State): State = {
val nextState = Parser.parse(command, state.combinedParser) match {
case Right(cmd) => cmd()
case Left(msg) => throw sys.error(s"Invalid programmatic input:\n$msg")
}
nextState.remainingCommands.toList match {
case Nil => nextState
case head :: tail => runCommand(head, nextState.copy(remainingCommands = tail))
}
}
runCommand(command, st.copy(remainingCommands = Nil)).
copy(remainingCommands = st.remainingCommands)
}
}
示例3: ParserOps
//设置package包名称以及导入依赖的类
import scalaz._
import Scalaz._
import sbt.complete.Parser
object ParserOps {
implicit class ParserImplicits[T](val that: Parser[T]) extends AnyVal {
def parse(input: String): ValidationNel[String, T] = Parser.parse(input, that).validationNel
}
implicit class EitherImplicits[T](val that: Either[String, T]) extends AnyVal {
def cleanup(input: String): Option[String] =
Option(input.replaceAll("\\n", "").replaceAll("\\t", "").replace("^", "").trim).filter(_.nonEmpty)
def validationNel: ValidationNel[String, T] = that.validation.leftMap { str =>
str.split("\\n").toList.flatMap(cleanup).mkString(" ...").wrapNel
}
}
}
示例4: Main
//设置package包名称以及导入依赖的类
import java.io.File
import Ansi._
import sbt.complete.Parser
import scala.util.Try
object Main extends App with Cli {
runCli()
}
trait Cli {
val parser = CliCommandParser.parser
// Starts the CLI and runs in a loop parsing commands until it encounters the
// Exit command. The Help command is passed as the initial command.
def runCli() = {
def loop(initialCmd: Option[CliCommand] = None): Unit =
Try(initialCmd orElse readLine(parser) match {
case Some(Exit) ? Exit.run()
case None ? loop()
case Some(cmd) ? cmd.run(); loop()
}).recover { case _ ?
println(red("Ooops! Something went wrong, let's try again \n")); loop()
}
loop(Some(Help))
}
// Uses sbt JLine reader to read input from the user
private def readLine[U](parser: Parser[U]): Option[U] = {
val reader = new sbt.FullReader(Some(new File("/tmp/clihistory")), parser)
reader.readLine(prompt = "> ") flatMap { line ?
Parser.parse(line, parser).fold(_ ? None, Some(_))
}
}
}
示例5: CloudFormationStackParsers
//设置package包名称以及导入依赖的类
package com.dwolla.sbt.cloudformation
import com.dwolla.sbt.cloudformation.CloudFormationStack.autoImport._
import sbt.complete.DefaultParsers._
import sbt.complete.Parser
import sbt.{Project, State}
object CloudFormationStackParsers {
val awsAccountIdParser: Parser[AwsAccountId] = charClass(_.isDigit, "digit").+.map(_.mkString).filter(_.length == 12, s ? s"`$s` is not a 12-digit AWS Account ID").map(AwsAccountId)
val awsRoleNameParser: Parser[AwsRoleName] = ("role/" ~> (charClass(_.isLetterOrDigit, "alphanumeric") | chars("+=,[email protected]_-/")).+.map(_.mkString)).map(AwsRoleName)
private def selectSome(items: Seq[(String, Parser[CloudFormationOption])]): Parser[Seq[CloudFormationOption]] = {
def select1(items: Seq[Parser[CloudFormationOption]]): Parser[CloudFormationOption] = {
val combined: Parser[CloudFormationOption] = items.reduceLeft(_ | _)
token(Space ~> combined)
}
select1(items.map(_._2)).flatMap { (v: CloudFormationOption) ?
val remaining = items.filter { tuple ?
tuple._1 != v.getClass.getCanonicalName
}
if (remaining.isEmpty)
success(v :: Nil)
else
selectSome(remaining).?.map(v +: _.getOrElse(Seq()))
}
}
def buildCloudFormationStackParser(state: State): Parser[Seq[CloudFormationOption]] = {
val generatedEnvironmentParser = Project.extract(state)
.get(deployEnvironmentOptions)
.map(Parser.literal)
.reduce(_ | _)
.map(Environment)
OptSpace ~> selectSome(Seq(
// these tuples are a terrible hack
classOf[AwsRoleName].getCanonicalName ? awsRoleNameParser,
classOf[AwsAccountId].getCanonicalName ? awsAccountIdParser,
classOf[Environment].getCanonicalName ? generatedEnvironmentParser
)).?.map {
case Some(x) ? x
case None ? Seq.empty[CloudFormationOption]
}
}
}
示例6: ResourceNameParser
//设置package包名称以及导入依赖的类
package x7c1.wheat.harvest
import sbt.complete.Parser
object ResourceNameParser {
import sbt.complete.DefaultParsers._
def readPrefix(name: String): Either[HarvestParserError, ResourcePrefix] = {
parse(name, parserToPrefix).left.map(HarvestParserError).joinRight
}
def identifier = HarvestParser.identifier
def parserToPrefix: Parser[Either[HarvestParserError, ResourcePrefix]] = {
val wordsParser = identifier ~ (token('_') ~> identifier).* map {
case (x, xs) => Words(x +: xs)
}
any.*.string <~ token(".xml") map { raw =>
val p = "_".? ~ (wordsParser <~ token("__")).? ~ wordsParser map {
case ((underscore, parent), words) =>
val parentName = parent map (_.camelize)
val privatePrefix = underscore getOrElse ""
ResourcePrefix(
raw = raw,
ofClass = privatePrefix + (parentName getOrElse "") + words.camelize,
ofKey = raw + "__",
parentClassName = parentName map (privatePrefix + _)
)
}
parse(raw, p).left map HarvestParserError
}
}
private case class Words(values: Seq[String]) {
def camelize = values.map(_.capitalize).mkString
}
}
示例7: HarvestParser
//设置package包名称以及导入依赖的类
package x7c1.wheat.harvest
import sbt.PathFinder
import sbt.complete.Parser
import x7c1.chaff.parser.reductive.ReductiveParser
object HarvestParser {
import sbt.complete.DefaultParsers._
lazy val identifier: Parser[String] = {
val alphabet = token('a' to 'z')
val numbers = token('0' to '9')
alphabet.+.string ~ (numbers | alphabet).*.string map {
case (a, b) => a + b
}
}
def camelizeTail(string: String): Either[HarvestParserError, String] = {
val parser = (identifier ~ (token('_') ~> identifier).*) map {
case (head, tail) => head + tail.map(_.capitalize).mkString
}
parse(string, parser).left.map(HarvestParserError)
}
def selectFrom(finder: PathFinder): Parser[Seq[String]] = {
val names = finder.get.map(_.getName) filterNot (_ startsWith "_")
ReductiveParser from names
}
}
case class HarvestParserError(message: String)
示例8: LineLoader
//设置package包名称以及导入依赖的类
package x7c1.wheat.splicer.android
import sbt.complete.DefaultParsers.parse
import sbt.complete.Parser
import x7c1.wheat.splicer.lib.Extractor
import x7c1.wheat.splicer.lib.Extractor.==>
class LineLoader(
source: PropertySource,
property: String,
target: Parser[String]) {
def requireSingle(): String = {
loadMultiple() match {
case x +: Seq() => x
case x +: xs =>
val targets = xs mkString ", "
throw new IllegalArgumentException(s"multiple $property found: $targets")
case Seq() =>
throw new IllegalArgumentException(s"$property not found: ${source.name}")
}
}
def loadMultiple(): Seq[String] = {
val pattern = toPattern
source.lines collect { case pattern(line) => line }
}
private def toPattern: String ==> String = Extractor {
line => parse(line, target).right.toOption
}
}
示例9: PropertyLoader
//设置package包名称以及导入依赖的类
package x7c1.wheat.splicer.android
import sbt.File
import sbt.complete.DefaultParsers._
import sbt.complete.Parser
object PropertyLoader {
object sdkRoot extends LinedProperty[File](
parser = _ ~> "=" ~> NotSpace,
property = "sdk.dir"
)
object buildToolsVersion extends LinedProperty[String](
parser = Space ~> _ ~> Space ~> quoted,
property = "buildToolsVersion"
)
object compileSdkVersion extends LinedProperty[Int](
parser = Space ~> _ ~> Space ~> Digit.+.string,
property = "compileSdkVersion"
)
object dependencies extends LinedProperty[Seq[String]](
parser = Space ~> _ ~> Space ~> quoted,
property = "compile"
)
private val quoted = {
val quoted1 = "'" ~> NotSpace <~ "'"
val quoted2 = '"' ~> NotSpace <~ '"'
quoted1 | quoted2
}
}
abstract class LinedProperty[A: LineLoadable](
parser: String => Parser[String],
property: String) {
def via(file: File): A = {
convertFrom(PropertyFile(file))
}
def fromResource(resourcePath: String): A = {
convertFrom(PropertyResource(resourcePath))
}
private def convertFrom(source: PropertySource) = {
val load = implicitly[LineLoadable[A]]
load by new LineLoader(source, property, parser(property))
}
}
示例10: ReductiveParser
//设置package包名称以及导入依赖的类
package x7c1.chaff.parser.reductive
import sbt.complete.DefaultParsers.{NotSpace, Space, failure, token}
import sbt.complete.Parser
import scala.util.{Failure, Success, Try}
object ReductiveParser {
def from(items: Seq[String]): Parser[Seq[String]] = {
new ReductiveParser(items).parser
}
}
class ReductiveParser private (items: Seq[String]) {
private type Filter = String => Boolean
def parser: Parser[Seq[String]] = {
val fixed: Parser[Filter] = {
val base = items map (token(_)) reduceOption (_ | _)
base getOrElse failure("none") map (item => _ == item)
}
val manually: Parser[Filter] = {
val base = NotSpace
base map (input => _ matches input)
}
(Space ~> (fixed | manually) flatMap next) ?? Nil
}
private def next(filter: Filter): Parser[Seq[String]] =
Try(items partition filter) match {
case Success((consumed, remains)) if consumed.nonEmpty =>
ReductiveParser from remains map (consumed ++ _)
case Success(_) =>
failure(s"input not matched")
case Failure(e) =>
failure(s"invalid input: ${e.getMessage}")
}
}