Minor code cleanup

This commit is contained in:
Jean-Rémi Desjardins 2014-12-03 09:56:34 -08:00
parent 015c61ad69
commit ca736e55d3
68 changed files with 126 additions and 126 deletions

View File

@ -73,7 +73,7 @@ object ClassToAPI {
val fields = mergeMap(c, c.getDeclaredFields, c.getFields, fieldToDef(enclPkg))
val constructors = mergeMap(c, c.getDeclaredConstructors, c.getConstructors, constructorToDef(enclPkg))
val classes = merge[Class[_]](c, c.getDeclaredClasses, c.getClasses, toDefinitions(cmap), (_: Seq[Class[_]]).partition(isStatic), _.getEnclosingClass != c)
val all = (methods ++ fields ++ constructors ++ classes)
val all = methods ++ fields ++ constructors ++ classes
val parentJavaTypes = allSuperTypes(c)
if (!Modifier.isPrivate(c.getModifiers))
cmap.inherited ++= parentJavaTypes.collect { case c: Class[_] => c }
@ -111,7 +111,7 @@ object ClassToAPI {
}
@tailrec def flattenAll(interfaces: Seq[Type], accum: Seq[Type] = Seq.empty): Seq[Type] =
{
if (!interfaces.isEmpty) {
if (interfaces.nonEmpty) {
val raw = interfaces map { case p: ParameterizedType => p.getRawType; case i => i }
val children = raw flatMap { case i: Class[_] => i.getGenericInterfaces; case _ => Seq.empty }
flattenAll(children, accum ++ interfaces ++ children)

View File

@ -1,6 +1,6 @@
each compilation group gets an Analysis
an sbt-style project could have multiple compilation groups or there could be multiple projects per compilation group.
Tradiationally, there has been a main group and a test group.
Traditionally, there has been a main group and a test group.
Each Analysis is associated with one or more classpath entries. Typically, it will be associated with the output directory and/or any artifacts produced from that output directory.

View File

@ -155,7 +155,7 @@ private class MAnalysis(val stamps: Stamps, val apis: APIs, val relations: Relat
def --(sources: Iterable[File]): Analysis =
{
val newRelations = relations -- sources
def keep[T](f: (Relations, T) => Set[_]): T => Boolean = !f(newRelations, _).isEmpty
def keep[T](f: (Relations, T) => Set[_]): T => Boolean = f(newRelations, _).nonEmpty
val newAPIs = apis.removeInternal(sources).filterExt(keep(_ usesExternal _))
val newStamps = stamps.filter(keep(_ produced _), sources, keep(_ usesBinary _))

View File

@ -38,7 +38,7 @@ object Incremental {
val analysis = manageClassfiles(options) { classfileManager =>
incremental.cycle(initialInv, sources, binaryChanges, previous, doCompile, classfileManager, 1)
}
(!initialInv.isEmpty, analysis)
(initialInv.nonEmpty, analysis)
}
// the name of system property that was meant to enable debugging mode of incremental compiler but

View File

@ -119,7 +119,7 @@ private[inc] abstract class IncrementalCommon(log: Logger, options: IncOptions)
protected def sameAPI[T](src: T, a: Source, b: Source): Option[APIChange[T]]
def shortcutSameSource(a: Source, b: Source): Boolean = !a.hash.isEmpty && !b.hash.isEmpty && sameCompilation(a.compilation, b.compilation) && (a.hash.deep equals b.hash.deep)
def shortcutSameSource(a: Source, b: Source): Boolean = a.hash.nonEmpty && b.hash.nonEmpty && sameCompilation(a.compilation, b.compilation) && (a.hash.deep equals b.hash.deep)
def sameCompilation(a: Compilation, b: Compilation): Boolean = a.startTime == b.startTime && a.outputs.corresponds(b.outputs) {
case (co1, co2) => co1.sourceDirectory == co2.sourceDirectory && co1.outputDirectory == co2.outputDirectory
}

View File

@ -54,7 +54,7 @@ private[inc] class MemberRefInvalidator(log: Logger) {
def get[T](memberRef: Relation[File, T], usedNames: Relation[File, String], apiChange: APIChange[_]): T => Set[File] = apiChange match {
case _: APIChangeDueToMacroDefinition[_] =>
new InvalidateUnconditionally(memberRef)
case NamesChange(_, modifiedNames) if !modifiedNames.implicitNames.isEmpty =>
case NamesChange(_, modifiedNames) if modifiedNames.implicitNames.nonEmpty =>
new InvalidateUnconditionally(memberRef)
case NamesChange(modifiedSrcFile, modifiedNames) =>
new NameHashFilteredInvalidator[T](usedNames, memberRef, modifiedNames.regularNames)
@ -65,7 +65,7 @@ private[inc] class MemberRefInvalidator(log: Logger) {
def invalidationReason(apiChange: APIChange[_]): String = apiChange match {
case APIChangeDueToMacroDefinition(modifiedSrcFile) =>
s"The $modifiedSrcFile source file declares a macro."
case NamesChange(modifiedSrcFile, modifiedNames) if !modifiedNames.implicitNames.isEmpty =>
case NamesChange(modifiedSrcFile, modifiedNames) if modifiedNames.implicitNames.nonEmpty =>
s"""|The $modifiedSrcFile source file has the following implicit definitions changed:
|\t${modifiedNames.implicitNames.mkString(", ")}.""".stripMargin
case NamesChange(modifiedSrcFile, modifiedNames) =>
@ -82,7 +82,7 @@ private[inc] class MemberRefInvalidator(log: Logger) {
private class InvalidateUnconditionally[T](memberRef: Relation[File, T]) extends (T => Set[File]) {
def apply(from: T): Set[File] = {
val invalidated = memberRef.reverse(from)
if (!invalidated.isEmpty)
if (invalidated.nonEmpty)
log.debug(s"The following member ref dependencies of $from are invalidated:\n" +
formatInvalidated(invalidated))
invalidated

View File

@ -90,7 +90,7 @@ class AggressiveCompile(cacheFile: File) {
val (javaSrcs, scalaSrcs) = incSrc partition javaOnly
logInputs(log, javaSrcs.size, scalaSrcs.size, outputDirs)
def compileScala() =
if (!scalaSrcs.isEmpty) {
if (scalaSrcs.nonEmpty) {
val sources = if (order == Mixed) incSrc else scalaSrcs
val arguments = cArgs(Nil, absClasspath, None, options.options)
timed("Scala compilation", log) {
@ -98,7 +98,7 @@ class AggressiveCompile(cacheFile: File) {
}
}
def compileJava() =
if (!javaSrcs.isEmpty) {
if (javaSrcs.nonEmpty) {
import Path._
@tailrec def ancestor(f1: File, f2: File): Boolean =
if (f2 eq null) false else if (f1 == f2) true else ancestor(f1, f2.getParentFile)
@ -173,7 +173,7 @@ class AggressiveCompile(cacheFile: File) {
val scalaMsg = Analysis.counted("Scala source", "", "s", scalaCount)
val javaMsg = Analysis.counted("Java source", "", "s", javaCount)
val combined = scalaMsg ++ javaMsg
if (!combined.isEmpty)
if (combined.nonEmpty)
log.info(combined.mkString("Compiling ", " and ", " to " + outputDirs.map(_.getAbsolutePath).mkString(",") + "..."))
}
private def extract(previous: Option[(Analysis, CompileSetup)], incOptions: IncOptions): (Analysis, Option[CompileSetup]) =

View File

@ -141,7 +141,7 @@ private final class CachedCompiler0(args: Array[String], output: Output, initial
final class Compat { def allConditionalWarnings = List[CondWarnCompat]() }
val warnings = run.allConditionalWarnings
if (!warnings.isEmpty)
if (warnings.nonEmpty)
compiler.logUnreportedWarnings(warnings.map(cw => ("" /*cw.what*/ , cw.warnings.toList)))
}

View File

@ -124,7 +124,7 @@ class LoggerReporter(maximumErrors: Int, log: Logger, sourcePositionMapper: Posi
false
else {
val key = new PositionKey(pos)
if (positions.get(key).map(_.ordinal >= severity.ordinal).getOrElse(false))
if (positions.get(key).exists(_.ordinal >= severity.ordinal))
true
else {
positions(key) = severity

View File

@ -30,7 +30,7 @@ object JavaNoPosition extends Position {
}
/** A wrapper around xsbti.Problem with java-specific options. */
final case class JavaProblem(val position: Position, val severity: Severity, val message: String) extends xsbti.Problem {
final case class JavaProblem(position: Position, severity: Severity, message: String) extends xsbti.Problem {
override def category: String = "javac" // TODO - what is this even supposed to be? For now it appears unused.
override def toString = s"$severity @ $position - $message"
}

View File

@ -10,7 +10,7 @@ public final class Modifiers implements java.io.Serializable
private static final int LazyBit = 5;
private static final int MacroBit = 6;
private static final int flag(boolean set, int bit)
private static int flag(boolean set, int bit)
{
return set ? (1 << bit) : 0;
}
@ -30,7 +30,7 @@ public final class Modifiers implements java.io.Serializable
private final byte flags;
private final boolean flag(int bit)
private boolean flag(int bit)
{
return (flags & (1 << bit)) != 0;
}

View File

@ -30,5 +30,5 @@ public enum CompileOrder
* Then, Java sources are passed to the Java compiler, which generates class files for the Java sources.
* The Scala classes compiled in the first step are included on the classpath to the Java compiler.
*/
ScalaThenJava;
ScalaThenJava
}

View File

@ -33,7 +33,7 @@ object ConflictWarning {
}
private[this] def processCrossVersioned(config: ConflictWarning, report: UpdateReport, log: Logger) {
val crossMismatches = crossVersionMismatches(report)
if (!crossMismatches.isEmpty) {
if (crossMismatches.nonEmpty) {
val pre = s"Modules were resolved with conflicting cross-version suffixes in ${config.label}:\n "
val conflictMsgs =
for (((org, rawName), fullNames) <- crossMismatches) yield {

View File

@ -93,7 +93,7 @@ object EvictionPair {
}
else ""
r.module.revision + callers
}).headOption map { " -> " + _ } getOrElse ""
}) map { " -> " + _ } getOrElse ""
Seq(s"\t* ${a.organization}:${a.name}:${revsStr}$winnerRev")
}
}
@ -160,7 +160,7 @@ object EvictionWarning {
pairs foreach {
case p if isScalaArtifact(module, p.organization, p.name) =>
(module.moduleSettings.ivyScala, p.winner) match {
case (Some(s), Some(winner)) if ((s.scalaFullVersion != winner.module.revision) && options.warnScalaVersionEviction) =>
case (Some(s), Some(winner)) if (s.scalaFullVersion != winner.module.revision) && options.warnScalaVersionEviction =>
scalaEvictions += p
case _ =>
}
@ -180,21 +180,21 @@ object EvictionWarning {
implicit val evictionWarningLines: ShowLines[EvictionWarning] = ShowLines { a: EvictionWarning =>
import ShowLines._
val out: mutable.ListBuffer[String] = mutable.ListBuffer()
if (!a.scalaEvictions.isEmpty) {
if (a.scalaEvictions.nonEmpty) {
out += "Scala version was updated by one of library dependencies:"
out ++= (a.scalaEvictions flatMap { _.lines })
out += "To force scalaVersion, add the following:"
out += "\tivyScala := ivyScala.value map { _.copy(overrideScalaVersion = true) }"
}
if (!a.directEvictions.isEmpty || !a.transitiveEvictions.isEmpty) {
if (a.directEvictions.nonEmpty || a.transitiveEvictions.nonEmpty) {
out += "There may be incompatibilities among your library dependencies."
out += "Here are some of the libraries that were evicted:"
out ++= (a.directEvictions flatMap { _.lines })
out ++= (a.transitiveEvictions flatMap { _.lines })
}
if (!a.allEvictions.isEmpty && !a.reportedEvictions.isEmpty && !a.options.showCallers) {
if (a.allEvictions.nonEmpty && a.reportedEvictions.nonEmpty && !a.options.showCallers) {
out += "Run 'evicted' to see detailed eviction warnings"
}

View File

@ -19,7 +19,7 @@ import org.apache.ivy.core.cache.{ CacheMetadataOptions, DefaultRepositoryCacheM
import org.apache.ivy.core.event.EventManager
import org.apache.ivy.core.module.descriptor.{ Artifact => IArtifact, DefaultArtifact, DefaultDependencyArtifactDescriptor, MDArtifact }
import org.apache.ivy.core.module.descriptor.{ DefaultDependencyDescriptor, DefaultModuleDescriptor, DependencyDescriptor, ModuleDescriptor, License }
import org.apache.ivy.core.module.descriptor.{ OverrideDependencyDescriptorMediator }
import org.apache.ivy.core.module.descriptor.OverrideDependencyDescriptorMediator
import org.apache.ivy.core.module.id.{ ArtifactId, ModuleId, ModuleRevisionId }
import org.apache.ivy.core.resolve.{ IvyNode, ResolveData, ResolvedModuleRevision, ResolveEngine }
import org.apache.ivy.core.settings.IvySettings
@ -496,7 +496,7 @@ private[sbt] object IvySbt {
private def hasInfo(module: ModuleID, x: scala.xml.NodeSeq) =
{
val info = <g>{ x }</g> \ "info"
if (!info.isEmpty) {
if (info.nonEmpty) {
def check(found: NodeSeq, expected: String, label: String) =
if (found.isEmpty)
sys.error("Missing " + label + " in inline Ivy XML.")
@ -508,7 +508,7 @@ private[sbt] object IvySbt {
check(info \ "@module", module.name, "name")
check(info \ "@revision", module.revision, "version")
}
!info.isEmpty
info.nonEmpty
}
/** Parses the given in-memory Ivy file 'xml', using the existing 'moduleID' and specifying the given 'defaultConfiguration'. */
private def parseIvyXML(settings: IvySettings, xml: scala.xml.NodeSeq, moduleID: DefaultModuleDescriptor, defaultConfiguration: String, validate: Boolean): CustomXmlParser.CustomParser =
@ -582,7 +582,7 @@ private[sbt] object IvySbt {
for (artifact <- dependency.explicitArtifacts) {
import artifact.{ name, classifier, `type`, extension, url }
val extraMap = extra(artifact)
val ivyArtifact = new DefaultDependencyArtifactDescriptor(dependencyDescriptor, name, `type`, extension, url.getOrElse(null), extraMap)
val ivyArtifact = new DefaultDependencyArtifactDescriptor(dependencyDescriptor, name, `type`, extension, url.orNull, extraMap)
copyConfigurations(artifact, ivyArtifact.addConfiguration)
for (conf <- dependencyDescriptor.getModuleConfigurations)
dependencyDescriptor.addDependencyArtifact(conf, ivyArtifact)

View File

@ -226,7 +226,7 @@ object IvyActions {
{
import config.{ configuration => c, module => mod, _ }
import mod.{ configurations => confs, _ }
assert(!classifiers.isEmpty, "classifiers cannot be empty")
assert(classifiers.nonEmpty, "classifiers cannot be empty")
val baseModules = modules map { m => restrictedCopy(m, true) }
val deps = baseModules.distinct flatMap classifiedArtifacts(classifiers, exclude)
val base = restrictedCopy(id, true).copy(name = id.name + classifiers.mkString("$", "_", ""))
@ -375,16 +375,16 @@ object UnresolvedWarning {
case _ => ""
}
implicit val unresolvedWarningLines: ShowLines[UnresolvedWarning] = ShowLines { a =>
val withExtra = a.resolveException.failed.filter(!_.extraDependencyAttributes.isEmpty)
val withExtra = a.resolveException.failed.filter(_.extraDependencyAttributes.nonEmpty)
val buffer = mutable.ListBuffer[String]()
if (!withExtra.isEmpty) {
if (withExtra.nonEmpty) {
buffer += "\n\tNote: Some unresolved dependencies have extra attributes. Check that these dependencies exist with the requested attributes."
withExtra foreach { id => buffer += "\t\t" + id }
}
if (!a.failedPaths.isEmpty) {
if (a.failedPaths.nonEmpty) {
buffer += "\n\tNote: Unresolved dependencies path:"
a.failedPaths foreach { path =>
if (!path.isEmpty) {
if (path.nonEmpty) {
val head = path.head
buffer += "\t\t" + head._1.toString + sourcePosStr(head._2)
path.tail foreach {

View File

@ -258,7 +258,7 @@ class MakePom(val log: Logger) {
@deprecated("No longer used and will be removed.", "0.12.1")
def classifier(dependency: DependencyDescriptor, includeTypes: Set[String]): NodeSeq =
{
val jarDep = dependency.getAllDependencyArtifacts.filter(d => includeTypes(d.getType)).headOption
val jarDep = dependency.getAllDependencyArtifacts.find(d => includeTypes(d.getType))
jarDep match {
case Some(a) => classifierElem(artifactClassifier(a))
case None => NodeSeq.Empty
@ -298,15 +298,15 @@ class MakePom(val log: Logger) {
val (opt, notOptional) = confs.partition(_ == Optional.name)
val defaultNotOptional = Configurations.defaultMavenConfigurations.find(notOptional contains _.name)
val scope = defaultNotOptional.map(_.name)
(scope, !opt.isEmpty)
(scope, opt.nonEmpty)
}
def exclusions(dependency: DependencyDescriptor): NodeSeq =
{
val excl = dependency.getExcludeRules(dependency.getModuleConfigurations)
val (warns, excls) = IvyUtil.separate(excl.map(makeExclusion))
if (!warns.isEmpty) log.warn(warns.mkString(IO.Newline))
if (!excls.isEmpty) <exclusions>{ excls }</exclusions>
if (warns.nonEmpty) log.warn(warns.mkString(IO.Newline))
if (excls.nonEmpty) <exclusions>{ excls }</exclusions>
else NodeSeq.Empty
}
def makeExclusion(exclRule: ExcludeRule): Either[String, NodeSeq] =

View File

@ -52,7 +52,7 @@ private[sbt] final class ResolutionCache(base: File, settings: IvySettings) exte
throw new IllegalStateException("Ivy file not found in cache for " + mrid + "!")
}
return XmlModuleDescriptorParser.getInstance().parseDescriptor(settings, ivyFile.toURI().toURL(), false)
XmlModuleDescriptorParser.getInstance().parseDescriptor(settings, ivyFile.toURI.toURL, false)
}
def saveResolvedModuleDescriptor(md: ModuleDescriptor): Unit = {

View File

@ -97,7 +97,7 @@ object VersionNumber {
case (0L, _, _, _, 0L, _, _, _) =>
// Major version zero (0.y.z) is for initial development. Anything may change at any time. The public API should not be considered stable.
equalsIgnoreExtra(v1, v2)
case (_, 0, 0, ts1, _, 0, 0, ts2) if (!ts1.isEmpty) || (!ts2.isEmpty) =>
case (_, 0, 0, ts1, _, 0, 0, ts2) if ts1.nonEmpty || ts2.nonEmpty =>
// A pre-release version MAY be denoted by appending a hyphen and a series of dot separated identifiers
equalsIgnoreExtra(v1, v2)
case (x1, _, _, _, x2, _, _, _) =>
@ -125,7 +125,7 @@ object VersionNumber {
(v1, v2) match {
case (v1, v2) if (v1.size >= 3) && (v2.size >= 3) => // A normal version number MUST take the form X.Y.Z
(v1._1.get, v1._2.get, v1._3.get, v1.tags, v2._1.get, v2._2.get, v2._3.get, v2.tags) match {
case (x1, y1, 0, ts1, x2, y2, 0, ts2) if (!ts1.isEmpty) || (!ts2.isEmpty) =>
case (x1, y1, 0, ts1, x2, y2, 0, ts2) if ts1.nonEmpty || ts2.nonEmpty =>
// A pre-release version MAY be denoted by appending a hyphen and a series of dot separated identifiers
equalsIgnoreExtra(v1, v2)
case (x1, y1, _, _, x2, y2, _, _) =>

View File

@ -67,7 +67,7 @@ private[sbt] class CachedResolutionResolveCache() {
// direct dependencies of an internal dependency
val directs0 = directDependencies(internal)
val directs = directs0 filter { dd =>
allConfigurations exists { conf => !dd.getDependencyConfigurations(conf).isEmpty }
allConfigurations exists { conf => dd.getDependencyConfigurations(conf).nonEmpty }
}
directs flatMap { dd => expandInternalDeps(dd, next) }
case _ =>

View File

@ -92,7 +92,7 @@ private[sbt] final class ErrorMessageAuthenticator(original: Option[Authenticato
// TODO - levenshtein distance "did you mean" message.
Message.error(s"Unable to find credentials for [${getRequestingPrompt} @ ${host}].")
val configuredRealms = IvyCredentialsLookup.realmsForHost.getOrElse(host, Set.empty)
if (!configuredRealms.isEmpty) {
if (configuredRealms.nonEmpty) {
Message.error(s" Is one of these realms mispelled for host [${host}]:")
configuredRealms foreach { realm =>
Message.error(s" * ${realm}")
@ -116,7 +116,7 @@ private[sbt] final class ErrorMessageAuthenticator(original: Option[Authenticato
getRequestingScheme))
finally Authenticator.setDefault(this)
}
originalAuthentication.getOrElse(null)
originalAuthentication.orNull
}
/**

View File

@ -2,5 +2,5 @@ package xsbti;
public enum CrossValue
{
Disabled, Full, Binary;
Disabled, Full, Binary
}

View File

@ -2,5 +2,5 @@ package xsbti;
enum Manage
{
Nop, Clean, Refresh;
Nop, Clean, Refresh
}

View File

@ -31,7 +31,7 @@ object Initialize {
val properties = readProperties(file)
val uninitialized =
for (property <- appProperties; init <- select(property) if properties.getProperty(property.name) == null) yield initialize(properties, property.name, init)
if (!uninitialized.isEmpty) writeProperties(properties, file, "")
if (uninitialized.nonEmpty) writeProperties(properties, file, "")
}
def initialize(properties: Properties, name: String, init: PropertyInit) {
init match {

View File

@ -24,7 +24,7 @@ object Launch {
case PropertiesFile => parseAndInitializeConfig(configLocation, currentDirectory)
}
if (arguments.isLocate) {
if (!newArgs2.isEmpty) {
if (newArgs2.nonEmpty) {
// TODO - Print the arguments without exploding proguard size.
System.err.println("Warning: --locate option ignores arguments.")
}

View File

@ -13,7 +13,7 @@ object ResolveValues {
private def notEmpty(s: String) = if (isEmpty(s)) None else Some(s)
}
import ResolveValues.{ trim }
import ResolveValues.trim
final class ResolveValues(conf: LaunchConfiguration) {
private def propertiesFile = conf.boot.properties
private lazy val properties = readProperties(propertiesFile)

View File

@ -63,7 +63,7 @@ object Sync {
case (target, srcs) =>
"\n\t" + target + "\nfrom\n\t" + srcs.mkString("\n\t\t")
}
if (!dups.isEmpty)
if (dups.nonEmpty)
sys.error("Duplicate mappings:" + dups.mkString)
}

View File

@ -142,7 +142,7 @@ object TestResultLogger {
}
def show(label: String, level: Level.Value, tests: Iterable[String]): Unit =
if (!tests.isEmpty) {
if (tests.nonEmpty) {
log.log(level, label)
log.log(level, tests.mkString("\t", "\n\t", ""))
}

View File

@ -133,7 +133,7 @@ object Tests {
for (option <- config.options) {
option match {
case Filter(include) => testFilters += include
case Filters(includes) => if (!orderedFilters.isEmpty) sys.error("Cannot define multiple ordered test filters.") else orderedFilters = includes
case Filters(includes) => if (orderedFilters.nonEmpty) sys.error("Cannot define multiple ordered test filters.") else orderedFilters = includes
case Exclude(exclude) => excludeTestsSet ++= exclude
case Listeners(listeners) => testListeners ++= listeners
case Setup(setupFunction) => setup += setupFunction

View File

@ -39,7 +39,7 @@ object EvalTest extends Properties("eval") {
val v = value(result).asInstanceOf[{ def i: Int }].i
(label("Value", v) |: (v == i)) &&
(label("Type", result.tpe) |: (result.tpe == LocalType)) &&
(label("Files", result.generated) |: (!result.generated.isEmpty))
(label("Files", result.generated) |: result.generated.nonEmpty)
}
}
@ -79,7 +79,7 @@ val p = {
private[this] def hasErrors(line: Int, src: String) =
{
val is = reporter.infos
("Has errors" |: (!is.isEmpty)) &&
("Has errors" |: is.nonEmpty) &&
all(is.toSeq.map(validPosition(line, src)): _*)
}
private[this] def validPosition(line: Int, src: String)(i: Info) =

View File

@ -172,7 +172,7 @@ object Act {
def extrasParser(knownKeys: Map[String, AttributeKey[_]], knownValues: IMap[AttributeKey, Set]): Parser[AttributeMap] =
{
val validKeys = knownKeys.filter { case (_, key) => knownValues get key exists (!_.isEmpty) }
val validKeys = knownKeys.filter { case (_, key) => knownValues get key exists (_.nonEmpty) }
if (validKeys.isEmpty)
failure("No valid extra keys.")
else

View File

@ -151,7 +151,7 @@ final object Aggregation {
base.map { res =>
() =>
val newState = res()
if (show.settingValues && !settings.isEmpty) printSettings(settings, show.print)
if (show.settingValues && settings.nonEmpty) printSettings(settings, show.print)
newState
}
}

View File

@ -10,15 +10,15 @@ import Alternatives._
import Types.{ const, idFun }
final class MultiHandler[S, T](builtIn: S => Option[T], root: Option[S => Option[T]], nonRoots: List[(URI, S => Option[T])], getURI: S => URI, log: S => Logger) {
def applyFun: S => Option[T] = apply _
def applyFun: S => Option[T] = apply
def apply(info: S): Option[T] =
(baseLoader(info), applyNonRoots(info)) match {
case (None, Nil) => None
case (None, xs @ (_, nr) :: ignored) =>
if (!ignored.isEmpty) warn("Using first of multiple matching non-root build resolvers for " + getURI(info), log(info), xs)
if (ignored.nonEmpty) warn("Using first of multiple matching non-root build resolvers for " + getURI(info), log(info), xs)
Some(nr)
case (Some(b), xs) =>
if (!xs.isEmpty) warn("Ignoring shadowed non-root build resolver(s) for " + getURI(info), log(info), xs)
if (xs.nonEmpty) warn("Ignoring shadowed non-root build resolver(s) for " + getURI(info), log(info), xs)
Some(b)
}

View File

@ -38,7 +38,7 @@ final class StructureIndex(
* The first root project is used as the default in several situations where a project is not otherwise selected.
*/
final class LoadedBuildUnit(val unit: BuildUnit, val defined: Map[String, ResolvedProject], val rootProjects: Seq[String], val buildSettings: Seq[Setting[_]]) extends BuildUnitBase {
assert(!rootProjects.isEmpty, "No root projects defined for build unit " + unit)
assert(rootProjects.nonEmpty, "No root projects defined for build unit " + unit)
/**
* The project to use as the default when one is not otherwise selected.
* [[LocalRootProject]] resolves to this from within the same build.
@ -112,7 +112,7 @@ final class DetectedModules[T](val modules: Seq[(String, T)]) {
}
/** Auto-detected auto plugin. */
case class DetectedAutoPlugin(val name: String, val value: AutoPlugin, val hasAutoImport: Boolean)
case class DetectedAutoPlugin(name: String, value: AutoPlugin, hasAutoImport: Boolean)
/**
* Auto-discovered modules for the build definition project. These include modules defined in build definition sources

View File

@ -27,7 +27,7 @@ object Cross {
val optionalCommand = token(Space ~> matched(state.combinedParser)) ?? ""
spacedVersion ~ optionalCommand
}
token(SwitchCommand ~> OptSpace) flatMap { sp => versionAndCommand(!sp.isEmpty) }
token(SwitchCommand ~> OptSpace) flatMap { sp => versionAndCommand(sp.nonEmpty) }
}
def spacedFirst(name: String) = opOrIDSpaced(name) ~ any.+

View File

@ -215,7 +215,7 @@ object EvaluateConfigurations {
/** Configures the use of the old sbt parser. */
private[sbt] def useOldParser: Boolean =
sys.props.get("sbt.parser.simple").map(java.lang.Boolean.parseBoolean).getOrElse(false)
sys.props.get("sbt.parser.simple").exists(java.lang.Boolean.parseBoolean)
/**
* Splits a set of lines into (imports, expressions). That is,
* anything on the right of the tuple is a scala expression (definition or setting).

View File

@ -256,12 +256,12 @@ object Load {
// the files aren't properly returned, even though they should be.
// TODO - figure out where the caching of whether or not to generate classfiles occurs, and
// put cleanups there, perhaps.
if (!keepSet.isEmpty) {
if (keepSet.nonEmpty) {
def keepFile(f: File) = keepSet(f.getCanonicalPath)
import Path._
val existing = (baseTarget.***.get).filterNot(_.isDirectory)
val toDelete = existing.filterNot(keepFile)
if (!toDelete.isEmpty) {
if (toDelete.nonEmpty) {
IO.delete(toDelete)
}
}
@ -711,11 +711,11 @@ object Load {
// How to merge SbtFiles we read into one thing
def merge(ls: Seq[LoadedSbtFile]): LoadedSbtFile = (LoadedSbtFile.empty /: ls) { _ merge _ }
// Loads a given file, or pulls from the cache.
def memoLoadSettingsFile(src: File): LoadedSbtFile = memoSettings.get(src) getOrElse {
def memoLoadSettingsFile(src: File): LoadedSbtFile = memoSettings.getOrElse(src, {
val lf = loadSettingsFile(src)
memoSettings.put(src, lf.clearProjects) // don't load projects twice
lf
}
})
// Loads a set of sbt files, sorted by their lexical name (current behavior of sbt).
def loadFiles(fs: Seq[File]): LoadedSbtFile =
merge(fs.sortBy(_.getName).map(memoLoadSettingsFile))
@ -777,7 +777,7 @@ object Load {
def hasDefinition(dir: File) =
{
import Path._
!(dir * -GlobFilter(DefaultTargetName)).get.isEmpty
(dir * -GlobFilter(DefaultTargetName)).get.nonEmpty
}
def noPlugins(dir: File, config: sbt.LoadBuildConfiguration): sbt.LoadedPlugins =
loadPluginDefinition(dir, config, PluginData(config.globalPluginClasspath, None, None))

View File

@ -139,7 +139,7 @@ object Plugins extends PluginsFunctions {
// TODO: defined should return all the plugins
val allReqs = (defined0 flatMap { asRequirements }).toSet
val diff = allReqs diff defined0.toSet
val defined = if (!diff.isEmpty) diff.toList ::: defined0
val defined = if (diff.nonEmpty) diff.toList ::: defined0
else defined0
val byAtom = defined map { x => (Atom(x.label), x) }
@ -170,7 +170,7 @@ object Plugins extends PluginsFunctions {
}
val forbidden: Set[AutoPlugin] = (selectedPlugins flatMap { Plugins.asExclusions }).toSet
val c = selectedPlugins.toSet & forbidden
if (!c.isEmpty) {
if (c.nonEmpty) {
exlusionConflictError(requestedPlugins, selectedPlugins, c.toSeq sortBy {_.label})
}
val retval = topologicalSort(selectedPlugins, log)
@ -217,12 +217,12 @@ object Plugins extends PluginsFunctions {
else Nil) ++
{
val reqs = selected filter { x => asRequirements(x) contains c }
if (!reqs.isEmpty) List(s"""required by ${reqs.mkString(", ")}""")
if (reqs.nonEmpty) List(s"""required by ${reqs.mkString(", ")}""")
else Nil
} ++
{
val exs = selected filter { x => asExclusions(x) contains c }
if (!exs.isEmpty) List(s"""excluded by ${exs.mkString(", ")}""")
if (exs.nonEmpty) List(s"""excluded by ${exs.mkString(", ")}""")
else Nil
}
s""" - conflict: ${c.label} is ${reasons.mkString("; ")}"""

View File

@ -126,7 +126,7 @@ object SessionSettings {
/** Checks to see if any session settings are being discarded and issues a warning. */
def checkSession(newSession: SessionSettings, oldState: State) {
val oldSettings = (oldState get Keys.sessionSettings).toList.flatMap(_.append).flatMap(_._2)
if (newSession.append.isEmpty && !oldSettings.isEmpty)
if (newSession.append.isEmpty && oldSettings.nonEmpty)
oldState.log.warn("Discarding " + pluralize(oldSettings.size, " session setting") + ". Use 'session save' to persist session settings.")
}
@ -167,7 +167,7 @@ object SessionSettings {
def saveSomeSettings(s: State)(include: ProjectRef => Boolean): State =
withSettings(s) { session =>
val newSettings =
for ((ref, settings) <- session.append if !settings.isEmpty && include(ref)) yield {
for ((ref, settings) <- session.append if settings.nonEmpty && include(ref)) yield {
val (news, olds) = writeSettings(ref, settings.toList, session.original, Project.structure(s))
(ref -> news, olds)
}
@ -206,7 +206,7 @@ object SessionSettings {
val newSettings = settings diff replace
val oldContent = IO.readLines(writeTo)
val (_, exist) = SbtRefactorings.applySessionSettings((writeTo, oldContent), replace)
val adjusted = if (!newSettings.isEmpty && needsTrailingBlank(exist)) exist :+ "" else exist
val adjusted = if (newSettings.nonEmpty && needsTrailingBlank(exist)) exist :+ "" else exist
val lines = adjusted ++ newSettings.flatMap(x => x._2 :+ "")
IO.writeLines(writeTo, lines)
val (newWithPos, _) = ((List[SessionSetting](), adjusted.size + 1) /: newSettings) {
@ -218,12 +218,12 @@ object SessionSettings {
}
@deprecated("This method will no longer be public", "0.13.7")
def needsTrailingBlank(lines: Seq[String]) = !lines.isEmpty && !lines.takeRight(1).exists(_.trim.isEmpty)
def needsTrailingBlank(lines: Seq[String]) = lines.nonEmpty && !lines.takeRight(1).exists(_.trim.isEmpty)
/** Prints all the user-defined SessionSettings (not raw) to System.out. */
def printAllSettings(s: State): State =
withSettings(s) { session =>
for ((ref, settings) <- session.append if !settings.isEmpty) {
for ((ref, settings) <- session.append if settings.nonEmpty) {
println("In " + Reference.display(ref))
printSettings(settings)
}

View File

@ -11,14 +11,14 @@ import Prop._
import Gen._
object Delegates extends Properties("delegates") {
property("generate non-empty configs") = forAll { (c: Seq[Config]) => !c.isEmpty }
property("generate non-empty tasks") = forAll { (t: Seq[Taskk]) => !t.isEmpty }
property("generate non-empty configs") = forAll { (c: Seq[Config]) => c.nonEmpty }
property("generate non-empty tasks") = forAll { (t: Seq[Taskk]) => t.nonEmpty }
property("no duplicate scopes") = forAll { (keys: Keys) =>
allDelegates(keys) { (_, ds) => ds.distinct.size == ds.size }
}
property("delegates non-empty") = forAll { (keys: Keys) =>
allDelegates(keys) { (_, ds) => !ds.isEmpty }
allDelegates(keys) { (_, ds) => ds.nonEmpty }
}
property("An initially Global axis is Global in all delegates") = allAxes(alwaysGlobal)

View File

@ -1,7 +1,7 @@
package sbt
import org.scalacheck._
import Gen.{ listOf }
import Gen.listOf
import Prop._
import Tags._

View File

@ -1,6 +1,6 @@
import sbt._
import Keys._
import Status.{ publishStatus }
import Status.publishStatus
import org.apache.ivy.util.url.CredentialsStore
import com.typesafe.sbt.JavaVersionCheckPlugin.autoImport._

View File

@ -18,7 +18,7 @@ object Transform {
def conscriptSettings(launch: Reference) = Seq(
conscriptConfigs <<= (managedResources in launch in Compile, sourceDirectory in Compile).map { (res, src) =>
val source = res.filter(_.getName == "sbt.boot.properties").headOption getOrElse sys.error("No managed boot.properties file.")
val source = res.find(_.getName == "sbt.boot.properties") getOrElse sys.error("No managed boot.properties file.")
copyConscriptProperties(source, src / "conscript")
()
}

View File

@ -124,12 +124,12 @@ object Util {
def cleanPom(pomNode: scala.xml.Node) =
{
import scala.xml._
def cleanNodes(nodes: Seq[Node]): Seq[Node] = nodes flatMap (_ match {
case elem @ Elem(prefix, "dependency", attributes, scope, children @ _*) if excludePomDependency(elem) =>
def cleanNodes(nodes: Seq[Node]): Seq[Node] = nodes flatMap ({
case elem@Elem(prefix, "dependency", attributes, scope, children@_*) if excludePomDependency(elem) =>
NodeSeq.Empty
case Elem(prefix, "classifier", attributes, scope, children @ _*) =>
case Elem(prefix, "classifier", attributes, scope, children@_*) =>
NodeSeq.Empty
case Elem(prefix, label, attributes, scope, children @ _*) =>
case Elem(prefix, label, attributes, scope, children@_*) =>
Elem(prefix, label, attributes, scope, cleanNodes(children): _*).theSeq
case other => other
})

View File

@ -50,9 +50,9 @@ class Run(instance: ScalaInstance, trapExit: Boolean, nativeTmp: File) extends S
def execute() =
try { run0(mainClass, classpath, options, log) }
catch { case e: java.lang.reflect.InvocationTargetException => throw e.getCause }
def directExecute() = try { execute; None } catch { case e: Exception => log.trace(e); Some(e.toString) }
def directExecute() = try { execute(); None } catch { case e: Exception => log.trace(e); Some(e.toString) }
if (trapExit) Run.executeTrapExit(execute, log) else directExecute
if (trapExit) Run.executeTrapExit(execute(), log) else directExecute()
}
private def run0(mainClassName: String, classpath: Seq[File], options: Seq[String], log: Logger) {
log.debug(" Classpath:\n\t" + classpath.mkString("\n\t"))
@ -62,9 +62,9 @@ class Run(instance: ScalaInstance, trapExit: Boolean, nativeTmp: File) extends S
}
private def invokeMain(loader: ClassLoader, main: Method, options: Seq[String]) {
val currentThread = Thread.currentThread
val oldLoader = Thread.currentThread.getContextClassLoader()
val oldLoader = Thread.currentThread.getContextClassLoader
currentThread.setContextClassLoader(loader)
try { main.invoke(null, options.toArray[String].asInstanceOf[Array[String]]) }
try { main.invoke(null, options.toArray[String]) }
finally { currentThread.setContextClassLoader(oldLoader) }
}
def getMainMethod(mainClassName: String, loader: ClassLoader) =

View File

@ -38,5 +38,5 @@ object InfoTest extends Build
} else
if( deliveredWithCustom(d) ) sys.error("Expected empty 'info' tag, got: \n" + (d \ "info")) else ()
}
def deliveredWithCustom(d: NodeSeq) = !(d \ "info" \ "license").isEmpty && !(d \ "info" \ "description").isEmpty
def deliveredWithCustom(d: NodeSeq) = (d \ "info" \ "license").nonEmpty && (d \ "info" \ "description").nonEmpty
}

View File

@ -4,7 +4,7 @@ ivyPaths <<= baseDirectory( dir => new IvyPaths(dir, Some(dir / "ivy-home")))
TaskKey[Unit]("check") <<= update map { report =>
val files = report.matching( moduleFilter(organization = "org.scalacheck", name = "scalacheck", revision = "1.5") )
assert(!files.isEmpty, "ScalaCheck module not found in update report")
assert(files.nonEmpty, "ScalaCheck module not found in update report")
val missing = files.filter(! _.exists)
assert(missing.isEmpty, "Reported ScalaCheck artifact files don't exist: " + missing.mkString(", "))
}

View File

@ -2,5 +2,5 @@ seq(externalIvySettings(), externalIvyFile())
TaskKey[Unit]("check") := {
val files = update.value.matching( moduleFilter(organization = "org.scalacheck", name = "scalacheck*", revision = "1.9") )
assert(!files.isEmpty, "ScalaCheck module not found in update report")
assert(files.nonEmpty, "ScalaCheck module not found in update report")
}

View File

@ -4,5 +4,5 @@ libraryDependencies += "org.scalacheck" % "scalacheck" % "1.5"
TaskKey[Unit]("check") <<= (baseDirectory, update) map { (base, report) =>
val files = report.matching( moduleFilter(organization = "org.scalacheck", name = "scalacheck", revision = "1.5") )
assert(!files.isEmpty, "ScalaCheck module not found in update report")
assert(files.nonEmpty, "ScalaCheck module not found in update report")
}

View File

@ -8,6 +8,6 @@ checkPom := {
val pomFile = makePom.value
val pom = xml.XML.loadFile(pomFile)
val tpe = pom \\ "type"
if(!tpe.isEmpty)
if(tpe.nonEmpty)
error("Expected no <type> sections, got: " + tpe + " in \n\n" + pom)
}

View File

@ -26,6 +26,6 @@ object Test extends Build
def checkBinaries(report: UpdateReport): Unit =
{
val srcs = getSources(report)
if(!srcs.isEmpty) sys.error("Sources retrieved:\n\t" + srcs.mkString("\n\t")) else ()
if(srcs.nonEmpty) sys.error("Sources retrieved:\n\t" + srcs.mkString("\n\t")) else ()
}
}

View File

@ -4,5 +4,5 @@ val root = Project("root", file("."), settings=Defaults.defaultSettings)
TaskKey[Unit]("checkArtifacts", "test") := {
val arts = packagedArtifacts.value
assert(!arts.isEmpty, "Packaged artifacts must not be empty!")
assert(arts.nonEmpty, "Packaged artifacts must not be empty!")
}

View File

@ -30,7 +30,7 @@ private object TestScriptParser {
import TestScriptParser._
class TestScriptParser(handlers: Map[Char, StatementHandler]) extends RegexParsers {
require(!handlers.isEmpty)
require(handlers.nonEmpty)
override def skipWhitespace = false
import IO.read

View File

@ -156,7 +156,7 @@ private[test] final class ListTests(baseDirectory: File, accept: ScriptedTest =>
val (included, skipped) = allTests.toList.partition(test => accept(ScriptedTest(groupName, test.getName)))
if (included.isEmpty)
log.warn("Test group " + groupName + " skipped.")
else if (!skipped.isEmpty) {
else if (skipped.nonEmpty) {
log.warn("Tests skipped in group " + group.getName + ":")
skipped.foreach(testName => log.warn(" " + testName.getName))
}

View File

@ -73,7 +73,7 @@ private[sbt] final class Execute[A[_] <: AnyRef](config: Config, triggers: Trigg
def processAll()(implicit strategy: Strategy) {
@tailrec def next() {
pre {
assert(!reverse.isEmpty, "Nothing to process.")
assert(reverse.nonEmpty, "Nothing to process.")
if (!state.values.exists(_ == Running)) {
snapshotCycleCheck()
assert(false, "Internal task engine error: nothing running. This usually indicates a cycle in tasks.\n Calling tasks (internal task engine state):\n" + dumpCalling)
@ -81,7 +81,7 @@ private[sbt] final class Execute[A[_] <: AnyRef](config: Config, triggers: Trigg
}
(strategy.take()).process()
if (!reverse.isEmpty) next()
if (reverse.nonEmpty) next()
}
next()

View File

@ -27,7 +27,7 @@ object TaskRunnerForkTest extends Properties("TaskRunner Fork") {
tryRun(List.range(0, a).map(inner).join, false, workers)
}
property("fork and reduce") = forAll(TaskListGen, MaxWorkersGen) { (m: List[Int], workers: Int) =>
(!m.isEmpty) ==> {
m.nonEmpty ==> {
val expected = m.reduceLeft(_ + _)
checkResult(tryRun(m.tasks.reduced(_ + _), false, workers), expected)
}

View File

@ -132,7 +132,7 @@ public class ForkMain {
private static class Run {
void run(ObjectInputStream is, ObjectOutputStream os) throws Exception {
void run(ObjectInputStream is, ObjectOutputStream os) {
try {
runTests(is, os);
} catch (RunAborted e) {

View File

@ -4,6 +4,6 @@
package sbt;
public enum ForkTags {
Error, Warn, Info, Debug, Done;
Error, Warn, Info, Debug, Done
}

View File

@ -1,7 +1,7 @@
package sbt
import java.io.{ IOException, StringWriter, PrintWriter, File }
import java.net.{ InetAddress }
import java.net.InetAddress
import scala.collection.mutable.ListBuffer
import scala.util.DynamicVariable

View File

@ -22,7 +22,7 @@ object TestFrameworks {
val JUnit = new TestFramework("com.novocode.junit.JUnitFramework")
}
case class TestFramework(val implClassNames: String*) {
case class TestFramework(implClassNames: String*) {
@tailrec
private def createFramework(loader: ClassLoader, log: Logger, frameworkClassNames: List[String]): Option[Framework] = {
frameworkClassNames match {
@ -150,7 +150,7 @@ object TestFramework {
for (framework <- frameworks.find(isTestForFramework))
map.getOrElseUpdate(framework, new HashSet[TestDefinition]) += test
}
if (!frameworks.isEmpty)
if (frameworks.nonEmpty)
for (test <- tests) assignTest(test)
map.toMap.mapValues(_.toSet)
}

View File

@ -46,7 +46,7 @@ object AList {
def traverse[M[_], N[_], P[_]](s: List[M[T]], f: M ~> (N P)#l)(implicit np: Applicative[N]): N[List[P[T]]] = ???
}
/** AList for the abitrary arity data structure KList. */
/** AList for the arbitrary arity data structure KList. */
def klist[KL[M[_]] <: KList[M] { type Transform[N[_]] = KL[N] }]: AList[KL] = new AList[KL] {
def transform[M[_], N[_]](k: KL[M], f: M ~> N) = k.transform(f)
def foldr[M[_], T](k: KL[M], f: (M[_], T) => T, init: T): T = k.foldr(f, init)

View File

@ -24,14 +24,14 @@ private final class Settings0[Scope](val data: Map[Scope, AttributeMap], val del
def get[T](scope: Scope, key: AttributeKey[T]): Option[T] =
delegates(scope).toStream.flatMap(sc => getDirect(sc, key)).headOption
def definingScope(scope: Scope, key: AttributeKey[_]): Option[Scope] =
delegates(scope).toStream.filter(sc => getDirect(sc, key).isDefined).headOption
delegates(scope).toStream.find(sc => getDirect(sc, key).isDefined)
def getDirect[T](scope: Scope, key: AttributeKey[T]): Option[T] =
(data get scope).flatMap(_ get key)
def set[T](scope: Scope, key: AttributeKey[T], value: T): Settings[Scope] =
{
val map = (data get scope) getOrElse AttributeMap.empty
val map = data getOrElse(scope, AttributeMap.empty)
val newData = data.updated(scope, map.put(key, value))
new Settings0(newData, delegates)
}
@ -85,7 +85,7 @@ trait Init[Scope] {
*/
private[sbt] final def validated[T](key: ScopedKey[T], selfRefOk: Boolean): ValidationCapture[T] = new ValidationCapture(key, selfRefOk)
@deprecated("0.13.7", "Use the version with default arguments and default paramter.")
@deprecated("0.13.7", "Use the version with default arguments and default parameter.")
final def derive[T](s: Setting[T], allowDynamic: Boolean, filter: Scope => Boolean, trigger: AttributeKey[_] => Boolean): Setting[T] =
derive(s, allowDynamic, filter, trigger, false)
/**
@ -258,7 +258,7 @@ trait Init[Scope] {
def Undefined(defining: Setting[_], referencedKey: ScopedKey[_]): Undefined = new Undefined(defining, referencedKey)
def Uninitialized(validKeys: Seq[ScopedKey[_]], delegates: Scope => Seq[Scope], keys: Seq[Undefined], runtime: Boolean)(implicit display: Show[ScopedKey[_]]): Uninitialized =
{
assert(!keys.isEmpty)
assert(keys.nonEmpty)
val suffix = if (keys.length > 1) "s" else ""
val prefix = if (runtime) "Runtime reference" else "Reference"
val keysString = keys.map(u => showUndefined(u, validKeys, delegates)).mkString("\n\n ", "\n\n ", "")
@ -487,7 +487,7 @@ trait Init[Scope] {
override def default(_id: => Long): DefaultSetting[T] = new DerivedSetting[T](sk, i, p, filter, trigger) with DefaultSetting[T] { val id = _id }
override def toString = "derived " + super.toString
}
// Only keep the first occurence of this setting and move it to the front so that it has lower precedence than non-defaults.
// Only keep the first occurrence of this setting and move it to the front so that it has lower precedence than non-defaults.
// This is intended for internal sbt use only, where alternatives like Plugin.globalSettings are not available.
private[Init] sealed trait DefaultSetting[T] extends Setting[T] {
val id: Long

View File

@ -42,10 +42,10 @@ object SettingsTest extends Properties("settings") {
{
val genScopedKeys = {
// We wan
// t to generate lists of keys that DO NOT inclue the "ch" key we use to check thigns.
// t to generate lists of keys that DO NOT inclue the "ch" key we use to check things.
val attrKeys = mkAttrKeys[Int](nr).filter(_.forall(_.label != "ch"))
attrKeys map (_ map (ak => ScopedKey(Scope(0), ak)))
}.label("scopedKeys").filter(!_.isEmpty)
}.label("scopedKeys").filter(_.nonEmpty)
forAll(genScopedKeys) { scopedKeys =>
try {
// Note; It's evil to grab last IF you haven't verified the set can't be empty.

View File

@ -187,7 +187,7 @@ object Parser extends ParserMain {
@deprecated("This method is deprecated and will be removed in the next major version. Use the parser directly to check for invalid completions.", since = "0.13.2")
def checkMatches(a: Parser[_], completions: Seq[String]) {
val bad = completions.filter(apply(a)(_).resultEmpty.isFailure)
if (!bad.isEmpty) sys.error("Invalid example completions: " + bad.mkString("'", "', '", "'"))
if (bad.nonEmpty) sys.error("Invalid example completions: " + bad.mkString("'", "', '", "'"))
}
def tuple[A, B](a: Option[A], b: Option[B]): Option[(A, B)] =
@ -378,7 +378,7 @@ trait ParserMain {
def unapply[A, B](t: (A, B)): Some[(A, B)] = Some(t)
}
/** Parses input `str` using `parser`. If successful, the result is provided wrapped in `Right`. If unsuccesful, an error message is provided in `Left`.*/
/** Parses input `str` using `parser`. If successful, the result is provided wrapped in `Right`. If unsuccessful, an error message is provided in `Left`.*/
def parse[T](str: String, parser: Parser[T]): Either[String, T] =
Parser.result(parser, str).left.map { failures =>
val (msgs, pos) = failures()
@ -480,7 +480,7 @@ trait ParserMain {
def matched(t: Parser[_], seen: Vector[Char] = Vector.empty, partial: Boolean = false): Parser[String] =
t match {
case i: Invalid => if (partial && !seen.isEmpty) success(seen.mkString) else i
case i: Invalid => if (partial && seen.nonEmpty) success(seen.mkString) else i
case _ =>
if (t.result.isEmpty)
new MatchedString(t, seen, partial)
@ -634,7 +634,7 @@ private final class HetParser[A, B](a: Parser[A], b: Parser[B]) extends ValidPar
override def toString = "(" + a + " || " + b + ")"
}
private final class ParserSeq[T](a: Seq[Parser[T]], errors: => Seq[String]) extends ValidParser[Seq[T]] {
assert(!a.isEmpty)
assert(a.nonEmpty)
lazy val resultEmpty: Result[Seq[T]] =
{
val res = a.map(_.resultEmpty)

View File

@ -92,14 +92,14 @@ trait Mapper {
import Alternatives._
/**
* Selects all descendents of `base` directory and maps them to a path relative to `base`.
* Selects all descendants of `base` directory and maps them to a path relative to `base`.
* `base` itself is not included.
*/
def allSubpaths(base: File): Traversable[(File, String)] =
selectSubpaths(base, AllPassFilter)
/**
* Selects descendents of `base` directory matching `filter` and maps them to a path relative to `base`.
* Selects descendants of `base` directory matching `filter` and maps them to a path relative to `base`.
* `base` itself is not included.
*/
def selectSubpaths(base: File, filter: FileFilter): Traversable[(File, String)] =

View File

@ -277,7 +277,7 @@ object Logic {
}
/** Represents the set of atoms in the heads of clauses and in the bodies (formulas) of clauses. */
final case class Atoms(val inHead: Set[Atom], val inFormula: Set[Atom]) {
final case class Atoms(inHead: Set[Atom], inFormula: Set[Atom]) {
/** Concatenates this with `as`. */
def ++(as: Atoms): Atoms = Atoms(inHead ++ as.inHead, inFormula ++ as.inFormula)
/** Atoms that cannot be true because they do not occur in a head. */

View File

@ -34,7 +34,7 @@ object Process extends ProcessExtra {
/** create ProcessBuilder with working dir set to File and extra environment variables */
def apply(command: Seq[String], cwd: File, extraEnv: (String, String)*): ProcessBuilder =
apply(command, Some(cwd), extraEnv: _*)
/** create ProcessBuilder with working dir optionaly set to File and extra environment variables */
/** create ProcessBuilder with working dir optionally set to File and extra environment variables */
def apply(command: String, cwd: Option[File], extraEnv: (String, String)*): ProcessBuilder = {
apply(command.split("""\s+"""), cwd, extraEnv: _*)
// not smart to use this on windows, because CommandParser uses \ to escape ".
@ -43,7 +43,7 @@ object Process extends ProcessExtra {
case Right((cmd, args)) => apply(cmd :: args, cwd, extraEnv : _*)
}*/
}
/** create ProcessBuilder with working dir optionaly set to File and extra environment variables */
/** create ProcessBuilder with working dir optionally set to File and extra environment variables */
def apply(command: Seq[String], cwd: Option[File], extraEnv: (String, String)*): ProcessBuilder = {
val jpb = new JProcessBuilder(command.toArray: _*)
cwd.foreach(jpb directory _)
@ -63,7 +63,7 @@ object Process extends ProcessExtra {
def cat(file: SourcePartialBuilder, files: SourcePartialBuilder*): ProcessBuilder = cat(file :: files.toList)
def cat(files: Seq[SourcePartialBuilder]): ProcessBuilder =
{
require(!files.isEmpty)
require(files.nonEmpty)
files.map(_.cat).reduceLeft(_ #&& _)
}
}

View File

@ -16,7 +16,7 @@ object cat {
catFiles(args.toList)
System.exit(0)
} catch {
case e =>
case e: Throwable =>
e.printStackTrace()
System.err.println("Error: " + e.toString)
System.exit(1)