Replace procedure syntax by explicit Unit annotation

This commit is contained in:
Pierre DAL-PRA 2015-08-03 23:13:59 +02:00
parent 303b0681da
commit 54d54b9f4f
149 changed files with 576 additions and 601 deletions

View File

@ -40,7 +40,7 @@ object Cache extends CacheImplicits {
println(label + ".read: " + v) println(label + ".read: " + v)
v v
} }
def write(to: Out, v: Internal) { def write(to: Out, v: Internal): Unit = {
println(label + ".write: " + v) println(label + ".write: " + v)
c.write(to, v) c.write(to, v)
} }
@ -119,7 +119,7 @@ trait BasicCacheImplicits {
if (left <= 0) acc.reverse else next(left - 1, t.read(from) :: acc) if (left <= 0) acc.reverse else next(left - 1, t.read(from) :: acc)
next(size, Nil) next(size, Nil)
} }
def write(to: Out, vs: Internal) { def write(to: Out, vs: Internal): Unit = {
val size = vs.length val size = vs.length
IntFormat.writes(to, size) IntFormat.writes(to, size)
for (v <- vs) t.write(to, v) for (v <- vs) t.write(to, v)
@ -165,7 +165,7 @@ trait HListCacheImplicits {
val t = tail.read(from) val t = tail.read(from)
(h, t) (h, t)
} }
def write(to: Out, j: Internal) { def write(to: Out, j: Internal): Unit = {
head.write(to, j._1) head.write(to, j._1)
tail.write(to, j._2) tail.write(to, j._2)
} }
@ -185,7 +185,7 @@ trait HListCacheImplicits {
val t = tail.reads(from) val t = tail.reads(from)
HCons(h, t) HCons(h, t)
} }
def writes(to: Out, hc: H :+: T) { def writes(to: Out, hc: H :+: T): Unit = {
head.writes(to, hc.head) head.writes(to, hc.head)
tail.writes(to, hc.tail) tail.writes(to, hc.tail)
} }
@ -205,8 +205,8 @@ trait UnionImplicits {
val value = cache.read(in) val value = cache.read(in)
new Found[cache.Internal](cache, clazz, value, index) new Found[cache.Internal](cache, clazz, value, index)
} }
def write(to: Out, i: Internal) { def write(to: Out, i: Internal): Unit = {
def write0[I](f: Found[I]) { def write0[I](f: Found[I]): Unit = {
ByteFormat.writes(to, f.index.toByte) ByteFormat.writes(to, f.index.toByte)
f.cache.write(to, f.value) f.cache.write(to, f.value)
} }

View File

@ -44,7 +44,11 @@ object ClassToAPI {
c.getEnclosingClass eq null c.getEnclosingClass eq null
final class ClassMap private[sbt] (private[sbt] val memo: mutable.Map[String, Seq[api.ClassLike]], private[sbt] val inherited: mutable.Set[Class[_]], private[sbt] val lz: mutable.Buffer[xsbti.api.Lazy[_]]) { final class ClassMap private[sbt] (private[sbt] val memo: mutable.Map[String, Seq[api.ClassLike]], private[sbt] val inherited: mutable.Set[Class[_]], private[sbt] val lz: mutable.Buffer[xsbti.api.Lazy[_]]) {
def clear() { memo.clear(); inherited.clear(); lz.clear() } def clear(): Unit = {
memo.clear()
inherited.clear()
lz.clear()
}
} }
def emptyClassMap: ClassMap = new ClassMap(new mutable.HashMap, new mutable.HashSet, new mutable.ListBuffer) def emptyClassMap: ClassMap = new ClassMap(new mutable.HashMap, new mutable.HashSet, new mutable.ListBuffer)

View File

@ -29,12 +29,12 @@ object APIUtil {
// Don't visit inherited definitions since we consider that a class // Don't visit inherited definitions since we consider that a class
// that inherits a macro does not have a macro. // that inherits a macro does not have a macro.
override def visitStructure0(structure: Structure) { override def visitStructure0(structure: Structure): Unit = {
visitTypes(structure.parents) visitTypes(structure.parents)
visitDefinitions(structure.declared) visitDefinitions(structure.declared)
} }
override def visitModifiers(m: Modifiers) { override def visitModifiers(m: Modifiers): Unit = {
hasMacro ||= m.isMacro hasMacro ||= m.isMacro
super.visitModifiers(m) super.visitModifiers(m)
} }

View File

@ -49,7 +49,7 @@ final class HashAPI(includePrivate: Boolean, includeParamNames: Boolean, include
private[this] val visitedStructures = visitedMap[Structure] private[this] val visitedStructures = visitedMap[Structure]
private[this] val visitedClassLike = visitedMap[ClassLike] private[this] val visitedClassLike = visitedMap[ClassLike]
private[this] def visitedMap[T] = new mutable.HashMap[T, List[Hash]] private[this] def visitedMap[T] = new mutable.HashMap[T, List[Hash]]
private[this] def visit[T](map: mutable.Map[T, List[Hash]], t: T)(hashF: T => Unit) { private[this] def visit[T](map: mutable.Map[T, List[Hash]], t: T)(hashF: T => Unit): Unit = {
map.put(t, hash :: map.getOrElse(t, Nil)) match { map.put(t, hash :: map.getOrElse(t, Nil)) match {
case Some(x :: _) => extend(x) case Some(x :: _) => extend(x)
case _ => case _ =>
@ -102,11 +102,11 @@ final class HashAPI(includePrivate: Boolean, includeParamNames: Boolean, include
@inline final def hashString(s: String): Unit = extend(stringHash(s)) @inline final def hashString(s: String): Unit = extend(stringHash(s))
@inline final def hashBoolean(b: Boolean): Unit = extend(if (b) TrueHash else FalseHash) @inline final def hashBoolean(b: Boolean): Unit = extend(if (b) TrueHash else FalseHash)
@inline final def hashSeq[T](s: Seq[T], hashF: T => Unit) { @inline final def hashSeq[T](s: Seq[T], hashF: T => Unit): Unit = {
extend(s.length) extend(s.length)
s foreach hashF s foreach hashF
} }
final def hashSymmetric[T](ts: TraversableOnce[T], hashF: T => Unit) { final def hashSymmetric[T](ts: TraversableOnce[T], hashF: T => Unit): Unit = {
val current = hash val current = hash
val mA = magicA val mA = magicA
val mB = magicB val mB = magicB
@ -123,7 +123,7 @@ final class HashAPI(includePrivate: Boolean, includeParamNames: Boolean, include
extend(symmetricHash(hashes, 0xb592f7ae)) // constant from MurmurHash3 extend(symmetricHash(hashes, 0xb592f7ae)) // constant from MurmurHash3
} }
@inline final def extend(a: Hash) { @inline final def extend(a: Hash): Unit = {
hash = extendHash(hash, a, magicA, magicB) hash = extendHash(hash, a, magicA, magicB)
magicA = nextMagicA(magicA) magicA = nextMagicA(magicA)
magicB = nextMagicB(magicB) magicB = nextMagicB(magicB)
@ -166,7 +166,7 @@ final class HashAPI(includePrivate: Boolean, includeParamNames: Boolean, include
} }
hashSymmetric(ds, (hashDefinitionCombined _).tupled) hashSymmetric(ds, (hashDefinitionCombined _).tupled)
} }
def hashDefinition(d: Definition) { def hashDefinition(d: Definition): Unit = {
hashString(d.name) hashString(d.name)
hashAnnotations(d.annotations) hashAnnotations(d.annotations)
hashModifiers(d.modifiers) hashModifiers(d.modifiers)
@ -180,20 +180,20 @@ final class HashAPI(includePrivate: Boolean, includeParamNames: Boolean, include
} }
} }
final def hashClass(c: ClassLike): Unit = visit(visitedClassLike, c)(hashClass0) final def hashClass(c: ClassLike): Unit = visit(visitedClassLike, c)(hashClass0)
def hashClass0(c: ClassLike) { def hashClass0(c: ClassLike): Unit = {
extend(ClassHash) extend(ClassHash)
hashParameterizedDefinition(c) hashParameterizedDefinition(c)
hashType(c.selfType) hashType(c.selfType)
hashStructure(c.structure, includeDefinitions) hashStructure(c.structure, includeDefinitions)
} }
def hashField(f: FieldLike) { def hashField(f: FieldLike): Unit = {
f match { f match {
case v: Var => extend(VarHash) case v: Var => extend(VarHash)
case v: Val => extend(ValHash) case v: Val => extend(ValHash)
} }
hashType(f.tpe) hashType(f.tpe)
} }
def hashDef(d: Def) { def hashDef(d: Def): Unit = {
extend(DefHash) extend(DefHash)
hashParameterizedDefinition(d) hashParameterizedDefinition(d)
hashValueParameters(d.valueParameters) hashValueParameters(d.valueParameters)
@ -236,23 +236,23 @@ final class HashAPI(includePrivate: Boolean, includeParamNames: Boolean, include
hashBoolean(parameter.hasDefault) hashBoolean(parameter.hasDefault)
} }
def hashParameterizedDefinition[T <: ParameterizedDefinition](d: T) { def hashParameterizedDefinition[T <: ParameterizedDefinition](d: T): Unit = {
hashTypeParameters(d.typeParameters) hashTypeParameters(d.typeParameters)
} }
def hashTypeDeclaration(d: TypeDeclaration) { def hashTypeDeclaration(d: TypeDeclaration): Unit = {
extend(TypeDeclHash) extend(TypeDeclHash)
hashParameterizedDefinition(d) hashParameterizedDefinition(d)
hashType(d.lowerBound) hashType(d.lowerBound)
hashType(d.upperBound) hashType(d.upperBound)
} }
def hashTypeAlias(d: TypeAlias) { def hashTypeAlias(d: TypeAlias): Unit = {
extend(TypeAliasHash) extend(TypeAliasHash)
hashParameterizedDefinition(d) hashParameterizedDefinition(d)
hashType(d.tpe) hashType(d.tpe)
} }
def hashTypeParameters(parameters: Seq[TypeParameter]) = hashSeq(parameters, hashTypeParameter) def hashTypeParameters(parameters: Seq[TypeParameter]) = hashSeq(parameters, hashTypeParameter)
def hashTypeParameter(parameter: TypeParameter) { def hashTypeParameter(parameter: TypeParameter): Unit = {
hashString(parameter.id) hashString(parameter.id)
extend(parameter.variance.ordinal) extend(parameter.variance.ordinal)
hashTypeParameters(parameter.typeParameters) hashTypeParameters(parameter.typeParameters)
@ -267,7 +267,7 @@ final class HashAPI(includePrivate: Boolean, includeParamNames: Boolean, include
hashAnnotationArguments(annotation.arguments) hashAnnotationArguments(annotation.arguments)
} }
def hashAnnotationArguments(args: Seq[AnnotationArgument]) = hashSeq(args, hashAnnotationArgument) def hashAnnotationArguments(args: Seq[AnnotationArgument]) = hashSeq(args, hashAnnotationArgument)
def hashAnnotationArgument(arg: AnnotationArgument) { def hashAnnotationArgument(arg: AnnotationArgument): Unit = {
hashString(arg.name) hashString(arg.name)
hashString(arg.value) hashString(arg.value)
} }
@ -288,11 +288,11 @@ final class HashAPI(includePrivate: Boolean, includeParamNames: Boolean, include
case pr: ParameterRef => hashParameterRef(pr) case pr: ParameterRef => hashParameterRef(pr)
} }
def hashParameterRef(p: ParameterRef) { def hashParameterRef(p: ParameterRef): Unit = {
extend(ParameterRefHash) extend(ParameterRefHash)
hashString(p.id) hashString(p.id)
} }
def hashSingleton(s: Singleton) { def hashSingleton(s: Singleton): Unit = {
extend(SingletonHash) extend(SingletonHash)
hashPath(s.path) hashPath(s.path)
} }
@ -302,11 +302,11 @@ final class HashAPI(includePrivate: Boolean, includeParamNames: Boolean, include
case s: Super => hashSuperPath(s) case s: Super => hashSuperPath(s)
case id: Id => hashIdPath(id) case id: Id => hashIdPath(id)
} }
def hashSuperPath(s: Super) { def hashSuperPath(s: Super): Unit = {
extend(SuperHash) extend(SuperHash)
hashPath(s.qualifier) hashPath(s.qualifier)
} }
def hashIdPath(id: Id) { def hashIdPath(id: Id): Unit = {
extend(IdPathHash) extend(IdPathHash)
hashString(id.id) hashString(id.id)
} }
@ -333,19 +333,19 @@ final class HashAPI(includePrivate: Boolean, includeParamNames: Boolean, include
hashString(p.id) hashString(p.id)
hashType(p.prefix) hashType(p.prefix)
} }
def hashParameterized(p: Parameterized) { def hashParameterized(p: Parameterized): Unit = {
extend(ParameterizedHash) extend(ParameterizedHash)
hashType(p.baseType) hashType(p.baseType)
hashTypes(p.typeArguments) hashTypes(p.typeArguments)
} }
def hashAnnotated(a: Annotated) { def hashAnnotated(a: Annotated): Unit = {
extend(AnnotatedHash) extend(AnnotatedHash)
hashType(a.baseType) hashType(a.baseType)
hashAnnotations(a.annotations) hashAnnotations(a.annotations)
} }
final def hashStructure(structure: Structure, includeDefinitions: Boolean) = final def hashStructure(structure: Structure, includeDefinitions: Boolean) =
visit(visitedStructures, structure)(structure => hashStructure0(structure, includeDefinitions)) visit(visitedStructures, structure)(structure => hashStructure0(structure, includeDefinitions))
def hashStructure0(structure: Structure, includeDefinitions: Boolean) { def hashStructure0(structure: Structure, includeDefinitions: Boolean): Unit = {
extend(StructureHash) extend(StructureHash)
hashTypes(structure.parents, includeDefinitions) hashTypes(structure.parents, includeDefinitions)
if (includeDefinitions) { if (includeDefinitions) {
@ -359,4 +359,3 @@ final class HashAPI(includePrivate: Boolean, includeParamNames: Boolean, include
hashType(base) hashType(base)
} }
} }

View File

@ -17,12 +17,12 @@ class Visit {
s.definitions foreach visitDefinition s.definitions foreach visitDefinition
} }
def visitPackage(p: Package) { def visitPackage(p: Package): Unit = {
visitString(p.name) visitString(p.name)
} }
def visitDefinitions(ds: Seq[Definition]) = ds foreach visitDefinition def visitDefinitions(ds: Seq[Definition]) = ds foreach visitDefinition
def visitDefinition(d: Definition) { def visitDefinition(d: Definition): Unit = {
visitString(d.name) visitString(d.name)
visitAnnotations(d.annotations) visitAnnotations(d.annotations)
visitModifiers(d.modifiers) visitModifiers(d.modifiers)
@ -36,21 +36,21 @@ class Visit {
} }
} }
final def visitClass(c: ClassLike): Unit = if (visitedClassLike add c) visitClass0(c) final def visitClass(c: ClassLike): Unit = if (visitedClassLike add c) visitClass0(c)
def visitClass0(c: ClassLike) { def visitClass0(c: ClassLike): Unit = {
visitParameterizedDefinition(c) visitParameterizedDefinition(c)
visitType(c.selfType) visitType(c.selfType)
visitStructure(c.structure) visitStructure(c.structure)
} }
def visitField(f: FieldLike) { def visitField(f: FieldLike): Unit = {
visitType(f.tpe) visitType(f.tpe)
f match { f match {
case v: Var => visitVar(v) case v: Var => visitVar(v)
case v: Val => visitVal(v) case v: Val => visitVal(v)
} }
} }
def visitVar(v: Var) {} def visitVar(v: Var): Unit = ()
def visitVal(v: Val) {} def visitVal(v: Val): Unit = ()
def visitDef(d: Def) { def visitDef(d: Def): Unit = {
visitParameterizedDefinition(d) visitParameterizedDefinition(d)
visitValueParameters(d.valueParameters) visitValueParameters(d.valueParameters)
visitType(d.returnType) visitType(d.returnType)
@ -71,15 +71,15 @@ class Visit {
case thisq: ThisQualifier => visitThisQualifier(thisq) case thisq: ThisQualifier => visitThisQualifier(thisq)
case id: IdQualifier => visitIdQualifier(id) case id: IdQualifier => visitIdQualifier(id)
} }
def visitIdQualifier(id: IdQualifier) { def visitIdQualifier(id: IdQualifier): Unit = {
visitString(id.value) visitString(id.value)
} }
def visitUnqualified(unq: Unqualified) {} def visitUnqualified(unq: Unqualified): Unit = ()
def visitThisQualifier(thisq: ThisQualifier) {} def visitThisQualifier(thisq: ThisQualifier): Unit = ()
def visitPublic(pub: Public) {} def visitPublic(pub: Public): Unit = ()
def visitPrivate(p: Private) { visitQualifier(p.qualifier) } def visitPrivate(p: Private): Unit = visitQualifier(p.qualifier)
def visitProtected(p: Protected) { visitQualifier(p.qualifier) } def visitProtected(p: Protected): Unit = visitQualifier(p.qualifier)
def visitModifiers(m: Modifiers) {} def visitModifiers(m: Modifiers): Unit = ()
def visitValueParameters(valueParameters: Seq[ParameterList]) = valueParameters foreach visitValueParameterList def visitValueParameters(valueParameters: Seq[ParameterList]) = valueParameters foreach visitValueParameterList
def visitValueParameterList(list: ParameterList) = list.parameters foreach visitValueParameter def visitValueParameterList(list: ParameterList) = list.parameters foreach visitValueParameter
@ -89,21 +89,20 @@ class Visit {
visitType(parameter.tpe) visitType(parameter.tpe)
} }
def visitParameterizedDefinition[T <: ParameterizedDefinition](d: T) { def visitParameterizedDefinition[T <: ParameterizedDefinition](d: T): Unit = visitTypeParameters(d.typeParameters)
visitTypeParameters(d.typeParameters)
} def visitTypeDeclaration(d: TypeDeclaration): Unit = {
def visitTypeDeclaration(d: TypeDeclaration) {
visitParameterizedDefinition(d) visitParameterizedDefinition(d)
visitType(d.lowerBound) visitType(d.lowerBound)
visitType(d.upperBound) visitType(d.upperBound)
} }
def visitTypeAlias(d: TypeAlias) { def visitTypeAlias(d: TypeAlias): Unit = {
visitParameterizedDefinition(d) visitParameterizedDefinition(d)
visitType(d.tpe) visitType(d.tpe)
} }
def visitTypeParameters(parameters: Seq[TypeParameter]) = parameters foreach visitTypeParameter def visitTypeParameters(parameters: Seq[TypeParameter]) = parameters foreach visitTypeParameter
def visitTypeParameter(parameter: TypeParameter) { def visitTypeParameter(parameter: TypeParameter): Unit = {
visitTypeParameters(parameter.typeParameters) visitTypeParameters(parameter.typeParameters)
visitType(parameter.lowerBound) visitType(parameter.lowerBound)
visitType(parameter.upperBound) visitType(parameter.upperBound)
@ -116,13 +115,13 @@ class Visit {
visitAnnotationArguments(annotation.arguments) visitAnnotationArguments(annotation.arguments)
} }
def visitAnnotationArguments(args: Seq[AnnotationArgument]) = args foreach visitAnnotationArgument def visitAnnotationArguments(args: Seq[AnnotationArgument]) = args foreach visitAnnotationArgument
def visitAnnotationArgument(arg: AnnotationArgument) { def visitAnnotationArgument(arg: AnnotationArgument): Unit = {
visitString(arg.name) visitString(arg.name)
visitString(arg.value) visitString(arg.value)
} }
def visitTypes(ts: Seq[Type]) = ts.foreach(visitType) def visitTypes(ts: Seq[Type]) = ts.foreach(visitType)
def visitType(t: Type) { def visitType(t: Type): Unit = {
t match { t match {
case s: Structure => visitStructure(s) case s: Structure => visitStructure(s)
case e: Existential => visitExistential(e) case e: Existential => visitExistential(e)
@ -137,18 +136,18 @@ class Visit {
} }
} }
def visitEmptyType() {} def visitEmptyType(): Unit = ()
def visitParameterRef(p: ParameterRef) {} def visitParameterRef(p: ParameterRef): Unit = ()
def visitSingleton(s: Singleton) { visitPath(s.path) } def visitSingleton(s: Singleton): Unit = visitPath(s.path)
def visitPath(path: Path) = path.components foreach visitPathComponent def visitPath(path: Path) = path.components foreach visitPathComponent
def visitPathComponent(pc: PathComponent) = pc match { def visitPathComponent(pc: PathComponent) = pc match {
case t: This => visitThisPath(t) case t: This => visitThisPath(t)
case s: Super => visitSuperPath(s) case s: Super => visitSuperPath(s)
case id: Id => visitIdPath(id) case id: Id => visitIdPath(id)
} }
def visitThisPath(t: This) {} def visitThisPath(t: This): Unit = ()
def visitSuperPath(s: Super) { visitPath(s.qualifier) } def visitSuperPath(s: Super): Unit = visitPath(s.qualifier)
def visitIdPath(id: Id) { visitString(id.id) } def visitIdPath(id: Id): Unit = visitString(id.id)
def visitConstant(c: Constant) = def visitConstant(c: Constant) =
{ {
@ -162,16 +161,16 @@ class Visit {
visitString(p.id) visitString(p.id)
visitType(p.prefix) visitType(p.prefix)
} }
def visitParameterized(p: Parameterized) { def visitParameterized(p: Parameterized): Unit = {
visitType(p.baseType) visitType(p.baseType)
visitTypes(p.typeArguments) visitTypes(p.typeArguments)
} }
def visitAnnotated(a: Annotated) { def visitAnnotated(a: Annotated): Unit = {
visitType(a.baseType) visitType(a.baseType)
visitAnnotations(a.annotations) visitAnnotations(a.annotations)
} }
final def visitStructure(structure: Structure) = if (visitedStructures add structure) visitStructure0(structure) final def visitStructure(structure: Structure) = if (visitedStructures add structure) visitStructure0(structure)
def visitStructure0(structure: Structure) { def visitStructure0(structure: Structure): Unit = {
visitTypes(structure.parents) visitTypes(structure.parents)
visitDefinitions(structure.declared) visitDefinitions(structure.declared)
visitDefinitions(structure.inherited) visitDefinitions(structure.inherited)
@ -181,5 +180,5 @@ class Visit {
visitTypeParameters(parameters) visitTypeParameters(parameters)
visitType(base) visitType(base)
} }
def visitString(s: String) {} def visitString(s: String): Unit = ()
} }

View File

@ -12,7 +12,7 @@ trait AnalysisStore {
object AnalysisStore { object AnalysisStore {
def cached(backing: AnalysisStore): AnalysisStore = new AnalysisStore { def cached(backing: AnalysisStore): AnalysisStore = new AnalysisStore {
private var last: Option[(Analysis, CompileSetup)] = None private var last: Option[(Analysis, CompileSetup)] = None
def set(analysis: Analysis, setup: CompileSetup) { def set(analysis: Analysis, setup: CompileSetup): Unit = {
backing.set(analysis, setup) backing.set(analysis, setup)
last = Some((analysis, setup)) last = Some((analysis, setup))
} }

View File

@ -27,8 +27,8 @@ object ClassfileManager {
/** Constructs a minimal ClassfileManager implementation that immediately deletes class files when requested. */ /** Constructs a minimal ClassfileManager implementation that immediately deletes class files when requested. */
val deleteImmediately: () => ClassfileManager = () => new ClassfileManager { val deleteImmediately: () => ClassfileManager = () => new ClassfileManager {
def delete(classes: Iterable[File]): Unit = IO.deleteFilesEmptyDirs(classes) def delete(classes: Iterable[File]): Unit = IO.deleteFilesEmptyDirs(classes)
def generated(classes: Iterable[File]) {} def generated(classes: Iterable[File]): Unit = ()
def complete(success: Boolean) {} def complete(success: Boolean): Unit = ()
} }
@deprecated("Use overloaded variant that takes additional logger argument, instead.", "0.13.5") @deprecated("Use overloaded variant that takes additional logger argument, instead.", "0.13.5")
def transactional(tempDir0: File): () => ClassfileManager = def transactional(tempDir0: File): () => ClassfileManager =
@ -44,7 +44,7 @@ object ClassfileManager {
private[this] val movedClasses = new mutable.HashMap[File, File] private[this] val movedClasses = new mutable.HashMap[File, File]
private def showFiles(files: Iterable[File]): String = files.map(f => s"\t$f").mkString("\n") private def showFiles(files: Iterable[File]): String = files.map(f => s"\t$f").mkString("\n")
def delete(classes: Iterable[File]) { def delete(classes: Iterable[File]): Unit = {
logger.debug(s"About to delete class files:\n${showFiles(classes)}") logger.debug(s"About to delete class files:\n${showFiles(classes)}")
val toBeBackedUp = classes.filter(c => c.exists && !movedClasses.contains(c) && !generatedClasses(c)) val toBeBackedUp = classes.filter(c => c.exists && !movedClasses.contains(c) && !generatedClasses(c))
logger.debug(s"We backup classs files:\n${showFiles(toBeBackedUp)}") logger.debug(s"We backup classs files:\n${showFiles(toBeBackedUp)}")
@ -57,7 +57,7 @@ object ClassfileManager {
logger.debug(s"Registering generated classes:\n${showFiles(classes)}") logger.debug(s"Registering generated classes:\n${showFiles(classes)}")
generatedClasses ++= classes generatedClasses ++= classes
} }
def complete(success: Boolean) { def complete(success: Boolean): Unit = {
if (!success) { if (!success) {
logger.debug("Rolling back changes to class files.") logger.debug("Rolling back changes to class files.")
logger.debug(s"Removing generated classes:\n${showFiles(generatedClasses)}") logger.debug(s"Removing generated classes:\n${showFiles(generatedClasses)}")

View File

@ -184,7 +184,7 @@ private final class AnalysisCallback(internalMap: File => Option[File], external
// empty value used when name hashing algorithm is disabled // empty value used when name hashing algorithm is disabled
private val emptyNameHashes = new xsbti.api._internalOnly_NameHashes(Array.empty, Array.empty) private val emptyNameHashes = new xsbti.api._internalOnly_NameHashes(Array.empty, Array.empty)
def api(sourceFile: File, source: SourceAPI) { def api(sourceFile: File, source: SourceAPI): Unit = {
import xsbt.api.{ APIUtil, HashAPI } import xsbt.api.{ APIUtil, HashAPI }
if (APIUtil.isScalaSourceName(sourceFile.getName) && APIUtil.hasMacro(source)) macroSources += sourceFile if (APIUtil.isScalaSourceName(sourceFile.getName) && APIUtil.hasMacro(source)) macroSources += sourceFile
publicNameHashes(sourceFile) = { publicNameHashes(sourceFile) = {

View File

@ -170,7 +170,7 @@ class AggressiveCompile(cacheFile: File) {
log.debug(label + " took " + (elapsed / 1e9) + " s") log.debug(label + " took " + (elapsed / 1e9) + " s")
result result
} }
private[this] def logInputs(log: Logger, javaCount: Int, scalaCount: Int, outputDirs: Seq[File]) { private[this] def logInputs(log: Logger, javaCount: Int, scalaCount: Int, outputDirs: Seq[File]): Unit = {
val scalaMsg = Analysis.counted("Scala source", "", "s", scalaCount) val scalaMsg = Analysis.counted("Scala source", "", "s", scalaCount)
val javaMsg = Analysis.counted("Java source", "", "s", javaCount) val javaMsg = Analysis.counted("Java source", "", "s", javaCount)
val combined = scalaMsg ++ javaMsg val combined = scalaMsg ++ javaMsg

View File

@ -77,7 +77,7 @@ final class MixedAnalyzingCompiler(
result result
} }
private[this] def logInputs(log: Logger, javaCount: Int, scalaCount: Int, outputDirs: Seq[File]) { private[this] def logInputs(log: Logger, javaCount: Int, scalaCount: Int, outputDirs: Seq[File]): Unit = {
val scalaMsg = Analysis.counted("Scala source", "", "s", scalaCount) val scalaMsg = Analysis.counted("Scala source", "", "s", scalaCount)
val javaMsg = Analysis.counted("Java source", "", "s", javaCount) val javaMsg = Analysis.counted("Java source", "", "s", javaCount)
val combined = scalaMsg ++ javaMsg val combined = scalaMsg ++ javaMsg

View File

@ -33,7 +33,7 @@ final class API(val global: CallbackGlobal) extends Compat {
debug("API phase took : " + ((stop - start) / 1000.0) + " s") debug("API phase took : " + ((stop - start) / 1000.0) + " s")
} }
def processUnit(unit: CompilationUnit) = if (!unit.isJava) processScalaUnit(unit) def processUnit(unit: CompilationUnit) = if (!unit.isJava) processScalaUnit(unit)
def processScalaUnit(unit: CompilationUnit) { def processScalaUnit(unit: CompilationUnit): Unit = {
val sourceFile = unit.source.file.file val sourceFile = unit.source.file.file
debug("Traversing " + sourceFile) debug("Traversing " + sourceFile)
val extractApi = new ExtractAPI[global.type](global, sourceFile) val extractApi = new ExtractAPI[global.type](global, sourceFile)
@ -59,7 +59,7 @@ final class API(val global: CallbackGlobal) extends Compat {
definitions += extractApi.classLike(c.owner, c) definitions += extractApi.classLike(c.owner, c)
} }
/** Record packages declared in the source file*/ /** Record packages declared in the source file*/
def `package`(p: Symbol) { def `package`(p: Symbol): Unit = {
if ((p eq null) || p == NoSymbol || p.isRoot || p.isRootPackage || p.isEmptyPackageClass || p.isEmptyPackage) if ((p eq null) || p == NoSymbol || p.isRoot || p.isRootPackage || p.isEmptyPackageClass || p.isEmptyPackage)
() ()
else { else {
@ -72,7 +72,7 @@ final class API(val global: CallbackGlobal) extends Compat {
private abstract class TopLevelTraverser extends Traverser { private abstract class TopLevelTraverser extends Traverser {
def `class`(s: Symbol) def `class`(s: Symbol)
def `package`(s: Symbol) def `package`(s: Symbol)
override def traverse(tree: Tree) { override def traverse(tree: Tree): Unit = {
tree match { tree match {
case (_: ClassDef | _: ModuleDef) if isTopLevel(tree.symbol) => `class`(tree.symbol) case (_: ClassDef | _: ModuleDef) if isTopLevel(tree.symbol) => `class`(tree.symbol)
case p: PackageDef => case p: PackageDef =>

View File

@ -28,7 +28,7 @@ final class Analyzer(val global: CallbackGlobal) extends LocateClassFile {
// build list of generated classes // build list of generated classes
for (iclass <- unit.icode) { for (iclass <- unit.icode) {
val sym = iclass.symbol val sym = iclass.symbol
def addGenerated(separatorRequired: Boolean) { def addGenerated(separatorRequired: Boolean): Unit = {
for (classFile <- outputDirs map (fileForClass(_, sym, separatorRequired)) find (_.exists)) for (classFile <- outputDirs map (fileForClass(_, sym, separatorRequired)) find (_.exists))
callback.generatedClass(sourceFile, classFile, className(sym, '.', separatorRequired)) callback.generatedClass(sourceFile, classFile, className(sym, '.', separatorRequired))
} }
@ -43,4 +43,3 @@ final class Analyzer(val global: CallbackGlobal) extends LocateClassFile {
} }
} }
} }

View File

@ -29,7 +29,7 @@ final class CompilerInterface {
sealed trait GlobalCompat { self: Global => sealed trait GlobalCompat { self: Global =>
def registerTopLevelSym(sym: Symbol): Unit def registerTopLevelSym(sym: Symbol): Unit
sealed trait RunCompat { sealed trait RunCompat {
def informUnitStarting(phase: Phase, unit: CompilationUnit) {} def informUnitStarting(phase: Phase, unit: CompilationUnit): Unit = ()
} }
} }
sealed abstract class CallbackGlobal(settings: Settings, reporter: reporters.Reporter, output: Output) extends Global(settings, reporter) with GlobalCompat { sealed abstract class CallbackGlobal(settings: Settings, reporter: reporters.Reporter, output: Output) extends Global(settings, reporter) with GlobalCompat {
@ -43,7 +43,7 @@ sealed abstract class CallbackGlobal(settings: Settings, reporter: reporters.Rep
} }
// Map source files to public inherited dependencies. These dependencies are tracked as the symbol for the dealiased base class. // Map source files to public inherited dependencies. These dependencies are tracked as the symbol for the dealiased base class.
val inheritedDependencies = new mutable.HashMap[File, mutable.Set[Symbol]] val inheritedDependencies = new mutable.HashMap[File, mutable.Set[Symbol]]
def addInheritedDependencies(file: File, deps: Iterable[Symbol]) { def addInheritedDependencies(file: File, deps: Iterable[Symbol]): Unit = {
inheritedDependencies.getOrElseUpdate(file, new mutable.HashSet) ++= deps inheritedDependencies.getOrElseUpdate(file, new mutable.HashSet) ++= deps
} }
} }
@ -52,13 +52,13 @@ class InterfaceCompileFailed(val arguments: Array[String], val problems: Array[P
class InterfaceCompileCancelled(val arguments: Array[String], override val toString: String) extends xsbti.CompileCancelled class InterfaceCompileCancelled(val arguments: Array[String], override val toString: String) extends xsbti.CompileCancelled
private final class WeakLog(private[this] var log: Logger, private[this] var delegate: Reporter) { private final class WeakLog(private[this] var log: Logger, private[this] var delegate: Reporter) {
def apply(message: String) { def apply(message: String): Unit = {
assert(log ne null, "Stale reference to logger") assert(log ne null, "Stale reference to logger")
log.error(Message(message)) log.error(Message(message))
} }
def logger: Logger = log def logger: Logger = log
def reporter: Reporter = delegate def reporter: Reporter = delegate
def clear() { def clear(): Unit = {
log = null log = null
delegate = null delegate = null
} }
@ -95,7 +95,7 @@ private final class CachedCompiler0(args: Array[String], output: Output, initial
try { run(sources.toList, changes, callback, log, dreporter, progress) } try { run(sources.toList, changes, callback, log, dreporter, progress) }
finally { dreporter.dropDelegate() } finally { dreporter.dropDelegate() }
} }
private[this] def run(sources: List[File], changes: DependencyChanges, callback: AnalysisCallback, log: Logger, dreporter: DelegatingReporter, compileProgress: CompileProgress) { private[this] def run(sources: List[File], changes: DependencyChanges, callback: AnalysisCallback, log: Logger, dreporter: DelegatingReporter, compileProgress: CompileProgress): Unit = {
if (command.shouldStopWithInfo) { if (command.shouldStopWithInfo) {
dreporter.info(null, command.getInfoMessage(compiler), true) dreporter.info(null, command.getInfoMessage(compiler), true)
throw new InterfaceCompileFailed(args, Array(), "Compiler option supplied that disabled actual compilation.") throw new InterfaceCompileFailed(args, Array(), "Compiler option supplied that disabled actual compilation.")
@ -104,10 +104,10 @@ private final class CachedCompiler0(args: Array[String], output: Output, initial
debug(log, args.mkString("Calling Scala compiler with arguments (CompilerInterface):\n\t", "\n\t", "")) debug(log, args.mkString("Calling Scala compiler with arguments (CompilerInterface):\n\t", "\n\t", ""))
compiler.set(callback, dreporter) compiler.set(callback, dreporter)
val run = new compiler.Run with compiler.RunCompat { val run = new compiler.Run with compiler.RunCompat {
override def informUnitStarting(phase: Phase, unit: compiler.CompilationUnit) { override def informUnitStarting(phase: Phase, unit: compiler.CompilationUnit): Unit = {
compileProgress.startUnit(phase.name, unit.source.path) compileProgress.startUnit(phase.name, unit.source.path)
} }
override def progress(current: Int, total: Int) { override def progress(current: Int, total: Int): Unit = {
if (!compileProgress.advance(current, total)) if (!compileProgress.advance(current, total))
cancel cancel
} }
@ -134,7 +134,7 @@ private final class CachedCompiler0(args: Array[String], output: Output, initial
debug(log, "Compilation cancelled (CompilerInterface)") debug(log, "Compilation cancelled (CompilerInterface)")
throw new InterfaceCompileCancelled(args, "Compilation has been cancelled") throw new InterfaceCompileCancelled(args, "Compilation has been cancelled")
} }
def processUnreportedWarnings(run: compiler.Run) { def processUnreportedWarnings(run: compiler.Run): Unit = {
// allConditionalWarnings and the ConditionalWarning class are only in 2.10+ // allConditionalWarnings and the ConditionalWarning class are only in 2.10+
final class CondWarnCompat(val what: String, val warnings: mutable.ListBuffer[(compiler.Position, String)]) final class CondWarnCompat(val what: String, val warnings: mutable.ListBuffer[(compiler.Position, String)])
implicit def compat(run: AnyRef): Compat = new Compat implicit def compat(run: AnyRef): Compat = new Compat
@ -225,11 +225,11 @@ private final class CachedCompiler0(args: Array[String], output: Output, initial
for ((what, warnings) <- seq; (pos, msg) <- warnings) yield callback.problem(what, drep.convert(pos), msg, Severity.Warn, false) for ((what, warnings) <- seq; (pos, msg) <- warnings) yield callback.problem(what, drep.convert(pos), msg, Severity.Warn, false)
} }
def set(callback: AnalysisCallback, dreporter: DelegatingReporter) { def set(callback: AnalysisCallback, dreporter: DelegatingReporter): Unit = {
this.callback0 = callback this.callback0 = callback
reporter = dreporter reporter = dreporter
} }
def clear() { def clear(): Unit = {
callback0 = null callback0 = null
superDropRun() superDropRun()
reporter = null reporter = null

View File

@ -13,7 +13,7 @@ class ConsoleInterface {
def commandArguments(args: Array[String], bootClasspathString: String, classpathString: String, log: Logger): Array[String] = def commandArguments(args: Array[String], bootClasspathString: String, classpathString: String, log: Logger): Array[String] =
MakeSettings.sync(args, bootClasspathString, classpathString, log).recreateArgs.toArray[String] MakeSettings.sync(args, bootClasspathString, classpathString, log).recreateArgs.toArray[String]
def run(args: Array[String], bootClasspathString: String, classpathString: String, initialCommands: String, cleanupCommands: String, loader: ClassLoader, bindNames: Array[String], bindValues: Array[Any], log: Logger) { def run(args: Array[String], bootClasspathString: String, classpathString: String, initialCommands: String, cleanupCommands: String, loader: ClassLoader, bindNames: Array[String], bindValues: Array[Any], log: Logger): Unit = {
lazy val interpreterSettings = MakeSettings.sync(args.toList, log) lazy val interpreterSettings = MakeSettings.sync(args.toList, log)
val compilerSettings = MakeSettings.sync(args, bootClasspathString, classpathString, log) val compilerSettings = MakeSettings.sync(args, bootClasspathString, classpathString, log)
@ -36,7 +36,7 @@ class ConsoleInterface {
} else } else
super.createInterpreter() super.createInterpreter()
def bind(values: Seq[(String, Any)]) { def bind(values: Seq[(String, Any)]): Unit = {
// for 2.8 compatibility // for 2.8 compatibility
final class Compat { final class Compat {
def bindValue(id: String, value: Any) = def bindValue(id: String, value: Any) =
@ -53,7 +53,7 @@ class ConsoleInterface {
if (!initialCommands.isEmpty) if (!initialCommands.isEmpty)
interpreter.interpret(initialCommands) interpreter.interpret(initialCommands)
} }
override def closeInterpreter() { override def closeInterpreter(): Unit = {
if (!cleanupCommands.isEmpty) if (!cleanupCommands.isEmpty)
interpreter.interpret(cleanupCommands) interpreter.interpret(cleanupCommands)
super.closeInterpreter() super.closeInterpreter()

View File

@ -17,22 +17,21 @@ private object DelegatingReporter {
private final class DelegatingReporter(warnFatal: Boolean, noWarn: Boolean, private[this] var delegate: xsbti.Reporter) extends scala.tools.nsc.reporters.Reporter { private final class DelegatingReporter(warnFatal: Boolean, noWarn: Boolean, private[this] var delegate: xsbti.Reporter) extends scala.tools.nsc.reporters.Reporter {
import scala.tools.nsc.util.{ FakePos, NoPosition, Position } import scala.tools.nsc.util.{ FakePos, NoPosition, Position }
def dropDelegate() { delegate = null } def dropDelegate(): Unit = { delegate = null }
def error(msg: String) { error(FakePos("scalac"), msg) } def error(msg: String): Unit = error(FakePos("scalac"), msg)
def printSummary() = delegate.printSummary() def printSummary(): Unit = delegate.printSummary()
override def hasErrors = delegate.hasErrors override def hasErrors = delegate.hasErrors
override def hasWarnings = delegate.hasWarnings override def hasWarnings = delegate.hasWarnings
def problems = delegate.problems def problems = delegate.problems
override def comment(pos: Position, msg: String) = delegate.comment(convert(pos), msg) override def comment(pos: Position, msg: String): Unit = delegate.comment(convert(pos), msg)
override def reset = override def reset(): Unit = {
{ super.reset
super.reset delegate.reset()
delegate.reset }
} protected def info0(pos: Position, msg: String, rawSeverity: Severity, force: Boolean): Unit = {
protected def info0(pos: Position, msg: String, rawSeverity: Severity, force: Boolean) {
val skip = rawSeverity == WARNING && noWarn val skip = rawSeverity == WARNING && noWarn
if (!skip) { if (!skip) {
val severity = if (warnFatal && rawSeverity == WARNING) ERROR else rawSeverity val severity = if (warnFatal && rawSeverity == WARNING) ERROR else rawSeverity

View File

@ -57,7 +57,7 @@ final class Dependency(val global: CallbackGlobal) extends LocateClassFile {
* that is coming from either source code (not necessarily compiled in this compilation * that is coming from either source code (not necessarily compiled in this compilation
* run) or from class file and calls respective callback method. * run) or from class file and calls respective callback method.
*/ */
def processDependency(on: Symbol, context: DependencyContext) { def processDependency(on: Symbol, context: DependencyContext): Unit = {
def binaryDependency(file: File, className: String) = callback.binaryDependency(file, className, sourceFile, context) def binaryDependency(file: File, className: String) = callback.binaryDependency(file, className, sourceFile, context)
val onSource = on.sourceFile val onSource = on.sourceFile
if (onSource == null) { if (onSource == null) {
@ -166,7 +166,7 @@ final class Dependency(val global: CallbackGlobal) extends LocateClassFile {
} }
/** Copied straight from Scala 2.10 as it does not exist in Scala 2.9 compiler */ /** Copied straight from Scala 2.10 as it does not exist in Scala 2.9 compiler */
private final def debuglog(msg: => String) { private final def debuglog(msg: => String): Unit = {
if (settings.debug.value) if (settings.debug.value)
log(msg) log(msg)
} }

View File

@ -18,7 +18,7 @@ private class Runner(args: Array[String], log: Logger, delegate: xsbti.Reporter)
def noErrors = !reporter.hasErrors && command.ok def noErrors = !reporter.hasErrors && command.ok
import forScope._ import forScope._
def run() { def run(): Unit = {
debug(log, "Calling Scaladoc with arguments:\n\t" + args.mkString("\n\t")) debug(log, "Calling Scaladoc with arguments:\n\t" + args.mkString("\n\t"))
if (noErrors) { if (noErrors) {
import doc._ // 2.8 trunk and Beta1-RC4 have doc.DocFactory. For other Scala versions, the next line creates forScope.DocFactory import doc._ // 2.8 trunk and Beta1-RC4 have doc.DocFactory. For other Scala versions, the next line creates forScope.DocFactory
@ -48,7 +48,7 @@ private class Runner(args: Array[String], log: Logger, delegate: xsbti.Reporter)
def process(units: Iterator[CompilationUnit]) = error("for 2.8 compatibility only") def process(units: Iterator[CompilationUnit]) = error("for 2.8 compatibility only")
} }
} }
def document(ignore: Seq[String]) { def document(ignore: Seq[String]): Unit = {
import compiler._ import compiler._
val run = new Run val run = new Run
run compile command.files run compile command.files

View File

@ -68,7 +68,7 @@ class ComponentCompiler(compiler: RawCompiler, manager: ComponentManager) {
val base = id + binSeparator + compiler.scalaInstance.actualVersion val base = id + binSeparator + compiler.scalaInstance.actualVersion
if (withJavaVersion) base + "__" + javaVersion else base if (withJavaVersion) base + "__" + javaVersion else base
} }
protected def compileAndInstall(id: String, binID: String) { protected def compileAndInstall(id: String, binID: String): Unit = {
val srcID = id + srcExtension val srcID = id + srcExtension
IO.withTemporaryDirectory { binaryDirectory => IO.withTemporaryDirectory { binaryDirectory =>
val targetJar = new File(binaryDirectory, id + ".jar") val targetJar = new File(binaryDirectory, id + ".jar")

View File

@ -37,7 +37,7 @@ object AnalysisFormats {
time(label + ".read.end") time(label + ".read.end")
r r
} }
def writes(out: Output, t: T) { def writes(out: Output, t: T): Unit = {
time(label + ".write.start") time(label + ".write.start")
f.writes(out, t) f.writes(out, t)
time(label + ".write.end") time(label + ".write.end")

View File

@ -8,7 +8,7 @@ import java.io.File
object FileBasedStore { object FileBasedStore {
def apply(file: File): AnalysisStore = new AnalysisStore { def apply(file: File): AnalysisStore = new AnalysisStore {
def set(analysis: Analysis, setup: CompileSetup) { def set(analysis: Analysis, setup: CompileSetup): Unit = {
Using.fileWriter(IO.utf8)(file) { writer => TextAnalysisFormat.write(writer, analysis, setup) } Using.fileWriter(IO.utf8)(file) { writer => TextAnalysisFormat.write(writer, analysis, setup) }
} }

View File

@ -27,7 +27,7 @@ private[inc] object FormatTimer {
ret ret
} }
def close(key: String) { def close(key: String): Unit = {
if (printTimings) { if (printTimings) {
println("[%s] %dms".format(key, timers.getOrElse(key, 0L) / 1000000)) println("[%s] %dms".format(key, timers.getOrElse(key, 0L) / 1000000))
} }
@ -52,7 +52,7 @@ object TextAnalysisFormat {
import AnalysisFormats._ import AnalysisFormats._
implicit val compilationF = xsbt.api.CompilationFormat implicit val compilationF = xsbt.api.CompilationFormat
def write(out: Writer, analysis: Analysis, setup: CompileSetup) { def write(out: Writer, analysis: Analysis, setup: CompileSetup): Unit = {
VersionF.write(out) VersionF.write(out)
// We start with writing compile setup which contains value of the `nameHashing` // We start with writing compile setup which contains value of the `nameHashing`
// flag that is needed to properly deserialize relations // flag that is needed to properly deserialize relations
@ -82,12 +82,12 @@ object TextAnalysisFormat {
private[this] object VersionF { private[this] object VersionF {
val currentVersion = "5" val currentVersion = "5"
def write(out: Writer) { def write(out: Writer): Unit = {
out.write("format version: %s\n".format(currentVersion)) out.write("format version: %s\n".format(currentVersion))
} }
private val versionPattern = """format version: (\w+)""".r private val versionPattern = """format version: (\w+)""".r
def read(in: BufferedReader) { def read(in: BufferedReader): Unit = {
in.readLine() match { in.readLine() match {
case versionPattern(version) => validateVersion(version) case versionPattern(version) => validateVersion(version)
case s: String => throw new ReadException("\"format version: <version>\"", s) case s: String => throw new ReadException("\"format version: <version>\"", s)
@ -95,7 +95,7 @@ object TextAnalysisFormat {
} }
} }
def validateVersion(version: String) { def validateVersion(version: String): Unit = {
// TODO: Support backwards compatibility? // TODO: Support backwards compatibility?
if (version != currentVersion) { if (version != currentVersion) {
throw new ReadException("File uses format version %s, but we are compatible with version %s only.".format(version, currentVersion)) throw new ReadException("File uses format version %s, but we are compatible with version %s only.".format(version, currentVersion))
@ -121,14 +121,14 @@ object TextAnalysisFormat {
val usedNames = "used names" val usedNames = "used names"
} }
def write(out: Writer, relations: Relations) { def write(out: Writer, relations: Relations): Unit = {
// This ordering is used to persist all values in order. Since all values will be // This ordering is used to persist all values in order. Since all values will be
// persisted using their string representation, it makes sense to sort them using // persisted using their string representation, it makes sense to sort them using
// their string representation. // their string representation.
val toStringOrd = new Ordering[Any] { val toStringOrd = new Ordering[Any] {
def compare(a: Any, b: Any) = a.toString compare b.toString def compare(a: Any, b: Any) = a.toString compare b.toString
} }
def writeRelation[T](header: String, rel: Relation[File, T]) { def writeRelation[T](header: String, rel: Relation[File, T]): Unit = {
writeHeader(out, header) writeHeader(out, header)
writeSize(out, rel.size) writeSize(out, rel.size)
// We sort for ease of debugging and for more efficient reconstruction when reading. // We sort for ease of debugging and for more efficient reconstruction when reading.
@ -156,7 +156,7 @@ object TextAnalysisFormat {
var currentItem: (File, T) = null var currentItem: (File, T) = null
var currentFile: File = null var currentFile: File = null
var currentVals: List[T] = Nil var currentVals: List[T] = Nil
def closeEntry() { def closeEntry(): Unit = {
if (currentFile != null) forward = (currentFile, currentVals.toSet) :: forward if (currentFile != null) forward = (currentFile, currentVals.toSet) :: forward
currentFile = currentItem._1 currentFile = currentItem._1
currentVals = currentItem._2 :: Nil currentVals = currentItem._2 :: Nil
@ -183,7 +183,7 @@ object TextAnalysisFormat {
val classNames = "class names" val classNames = "class names"
} }
def write(out: Writer, stamps: Stamps) { def write(out: Writer, stamps: Stamps): Unit = {
def doWriteMap[V](header: String, m: Map[File, V]) = writeMap(out)(header, m, { v: V => v.toString }) def doWriteMap[V](header: String, m: Map[File, V]) = writeMap(out)(header, m, { v: V => v.toString })
doWriteMap(Headers.products, stamps.products) doWriteMap(Headers.products, stamps.products)
@ -212,7 +212,7 @@ object TextAnalysisFormat {
val stringToSource = ObjectStringifier.stringToObj[Source] _ val stringToSource = ObjectStringifier.stringToObj[Source] _
val sourceToString = ObjectStringifier.objToString[Source] _ val sourceToString = ObjectStringifier.objToString[Source] _
def write(out: Writer, apis: APIs) { def write(out: Writer, apis: APIs): Unit = {
writeMap(out)(Headers.internal, apis.internal, sourceToString, inlineVals = false) writeMap(out)(Headers.internal, apis.internal, sourceToString, inlineVals = false)
writeMap(out)(Headers.external, apis.external, sourceToString, inlineVals = false) writeMap(out)(Headers.external, apis.external, sourceToString, inlineVals = false)
FormatTimer.close("bytes -> base64") FormatTimer.close("bytes -> base64")
@ -237,7 +237,7 @@ object TextAnalysisFormat {
val stringToSourceInfo = ObjectStringifier.stringToObj[SourceInfo] _ val stringToSourceInfo = ObjectStringifier.stringToObj[SourceInfo] _
val sourceInfoToString = ObjectStringifier.objToString[SourceInfo] _ val sourceInfoToString = ObjectStringifier.objToString[SourceInfo] _
def write(out: Writer, infos: SourceInfos) { writeMap(out)(Headers.infos, infos.allInfos, sourceInfoToString, inlineVals = false) } def write(out: Writer, infos: SourceInfos): Unit = writeMap(out)(Headers.infos, infos.allInfos, sourceInfoToString, inlineVals = false)
def read(in: BufferedReader): SourceInfos = SourceInfos.make(readMap(in)(Headers.infos, new File(_), stringToSourceInfo)) def read(in: BufferedReader): SourceInfos = SourceInfos.make(readMap(in)(Headers.infos, new File(_), stringToSourceInfo))
} }
@ -249,9 +249,8 @@ object TextAnalysisFormat {
val stringToCompilation = ObjectStringifier.stringToObj[Compilation] _ val stringToCompilation = ObjectStringifier.stringToObj[Compilation] _
val compilationToString = ObjectStringifier.objToString[Compilation] _ val compilationToString = ObjectStringifier.objToString[Compilation] _
def write(out: Writer, compilations: Compilations) { def write(out: Writer, compilations: Compilations): Unit =
writeSeq(out)(Headers.compilations, compilations.allCompilations, compilationToString) writeSeq(out)(Headers.compilations, compilations.allCompilations, compilationToString)
}
def read(in: BufferedReader): Compilations = Compilations.make( def read(in: BufferedReader): Compilations = Compilations.make(
readSeq[Compilation](in)(Headers.compilations, stringToCompilation)) readSeq[Compilation](in)(Headers.compilations, stringToCompilation))
@ -272,7 +271,7 @@ object TextAnalysisFormat {
private[this] val multipleOutputMode = "multiple" private[this] val multipleOutputMode = "multiple"
private[this] val singleOutputKey = new File("output dir") private[this] val singleOutputKey = new File("output dir")
def write(out: Writer, setup: CompileSetup) { def write(out: Writer, setup: CompileSetup): Unit = {
val (mode, outputAsMap) = setup.output match { val (mode, outputAsMap) = setup.output match {
case s: SingleOutput => (singleOutputMode, Map(singleOutputKey -> s.outputDirectory)) case s: SingleOutput => (singleOutputMode, Map(singleOutputKey -> s.outputDirectory))
case m: MultipleOutput => (multipleOutputMode, m.outputGroups.map(x => x.sourceDirectory -> x.outputDirectory).toMap) case m: MultipleOutput => (multipleOutputMode, m.outputGroups.map(x => x.sourceDirectory -> x.outputDirectory).toMap)
@ -341,18 +340,14 @@ object TextAnalysisFormat {
// Various helper functions. // Various helper functions.
private[this] def writeHeader(out: Writer, header: String) { private[this] def writeHeader(out: Writer, header: String): Unit = out.write(header + ":\n")
out.write(header + ":\n")
}
private[this] def expectHeader(in: BufferedReader, expectedHeader: String) { private[this] def expectHeader(in: BufferedReader, expectedHeader: String): Unit = {
val header = in.readLine() val header = in.readLine()
if (header != expectedHeader + ":") throw new ReadException(expectedHeader, if (header == null) "EOF" else header) if (header != expectedHeader + ":") throw new ReadException(expectedHeader, if (header == null) "EOF" else header)
} }
private[this] def writeSize(out: Writer, n: Int) { private[this] def writeSize(out: Writer, n: Int): Unit = out.write("%d items\n".format(n))
out.write("%d items\n".format(n))
}
private val itemsPattern = """(\d+) items""".r private val itemsPattern = """(\d+) items""".r
private[this] def readSize(in: BufferedReader): Int = { private[this] def readSize(in: BufferedReader): Int = {
@ -363,7 +358,7 @@ object TextAnalysisFormat {
} }
} }
private[this] def writeSeq[T](out: Writer)(header: String, s: Seq[T], t2s: T => String) { private[this] def writeSeq[T](out: Writer)(header: String, s: Seq[T], t2s: T => String): Unit = {
// We write sequences as idx -> element maps, for uniformity with maps/relations. // We write sequences as idx -> element maps, for uniformity with maps/relations.
def n = s.length def n = s.length
val numDigits = if (n < 2) 1 else math.log10(n - 1).toInt + 1 val numDigits = if (n < 2) 1 else math.log10(n - 1).toInt + 1
@ -376,7 +371,7 @@ object TextAnalysisFormat {
private[this] def readSeq[T](in: BufferedReader)(expectedHeader: String, s2t: String => T): Seq[T] = private[this] def readSeq[T](in: BufferedReader)(expectedHeader: String, s2t: String => T): Seq[T] =
(readPairs(in)(expectedHeader, identity[String], s2t).toSeq.sortBy(_._1) map (_._2)) (readPairs(in)(expectedHeader, identity[String], s2t).toSeq.sortBy(_._1) map (_._2))
private[this] def writeMap[K, V](out: Writer)(header: String, m: Map[K, V], v2s: V => String, inlineVals: Boolean = true)(implicit ord: Ordering[K]) { private[this] def writeMap[K, V](out: Writer)(header: String, m: Map[K, V], v2s: V => String, inlineVals: Boolean = true)(implicit ord: Ordering[K]): Unit = {
writeHeader(out, header) writeHeader(out, header)
writeSize(out, m.size) writeSize(out, m.size)
m.keys.toSeq.sorted foreach { k => m.keys.toSeq.sorted foreach { k =>

View File

@ -9,7 +9,7 @@ object CompilationFormat extends Format[Compilation] {
val oin = new ObjectInputStream(new InputWrapperStream(in)) val oin = new ObjectInputStream(new InputWrapperStream(in))
try { oin.readObject.asInstanceOf[Compilation] } finally { oin.close() } try { oin.readObject.asInstanceOf[Compilation] } finally { oin.close() }
} }
def writes(out: Output, src: Compilation) { def writes(out: Output, src: Compilation): Unit = {
val oout = new ObjectOutputStream(new OutputWrapperStream(out)) val oout = new ObjectOutputStream(new OutputWrapperStream(out))
try { oout.writeObject(src) } finally { oout.close() } try { oout.writeObject(src) } finally { oout.close() }
} }

View File

@ -19,7 +19,7 @@ object SourceFormat extends Format[Source] {
val oin = new ObjectInputStream(new InputWrapperStream(in)) val oin = new ObjectInputStream(new InputWrapperStream(in))
try { oin.readObject.asInstanceOf[Source] } finally { oin.close() } try { oin.readObject.asInstanceOf[Source] } finally { oin.close() }
} }
def writes(out: Output, src: Source) { def writes(out: Output, src: Source): Unit = {
val oout = new ObjectOutputStream(new OutputWrapperStream(out)) val oout = new ObjectOutputStream(new OutputWrapperStream(out))
try { oout.writeObject(src) } finally { oout.close() } try { oout.writeObject(src) } finally { oout.close() }
} }

View File

@ -50,7 +50,7 @@ class LoggerReporter(maximumErrors: Int, log: Logger, sourcePositionMapper: Posi
reset() reset()
def reset() { def reset(): Unit = {
count.put(Warn, 0) count.put(Warn, 0)
count.put(SInfo, 0) count.put(SInfo, 0)
count.put(Error, 0) count.put(Error, 0)
@ -60,9 +60,9 @@ class LoggerReporter(maximumErrors: Int, log: Logger, sourcePositionMapper: Posi
def hasWarnings = count.get(Warn) > 0 def hasWarnings = count.get(Warn) > 0
def hasErrors = count.get(Error) > 0 def hasErrors = count.get(Error) > 0
def problems: Array[Problem] = allProblems.toArray def problems: Array[Problem] = allProblems.toArray
def comment(pos: Position, msg: String) {} def comment(pos: Position, msg: String): Unit = ()
def printSummary() { def printSummary(): Unit = {
val warnings = count.get(Severity.Warn) val warnings = count.get(Severity.Warn)
if (warnings > 0) if (warnings > 0)
log.warn(countElementsAsString(warnings, "warning") + " found") log.warn(countElementsAsString(warnings, "warning") + " found")
@ -73,7 +73,7 @@ class LoggerReporter(maximumErrors: Int, log: Logger, sourcePositionMapper: Posi
def inc(sev: Severity) = count.put(sev, count.get(sev) + 1) def inc(sev: Severity) = count.put(sev, count.get(sev) + 1)
def display(pos: Position, msg: String, severity: Severity) { def display(pos: Position, msg: String, severity: Severity): Unit = {
inc(severity) inc(severity)
if (severity != Error || maximumErrors <= 0 || count.get(severity) <= maximumErrors) if (severity != Error || maximumErrors <= 0 || count.get(severity) <= maximumErrors)
print(severityLogger(severity), pos, msg) print(severityLogger(severity), pos, msg)
@ -88,7 +88,7 @@ class LoggerReporter(maximumErrors: Int, log: Logger, sourcePositionMapper: Posi
}) })
} }
def print(log: (=> String) => Unit, pos: Position, msg: String) { def print(log: (=> String) => Unit, pos: Position, msg: String): Unit = {
if (pos.sourcePath.isEmpty && pos.line.isEmpty) if (pos.sourcePath.isEmpty && pos.line.isEmpty)
log(msg) log(msg)
else { else {

View File

@ -32,7 +32,7 @@ final class CompilerArguments(scalaInstance: xsbti.compile.ScalaInstance, cp: xs
filterLibrary(classpath) ++ include(cp.compiler, scalaInstance.compilerJar) ++ include(cp.extra, scalaInstance.otherJars: _*) filterLibrary(classpath) ++ include(cp.compiler, scalaInstance.compilerJar) ++ include(cp.extra, scalaInstance.otherJars: _*)
private[this] def include(flag: Boolean, jars: File*) = if (flag) jars else Nil private[this] def include(flag: Boolean, jars: File*) = if (flag) jars else Nil
private[this] def abs(files: Seq[File]) = files.map(_.getAbsolutePath).sortWith(_ < _) private[this] def abs(files: Seq[File]) = files.map(_.getAbsolutePath).sortWith(_ < _)
private[this] def checkScalaHomeUnset() { private[this] def checkScalaHomeUnset(): Unit = {
val scalaHome = System.getProperty("scala.home") val scalaHome = System.getProperty("scala.home")
assert((scalaHome eq null) || scalaHome.isEmpty, "'scala.home' should not be set (was " + scalaHome + ")") assert((scalaHome eq null) || scalaHome.isEmpty, "'scala.home' should not be set (was " + scalaHome + ")")
} }

View File

@ -42,7 +42,7 @@ object CompilerCache {
def apply(maxInstances: Int): GlobalsCache = new CompilerCache(maxInstances) def apply(maxInstances: Int): GlobalsCache = new CompilerCache(maxInstances)
val fresh: GlobalsCache = new GlobalsCache { val fresh: GlobalsCache = new GlobalsCache {
def clear() {} def clear(): Unit = ()
def apply(args: Array[String], output: Output, forceNew: Boolean, c: CachedCompilerProvider, log: xLogger, reporter: Reporter): CachedCompiler = def apply(args: Array[String], output: Output, forceNew: Boolean, c: CachedCompilerProvider, log: xLogger, reporter: Reporter): CachedCompiler =
c.newCachedCompiler(args, output, log, reporter, /*resident = */ false) c.newCachedCompiler(args, output, log, reporter, /*resident = */ false)
} }

View File

@ -89,7 +89,7 @@ object JavaCompiler {
val javaCp = ClasspathOptions.javac(cp.compiler) val javaCp = ClasspathOptions.javac(cp.compiler)
(new CompilerArguments(scalaInstance, javaCp))(sources, augmentedClasspath, Some(outputDirectory), options) (new CompilerArguments(scalaInstance, javaCp))(sources, augmentedClasspath, Some(outputDirectory), options)
} }
def compile(contract: JavacContract, sources: Seq[File], classpath: Seq[File], outputDirectory: File, options: Seq[String])(implicit log: Logger) { def compile(contract: JavacContract, sources: Seq[File], classpath: Seq[File], outputDirectory: File, options: Seq[String])(implicit log: Logger): Unit = {
val arguments = commandArguments(sources, classpath, outputDirectory, options, log) val arguments = commandArguments(sources, classpath, outputDirectory, options, log)
onArgsF(arguments) onArgsF(arguments)
val code: Int = f(contract, arguments, log) val code: Int = f(contract, arguments, log)

View File

@ -13,7 +13,7 @@ import java.io.File
* the scala-library.jar from `scalaInstance` is put on bootclasspath and the scala-compiler jar goes on the classpath. * the scala-library.jar from `scalaInstance` is put on bootclasspath and the scala-compiler jar goes on the classpath.
*/ */
class RawCompiler(val scalaInstance: xsbti.compile.ScalaInstance, cp: ClasspathOptions, log: Logger) { class RawCompiler(val scalaInstance: xsbti.compile.ScalaInstance, cp: ClasspathOptions, log: Logger) {
def apply(sources: Seq[File], classpath: Seq[File], outputDirectory: File, options: Seq[String]) { def apply(sources: Seq[File], classpath: Seq[File], outputDirectory: File, options: Seq[String]): Unit = {
// reflection is required for binary compatibility // reflection is required for binary compatibility
// The following import ensures there is a compile error if the identifiers change, // The following import ensures there is a compile error if the identifiers change,
// but should not be otherwise directly referenced // but should not be otherwise directly referenced
@ -27,7 +27,7 @@ class RawCompiler(val scalaInstance: xsbti.compile.ScalaInstance, cp: ClasspathO
checkForFailure(mainClass, arguments.toArray) checkForFailure(mainClass, arguments.toArray)
} }
def compilerArguments = new CompilerArguments(scalaInstance, cp) def compilerArguments = new CompilerArguments(scalaInstance, cp)
protected def checkForFailure(mainClass: Class[_], args: Array[String]) { protected def checkForFailure(mainClass: Class[_], args: Array[String]): Unit = {
val reporter = mainClass.getMethod("reporter").invoke(null) val reporter = mainClass.getMethod("reporter").invoke(null)
val failed = reporter.getClass.getMethod("hasErrors").invoke(reporter).asInstanceOf[Boolean] val failed = reporter.getClass.getMethod("hasErrors").invoke(reporter).asInstanceOf[Boolean]
if (failed) throw new CompileFailed(args, "Plain compile failed", Array()) if (failed) throw new CompileFailed(args, "Plain compile failed", Array())

View File

@ -46,7 +46,7 @@ final class DiagnosticsReporter(reporter: Reporter) extends DiagnosticListener[J
Option(source).map(_.toUri.toString) Option(source).map(_.toUri.toString)
} }
} }
override def report(d: Diagnostic[_ <: JavaFileObject]) { override def report(d: Diagnostic[_ <: JavaFileObject]): Unit = {
val severity = val severity =
d.getKind match { d.getKind match {
case Diagnostic.Kind.ERROR => Severity.Error case Diagnostic.Kind.ERROR => Severity.Error

View File

@ -19,7 +19,7 @@ private class ProcessLoggerWriter(delegate: ProcessLogger, level: Level.Value, n
process() process()
} }
private[this] def process() { private[this] def process(): Unit = {
val i = buffer.indexOf(nl) val i = buffer.indexOf(nl)
if (i >= 0) { if (i >= 0) {
log(buffer.substring(0, i)) log(buffer.substring(0, i))

View File

@ -13,22 +13,22 @@ class TestCallback(override val nameHashing: Boolean = false) extends AnalysisCa
val usedNames = scala.collection.mutable.Map.empty[File, Set[String]].withDefaultValue(Set.empty) val usedNames = scala.collection.mutable.Map.empty[File, Set[String]].withDefaultValue(Set.empty)
val apis: scala.collection.mutable.Map[File, SourceAPI] = scala.collection.mutable.Map.empty val apis: scala.collection.mutable.Map[File, SourceAPI] = scala.collection.mutable.Map.empty
def sourceDependency(dependsOn: File, source: File, inherited: Boolean) { def sourceDependency(dependsOn: File, source: File, inherited: Boolean): Unit = {
val context = if(inherited) DependencyByInheritance else DependencyByMemberRef val context = if(inherited) DependencyByInheritance else DependencyByMemberRef
sourceDependency(dependsOn, source, context) sourceDependency(dependsOn, source, context)
} }
def sourceDependency(dependsOn: File, source: File, context: DependencyContext) { sourceDependencies += ((dependsOn, source, context)) } def sourceDependency(dependsOn: File, source: File, context: DependencyContext): Unit = { sourceDependencies += ((dependsOn, source, context)) }
def binaryDependency(binary: File, name: String, source: File, inherited: Boolean) { def binaryDependency(binary: File, name: String, source: File, inherited: Boolean): Unit = {
val context = if(inherited) DependencyByInheritance else DependencyByMemberRef val context = if(inherited) DependencyByInheritance else DependencyByMemberRef
binaryDependency(binary, name, source, context) binaryDependency(binary, name, source, context)
} }
def binaryDependency(binary: File, name: String, source: File, context: DependencyContext) { binaryDependencies += ((binary, name, source, context)) } def binaryDependency(binary: File, name: String, source: File, context: DependencyContext): Unit = { binaryDependencies += ((binary, name, source, context)) }
def generatedClass(source: File, module: File, name: String) { products += ((source, module, name)) } def generatedClass(source: File, module: File, name: String): Unit = { products += ((source, module, name)) }
def usedName(source: File, name: String) { usedNames(source) += name } def usedName(source: File, name: String): Unit = { usedNames(source) += name }
def api(source: File, sourceAPI: SourceAPI): Unit = { def api(source: File, sourceAPI: SourceAPI): Unit = {
assert(!apis.contains(source), s"The `api` method should be called once per source file: $source") assert(!apis.contains(source), s"The `api` method should be called once per source file: $source")
apis(source) = sourceAPI apis(source) = sourceAPI
} }
def problem(category: String, pos: xsbti.Position, message: String, severity: xsbti.Severity, reported: Boolean) {} def problem(category: String, pos: xsbti.Position, message: String, severity: xsbti.Severity, reported: Boolean): Unit = ()
} }

View File

@ -38,7 +38,7 @@ object ReplaceMavenConfigurationMappings {
// NOTE - This code is copied from org.apache.ivy.plugins.parser.m2.PomModuleDescriptorBuilder // NOTE - This code is copied from org.apache.ivy.plugins.parser.m2.PomModuleDescriptorBuilder
// except with altered default configurations... // except with altered default configurations...
REPLACEMENT_MAPPINGS.put("compile", new PomModuleDescriptorBuilder.ConfMapper { REPLACEMENT_MAPPINGS.put("compile", new PomModuleDescriptorBuilder.ConfMapper {
def addMappingConfs(dd: DefaultDependencyDescriptor, isOptional: Boolean) { def addMappingConfs(dd: DefaultDependencyDescriptor, isOptional: Boolean): Unit = {
if (isOptional) { if (isOptional) {
dd.addDependencyConfiguration("optional", "compile(*)") dd.addDependencyConfiguration("optional", "compile(*)")
// FIX - Here we take a mroe conservative approach of depending on the compile configuration if master isn't there. // FIX - Here we take a mroe conservative approach of depending on the compile configuration if master isn't there.
@ -52,7 +52,7 @@ object ReplaceMavenConfigurationMappings {
} }
}) })
REPLACEMENT_MAPPINGS.put("provided", new PomModuleDescriptorBuilder.ConfMapper { REPLACEMENT_MAPPINGS.put("provided", new PomModuleDescriptorBuilder.ConfMapper {
def addMappingConfs(dd: DefaultDependencyDescriptor, isOptional: Boolean) { def addMappingConfs(dd: DefaultDependencyDescriptor, isOptional: Boolean): Unit = {
if (isOptional) { if (isOptional) {
dd.addDependencyConfiguration("optional", "compile(*)") dd.addDependencyConfiguration("optional", "compile(*)")
dd.addDependencyConfiguration("optional", "provided(*)") dd.addDependencyConfiguration("optional", "provided(*)")
@ -70,7 +70,7 @@ object ReplaceMavenConfigurationMappings {
}) })
REPLACEMENT_MAPPINGS.put("runtime", new PomModuleDescriptorBuilder.ConfMapper { REPLACEMENT_MAPPINGS.put("runtime", new PomModuleDescriptorBuilder.ConfMapper {
def addMappingConfs(dd: DefaultDependencyDescriptor, isOptional: Boolean) { def addMappingConfs(dd: DefaultDependencyDescriptor, isOptional: Boolean): Unit = {
if (isOptional) { if (isOptional) {
dd.addDependencyConfiguration("optional", "compile(*)") dd.addDependencyConfiguration("optional", "compile(*)")
dd.addDependencyConfiguration("optional", "provided(*)") dd.addDependencyConfiguration("optional", "provided(*)")
@ -86,7 +86,7 @@ object ReplaceMavenConfigurationMappings {
}) })
REPLACEMENT_MAPPINGS.put("test", new PomModuleDescriptorBuilder.ConfMapper { REPLACEMENT_MAPPINGS.put("test", new PomModuleDescriptorBuilder.ConfMapper {
def addMappingConfs(dd: DefaultDependencyDescriptor, isOptional: Boolean) { def addMappingConfs(dd: DefaultDependencyDescriptor, isOptional: Boolean): Unit = {
dd.addDependencyConfiguration("test", "runtime(*)") dd.addDependencyConfiguration("test", "runtime(*)")
// FIX - Here we take a mroe conservative approach of depending on the compile configuration if master isn't there. // FIX - Here we take a mroe conservative approach of depending on the compile configuration if master isn't there.
dd.addDependencyConfiguration("test", "master(compile)") dd.addDependencyConfiguration("test", "master(compile)")
@ -94,7 +94,7 @@ object ReplaceMavenConfigurationMappings {
}) })
REPLACEMENT_MAPPINGS.put("system", new PomModuleDescriptorBuilder.ConfMapper { REPLACEMENT_MAPPINGS.put("system", new PomModuleDescriptorBuilder.ConfMapper {
def addMappingConfs(dd: DefaultDependencyDescriptor, isOptional: Boolean) { def addMappingConfs(dd: DefaultDependencyDescriptor, isOptional: Boolean): Unit = {
// FIX - Here we take a mroe conservative approach of depending on the compile configuration if master isn't there. // FIX - Here we take a mroe conservative approach of depending on the compile configuration if master isn't there.
dd.addDependencyConfiguration("system", "master(compile)") dd.addDependencyConfiguration("system", "master(compile)")
} }

View File

@ -28,10 +28,10 @@ object ConflictWarning {
@deprecated("Warning on evicted modules is no longer done, so this is the same as `default`. Use a standard Ivy conflict manager.", "0.13.0") @deprecated("Warning on evicted modules is no longer done, so this is the same as `default`. Use a standard Ivy conflict manager.", "0.13.0")
def strict(label: String): ConflictWarning = ConflictWarning(label, Level.Error, true) def strict(label: String): ConflictWarning = ConflictWarning(label, Level.Error, true)
def apply(config: ConflictWarning, report: UpdateReport, log: Logger) { def apply(config: ConflictWarning, report: UpdateReport, log: Logger): Unit = {
processCrossVersioned(config, report, log) processCrossVersioned(config, report, log)
} }
private[this] def processCrossVersioned(config: ConflictWarning, report: UpdateReport, log: Logger) { private[this] def processCrossVersioned(config: ConflictWarning, report: UpdateReport, log: Logger): Unit = {
val crossMismatches = crossVersionMismatches(report) val crossMismatches = crossVersionMismatches(report)
if (crossMismatches.nonEmpty) { if (crossMismatches.nonEmpty) {
val pre = s"Modules were resolved with conflicting cross-version suffixes in ${config.label}:\n " val pre = s"Modules were resolved with conflicting cross-version suffixes in ${config.label}:\n "

View File

@ -113,7 +113,7 @@ private[sbt] object ConvertResolver {
{ {
val pattern = Collections.singletonList(Resolver.resolvePattern(repo.root, Resolver.mavenStyleBasePattern)) val pattern = Collections.singletonList(Resolver.resolvePattern(repo.root, Resolver.mavenStyleBasePattern))
final class PluginCapableResolver extends IBiblioResolver with ChecksumFriendlyURLResolver with DescriptorRequired { final class PluginCapableResolver extends IBiblioResolver with ChecksumFriendlyURLResolver with DescriptorRequired {
def setPatterns() { def setPatterns(): Unit = {
// done this way for access to protected methods. // done this way for access to protected methods.
setArtifactPatterns(pattern) setArtifactPatterns(pattern)
setIvyPatterns(pattern) setIvyPatterns(pattern)
@ -189,18 +189,18 @@ private[sbt] object ConvertResolver {
def hasExplicitURL(dd: DependencyDescriptor): Boolean = def hasExplicitURL(dd: DependencyDescriptor): Boolean =
dd.getAllDependencyArtifacts.exists(_.getUrl != null) dd.getAllDependencyArtifacts.exists(_.getUrl != null)
} }
private def initializeMavenStyle(resolver: IBiblioResolver, name: String, root: String) { private def initializeMavenStyle(resolver: IBiblioResolver, name: String, root: String): Unit = {
resolver.setName(name) resolver.setName(name)
resolver.setM2compatible(true) resolver.setM2compatible(true)
resolver.setRoot(root) resolver.setRoot(root)
} }
private def initializeSSHResolver(resolver: AbstractSshBasedResolver, repo: SshBasedRepository, settings: IvySettings) { private def initializeSSHResolver(resolver: AbstractSshBasedResolver, repo: SshBasedRepository, settings: IvySettings): Unit = {
resolver.setName(repo.name) resolver.setName(repo.name)
resolver.setPassfile(null) resolver.setPassfile(null)
initializePatterns(resolver, repo.patterns, settings) initializePatterns(resolver, repo.patterns, settings)
initializeConnection(resolver, repo.connection) initializeConnection(resolver, repo.connection)
} }
private def initializeConnection(resolver: AbstractSshBasedResolver, connection: RepositoryHelpers.SshConnection) { private def initializeConnection(resolver: AbstractSshBasedResolver, connection: RepositoryHelpers.SshConnection): Unit = {
import resolver._ import resolver._
import connection._ import connection._
hostname.foreach(setHost) hostname.foreach(setHost)
@ -216,7 +216,7 @@ private[sbt] object ConvertResolver {
setUser(user) setUser(user)
} }
} }
private def initializePatterns(resolver: AbstractPatternsBasedResolver, patterns: Patterns, settings: IvySettings) { private def initializePatterns(resolver: AbstractPatternsBasedResolver, patterns: Patterns, settings: IvySettings): Unit = {
resolver.setM2compatible(patterns.isMavenCompatible) resolver.setM2compatible(patterns.isMavenCompatible)
resolver.setDescriptor(if (patterns.descriptorOptional) BasicResolver.DESCRIPTOR_OPTIONAL else BasicResolver.DESCRIPTOR_REQUIRED) resolver.setDescriptor(if (patterns.descriptorOptional) BasicResolver.DESCRIPTOR_OPTIONAL else BasicResolver.DESCRIPTOR_REQUIRED)
resolver.setCheckconsistency(!patterns.skipConsistencyCheck) resolver.setCheckconsistency(!patterns.skipConsistencyCheck)

View File

@ -21,9 +21,9 @@ private[sbt] object CustomXmlParser extends XmlModuleDescriptorParser {
super.setResource(new URLResource(url)) super.setResource(new URLResource(url))
super.setInput(url) super.setInput(url)
} }
def setInput(bytes: Array[Byte]) { setInput(new ByteArrayInputStream(bytes)) } def setInput(bytes: Array[Byte]): Unit = setInput(new ByteArrayInputStream(bytes))
/** Overridden because the super implementation overwrites the module descriptor.*/ /** Overridden because the super implementation overwrites the module descriptor.*/
override def setResource(res: Resource) {} override def setResource(res: Resource): Unit = ()
override def setMd(md: DefaultModuleDescriptor) = override def setMd(md: DefaultModuleDescriptor) =
{ {
super.setMd(md) super.setMd(md)

View File

@ -231,7 +231,7 @@ final class IvySbt(val configuration: IvyConfiguration) {
addScalaToolDependencies(dmd, parser, is) addScalaToolDependencies(dmd, parser, is)
(dmd, parser.getDefaultConf) (dmd, parser.getDefaultConf)
} }
private def addScalaToolDependencies(dmd: DefaultModuleDescriptor, parser: CustomXmlParser.CustomParser, is: IvyScala) { private def addScalaToolDependencies(dmd: DefaultModuleDescriptor, parser: CustomXmlParser.CustomParser, is: IvyScala): Unit = {
IvySbt.addConfigurations(dmd, Configurations.ScalaTool :: Nil) IvySbt.addConfigurations(dmd, Configurations.ScalaTool :: Nil)
IvySbt.addDependencies(dmd, ScalaArtifacts.toolDependencies(is.scalaOrganization, is.scalaFullVersion), parser) IvySbt.addDependencies(dmd, ScalaArtifacts.toolDependencies(is.scalaOrganization, is.scalaFullVersion), parser)
} }
@ -257,7 +257,7 @@ private[sbt] object IvySbt {
def defaultIvyConfiguration(project: File) = new File(project, DefaultIvyConfigFilename) def defaultIvyConfiguration(project: File) = new File(project, DefaultIvyConfigFilename)
def defaultPOM(project: File) = new File(project, DefaultMavenFilename) def defaultPOM(project: File) = new File(project, DefaultMavenFilename)
def loadURI(is: IvySettings, uri: URI) { def loadURI(is: IvySettings, uri: URI): Unit = {
if (uri.getScheme == "file") if (uri.getScheme == "file")
is.load(new File(uri)) // IVY-1114 is.load(new File(uri)) // IVY-1114
else else
@ -268,7 +268,7 @@ private[sbt] object IvySbt {
* Sets the resolvers for 'settings' to 'resolvers'. This is done by creating a new chain and making it the default. * Sets the resolvers for 'settings' to 'resolvers'. This is done by creating a new chain and making it the default.
* 'other' is for resolvers that should be in a different chain. These are typically used for publishing or other actions. * 'other' is for resolvers that should be in a different chain. These are typically used for publishing or other actions.
*/ */
private def setResolvers(settings: IvySettings, resolvers: Seq[Resolver], other: Seq[Resolver], localOnly: Boolean, updateOptions: UpdateOptions, log: Logger) { private def setResolvers(settings: IvySettings, resolvers: Seq[Resolver], other: Seq[Resolver], localOnly: Boolean, updateOptions: UpdateOptions, log: Logger): Unit = {
def makeChain(label: String, name: String, rs: Seq[Resolver]) = { def makeChain(label: String, name: String, rs: Seq[Resolver]) = {
log.debug(label + " repositories:") log.debug(label + " repositories:")
val chain = resolverChain(name, rs, localOnly, settings, updateOptions, log) val chain = resolverChain(name, rs, localOnly, settings, updateOptions, log)
@ -304,7 +304,7 @@ private[sbt] object IvySbt {
} }
} }
def addResolvers(resolvers: Seq[Resolver], settings: IvySettings, log: Logger) { def addResolvers(resolvers: Seq[Resolver], settings: IvySettings, log: Logger): Unit = {
for (r <- resolvers) { for (r <- resolvers) {
log.debug("\t" + r) log.debug("\t" + r)
settings.addResolver(ConvertResolver(r, settings, log)) settings.addResolver(ConvertResolver(r, settings, log))
@ -320,7 +320,7 @@ private[sbt] object IvySbt {
import collection.JavaConversions._ import collection.JavaConversions._
artifact.getQualifiedExtraAttributes.keys.exists(_.asInstanceOf[String] startsWith "m:") artifact.getQualifiedExtraAttributes.keys.exists(_.asInstanceOf[String] startsWith "m:")
} }
private def setModuleConfigurations(settings: IvySettings, moduleConfigurations: Seq[ModuleConfiguration], log: Logger) { private def setModuleConfigurations(settings: IvySettings, moduleConfigurations: Seq[ModuleConfiguration], log: Logger): Unit = {
val existing = settings.getResolverNames val existing = settings.getResolverNames
for (moduleConf <- moduleConfigurations) { for (moduleConf <- moduleConfigurations) {
import moduleConf._ import moduleConf._
@ -332,11 +332,11 @@ private[sbt] object IvySbt {
settings.addModuleConfiguration(attributes, settings.getMatcher(EXACT_OR_REGEXP), resolver.name, null, null, null) settings.addModuleConfiguration(attributes, settings.getMatcher(EXACT_OR_REGEXP), resolver.name, null, null, null)
} }
} }
private def configureCache(settings: IvySettings, localOnly: Boolean, resCacheDir: Option[File]) { private def configureCache(settings: IvySettings, localOnly: Boolean, resCacheDir: Option[File]): Unit = {
configureResolutionCache(settings, localOnly, resCacheDir) configureResolutionCache(settings, localOnly, resCacheDir)
configureRepositoryCache(settings, localOnly) configureRepositoryCache(settings, localOnly)
} }
private[this] def configureResolutionCache(settings: IvySettings, localOnly: Boolean, resCacheDir: Option[File]) { private[this] def configureResolutionCache(settings: IvySettings, localOnly: Boolean, resCacheDir: Option[File]): Unit = {
val base = resCacheDir getOrElse settings.getDefaultResolutionCacheBasedir val base = resCacheDir getOrElse settings.getDefaultResolutionCacheBasedir
settings.setResolutionCacheManager(new ResolutionCache(base, settings)) settings.setResolutionCacheManager(new ResolutionCache(base, settings))
} }
@ -385,7 +385,7 @@ private[sbt] object IvySbt {
case _ => false case _ => false
} }
// ignore the original resolver wherever possible to avoid issues like #704 // ignore the original resolver wherever possible to avoid issues like #704
override def saveResolvers(descriptor: ModuleDescriptor, metadataResolverName: String, artifactResolverName: String) {} override def saveResolvers(descriptor: ModuleDescriptor, metadataResolverName: String, artifactResolverName: String): Unit = ()
} }
manager.setArtifactPattern(PluginPattern + manager.getArtifactPattern) manager.setArtifactPattern(PluginPattern + manager.getArtifactPattern)
manager.setDataFilePattern(PluginPattern + manager.getDataFilePattern) manager.setDataFilePattern(PluginPattern + manager.getDataFilePattern)
@ -411,12 +411,12 @@ private[sbt] object IvySbt {
dmd.addExtraAttributeNamespace("e", "http://ant.apache.org/ivy/extra") dmd.addExtraAttributeNamespace("e", "http://ant.apache.org/ivy/extra")
/** Adds the ivy.xml main artifact. */ /** Adds the ivy.xml main artifact. */
private def addMainArtifact(moduleID: DefaultModuleDescriptor) { private def addMainArtifact(moduleID: DefaultModuleDescriptor): Unit = {
val artifact = DefaultArtifact.newIvyArtifact(moduleID.getResolvedModuleRevisionId, moduleID.getPublicationDate) val artifact = DefaultArtifact.newIvyArtifact(moduleID.getResolvedModuleRevisionId, moduleID.getPublicationDate)
moduleID.setModuleArtifact(artifact) moduleID.setModuleArtifact(artifact)
moduleID.check() moduleID.check()
} }
private def setConflictManager(moduleID: DefaultModuleDescriptor, conflict: ConflictManager, is: IvySettings) { private def setConflictManager(moduleID: DefaultModuleDescriptor, conflict: ConflictManager, is: IvySettings): Unit = {
val mid = ModuleId.newInstance(conflict.organization, conflict.module) val mid = ModuleId.newInstance(conflict.organization, conflict.module)
val matcher = is.getMatcher(PatternMatcher.EXACT_OR_REGEXP) val matcher = is.getMatcher(PatternMatcher.EXACT_OR_REGEXP)
val manager = is.getConflictManager(conflict.name) val manager = is.getConflictManager(conflict.name)
@ -555,7 +555,7 @@ private[sbt] object IvySbt {
} }
/** This method is used to add inline dependencies to the provided module. */ /** This method is used to add inline dependencies to the provided module. */
def addDependencies(moduleID: DefaultModuleDescriptor, dependencies: Seq[ModuleID], parser: CustomXmlParser.CustomParser) { def addDependencies(moduleID: DefaultModuleDescriptor, dependencies: Seq[ModuleID], parser: CustomXmlParser.CustomParser): Unit = {
val converted = dependencies map { dependency => convertDependency(moduleID, dependency, parser) } val converted = dependencies map { dependency => convertDependency(moduleID, dependency, parser) }
val unique = if (hasDuplicateDependencies(converted)) mergeDuplicateDefinitions(converted) else converted val unique = if (hasDuplicateDependencies(converted)) mergeDuplicateDefinitions(converted) else converted
unique foreach moduleID.addDependency unique foreach moduleID.addDependency

View File

@ -61,7 +61,7 @@ object UpdateLogging extends Enumeration {
object IvyActions { object IvyActions {
/** Installs the dependencies of the given 'module' from the resolver named 'from' to the resolver named 'to'.*/ /** Installs the dependencies of the given 'module' from the resolver named 'from' to the resolver named 'to'.*/
def install(module: IvySbt#Module, from: String, to: String, log: Logger) { def install(module: IvySbt#Module, from: String, to: String, log: Logger): Unit = {
module.withModule(log) { (ivy, md, default) => module.withModule(log) { (ivy, md, default) =>
for (dependency <- md.getDependencies) { for (dependency <- md.getDependencies) {
log.info("Installing " + dependency) log.info("Installing " + dependency)
@ -89,7 +89,7 @@ object IvyActions {
} }
/** Creates a Maven pom from the given Ivy configuration*/ /** Creates a Maven pom from the given Ivy configuration*/
def makePom(module: IvySbt#Module, configuration: MakePomConfiguration, log: Logger) { def makePom(module: IvySbt#Module, configuration: MakePomConfiguration, log: Logger): Unit = {
import configuration.{ allRepositories, moduleInfo, configurations, extra, file, filterRepositories, process, includeTypes } import configuration.{ allRepositories, moduleInfo, configurations, extra, file, filterRepositories, process, includeTypes }
module.withModule(log) { (ivy, md, default) => module.withModule(log) { (ivy, md, default) =>
(new MakePom(log)).write(ivy, md, moduleInfo, configurations, includeTypes, extra, process, filterRepositories, allRepositories, file) (new MakePom(log)).write(ivy, md, moduleInfo, configurations, includeTypes, extra, process, filterRepositories, allRepositories, file)
@ -112,7 +112,7 @@ object IvyActions {
def deliveredFile(ivy: Ivy, pattern: String, md: ModuleDescriptor): File = def deliveredFile(ivy: Ivy, pattern: String, md: ModuleDescriptor): File =
ivy.getSettings.resolveFile(IvyPatternHelper.substitute(pattern, md.getResolvedModuleRevisionId)) ivy.getSettings.resolveFile(IvyPatternHelper.substitute(pattern, md.getResolvedModuleRevisionId))
def publish(module: IvySbt#Module, configuration: PublishConfiguration, log: Logger) { def publish(module: IvySbt#Module, configuration: PublishConfiguration, log: Logger): Unit = {
import configuration._ import configuration._
module.withModule(log) { module.withModule(log) {
case (ivy, md, default) => case (ivy, md, default) =>
@ -368,7 +368,7 @@ object IvyActions {
} }
} }
} }
private[this] def checkFilesPresent(artifacts: Seq[(IArtifact, File)]) { private[this] def checkFilesPresent(artifacts: Seq[(IArtifact, File)]): Unit = {
val missing = artifacts filter { case (a, file) => !file.exists } val missing = artifacts filter { case (a, file) => !file.exists }
if (missing.nonEmpty) if (missing.nonEmpty)
sys.error("Missing files for publishing:\n\t" + missing.map(_._2.getAbsolutePath).mkString("\n\t")) sys.error("Missing files for publishing:\n\t" + missing.map(_._2.getAbsolutePath).mkString("\n\t"))

View File

@ -28,7 +28,7 @@ private object NotInCache {
class IvyCache(val ivyHome: Option[File]) { class IvyCache(val ivyHome: Option[File]) {
def lockFile = new File(ivyHome getOrElse Path.userHome, ".sbt.cache.lock") def lockFile = new File(ivyHome getOrElse Path.userHome, ".sbt.cache.lock")
/** Caches the given 'file' with the given ID. It may be retrieved or cleared using this ID.*/ /** Caches the given 'file' with the given ID. It may be retrieved or cleared using this ID.*/
def cacheJar(moduleID: ModuleID, file: File, lock: Option[xsbti.GlobalLock], log: Logger) { def cacheJar(moduleID: ModuleID, file: File, lock: Option[xsbti.GlobalLock], log: Logger): Unit = {
val artifact = defaultArtifact(moduleID) val artifact = defaultArtifact(moduleID)
val resolved = new ResolvedResource(new FileResource(new IvyFileRepository, file), moduleID.revision) val resolved = new ResolvedResource(new FileResource(new IvyFileRepository, file), moduleID.revision)
withDefaultCache(lock, log) { cache => withDefaultCache(lock, log) { cache =>
@ -37,7 +37,7 @@ class IvyCache(val ivyHome: Option[File]) {
} }
} }
/** Clears the cache of the jar for the given ID.*/ /** Clears the cache of the jar for the given ID.*/
def clearCachedJar(id: ModuleID, lock: Option[xsbti.GlobalLock], log: Logger) { def clearCachedJar(id: ModuleID, lock: Option[xsbti.GlobalLock], log: Logger): Unit = {
try { withCachedJar(id, lock, log)(_.delete) } try { withCachedJar(id, lock, log)(_.delete) }
catch { case e: Exception => log.debug("Error cleaning cached jar: " + e.toString) } catch { case e: Exception => log.debug("Error cleaning cached jar: " + e.toString) }
} }
@ -87,7 +87,7 @@ class IvyCache(val ivyHome: Option[File]) {
} }
/** Required by Ivy for copying to the cache.*/ /** Required by Ivy for copying to the cache.*/
private class FileDownloader extends ResourceDownloader with NotNull { private class FileDownloader extends ResourceDownloader with NotNull {
def download(artifact: IvyArtifact, resource: Resource, dest: File) { def download(artifact: IvyArtifact, resource: Resource, dest: File): Unit = {
if (dest.exists()) dest.delete() if (dest.exists()) dest.delete()
val part = new File(dest.getAbsolutePath + ".part") val part = new File(dest.getAbsolutePath + ".part")
FileUtil.copy(resource.openStream, part, null) FileUtil.copy(resource.openStream, part, null)

View File

@ -7,8 +7,8 @@ import org.apache.ivy.util.{ Message, MessageLogger, MessageLoggerEngine }
/** Interface to Ivy logging. */ /** Interface to Ivy logging. */
private final class IvyLoggerInterface(logger: Logger) extends MessageLogger { private final class IvyLoggerInterface(logger: Logger) extends MessageLogger {
def rawlog(msg: String, level: Int) = log(msg, level) def rawlog(msg: String, level: Int): Unit = log(msg, level)
def log(msg: String, level: Int) { def log(msg: String, level: Int): Unit = {
import Message.{ MSG_DEBUG, MSG_VERBOSE, MSG_INFO, MSG_WARN, MSG_ERR } import Message.{ MSG_DEBUG, MSG_VERBOSE, MSG_INFO, MSG_WARN, MSG_ERR }
level match { level match {
case MSG_DEBUG => debug(msg) case MSG_DEBUG => debug(msg)
@ -20,32 +20,32 @@ private final class IvyLoggerInterface(logger: Logger) extends MessageLogger {
} }
//DEBUG level messages are very verbose and rarely useful to users. //DEBUG level messages are very verbose and rarely useful to users.
// TODO: provide access to this information some other way // TODO: provide access to this information some other way
def debug(msg: String) {} def debug(msg: String): Unit = ()
def verbose(msg: String) = logger.verbose(msg) def verbose(msg: String): Unit = logger.verbose(msg)
def deprecated(msg: String) = warn(msg) def deprecated(msg: String): Unit = warn(msg)
def info(msg: String) = logger.info(msg) def info(msg: String): Unit = logger.info(msg)
def rawinfo(msg: String) = info(msg) def rawinfo(msg: String): Unit = info(msg)
def warn(msg: String) = logger.warn(msg) def warn(msg: String): Unit = logger.warn(msg)
def error(msg: String) = if (SbtIvyLogger.acceptError(msg)) logger.error(msg) def error(msg: String): Unit = if (SbtIvyLogger.acceptError(msg)) logger.error(msg)
private def emptyList = java.util.Collections.emptyList[String] private def emptyList = java.util.Collections.emptyList[String]
def getProblems = emptyList def getProblems = emptyList
def getWarns = emptyList def getWarns = emptyList
def getErrors = emptyList def getErrors = emptyList
def clearProblems = () def clearProblems(): Unit = ()
def sumupProblems = clearProblems() def sumupProblems(): Unit = clearProblems()
def progress = () def progress(): Unit = ()
def endProgress = () def endProgress(): Unit = ()
def endProgress(msg: String) = info(msg) def endProgress(msg: String): Unit = info(msg)
def isShowProgress = false def isShowProgress = false
def setShowProgress(progress: Boolean) {} def setShowProgress(progress: Boolean): Unit = ()
} }
private final class SbtMessageLoggerEngine extends MessageLoggerEngine { private final class SbtMessageLoggerEngine extends MessageLoggerEngine {
/** This is a hack to filter error messages about 'unknown resolver ...'. */ /** This is a hack to filter error messages about 'unknown resolver ...'. */
override def error(msg: String) = if (SbtIvyLogger.acceptError(msg)) super.error(msg) override def error(msg: String): Unit = if (SbtIvyLogger.acceptError(msg)) super.error(msg)
override def sumupProblems = clearProblems() override def sumupProblems(): Unit = clearProblems()
} }
private object SbtIvyLogger { private object SbtIvyLogger {
val UnknownResolver = "unknown resolver" val UnknownResolver = "unknown resolver"

View File

@ -37,7 +37,7 @@ final case class IvyScala(scalaFullVersion: String, scalaBinaryVersion: String,
private object IvyScala { private object IvyScala {
/** Performs checks/adds filters on Scala dependencies (if enabled in IvyScala). */ /** Performs checks/adds filters on Scala dependencies (if enabled in IvyScala). */
def checkModule(module: DefaultModuleDescriptor, conf: String, log: Logger)(check: IvyScala) { def checkModule(module: DefaultModuleDescriptor, conf: String, log: Logger)(check: IvyScala): Unit = {
if (check.checkExplicit) if (check.checkExplicit)
checkDependencies(module, check.scalaBinaryVersion, check.configurations, log) checkDependencies(module, check.scalaBinaryVersion, check.configurations, log)
if (check.filterImplicit) if (check.filterImplicit)
@ -45,12 +45,12 @@ private object IvyScala {
if (check.overrideScalaVersion) if (check.overrideScalaVersion)
overrideScalaVersion(module, check.scalaFullVersion) overrideScalaVersion(module, check.scalaFullVersion)
} }
def overrideScalaVersion(module: DefaultModuleDescriptor, version: String) { def overrideScalaVersion(module: DefaultModuleDescriptor, version: String): Unit = {
overrideVersion(module, Organization, LibraryID, version) overrideVersion(module, Organization, LibraryID, version)
overrideVersion(module, Organization, CompilerID, version) overrideVersion(module, Organization, CompilerID, version)
overrideVersion(module, Organization, ReflectID, version) overrideVersion(module, Organization, ReflectID, version)
} }
def overrideVersion(module: DefaultModuleDescriptor, org: String, name: String, version: String) { def overrideVersion(module: DefaultModuleDescriptor, org: String, name: String, version: String): Unit = {
val id = new ModuleId(org, name) val id = new ModuleId(org, name)
val over = new OverrideDependencyDescriptorMediator(null, version) val over = new OverrideDependencyDescriptorMediator(null, version)
module.addDependencyDescriptorMediator(id, ExactPatternMatcher.INSTANCE, over) module.addDependencyDescriptorMediator(id, ExactPatternMatcher.INSTANCE, over)
@ -60,7 +60,7 @@ private object IvyScala {
* Checks the immediate dependencies of module for dependencies on scala jars and verifies that the version on the * Checks the immediate dependencies of module for dependencies on scala jars and verifies that the version on the
* dependencies matches scalaVersion. * dependencies matches scalaVersion.
*/ */
private def checkDependencies(module: ModuleDescriptor, scalaBinaryVersion: String, configurations: Iterable[Configuration], log: Logger) { private def checkDependencies(module: ModuleDescriptor, scalaBinaryVersion: String, configurations: Iterable[Configuration], log: Logger): Unit = {
val configSet = if (configurations.isEmpty) (c: String) => true else configurationSet(configurations) val configSet = if (configurations.isEmpty) (c: String) => true else configurationSet(configurations)
def binaryScalaWarning(dep: DependencyDescriptor): Option[String] = def binaryScalaWarning(dep: DependencyDescriptor): Option[String] =
{ {
@ -88,7 +88,7 @@ private object IvyScala {
* done because these jars are provided by the ScalaInstance of the project. The version of Scala to use * done because these jars are provided by the ScalaInstance of the project. The version of Scala to use
* is done by setting scalaVersion in the project definition. * is done by setting scalaVersion in the project definition.
*/ */
private def excludeScalaJars(module: DefaultModuleDescriptor, configurations: Iterable[Configuration]) { private def excludeScalaJars(module: DefaultModuleDescriptor, configurations: Iterable[Configuration]): Unit = {
val configurationNames = val configurationNames =
{ {
val names = module.getConfigurationsNames val names = module.getConfigurationsNames

View File

@ -83,9 +83,8 @@ class MakePom(val log: Logger) {
write(process(toPom(ivy, module, moduleInfo, configurations, includeTypes, extra, filterRepositories, allRepositories)), output) write(process(toPom(ivy, module, moduleInfo, configurations, includeTypes, extra, filterRepositories, allRepositories)), output)
// use \n as newline because toString uses PrettyPrinter, which hard codes line endings to be \n // use \n as newline because toString uses PrettyPrinter, which hard codes line endings to be \n
def write(node: XNode, output: File): Unit = write(toString(node), output, "\n") def write(node: XNode, output: File): Unit = write(toString(node), output, "\n")
def write(xmlString: String, output: File, newline: String) { def write(xmlString: String, output: File, newline: String): Unit =
IO.write(output, "<?xml version='1.0' encoding='" + IO.utf8.name + "'?>" + newline + xmlString) IO.write(output, "<?xml version='1.0' encoding='" + IO.utf8.name + "'?>" + newline + xmlString)
}
def toString(node: XNode): String = new PrettyPrinter(1000, 4).format(node) def toString(node: XNode): String = new PrettyPrinter(1000, 4).format(node)
@deprecated("Use `toPom(Ivy, ModuleDescriptor, ModuleInfo, Option[Iterable[Configuration]], Set[String], NodeSeq, MavenRepository => Boolean, Boolean)` instead", "0.11.2") @deprecated("Use `toPom(Ivy, ModuleDescriptor, ModuleInfo, Option[Iterable[Configuration]], Set[String], NodeSeq, MavenRepository => Boolean, Boolean)` instead", "0.11.2")

View File

@ -70,12 +70,12 @@ class ProjectResolver(name: String, map: Map[ModuleRevisionId, ModuleDescriptor]
// doesn't support publishing // doesn't support publishing
def publish(artifact: IArtifact, src: File, overwrite: Boolean) = sys.error("Publish not supported by ProjectResolver") def publish(artifact: IArtifact, src: File, overwrite: Boolean) = sys.error("Publish not supported by ProjectResolver")
def beginPublishTransaction(module: ModuleRevisionId, overwrite: Boolean) {} def beginPublishTransaction(module: ModuleRevisionId, overwrite: Boolean): Unit = ()
def abortPublishTransaction() {} def abortPublishTransaction(): Unit = ()
def commitPublishTransaction() {} def commitPublishTransaction(): Unit = ()
def reportFailure() {} def reportFailure(): Unit = ()
def reportFailure(art: IArtifact) {} def reportFailure(art: IArtifact): Unit = ()
def listOrganisations() = new Array[OrganisationEntry](0) def listOrganisations() = new Array[OrganisationEntry](0)
def listModules(org: OrganisationEntry) = new Array[ModuleEntry](0) def listModules(org: OrganisationEntry) = new Array[ModuleEntry](0)
@ -85,8 +85,8 @@ class ProjectResolver(name: String, map: Map[ModuleRevisionId, ModuleDescriptor]
private[this] var settings: Option[ResolverSettings] = None private[this] var settings: Option[ResolverSettings] = None
def dumpSettings() {} def dumpSettings(): Unit = ()
def setSettings(settings: ResolverSettings) { this.settings = Some(settings) } def setSettings(settings: ResolverSettings): Unit = { this.settings = Some(settings) }
def getRepositoryCacheManager = settings match { case Some(s) => s.getDefaultRepositoryCacheManager; case None => sys.error("No settings defined for ProjectResolver") } def getRepositoryCacheManager = settings match { case Some(s) => s.getDefaultRepositoryCacheManager; case None => sys.error("No settings defined for ProjectResolver") }
} }

View File

@ -28,7 +28,7 @@ private[sbt] final class ResolutionCache(base: File, settings: IvySettings) exte
private[this] val reportBase: File = new File(base, ReportDirectory) private[this] val reportBase: File = new File(base, ReportDirectory)
def getResolutionCacheRoot: File = base def getResolutionCacheRoot: File = base
def clean() { IO.delete(base) } def clean(): Unit = IO.delete(base)
override def toString = Name override def toString = Name
def getResolvedIvyFileInCache(mrid: ModuleRevisionId): File = def getResolvedIvyFileInCache(mrid: ModuleRevisionId): File =
@ -66,7 +66,7 @@ private[sbt] object ResolutionCache {
* Removes cached files from the resolution cache for the module with ID `mrid` * Removes cached files from the resolution cache for the module with ID `mrid`
* and the resolveId (as set on `ResolveOptions`). * and the resolveId (as set on `ResolveOptions`).
*/ */
private[sbt] def cleanModule(mrid: ModuleRevisionId, resolveId: String, manager: ResolutionCacheManager) { private[sbt] def cleanModule(mrid: ModuleRevisionId, resolveId: String, manager: ResolutionCacheManager): Unit = {
val files = val files =
Option(manager.getResolvedIvyFileInCache(mrid)).toList ::: Option(manager.getResolvedIvyFileInCache(mrid)).toList :::
Option(manager.getResolvedIvyPropertiesInCache(mrid)).toList ::: Option(manager.getResolvedIvyPropertiesInCache(mrid)).toList :::

View File

@ -8,8 +8,6 @@ import java.util.Locale
object StringUtilities { object StringUtilities {
@deprecated("Different use cases require different normalization. Use Project.normalizeModuleID or normalizeProjectID instead.", "0.13.0") @deprecated("Different use cases require different normalization. Use Project.normalizeModuleID or normalizeProjectID instead.", "0.13.0")
def normalize(s: String) = s.toLowerCase(Locale.ENGLISH).replaceAll("""\W+""", "-") def normalize(s: String) = s.toLowerCase(Locale.ENGLISH).replaceAll("""\W+""", "-")
def nonEmpty(s: String, label: String) { def nonEmpty(s: String, label: String): Unit = require(s.trim.length > 0, label + " cannot be empty.")
require(s.trim.length > 0, label + " cannot be empty.")
}
def appendable(s: String) = if (s.isEmpty) "" else "_" + s def appendable(s: String) = if (s.isEmpty) "" else "_" + s
} }

View File

@ -54,7 +54,7 @@ object ErrorMessageAuthenticator {
} }
/** Installs the error message authenticator so we have nicer error messages when using java's URL for downloading. */ /** Installs the error message authenticator so we have nicer error messages when using java's URL for downloading. */
def install() { def install(): Unit = {
// Actually installs the error message authenticator. // Actually installs the error message authenticator.
def doInstall(original: Option[Authenticator]): Unit = def doInstall(original: Option[Authenticator]): Unit =
try Authenticator.setDefault(new ErrorMessageAuthenticator(original)) try Authenticator.setDefault(new ErrorMessageAuthenticator(original))

View File

@ -9,11 +9,11 @@ import inc.Relations
object DotGraph { object DotGraph {
private def fToString(roots: Iterable[File]): (File => String) = private def fToString(roots: Iterable[File]): (File => String) =
(x: File) => sourceToString(roots, x) (x: File) => sourceToString(roots, x)
def sources(relations: Relations, outputDirectory: File, sourceRoots: Iterable[File]) { def sources(relations: Relations, outputDirectory: File, sourceRoots: Iterable[File]): Unit = {
val toString = fToString(sourceRoots) val toString = fToString(sourceRoots)
apply(relations, outputDirectory, toString, toString) apply(relations, outputDirectory, toString, toString)
} }
def packages(relations: Relations, outputDirectory: File, sourceRoots: Iterable[File]) { def packages(relations: Relations, outputDirectory: File, sourceRoots: Iterable[File]): Unit = {
val packageOnly = (path: String) => val packageOnly = (path: String) =>
{ {
val last = path.lastIndexOf(File.separatorChar) val last = path.lastIndexOf(File.separatorChar)
@ -23,7 +23,7 @@ object DotGraph {
val toString = packageOnly compose fToString(sourceRoots) val toString = packageOnly compose fToString(sourceRoots)
apply(relations, outputDirectory, toString, toString) apply(relations, outputDirectory, toString, toString)
} }
def apply(relations: Relations, outputDir: File, sourceToString: File => String, externalToString: File => String) { def apply(relations: Relations, outputDir: File, sourceToString: File => String, externalToString: File => String): Unit = {
def file(name: String) = new File(outputDir, name) def file(name: String) = new File(outputDir, name)
IO.createDirectory(outputDir) IO.createDirectory(outputDir)
generateGraph(file("int-source-deps"), "dependencies", relations.internalSrcDep, sourceToString, sourceToString) generateGraph(file("int-source-deps"), "dependencies", relations.internalSrcDep, sourceToString, sourceToString)

View File

@ -32,7 +32,7 @@ object Package {
def mergeAttributes(a1: Attributes, a2: Attributes) = a1 ++= a2 def mergeAttributes(a1: Attributes, a2: Attributes) = a1 ++= a2
// merges `mergeManifest` into `manifest` (mutating `manifest` in the process) // merges `mergeManifest` into `manifest` (mutating `manifest` in the process)
def mergeManifests(manifest: Manifest, mergeManifest: Manifest) { def mergeManifests(manifest: Manifest, mergeManifest: Manifest): Unit = {
mergeAttributes(manifest.getMainAttributes, mergeManifest.getMainAttributes) mergeAttributes(manifest.getMainAttributes, mergeManifest.getMainAttributes)
val entryMap = mapAsScalaMap(manifest.getEntries) val entryMap = mapAsScalaMap(manifest.getEntries)
for ((key, value) <- mergeManifest.getEntries) { for ((key, value) <- mergeManifest.getEntries) {
@ -44,7 +44,7 @@ object Package {
} }
final class Configuration(val sources: Seq[(File, String)], val jar: File, val options: Seq[PackageOption]) final class Configuration(val sources: Seq[(File, String)], val jar: File, val options: Seq[PackageOption])
def apply(conf: Configuration, cacheFile: File, log: Logger) { def apply(conf: Configuration, cacheFile: File, log: Logger): Unit = {
val manifest = new Manifest val manifest = new Manifest
val main = manifest.getMainAttributes val main = manifest.getMainAttributes
for (option <- conf.options) { for (option <- conf.options) {
@ -71,7 +71,7 @@ object Package {
val inputs = map :+: lastModified(map.keySet) :+: manifest :+: HNil val inputs = map :+: lastModified(map.keySet) :+: manifest :+: HNil
cachedMakeJar(inputs)(() => exists(conf.jar)) cachedMakeJar(inputs)(() => exists(conf.jar))
} }
def setVersion(main: Attributes) { def setVersion(main: Attributes): Unit = {
val version = Attributes.Name.MANIFEST_VERSION val version = Attributes.Name.MANIFEST_VERSION
if (main.getValue(version) eq null) if (main.getValue(version) eq null)
main.put(version, "1.0") main.put(version, "1.0")
@ -90,7 +90,7 @@ object Package {
val attribVals = Seq(name, version, orgName, org) val attribVals = Seq(name, version, orgName, org)
ManifestAttributes((attribKeys zip attribVals) ++ { homepage map (h => (IMPLEMENTATION_URL, h.toString)) }: _*) ManifestAttributes((attribKeys zip attribVals) ++ { homepage map (h => (IMPLEMENTATION_URL, h.toString)) }: _*)
} }
def makeJar(sources: Seq[(File, String)], jar: File, manifest: Manifest, log: Logger) { def makeJar(sources: Seq[(File, String)], jar: File, manifest: Manifest, log: Logger): Unit = {
log.info("Packaging " + jar.getAbsolutePath + " ...") log.info("Packaging " + jar.getAbsolutePath + " ...")
IO.delete(jar) IO.delete(jar)
log.debug(sourcesDebugString(sources)) log.debug(sourcesDebugString(sources))

View File

@ -70,7 +70,7 @@ final class Eval(optionsNoncp: Seq[String], classpath: Seq[File], mkReporter: Se
import global._ import global._
import definitions._ import definitions._
private[sbt] def unlinkDeferred() { private[sbt] def unlinkDeferred(): Unit = {
toUnlinkLater foreach unlink toUnlinkLater foreach unlink
toUnlinkLater = Nil toUnlinkLater = Nil
} }

View File

@ -14,9 +14,7 @@ object MainLoop {
// the jline terminal in finally blocks, but hitting ctrl+c prevents finally blocks from being executed, in that // the jline terminal in finally blocks, but hitting ctrl+c prevents finally blocks from being executed, in that
// case the only way to restore the terminal is in a shutdown hook. // case the only way to restore the terminal is in a shutdown hook.
val shutdownHook = new Thread(new Runnable { val shutdownHook = new Thread(new Runnable {
def run() { def run(): Unit = TerminalFactory.get().restore()
TerminalFactory.get().restore()
}
}) })
try { try {
@ -71,7 +69,7 @@ object MainLoop {
} }
/** Transfers logging and trace levels from the old global loggers to the new ones. */ /** Transfers logging and trace levels from the old global loggers to the new ones. */
private[this] def transferLevels(state: State, logging: GlobalLogging) { private[this] def transferLevels(state: State, logging: GlobalLogging): Unit = {
val old = state.globalLogging val old = state.globalLogging
Logger.transferLevels(old.backed, logging.backed) Logger.transferLevels(old.backed, logging.backed)
(old.full, logging.full) match { // well, this is a hack (old.full, logging.full) match { // well, this is a hack

View File

@ -246,7 +246,7 @@ object State {
} }
s.fail s.fail
} }
private[sbt] def logFullException(e: Throwable, log: Logger) { private[sbt] def logFullException(e: Throwable, log: Logger): Unit = {
log.trace(e) log.trace(e)
log.error(ErrorHandling reducedToString e) log.error(ErrorHandling reducedToString e)
log.error("Use 'last' for the full log.") log.error("Use 'last' for the full log.")

View File

@ -39,7 +39,7 @@ final object Aggregation {
showRun(complete, show) showRun(complete, show)
(complete.state, complete.results) (complete.state, complete.results)
} }
def showRun[T](complete: Complete[T], show: ShowConfig)(implicit display: Show[ScopedKey[_]]) { def showRun[T](complete: Complete[T], show: ShowConfig)(implicit display: Show[ScopedKey[_]]): Unit = {
import complete._ import complete._
val log = state.log val log = state.log
val extracted = Project extract state val extracted = Project extract state
@ -76,7 +76,7 @@ final object Aggregation {
} }
} }
def printSuccess(start: Long, stop: Long, extracted: Extracted, success: Boolean, log: Logger) { def printSuccess(start: Long, stop: Long, extracted: Extracted, success: Boolean, log: Logger): Unit = {
import extracted._ import extracted._
def get(key: SettingKey[Boolean]): Boolean = key in currentRef get structure.data getOrElse true def get(key: SettingKey[Boolean]): Boolean = key in currentRef get structure.data getOrElse true
if (get(showSuccess)) { if (get(showSuccess)) {

View File

@ -29,7 +29,7 @@ final class MultiHandler[S, T](builtIn: S => Option[T], root: Option[S => Option
def applyNonRoots(info: S): List[(URI, T)] = def applyNonRoots(info: S): List[(URI, T)] =
nonRoots flatMap { case (definingURI, loader) => loader(info) map { unit => (definingURI, unit) } } nonRoots flatMap { case (definingURI, loader) => loader(info) map { unit => (definingURI, unit) } }
private[this] def warn(baseMessage: String, log: Logger, matching: Seq[(URI, T)]) { private[this] def warn(baseMessage: String, log: Logger, matching: Seq[(URI, T)]): Unit = {
log.warn(baseMessage) log.warn(baseMessage)
log.debug("Non-root build resolvers defined in:") log.debug("Non-root build resolvers defined in:")
log.debug(matching.map(_._1).mkString("\n\t")) log.debug(matching.map(_._1).mkString("\n\t"))

View File

@ -21,7 +21,7 @@ object BuildPaths {
def getDefault = { checkTransition(state, default); default } def getDefault = { checkTransition(state, default); default }
getFileSetting(globalBaseDirectory, GlobalBaseProperty, getDefault)(state) getFileSetting(globalBaseDirectory, GlobalBaseProperty, getDefault)(state)
} }
private[this] def checkTransition(state: State, versioned: File) { private[this] def checkTransition(state: State, versioned: File): Unit = {
val unversioned = defaultGlobalBase val unversioned = defaultGlobalBase
def globalDefined(base: File): Boolean = def globalDefined(base: File): Boolean =
getGlobalPluginsDirectory(state, base).exists || getGlobalPluginsDirectory(state, base).exists ||

View File

@ -58,7 +58,7 @@ object BuildUtil {
BuildDependencies(cp.toMap, agg.toMap) BuildDependencies(cp.toMap, agg.toMap)
} }
def checkCycles(units: Map[URI, LoadedBuildUnit]) { def checkCycles(units: Map[URI, LoadedBuildUnit]): Unit = {
def getRef(pref: ProjectRef) = units(pref.build).defined(pref.project) def getRef(pref: ProjectRef) = units(pref.build).defined(pref.project)
def deps(proj: ResolvedProject)(base: ResolvedProject => Seq[ProjectRef]): Seq[ResolvedProject] = Dag.topologicalSort(proj)(p => base(p) map getRef) def deps(proj: ResolvedProject)(base: ResolvedProject => Seq[ProjectRef]): Seq[ResolvedProject] = Dag.topologicalSort(proj)(p => base(p) map getRef)
// check for cycles // check for cycles

View File

@ -6,7 +6,7 @@ package sbt
import java.io.File import java.io.File
object ConsoleProject { object ConsoleProject {
def apply(state: State, extra: String, cleanupCommands: String = "", options: Seq[String] = Nil)(implicit log: Logger) { def apply(state: State, extra: String, cleanupCommands: String = "", options: Seq[String] = Nil)(implicit log: Logger): Unit = {
val extracted = Project extract state val extracted = Project extract state
val cpImports = new Imports(extracted, state) val cpImports = new Imports(extracted, state)
val bindings = ("currentState" -> state) :: ("extracted" -> extracted) :: ("cpHelpers" -> cpImports) :: Nil val bindings = ("currentState" -> state) :: ("extracted" -> extracted) :: ("cpHelpers" -> cpImports) :: Nil

View File

@ -1253,7 +1253,7 @@ object Classpaths {
@deprecated("Split into ivyBaseSettings and jvmBaseSettings.", "0.13.2") @deprecated("Split into ivyBaseSettings and jvmBaseSettings.", "0.13.2")
val baseSettings: Seq[Setting[_]] = ivyBaseSettings ++ jvmBaseSettings val baseSettings: Seq[Setting[_]] = ivyBaseSettings ++ jvmBaseSettings
def warnResolversConflict(ress: Seq[Resolver], log: Logger) { def warnResolversConflict(ress: Seq[Resolver], log: Logger): Unit = {
val resset = ress.toSet val resset = ress.toSet
for ((name, r) <- resset groupBy (_.name) if r.size > 1) { for ((name, r) <- resset groupBy (_.name) if r.size > 1) {
log.warn("Multiple resolvers having different access mechanism configured with same name '" + name + "'. To avoid conflict, Remove duplicate project resolvers (`resolvers`) or rename publishing resolver (`publishTo`).") log.warn("Multiple resolvers having different access mechanism configured with same name '" + name + "'. To avoid conflict, Remove duplicate project resolvers (`resolvers`) or rename publishing resolver (`publishTo`).")
@ -1588,7 +1588,7 @@ object Classpaths {
def interSort(projectRef: ProjectRef, conf: Configuration, data: Settings[Scope], deps: BuildDependencies): Seq[(ProjectRef, String)] = def interSort(projectRef: ProjectRef, conf: Configuration, data: Settings[Scope], deps: BuildDependencies): Seq[(ProjectRef, String)] =
{ {
val visited = asScalaSet(new LinkedHashSet[(ProjectRef, String)]) val visited = asScalaSet(new LinkedHashSet[(ProjectRef, String)])
def visit(p: ProjectRef, c: Configuration) { def visit(p: ProjectRef, c: Configuration): Unit = {
val applicableConfigs = allConfigs(c) val applicableConfigs = allConfigs(c)
for (ac <- applicableConfigs) // add all configurations in this project for (ac <- applicableConfigs) // add all configurations in this project
visited add (p -> ac.name) visited add (p -> ac.name)

View File

@ -280,7 +280,7 @@ object EvaluateTask {
} }
} }
def logIncResult(result: Result[_], state: State, streams: Streams) = result match { case Inc(i) => logIncomplete(i, state, streams); case _ => () } def logIncResult(result: Result[_], state: State, streams: Streams) = result match { case Inc(i) => logIncomplete(i, state, streams); case _ => () }
def logIncomplete(result: Incomplete, state: State, streams: Streams) { def logIncomplete(result: Incomplete, state: State, streams: Streams): Unit = {
val all = Incomplete linearize result val all = Incomplete linearize result
val keyed = for (Incomplete(Some(key: ScopedKey[_]), _, msg, _, ex) <- all) yield (key, msg, ex) val keyed = for (Incomplete(Some(key: ScopedKey[_]), _, msg, _, ex) <- all) yield (key, msg, ex)
val un = all.filter { i => i.node.isEmpty || i.message.isEmpty } val un = all.filter { i => i.node.isEmpty || i.message.isEmpty }

View File

@ -340,12 +340,12 @@ object Load {
} }
case Nil => (references, builds, loaders) case Nil => (references, builds, loaders)
} }
def checkProjectBase(buildBase: File, projectBase: File) { def checkProjectBase(buildBase: File, projectBase: File): Unit = {
checkDirectory(projectBase) checkDirectory(projectBase)
assert(buildBase == projectBase || IO.relativize(buildBase, projectBase).isDefined, "Directory " + projectBase + " is not contained in build root " + buildBase) assert(buildBase == projectBase || IO.relativize(buildBase, projectBase).isDefined, "Directory " + projectBase + " is not contained in build root " + buildBase)
} }
def checkBuildBase(base: File) = checkDirectory(base) def checkBuildBase(base: File) = checkDirectory(base)
def checkDirectory(base: File) { def checkDirectory(base: File): Unit = {
assert(base.isAbsolute, "Not absolute: " + base) assert(base.isAbsolute, "Not absolute: " + base)
if (base.isFile) if (base.isFile)
sys.error("Not a directory: " + base) sys.error("Not a directory: " + base)
@ -360,7 +360,7 @@ object Load {
(uri, unit.resolveRefs(ref => Scope.resolveProjectRef(uri, rootProject, ref))) (uri, unit.resolveRefs(ref => Scope.resolveProjectRef(uri, rootProject, ref)))
} }
} }
def checkAll(referenced: Map[URI, List[ProjectReference]], builds: Map[URI, sbt.PartBuildUnit]) { def checkAll(referenced: Map[URI, List[ProjectReference]], builds: Map[URI, sbt.PartBuildUnit]): Unit = {
val rootProject = getRootProject(builds) val rootProject = getRootProject(builds)
for ((uri, refs) <- referenced; ref <- refs) { for ((uri, refs) <- referenced; ref <- refs) {
val ProjectRef(refURI, refID) = Scope.resolveProjectRef(uri, rootProject, ref) val ProjectRef(refURI, refID) = Scope.resolveProjectRef(uri, rootProject, ref)

View File

@ -73,7 +73,7 @@ object LogManager {
else { else {
val logging = s.globalLogging val logging = s.globalLogging
def get[T](key: SettingKey[T]) = key in GlobalScope get data def get[T](key: SettingKey[T]) = key in GlobalScope get data
def transfer(l: AbstractLogger, traceKey: SettingKey[Int], levelKey: SettingKey[Level.Value]) { def transfer(l: AbstractLogger, traceKey: SettingKey[Int], levelKey: SettingKey[Level.Value]): Unit = {
get(traceKey).foreach(l.setTrace) get(traceKey).foreach(l.setTrace)
get(levelKey).foreach(l.setLevel) get(levelKey).foreach(l.setLevel)
} }

View File

@ -211,13 +211,13 @@ object BuiltinCommands {
if (Project.isProjectLoaded(s)) loadedEval(s, arg) else rawEval(s, arg) if (Project.isProjectLoaded(s)) loadedEval(s, arg) else rawEval(s, arg)
s s
} }
private[this] def loadedEval(s: State, arg: String) { private[this] def loadedEval(s: State, arg: String): Unit = {
val extracted = Project extract s val extracted = Project extract s
import extracted._ import extracted._
val result = session.currentEval().eval(arg, srcName = "<eval>", imports = autoImports(extracted)) val result = session.currentEval().eval(arg, srcName = "<eval>", imports = autoImports(extracted))
s.log.info(s"ans: ${result.tpe} = ${result.getValue(currentLoader)}") s.log.info(s"ans: ${result.tpe} = ${result.getValue(currentLoader)}")
} }
private[this] def rawEval(s: State, arg: String) { private[this] def rawEval(s: State, arg: String): Unit = {
val app = s.configuration.provider val app = s.configuration.provider
val classpath = app.mainClasspath ++ app.scalaProvider.jars val classpath = app.mainClasspath ++ app.scalaProvider.jars
val result = Load.mkEval(classpath, s.baseDir, Nil).eval(arg, srcName = "<eval>", imports = new EvalImports(Nil, "")) val result = Load.mkEval(classpath, s.baseDir, Nil).eval(arg, srcName = "<eval>", imports = new EvalImports(Nil, ""))
@ -405,7 +405,7 @@ object BuiltinCommands {
case (s, Some(modifyBuilds)) => transformExtraBuilds(s, modifyBuilds) case (s, Some(modifyBuilds)) => transformExtraBuilds(s, modifyBuilds)
case (s, None) => showProjects(s); s case (s, None) => showProjects(s); s
} }
def showProjects(s: State) { def showProjects(s: State): Unit = {
val extracted = Project extract s val extracted = Project extract s
import extracted._ import extracted._
import currentRef.{ build => curi, project => cid } import currentRef.{ build => curi, project => cid }

View File

@ -207,7 +207,7 @@ object Plugins extends PluginsFunctions {
private[this] def literalsString(lits: Seq[Literal]): String = private[this] def literalsString(lits: Seq[Literal]): String =
lits map { case Atom(l) => l; case Negated(Atom(l)) => l } mkString(", ") lits map { case Atom(l) => l; case Negated(Atom(l)) => l } mkString(", ")
private[this] def duplicateProvidesError(byAtom: Seq[(Atom, AutoPlugin)]) { private[this] def duplicateProvidesError(byAtom: Seq[(Atom, AutoPlugin)]): Unit = {
val dupsByAtom = byAtom.groupBy(_._1).mapValues(_.map(_._2)) val dupsByAtom = byAtom.groupBy(_._1).mapValues(_.map(_._2))
val dupStrings = for( (atom, dups) <- dupsByAtom if dups.size > 1 ) yield val dupStrings = for( (atom, dups) <- dupsByAtom if dups.size > 1 ) yield
s"${atom.label} by ${dups.mkString(", ")}" s"${atom.label} by ${dups.mkString(", ")}"
@ -215,7 +215,7 @@ object Plugins extends PluginsFunctions {
val message = s"Plugin$ns provided by multiple AutoPlugins:$nl${dupStrings.mkString(nl)}" val message = s"Plugin$ns provided by multiple AutoPlugins:$nl${dupStrings.mkString(nl)}"
throw AutoPluginException(message) throw AutoPluginException(message)
} }
private[this] def exlusionConflictError(requested: Plugins, selected: Seq[AutoPlugin], conflicting: Seq[AutoPlugin]) { private[this] def exlusionConflictError(requested: Plugins, selected: Seq[AutoPlugin], conflicting: Seq[AutoPlugin]): Unit = {
def listConflicts(ns: Seq[AutoPlugin]) = (ns map { c => def listConflicts(ns: Seq[AutoPlugin]) = (ns map { c =>
val reasons = (if (flatten(requested) contains c) List("requested") val reasons = (if (flatten(requested) contains c) List("requested")
else Nil) ++ else Nil) ++

View File

@ -451,12 +451,12 @@ object Project extends ProjectExtra {
} }
def settingGraph(structure: BuildStructure, basedir: File, scoped: ScopedKey[_])(implicit display: Show[ScopedKey[_]]): SettingGraph = def settingGraph(structure: BuildStructure, basedir: File, scoped: ScopedKey[_])(implicit display: Show[ScopedKey[_]]): SettingGraph =
SettingGraph(structure, basedir, scoped, 0) SettingGraph(structure, basedir, scoped, 0)
def graphSettings(structure: BuildStructure, basedir: File)(implicit display: Show[ScopedKey[_]]) { def graphSettings(structure: BuildStructure, basedir: File)(implicit display: Show[ScopedKey[_]]): Unit = {
def graph(actual: Boolean, name: String) = graphSettings(structure, actual, name, new File(basedir, name + ".dot")) def graph(actual: Boolean, name: String) = graphSettings(structure, actual, name, new File(basedir, name + ".dot"))
graph(true, "actual_dependencies") graph(true, "actual_dependencies")
graph(false, "declared_dependencies") graph(false, "declared_dependencies")
} }
def graphSettings(structure: BuildStructure, actual: Boolean, graphName: String, file: File)(implicit display: Show[ScopedKey[_]]) { def graphSettings(structure: BuildStructure, actual: Boolean, graphName: String, file: File)(implicit display: Show[ScopedKey[_]]): Unit = {
val rel = relation(structure, actual) val rel = relation(structure, actual)
val keyToString = display.apply _ val keyToString = display.apply _
DotGraph.generateGraph(file, graphName, rel, keyToString, keyToString) DotGraph.generateGraph(file, graphName, rel, keyToString, keyToString)

View File

@ -58,11 +58,11 @@ object Resolvers {
val mercurial: Resolver = new DistributedVCS { val mercurial: Resolver = new DistributedVCS {
override val scheme = "hg" override val scheme = "hg"
override def clone(from: String, to: File) { override def clone(from: String, to: File): Unit = {
run("hg", "clone", "-q", from, to.getAbsolutePath) run("hg", "clone", "-q", from, to.getAbsolutePath)
} }
override def checkout(branch: String, in: File) { override def checkout(branch: String, in: File): Unit = {
run(Some(in), "hg", "checkout", "-q", branch) run(Some(in), "hg", "checkout", "-q", branch)
} }
}.toResolver }.toResolver
@ -121,11 +121,10 @@ object Resolvers {
isWindows && !isCygwin isWindows && !isCygwin
} }
def run(command: String*) { def run(command: String*): Unit =
run(None, command: _*) run(None, command: _*)
}
def run(cwd: Option[File], command: String*) { def run(cwd: Option[File], command: String*): Unit = {
val result = Process( val result = Process(
if (onWindows) "cmd" +: "/c" +: command if (onWindows) "cmd" +: "/c" +: command
else command, else command,

View File

@ -124,7 +124,7 @@ object SessionSettings {
def pluralize(size: Int, of: String) = size.toString + (if (size == 1) of else (of + "s")) def pluralize(size: Int, of: String) = size.toString + (if (size == 1) of else (of + "s"))
/** Checks to see if any session settings are being discarded and issues a warning. */ /** Checks to see if any session settings are being discarded and issues a warning. */
def checkSession(newSession: SessionSettings, oldState: State) { def checkSession(newSession: SessionSettings, oldState: State): Unit = {
val oldSettings = (oldState get Keys.sessionSettings).toList.flatMap(_.append).flatMap(_._2) val oldSettings = (oldState get Keys.sessionSettings).toList.flatMap(_.append).flatMap(_._2)
if (newSession.append.isEmpty && oldSettings.nonEmpty) if (newSession.append.isEmpty && oldSettings.nonEmpty)
oldState.log.warn("Discarding " + pluralize(oldSettings.size, " session setting") + ". Use 'session save' to persist session settings.") oldState.log.warn("Discarding " + pluralize(oldSettings.size, " session setting") + ". Use 'session save' to persist session settings.")

View File

@ -11,7 +11,7 @@ trait SplitExpression {
trait SplitExpressionsBehavior extends SplitExpression { trait SplitExpressionsBehavior extends SplitExpression {
this: SpecificationLike => this: SpecificationLike =>
def oldExpressionsSplitter(implicit splitter: SplitExpressions.SplitExpression) { def oldExpressionsSplitter(implicit splitter: SplitExpressions.SplitExpression): Unit = {
"parse a simple setting" in { "parse a simple setting" in {
val (imports, settingsAndDefs) = split("""version := "1.0"""") val (imports, settingsAndDefs) = split("""version := "1.0"""")
@ -60,7 +60,7 @@ trait SplitExpressionsBehavior extends SplitExpression {
} }
def newExpressionsSplitter(implicit splitter: SplitExpressions.SplitExpression) { def newExpressionsSplitter(implicit splitter: SplitExpressions.SplitExpression): Unit = {
"parse a two settings without intervening blank line" in { "parse a two settings without intervening blank line" in {
val (imports, settings) = split("""version := "1.0" val (imports, settings) = split("""version := "1.0"

View File

@ -65,7 +65,7 @@ object Scripted {
launchOpts: Array[String], prescripted: java.util.List[File]): Unit launchOpts: Array[String], prescripted: java.util.List[File]): Unit
} }
def doScripted(launcher: File, scriptedSbtClasspath: Seq[Attributed[File]], scriptedSbtInstance: ScalaInstance, sourcePath: File, args: Seq[String], prescripted: File => Unit) { def doScripted(launcher: File, scriptedSbtClasspath: Seq[Attributed[File]], scriptedSbtInstance: ScalaInstance, sourcePath: File, args: Seq[String], prescripted: File => Unit): Unit = {
System.err.println(s"About to run tests: ${args.mkString("\n * ", "\n * ", "\n")}") System.err.println(s"About to run tests: ${args.mkString("\n * ", "\n * ", "\n")}")
val noJLine = new classpath.FilteredLoader(scriptedSbtInstance.loader, "jline." :: Nil) val noJLine = new classpath.FilteredLoader(scriptedSbtInstance.loader, "jline." :: Nil)
val loader = classpath.ClasspathUtilities.toLoader(scriptedSbtClasspath.files, noJLine) val loader = classpath.ClasspathUtilities.toLoader(scriptedSbtClasspath.files, noJLine)

View File

@ -82,7 +82,7 @@ object SiteMap {
private[this] def writeXML(output: File, node: xml.Node): Unit = private[this] def writeXML(output: File, node: xml.Node): Unit =
write(output, new xml.PrettyPrinter(1000, 4).format(node)) write(output, new xml.PrettyPrinter(1000, 4).format(node))
private[this] def write(output: File, xmlString: String) { private[this] def write(output: File, xmlString: String): Unit = {
// use \n as newline because toString uses PrettyPrinter, which hard codes line endings to be \n // use \n as newline because toString uses PrettyPrinter, which hard codes line endings to be \n
IO.write(output, s"<?xml version='1.0' encoding='${IO.utf8.name}'?>\n") IO.write(output, s"<?xml version='1.0' encoding='${IO.utf8.name}'?>\n")
IO.append(output, xmlString) IO.append(output, xmlString)

View File

@ -37,7 +37,7 @@ object Transform {
file file
} }
} }
def copyPropertiesFile(source: File, newMain: String, target: File) { def copyPropertiesFile(source: File, newMain: String, target: File): Unit = {
def subMain(line: String): String = if (line.trim.startsWith("class:")) " class: " + newMain else line def subMain(line: String): String = if (line.trim.startsWith("class:")) " class: " + newMain else line
IO.writeLines(target, IO.readLines(source) map subMain) IO.writeLines(target, IO.readLines(source) map subMain)
} }

View File

@ -54,13 +54,13 @@ class Run(instance: ScalaInstance, trapExit: Boolean, nativeTmp: File) extends S
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) { private def run0(mainClassName: String, classpath: Seq[File], options: Seq[String], log: Logger): Unit = {
log.debug(" Classpath:\n\t" + classpath.mkString("\n\t")) log.debug(" Classpath:\n\t" + classpath.mkString("\n\t"))
val loader = ClasspathUtilities.makeLoader(classpath, instance, nativeTmp) val loader = ClasspathUtilities.makeLoader(classpath, instance, nativeTmp)
val main = getMainMethod(mainClassName, loader) val main = getMainMethod(mainClassName, loader)
invokeMain(loader, main, options) invokeMain(loader, main, options)
} }
private def invokeMain(loader: ClassLoader, main: Method, options: Seq[String]) { private def invokeMain(loader: ClassLoader, main: Method, options: Seq[String]): Unit = {
val currentThread = Thread.currentThread val currentThread = Thread.currentThread
val oldLoader = Thread.currentThread.getContextClassLoader val oldLoader = Thread.currentThread.getContextClassLoader
currentThread.setContextClassLoader(loader) currentThread.setContextClassLoader(loader)

View File

@ -84,14 +84,14 @@ object TrapExit {
s"${hex(System.identityHashCode(t))}" s"${hex(System.identityHashCode(t))}"
/** Waits for the given `thread` to terminate. However, if the thread state is NEW, this method returns immediately. */ /** Waits for the given `thread` to terminate. However, if the thread state is NEW, this method returns immediately. */
private def waitOnThread(thread: Thread, log: Logger) { private def waitOnThread(thread: Thread, log: Logger): Unit = {
log.debug("Waiting for thread " + thread.getName + " to terminate.") log.debug("Waiting for thread " + thread.getName + " to terminate.")
thread.join thread.join
log.debug("\tThread " + thread.getName + " exited.") log.debug("\tThread " + thread.getName + " exited.")
} }
// interrupts the given thread, but first replaces the exception handler so that the InterruptedException is not printed // interrupts the given thread, but first replaces the exception handler so that the InterruptedException is not printed
private def safeInterrupt(thread: Thread, log: Logger) { private def safeInterrupt(thread: Thread, log: Logger): Unit = {
val name = thread.getName val name = thread.getName
log.debug("Interrupting thread " + thread.getName) log.debug("Interrupting thread " + thread.getName)
thread.setUncaughtExceptionHandler(new TrapInterrupt(thread.getUncaughtExceptionHandler)) thread.setUncaughtExceptionHandler(new TrapInterrupt(thread.getUncaughtExceptionHandler))
@ -100,7 +100,7 @@ object TrapExit {
} }
// an uncaught exception handler that swallows InterruptedExceptions and otherwise defers to originalHandler // an uncaught exception handler that swallows InterruptedExceptions and otherwise defers to originalHandler
private final class TrapInterrupt(originalHandler: Thread.UncaughtExceptionHandler) extends Thread.UncaughtExceptionHandler { private final class TrapInterrupt(originalHandler: Thread.UncaughtExceptionHandler) extends Thread.UncaughtExceptionHandler {
def uncaughtException(thread: Thread, e: Throwable) { def uncaughtException(thread: Thread, e: Throwable): Unit = {
withCause[InterruptedException, Unit](e) { interrupted => () } { other => originalHandler.uncaughtException(thread, e) } withCause[InterruptedException, Unit](e) { interrupted => () } { other => originalHandler.uncaughtException(thread, e) }
thread.setUncaughtExceptionHandler(originalHandler) thread.setUncaughtExceptionHandler(originalHandler)
} }
@ -187,7 +187,7 @@ private final class TrapExit(delegateManager: SecurityManager) extends SecurityM
} }
// wait for all non-daemon threads to terminate // wait for all non-daemon threads to terminate
private[this] def waitForExit(app: App) { private[this] def waitForExit(app: App): Unit = {
var daemonsOnly = true var daemonsOnly = true
app.processThreads { thread => app.processThreads { thread =>
// check isAlive because calling `join` on a thread that hasn't started returns immediately // check isAlive because calling `join` on a thread that hasn't started returns immediately
@ -244,7 +244,7 @@ private final class TrapExit(delegateManager: SecurityManager) extends SecurityM
val exitCode = new ExitCode val exitCode = new ExitCode
def run() { def run(): Unit = {
try execute() try execute()
catch { catch {
case x: Throwable => case x: Throwable =>
@ -282,7 +282,7 @@ private final class TrapExit(delegateManager: SecurityManager) extends SecurityM
} }
/** Registers the logging exception handler on `t`, delegating to the existing handler if it isn't the default. */ /** Registers the logging exception handler on `t`, delegating to the existing handler if it isn't the default. */
private[this] def setExceptionHandler(t: Thread) { private[this] def setExceptionHandler(t: Thread): Unit = {
val group = t.getThreadGroup val group = t.getThreadGroup
val previousHandler = t.getUncaughtExceptionHandler match { val previousHandler = t.getUncaughtExceptionHandler match {
case null | `group` | (_: LoggingExceptionHandler) => None case null | `group` | (_: LoggingExceptionHandler) => None
@ -302,7 +302,7 @@ private final class TrapExit(delegateManager: SecurityManager) extends SecurityM
cleanup(threads) cleanup(threads)
cleanup(groups) cleanup(groups)
} }
private[this] def cleanup(resources: TrieMap[ThreadID, _]) { private[this] def cleanup(resources: TrieMap[ThreadID, _]): Unit = {
val snap = resources.readOnlySnapshot val snap = resources.readOnlySnapshot
resources.clear() resources.clear()
for ((id, _) <- snap) for ((id, _) <- snap)
@ -312,7 +312,7 @@ private final class TrapExit(delegateManager: SecurityManager) extends SecurityM
// only want to operate on unterminated threads // only want to operate on unterminated threads
// want to drop terminated threads, including those that have been gc'd // want to drop terminated threads, including those that have been gc'd
/** Evaluates `f` on each `Thread` started by this [[App]] at single instant shortly after this method is called. */ /** Evaluates `f` on each `Thread` started by this [[App]] at single instant shortly after this method is called. */
def processThreads(f: Thread => Unit) { def processThreads(f: Thread => Unit): Unit = {
// pulls in threads that weren't recorded by checkAccess(Thread) (which is jvm-dependent) // pulls in threads that weren't recorded by checkAccess(Thread) (which is jvm-dependent)
// but can be reached via the Threads in the ThreadGroups recorded by checkAccess(ThreadGroup) (not jvm-dependent) // but can be reached via the Threads in the ThreadGroups recorded by checkAccess(ThreadGroup) (not jvm-dependent)
addUntrackedThreads() addUntrackedThreads()
@ -372,7 +372,7 @@ private final class TrapExit(delegateManager: SecurityManager) extends SecurityM
} }
} }
private[this] def stopAllThreads(app: App) { private[this] def stopAllThreads(app: App): Unit = {
// only try to dispose frames if we think the App used AWT // only try to dispose frames if we think the App used AWT
// otherwise, we initialize AWT as a side effect of asking for the frames // otherwise, we initialize AWT as a side effect of asking for the frames
// also, we only assume one AWT application at a time // also, we only assume one AWT application at a time
@ -419,17 +419,17 @@ private final class TrapExit(delegateManager: SecurityManager) extends SecurityM
// These are overridden to do nothing because there is a substantial filesystem performance penalty // These are overridden to do nothing because there is a substantial filesystem performance penalty
// when there is a SecurityManager defined. The default implementations of these construct a // when there is a SecurityManager defined. The default implementations of these construct a
// FilePermission, and its initialization involves canonicalization, which is expensive. // FilePermission, and its initialization involves canonicalization, which is expensive.
override def checkRead(file: String) {} override def checkRead(file: String): Unit = ()
override def checkRead(file: String, context: AnyRef) {} override def checkRead(file: String, context: AnyRef): Unit = ()
override def checkWrite(file: String) {} override def checkWrite(file: String): Unit = ()
override def checkDelete(file: String) {} override def checkDelete(file: String): Unit = ()
override def checkExec(cmd: String) {} override def checkExec(cmd: String): Unit = ()
override def checkPermission(perm: Permission) { override def checkPermission(perm: Permission): Unit = {
if (delegateManager ne null) if (delegateManager ne null)
delegateManager.checkPermission(perm) delegateManager.checkPermission(perm)
} }
override def checkPermission(perm: Permission, context: AnyRef) { override def checkPermission(perm: Permission, context: AnyRef): Unit = {
if (delegateManager ne null) if (delegateManager ne null)
delegateManager.checkPermission(perm, context) delegateManager.checkPermission(perm, context)
} }
@ -439,7 +439,7 @@ private final class TrapExit(delegateManager: SecurityManager) extends SecurityM
* This is not reliably called on different jvm implementations. On openjdk and similar jvms, the Thread constructor * This is not reliably called on different jvm implementations. On openjdk and similar jvms, the Thread constructor
* calls setPriority, which triggers this SecurityManager check. For Java 6 on OSX, this is not called, however. * calls setPriority, which triggers this SecurityManager check. For Java 6 on OSX, this is not called, however.
*/ */
override def checkAccess(t: Thread) { override def checkAccess(t: Thread): Unit = {
if (active) { if (active) {
val group = t.getThreadGroup val group = t.getThreadGroup
noteAccess(group) { app => noteAccess(group) { app =>
@ -455,7 +455,7 @@ private final class TrapExit(delegateManager: SecurityManager) extends SecurityM
* This is specified to be called in every Thread's constructor and every time a ThreadGroup is created. * This is specified to be called in every Thread's constructor and every time a ThreadGroup is created.
* This allows us to reliably track every ThreadGroup that is created and map it back to the constructing application. * This allows us to reliably track every ThreadGroup that is created and map it back to the constructing application.
*/ */
override def checkAccess(tg: ThreadGroup) { override def checkAccess(tg: ThreadGroup): Unit = {
if (active && !isSystemGroup(tg)) { if (active && !isSystemGroup(tg)) {
noteAccess(tg) { app => noteAccess(tg) { app =>
app.register(tg) app.register(tg)
@ -476,7 +476,7 @@ private final class TrapExit(delegateManager: SecurityManager) extends SecurityM
/** `true` if there is at least one application currently being managed. */ /** `true` if there is at least one application currently being managed. */
private[this] def active = running.get > 0 private[this] def active = running.get > 0
private def disposeAllFrames(log: Logger) { private def disposeAllFrames(log: Logger): Unit = {
val allFrames = java.awt.Frame.getFrames val allFrames = java.awt.Frame.getFrames
if (allFrames.nonEmpty) { if (allFrames.nonEmpty) {
log.debug(s"Disposing ${allFrames.length} top-level windows...") log.debug(s"Disposing ${allFrames.length} top-level windows...")
@ -512,7 +512,7 @@ private final class ExitCode {
* It logs the thread and the exception. * It logs the thread and the exception.
*/ */
private final class LoggingExceptionHandler(log: Logger, delegate: Option[Thread.UncaughtExceptionHandler]) extends Thread.UncaughtExceptionHandler { private final class LoggingExceptionHandler(log: Logger, delegate: Option[Thread.UncaughtExceptionHandler]) extends Thread.UncaughtExceptionHandler {
def uncaughtException(t: Thread, e: Throwable) { def uncaughtException(t: Thread, e: Throwable): Unit = {
log.error("(" + t.getName + ") " + e.toString) log.error("(" + t.getName + ") " + e.toString)
log.trace(e) log.trace(e)
delegate.foreach(_.uncaughtException(t, e)) delegate.foreach(_.uncaughtException(t, e))

View File

@ -7,7 +7,7 @@ package sbt
*/ */
private final class TrapExitSecurityException(val exitCode: Int) extends SecurityException { private final class TrapExitSecurityException(val exitCode: Int) extends SecurityException {
private var accessAllowed = false private var accessAllowed = false
def allowAccess() { def allowAccess(): Unit = {
accessAllowed = true accessAllowed = true
} }
override def printStackTrace = ifAccessAllowed(super.printStackTrace) override def printStackTrace = ifAccessAllowed(super.printStackTrace)

View File

@ -14,7 +14,7 @@ object TestBuild extends Build
lazy val b = Project("b", file("b")).settings(t <<= Def.task("").updateState(updater)) lazy val b = Project("b", file("b")).settings(t <<= Def.task("").updateState(updater))
def checkState(runs: Int, s: State) { def checkState(runs: Int, s: State): Unit = {
val stored = s.get(akey).getOrElse(0) val stored = s.get(akey).getOrElse(0)
assert(stored == runs, "Expected " + runs + ", got " + stored) assert(stored == runs, "Expected " + runs + ", got " + stored)
} }

View File

@ -2,5 +2,5 @@ package jartest
object Main object Main
{ {
def main(args: Array[String]) {} def main(args: Array[String]): Unit = ()
} }

View File

@ -78,6 +78,6 @@ keyTest := "foo"
topLevelKeyTest := "bar" topLevelKeyTest := "bar"
def same[T](actual: T, expected: T, label: String) { def same[T](actual: T, expected: T, label: String): Unit = {
assert(actual == expected, s"Expected '$expected' for `$label`, got '$actual'") assert(actual == expected, s"Expected '$expected' for `$label`, got '$actual'")
} }

View File

@ -56,7 +56,7 @@ lazy val b = project.settings(
// ---------------- Verification // ---------------- Verification
def same[T](x: T, y: T) { def same[T](x: T, y: T): Unit = {
assert(x == y, s"Actual: '$x', Expected: '$y'") assert(x == y, s"Actual: '$x', Expected: '$y'")
} }

View File

@ -11,5 +11,5 @@ class SimpleTest extends Properties("Simple")
} }
object MainTest object MainTest
{ {
def main(args: Array[String]) {} def main(args: Array[String]): Unit = ()
} }

View File

@ -12,10 +12,9 @@ object MyBuild extends Build {
lazy val check = taskKey[Unit]("Verifies that the junit dependency has the newer version (4.8)") lazy val check = taskKey[Unit]("Verifies that the junit dependency has the newer version (4.8)")
def checkVersion(report: UpdateReport) { def checkVersion(report: UpdateReport): Unit = {
for(mod <- report.allModules) { for(mod <- report.allModules) {
if(mod.name == "junit") assert(mod.revision == "4.8", s"JUnit version (${mod.revision}) does not have the correct version") if(mod.name == "junit") assert(mod.revision == "4.8", s"JUnit version (${mod.revision}) does not have the correct version")
} }
} }
} }

View File

@ -9,6 +9,6 @@ check := {
same(bv, "2.10") same(bv, "2.10")
} }
def same(actual: String, expected: String) { def same(actual: String, expected: String): Unit = {
assert(actual == expected, s"Expected binary version to be $expected, was $actual") assert(actual == expected, s"Expected binary version to be $expected, was $actual")
} }

View File

@ -1,5 +1,5 @@
object O { object O {
def main(argv: Array[String]) { def main(argv: Array[String]): Unit = {
new java.awt.Color(0,0,0) new java.awt.Color(0,0,0)
} }
} }

View File

@ -32,7 +32,7 @@ def waitForCStart =
waitFor( (baseDirectory in c).value / "started" ) waitFor( (baseDirectory in c).value / "started" )
} }
def waitFor(f: File) { def waitFor(f: File): Unit = {
if(!f.exists) { if(!f.exists) {
Thread.sleep(300) Thread.sleep(300)
waitFor(f) waitFor(f)

View File

@ -1,7 +1,7 @@
import java.io.File import java.io.File
object C { object C {
def main(args: Array[String]) { def main(args: Array[String]): Unit = {
val base = new File(args(0)) val base = new File(args(0))
create(new File(base, "started")) create(new File(base, "started"))
val bFin = new File(base, "../b/finished") val bFin = new File(base, "../b/finished")
@ -9,13 +9,13 @@ object C {
create(new File(base, "finished")) create(new File(base, "finished"))
} }
def create(f: File) { def create(f: File): Unit = {
val fabs = f.getAbsoluteFile val fabs = f.getAbsoluteFile
fabs.getParentFile.mkdirs fabs.getParentFile.mkdirs
fabs.createNewFile fabs.createNewFile
} }
def waitFor(f: File) { def waitFor(f: File): Unit = {
if(!f.exists) { if(!f.exists) {
Thread.sleep(300) Thread.sleep(300)
waitFor(f) waitFor(f)

View File

@ -2,10 +2,9 @@
object DaemonExit object DaemonExit
{ {
def main(args: Array[String]) def main(args: Array[String]): Unit = {
{
val t = new Thread { val t = new Thread {
override def run() { override def run(): Unit = {
Thread.sleep(1000) Thread.sleep(1000)
System.exit(0) System.exit(0)
} }
@ -14,9 +13,7 @@ object DaemonExit
t.start() t.start()
val t2 = new Thread { val t2 = new Thread {
override def run() { override def run(): Unit = synchronized { wait() }
synchronized { wait() }
}
} }
t2.start() t2.start()
} }

View File

@ -3,9 +3,7 @@ object Daemon
def main(args: Array[String]) def main(args: Array[String])
{ {
val t = new Thread { val t = new Thread {
override def run() { override def run(): Unit = synchronized { wait() }
synchronized { wait() }
}
} }
t.setDaemon(true); t.setDaemon(true);
t.start t.start

View File

@ -1,4 +1,4 @@
object Spawn object Spawn
{ {
def main(args: Array[String]) { System.exit(1); } def main(args: Array[String]): Unit = System.exit(1)
} }

View File

@ -1,4 +1,4 @@
object Spawn object Spawn
{ {
def main(args: Array[String]) { System.exit(0); } def main(args: Array[String]): Unit = System.exit(0)
} }

View File

@ -1,4 +1,4 @@
object Spawn object Spawn
{ {
def main(args: Array[String]) {} def main(args: Array[String]): Unit = ()
} }

View File

@ -1,6 +1,6 @@
object CheckLoader { object CheckLoader {
def main(args: Array[String]) { apply() } def main(args: Array[String]): Unit = apply()
def apply() { def apply(): Unit = {
val loader = getClass.getClassLoader val loader = getClass.getClassLoader
val appLoader = ClassLoader.getSystemClassLoader val appLoader = ClassLoader.getSystemClassLoader
assert(loader eq appLoader, "Application classes not loaded in the system class loader") assert(loader eq appLoader, "Application classes not loaded in the system class loader")

View File

@ -1,5 +1,5 @@
object ForkTest { object ForkTest {
def main(args:Array[String]) { def main(args:Array[String]): Unit = {
val name = Option(System.getenv("flag.name")) getOrElse("flag") val name = Option(System.getenv("flag.name")) getOrElse("flag")
println("Name: " + name) println("Name: " + name)
val cwd = (new java.io.File(name)).getAbsoluteFile val cwd = (new java.io.File(name)).getAbsoluteFile

View File

@ -5,31 +5,25 @@
object Spawn object Spawn
{ {
def main(args: Array[String]) def main(args: Array[String]): Unit = {
{
(new ThreadA).start (new ThreadA).start
} }
class ThreadA extends Thread
{ class ThreadA extends Thread {
override def run() override def run(): Unit = {
{
sleep() sleep()
(new ThreadB).start() (new ThreadB).start()
} }
} }
class ThreadB extends Thread class ThreadB extends Thread {
{ override def run(): Unit = sleep()
override def run() { sleep() }
} }
private def sleep() private def sleep(): Unit = {
{
try { Thread.sleep(1000) } try { Thread.sleep(1000) }
catch catch { case e: InterruptedException =>
{ val msg = "TrapExit improperly interrupted non-daemon thread"
case e: InterruptedException => System.err.println(msg)
val msg = "TrapExit improperly interrupted non-daemon thread" error(msg)
System.err.println(msg)
error(msg)
} }
} }
} }

View File

@ -2,6 +2,5 @@ object C {
import A._, B._ import A._, B._
implicitly[Ordering[Int]] implicitly[Ordering[Int]]
def main(args: Array[String]) {} def main(args: Array[String]): Unit = ()
} }

View File

@ -6,12 +6,12 @@ class B {
// not public, so this shouldn't be tracked as an inherited dependency // not public, so this shouldn't be tracked as an inherited dependency
private[this] class X extends D with E[Int] private[this] class X extends D with E[Int]
def x(i: Int) { def x(i: Int): Unit = {
// not public, not an inherited dependency // not public, not an inherited dependency
trait Y extends D trait Y extends D
} }
def y(j: Int) { def y(j: Int): Unit = {
// not public // not public
val w: D { def length: Int } = ??? val w: D { def length: Int } = ???
() ()

View File

@ -31,6 +31,6 @@ verifyDeps := {
same(inheritedDeps("J"), JDeps) same(inheritedDeps("J"), JDeps)
} }
def same[T](x: T, y: T) { def same[T](x: T, y: T): Unit = {
assert(x == y, s"\nActual: $x, \nExpected: $y") assert(x == y, s"\nActual: $x, \nExpected: $y")
} }

View File

@ -25,6 +25,6 @@ lazy val pairs =
lazy val expectedDeps = (Relation.empty[File,File] /: pairs) { case (r, (x,ys)) => r + (x,ys) } lazy val expectedDeps = (Relation.empty[File,File] /: pairs) { case (r, (x,ys)) => r + (x,ys) }
def toFile(s: String) = file(s + ".java").getAbsoluteFile def toFile(s: String) = file(s + ".java").getAbsoluteFile
def same[T](x: T, y: T) { def same[T](x: T, y: T): Unit = {
assert(x == y, s"\nActual: $x, \nExpected: $y") assert(x == y, s"\nActual: $x, \nExpected: $y")
} }

View File

@ -1,3 +1,3 @@
class S { class S {
def foo(s:String) { println("I am foo") } def foo(s:String): Unit = println("I am foo")
} }

View File

@ -1,3 +1,3 @@
class S { class S {
def foo2(s:String) { println("I am foo") } def foo2(s:String): Unit = println("I am foo")
} }

View File

@ -1,4 +1,4 @@
object First object First
{ {
def main(args: Array[String]) {} def main(args: Array[String]): Unit = ()
} }

View File

@ -1,4 +1,4 @@
object Second object Second
{ {
def main(args: Array[String]) {} def main(args: Array[String]): Unit = ()
} }

View File

@ -1,6 +1,6 @@
object B object B
{ {
def main(args: Array[String]) { def main(args: Array[String]): Unit = {
val a = new A val a = new A
a.x(3) a.x(3)
} }

View File

@ -2,7 +2,7 @@ class X extends E with C with B
object Main { object Main {
def main(args: Array[String]) { def main(args: Array[String]): Unit = {
val x = new X val x = new X
val expected = args(0).toInt val expected = args(0).toInt
assert(x.x == expected, "Expected " + expected + ", got " + x.x) assert(x.x == expected, "Expected " + expected + ", got " + x.x)

View File

@ -4,7 +4,7 @@ import org.scalatest.Tag
class ArgumentTest extends FixtureFunSuite{ class ArgumentTest extends FixtureFunSuite{
type FixtureParam = Map[String,Any] type FixtureParam = Map[String,Any]
override def withFixture(test: OneArgTest) { override def withFixture(test: OneArgTest): Unit = {
test(test.configMap) test(test.configMap)
} }
test("1", Tag("test1")){ conf => sys.error("error #1") } test("1", Tag("test1")){ conf => sys.error("error #1") }

Some files were not shown because too many files have changed in this diff Show More