diff --git a/buildfile/src/main/scala/sbt/internal/Eval.scala b/buildfile/src/main/scala/sbt/internal/Eval.scala index e22a5d10b..aa2fb957b 100644 --- a/buildfile/src/main/scala/sbt/internal/Eval.scala +++ b/buildfile/src/main/scala/sbt/internal/Eval.scala @@ -184,7 +184,7 @@ class Eval( end evalDefinitions - private[this] def evalCommon[A]( + private def evalCommon[A]( content: Seq[String], imports: EvalImports, tpeName: Option[String], @@ -222,10 +222,10 @@ class Eval( ) // location of the cached type or definition information - private[this] def cacheFile(base: Path, moduleName: String): Path = + private def cacheFile(base: Path, moduleName: String): Path = base.resolve(moduleName + ".cache") - private[this] def compileAndLoad[A]( + private def compileAndLoad[A]( ev: EvalType[A], moduleName: String, ): (A, ClassLoader => ClassLoader) = @@ -242,17 +242,17 @@ class Eval( val loader = (parent: ClassLoader) => AbstractFileClassLoader(outputDir, parent) (extra, loader) - private[this] final class EvalIntermediate[A]( + private final class EvalIntermediate[A]( val extra: A, val loader: ClassLoader => ClassLoader, val generated: Seq[Path], val enclosingModule: String, ) - private[this] def classExists(dir: Path, name: String): Boolean = + private def classExists(dir: Path, name: String): Boolean = Files.exists(dir.resolve(s"$name.class")) - private[this] def getGeneratedFiles(moduleName: String): Seq[Path] = + private def getGeneratedFiles(moduleName: String): Seq[Path] = backingDir match case Some(dir) => Files @@ -264,9 +264,9 @@ class Eval( .toList case None => Nil - private[this] def makeModuleName(hash: String): String = "$Wrap" + hash.take(10) + private def makeModuleName(hash: String): String = "$Wrap" + hash.take(10) - private[this] def checkError(label: String)(using ctx: Context): Unit = + private def checkError(label: String)(using ctx: Context): Unit = if ctx.reporter.hasErrors then throw new EvalException(label + ": " + ctx.reporter.allErrors.head.toString) else () @@ -349,7 +349,7 @@ object Eval: end EvalType class TypeExtractor extends tpd.TreeTraverser: - private[this] var result = "" + private var result = "" def getType(t: tpd.Tree)(using ctx: Context): String = result = "" this((), t) @@ -369,7 +369,7 @@ object Eval: * one of `types`. */ class ValExtractor(tpes: Set[String]) extends tpd.TreeTraverser: - private[this] var vals = List[String]() + private var vals = List[String]() def getVals(t: tpd.Tree)(using ctx: Context): List[String] = vals = Nil diff --git a/buildfile/src/main/scala/sbt/internal/EvaluateConfigurations.scala b/buildfile/src/main/scala/sbt/internal/EvaluateConfigurations.scala index ec935626d..6bc7c9ca0 100644 --- a/buildfile/src/main/scala/sbt/internal/EvaluateConfigurations.scala +++ b/buildfile/src/main/scala/sbt/internal/EvaluateConfigurations.scala @@ -52,14 +52,14 @@ private[sbt] object EvaluateConfigurations { /** * This represents the parsed expressions in a build sbt, as well as where they were defined. */ - private[this] final class ParsedFile( + private final class ParsedFile( val imports: Seq[(String, Int)], val definitions: Seq[(String, LineRange)], val settings: Seq[(String, LineRange)] ) /** The keywords we look for when classifying a string as a definition. */ - private[this] val DefinitionKeywords = Seq("lazy val ", "def ", "val ") + private val DefinitionKeywords = Seq("lazy val ", "def ", "val ") /** * Using an evaluating instance of the scala compiler, a sequence of files and @@ -99,7 +99,7 @@ private[sbt] object EvaluateConfigurations { * * @param builtinImports The set of import statements to add to those parsed in the .sbt file. */ - private[this] def parseConfiguration( + private def parseConfiguration( file: VirtualFileRef, lines: Seq[String], builtinImports: Seq[String], @@ -199,7 +199,7 @@ private[sbt] object EvaluateConfigurations { } /** move a project to be relative to this file after we've evaluated it. */ - private[this] def resolveBase(f: File, p: Project) = + private def resolveBase(f: File, p: Project) = p.copy(base = IO.resolve(f, p.base)) def addOffset(offset: Int, lines: Seq[(String, Int)]): Seq[(String, Int)] = @@ -300,17 +300,17 @@ private[sbt] object EvaluateConfigurations { // scala compiler rather than re-parsing. (split.imports, split.settings) - private[this] def splitSettingsDefinitions( + private def splitSettingsDefinitions( lines: Seq[(String, LineRange)] ): (Seq[(String, LineRange)], Seq[(String, LineRange)]) = lines partition { case (line, _) => isDefinition(line) } - private[this] def isDefinition(line: String): Boolean = { + private def isDefinition(line: String): Boolean = { val trimmed = line.trim DefinitionKeywords.exists(trimmed startsWith _) } - private[this] def extractedValTypes: Seq[String] = + private def extractedValTypes: Seq[String] = Seq( classOf[CompositeProject], classOf[InputKey[_]], @@ -318,7 +318,7 @@ private[sbt] object EvaluateConfigurations { classOf[SettingKey[_]] ).map(_.getName) - private[this] def evaluateDefinitions( + private def evaluateDefinitions( eval: Eval, name: String, imports: Seq[(String, Int)], @@ -378,7 +378,7 @@ object Index { def stringToKeyMap(settings: Set[AttributeKey[_]]): Map[String, AttributeKey[_]] = stringToKeyMap0(settings)(_.label) - private[this] def stringToKeyMap0( + private def stringToKeyMap0( settings: Set[AttributeKey[_]] )(label: AttributeKey[_] => String): Map[String, AttributeKey[_]] = { val multiMap = settings.groupBy(label) @@ -394,7 +394,7 @@ object Index { sys.error(s"Some keys were defined with the same name but different types: $duplicateStr") } - private[this] type TriggerMap = collection.mutable.HashMap[TaskId[?], Seq[TaskId[?]]] + private type TriggerMap = collection.mutable.HashMap[TaskId[?], Seq[TaskId[?]]] def triggers(ss: Settings[Scope]): Triggers = { val runBefore = new TriggerMap diff --git a/internal/util-complete/src/main/scala/sbt/internal/util/LineReader.scala b/internal/util-complete/src/main/scala/sbt/internal/util/LineReader.scala index 37022cb84..1e2d055b5 100644 --- a/internal/util-complete/src/main/scala/sbt/internal/util/LineReader.scala +++ b/internal/util-complete/src/main/scala/sbt/internal/util/LineReader.scala @@ -74,7 +74,7 @@ object LineReader { } } } - private[this] def inputrcFileUrl(): Option[URL] = { + private def inputrcFileUrl(): Option[URL] = { // keep jline2 compatibility // https://github.com/jline/jline2/blob/12b98d94589e3bd6a6/src/main/java/jline/console/ConsoleReader.java#L291-L306 sys.props @@ -95,7 +95,7 @@ object LineReader { } } // cache on memory. - private[this] lazy val inputrcFileContents: Option[Array[Byte]] = + private lazy val inputrcFileContents: Option[Array[Byte]] = inputrcFileUrl().map(in => sbt.io.IO.readBytes(in.openStream())) def createReader( historyPath: Option[File], @@ -171,22 +171,22 @@ object LineReader { } abstract class JLine extends LineReader { - protected[this] def handleCONT: Boolean - protected[this] def reader: ConsoleReader + protected def handleCONT: Boolean + protected def reader: ConsoleReader @deprecated("For binary compatibility only", "1.4.0") - protected[this] def injectThreadSleep: Boolean = false + protected def injectThreadSleep: Boolean = false @deprecated("For binary compatibility only", "1.4.0") - protected[this] lazy val in: InputStream = Terminal.wrappedSystemIn + protected lazy val in: InputStream = Terminal.wrappedSystemIn override def readLine(prompt: String, mask: Option[Char] = None): Option[String] = unsynchronizedReadLine(prompt, mask) - private[this] def unsynchronizedReadLine(prompt: String, mask: Option[Char]): Option[String] = + private def unsynchronizedReadLine(prompt: String, mask: Option[Char]): Option[String] = readLineWithHistory(prompt, mask) map { x => x.trim } - private[this] def readLineWithHistory(prompt: String, mask: Option[Char]): Option[String] = + private def readLineWithHistory(prompt: String, mask: Option[Char]): Option[String] = reader.getHistory match { case fh: FileHistory => try readLineDirect(prompt, mask) @@ -194,7 +194,7 @@ abstract class JLine extends LineReader { case _ => readLineDirect(prompt, mask) } - private[this] def readLineDirect(prompt: String, mask: Option[Char]): Option[String] = + private def readLineDirect(prompt: String, mask: Option[Char]): Option[String] = if (handleCONT) Signals.withHandler(() => resume(), signal = Signals.CONT)(() => readLineDirectRaw(prompt, mask) @@ -202,7 +202,7 @@ abstract class JLine extends LineReader { else readLineDirectRaw(prompt, mask) - private[this] def readLineDirectRaw(prompt: String, mask: Option[Char]): Option[String] = { + private def readLineDirectRaw(prompt: String, mask: Option[Char]): Option[String] = { val newprompt = handleMultilinePrompt(prompt) mask match { case Some(m) => Option(reader.readLine(newprompt, m)) @@ -210,7 +210,7 @@ abstract class JLine extends LineReader { } } - private[this] def handleMultilinePrompt(prompt: String): String = { + private def handleMultilinePrompt(prompt: String): String = { val lines0 = """\r?\n""".r.split(prompt) lines0.length match { case 0 | 1 => handleProgress(prompt) @@ -222,13 +222,13 @@ abstract class JLine extends LineReader { } } - private[this] def handleProgress(prompt: String): String = { + private def handleProgress(prompt: String): String = { import ConsoleAppender._ if (showProgress) s"$DeleteLine" + prompt else prompt } - private[this] def resume(): Unit = { + private def resume(): Unit = { Terminal.reset() reader.drawLine() reader.flush() @@ -308,7 +308,7 @@ final class FullReader( handleCONT, Terminal.console ) - protected[this] val reader: ConsoleReader = { + protected val reader: ConsoleReader = { val cr = LineReader.createJLine2Reader(historyPath, terminal) sbt.internal.util.complete.JLineCompletion.installCustomCompletor(cr, complete) cr @@ -322,7 +322,7 @@ class SimpleReader private[sbt] ( ) extends JLine { def this(historyPath: Option[File], handleCONT: Boolean, injectThreadSleep: Boolean) = this(historyPath, handleCONT, Terminal.console) - protected[this] lazy val reader: ConsoleReader = + protected lazy val reader: ConsoleReader = LineReader.createJLine2Reader(historyPath, terminal) } diff --git a/internal/util-complete/src/main/scala/sbt/internal/util/complete/JLineCompletion.scala b/internal/util-complete/src/main/scala/sbt/internal/util/complete/JLineCompletion.scala index d9812a6d5..9f265a048 100644 --- a/internal/util-complete/src/main/scala/sbt/internal/util/complete/JLineCompletion.scala +++ b/internal/util-complete/src/main/scala/sbt/internal/util/complete/JLineCompletion.scala @@ -32,10 +32,10 @@ object JLineCompletion { reader.setCompletionHandler(new CustomHandler(complete)) } - private[this] final class CustomHandler(completeImpl: (ConsoleReader, Int) => Boolean) + private final class CustomHandler(completeImpl: (ConsoleReader, Int) => Boolean) extends CompletionHandler { - private[this] var previous: Option[(String, Int)] = None - private[this] var level: Int = 1 + private var previous: Option[(String, Int)] = None + private var level: Int = 1 override def complete( reader: ConsoleReader, @@ -58,7 +58,7 @@ object JLineCompletion { // always provides dummy completions so that the custom completion handler gets called // (ConsoleReader doesn't call the handler if there aren't any completions) // the custom handler will then throw away the candidates and call the custom function - private[this] object DummyCompletor extends Completer { + private object DummyCompletor extends Completer { override def complete( buffer: String, cursor: Int, diff --git a/internal/util-complete/src/main/scala/sbt/internal/util/complete/Parser.scala b/internal/util-complete/src/main/scala/sbt/internal/util/complete/Parser.scala index 6bc1452b0..6bc9b8524 100644 --- a/internal/util-complete/src/main/scala/sbt/internal/util/complete/Parser.scala +++ b/internal/util-complete/src/main/scala/sbt/internal/util/complete/Parser.scala @@ -442,7 +442,7 @@ trait ParserMain { /** Presents a single Char `ch` as a Parser that only parses that exact character. */ implicit def literal(ch: Char): Parser[Char] = new ValidParser[Char] { def result = None - private[this] lazy val fail = mkFailure("Expected '" + ch + "'") + private lazy val fail = mkFailure("Expected '" + ch + "'") def resultEmpty = fail def derive(c: Char) = if (c == ch) success(ch) else new Invalid(fail) def completions(level: Int) = Completions.single(Completion.suggestion(ch.toString)) @@ -712,7 +712,7 @@ private final class TrapAndFail[A](a: Parser[A]) extends ValidParser[A] { override def toString = "trap(" + a + ")" override def isTokenStart = a.isTokenStart - private[this] def fail(e: Exception): Failure = mkFailure(e.toString) + private def fail(e: Exception): Failure = mkFailure(e.toString) } private final class OnFailure[A](a: Parser[A], message: String) extends ValidParser[A] { @@ -950,7 +950,7 @@ private final class StringLiteral(str: String, start: Int) extends ValidParser[S assert(0 <= start && start < str.length) def failMsg = "Expected '" + str + "'" - private[this] lazy val fail = mkFailure(failMsg) + private lazy val fail = mkFailure(failMsg) def resultEmpty = mkFailure(failMsg) def result = None @@ -963,7 +963,7 @@ private final class StringLiteral(str: String, start: Int) extends ValidParser[S private final class CharacterClass(f: Char => Boolean, label: String) extends ValidParser[Char] { def result = None - private[this] def fail: Failure = mkFailure("Expected " + label) + private def fail: Failure = mkFailure("Expected " + label) def resultEmpty = fail def derive(c: Char) = if (f(c)) success(c) else Invalid(fail) def completions(level: Int) = Completions.empty diff --git a/internal/util-complete/src/main/scala/sbt/internal/util/complete/Parsers.scala b/internal/util-complete/src/main/scala/sbt/internal/util/complete/Parsers.scala index e30173fd8..38c4b36ac 100644 --- a/internal/util-complete/src/main/scala/sbt/internal/util/complete/Parsers.scala +++ b/internal/util-complete/src/main/scala/sbt/internal/util/complete/Parsers.scala @@ -226,7 +226,7 @@ trait Parsers { /** Parses an unsigned integer. */ lazy val NatBasic = mapOrFail(Digit.+)(_.mkString.toInt) - private[this] def toInt(neg: Option[Char], digits: Seq[Char]): Int = + private def toInt(neg: Option[Char], digits: Seq[Char]): Int = (neg.toSeq ++ digits).mkString.toInt /** Parses the lower-case values `true` and `false` into their corresponding Boolean values. */ diff --git a/internal/util-complete/src/main/scala/sbt/internal/util/complete/SizeParser.scala b/internal/util-complete/src/main/scala/sbt/internal/util/complete/SizeParser.scala index d8b9f3bab..986321fac 100644 --- a/internal/util-complete/src/main/scala/sbt/internal/util/complete/SizeParser.scala +++ b/internal/util-complete/src/main/scala/sbt/internal/util/complete/SizeParser.scala @@ -23,21 +23,21 @@ private[sbt] object SizeParser { private def parseLong(s: String): Parser[Either[Double, Long]] = try Parser.success(Right(java.lang.Long.valueOf(s))) catch { case _: NumberFormatException => Parser.failure(s"Couldn't parse $s as double.") } - private[this] val digit = charClass(_.isDigit, "digit") - private[this] val numberParser: Parser[Either[Double, Long]] = + private val digit = charClass(_.isDigit, "digit") + private val numberParser: Parser[Either[Double, Long]] = (digit.+ ~ ('.'.examples() ~> digit.+).?).flatMap { case (leading, Some(decimalPart)) => parseDouble(s"${leading.mkString}.${decimalPart.mkString}") case (leading, _) => parseLong(leading.mkString) } - private[this] val unitParser: Parser[SizeUnit] = + private val unitParser: Parser[SizeUnit] = token("b" | "B" | "g" | "G" | "k" | "K" | "m" | "M").map { case "b" | "B" => Bytes case "g" | "G" => GigaBytes case "k" | "K" => KiloBytes case "m" | "M" => MegaBytes } - private[this] def multiply(left: Either[Double, Long], right: Long): Long = left match { + private def multiply(left: Either[Double, Long], right: Long): Long = left match { case Left(d) => (d * right).toLong case Right(l) => l * right } diff --git a/internal/util-core/src/main/scala/sbt/internal/util/Util.scala b/internal/util-core/src/main/scala/sbt/internal/util/Util.scala index 3b583fd40..c938471b6 100644 --- a/internal/util-core/src/main/scala/sbt/internal/util/Util.scala +++ b/internal/util-core/src/main/scala/sbt/internal/util/Util.scala @@ -26,14 +26,14 @@ object Util { def pairID[A, B] = (a: A, b: B) => (a, b) - private[this] lazy val Hyphen = """-(\p{javaLowerCase})""".r + private lazy val Hyphen = """-(\p{javaLowerCase})""".r def hasHyphen(s: String): Boolean = s.indexOf('-') >= 0 def hyphenToCamel(s: String): String = if (hasHyphen(s)) Hyphen.replaceAllIn(s, _.group(1).toUpperCase(Locale.ENGLISH)) else s - private[this] lazy val Camel = """(\p{javaLowerCase})(\p{javaUpperCase})""".r + private lazy val Camel = """(\p{javaLowerCase})(\p{javaUpperCase})""".r def camelToHyphen(s: String): String = Camel.replaceAllIn(s, m => m.group(1) + "-" + m.group(2).toLowerCase(Locale.ENGLISH)) diff --git a/internal/util-logging/src/main/scala/sbt/internal/util/BufferedLogger.scala b/internal/util-logging/src/main/scala/sbt/internal/util/BufferedLogger.scala index 06c3e370b..ff83d843d 100644 --- a/internal/util-logging/src/main/scala/sbt/internal/util/BufferedLogger.scala +++ b/internal/util-logging/src/main/scala/sbt/internal/util/BufferedLogger.scala @@ -43,7 +43,7 @@ class BufferedAppender(override val name: String, delegate: Appender) extends Ap override private[sbt] def properties: ConsoleAppender.Properties = delegate.properties override private[sbt] def suppressedMessage: SuppressedTraceContext => Option[String] = delegate.suppressedMessage - private[this] val log4j = new AtomicReference[AbstractAppender] + private val log4j = new AtomicReference[AbstractAppender] override private[sbt] def toLog4J = log4j.get match { case null => val a = new AbstractAppender( @@ -67,9 +67,9 @@ class BufferedAppender(override val name: String, delegate: Appender) extends Ap case a => a } - private[this] val buffer = + private val buffer = new java.util.Vector[Either[XLogEvent, (Level.Value, Option[String], Option[ObjectEvent[_]])]] - private[this] var recording = false + private var recording = false override def appendLog(level: Level.Value, message: => String): Unit = { if (recording) Util.ignoreResult(buffer.add(Right((level, Some(message), None)))) @@ -139,8 +139,8 @@ class BufferedAppender(override val name: String, delegate: Appender) extends Ap * This class assumes that it is the only client of the delegate logger. */ class BufferedLogger(delegate: AbstractLogger) extends BasicLogger { - private[this] val buffer = new ListBuffer[LogEvent] - private[this] var recording = false + private val buffer = new ListBuffer[LogEvent] + private var recording = false /** Enables buffering. */ def record() = synchronized { recording = true } diff --git a/internal/util-logging/src/main/scala/sbt/internal/util/ConsoleAppender.scala b/internal/util-logging/src/main/scala/sbt/internal/util/ConsoleAppender.scala index e1e50c082..5f14043ff 100644 --- a/internal/util-logging/src/main/scala/sbt/internal/util/ConsoleAppender.scala +++ b/internal/util-logging/src/main/scala/sbt/internal/util/ConsoleAppender.scala @@ -126,7 +126,7 @@ object ConsoleAppender { private[sbt] final val CursorLeft1000 = cursorLeft(1000) private[sbt] final val CursorDown1 = cursorDown(1) private[sbt] final val ClearPromptLine = CursorLeft1000 + ClearScreenAfterCursor - private[this] val showProgressHolder: AtomicBoolean = new AtomicBoolean(false) + private val showProgressHolder: AtomicBoolean = new AtomicBoolean(false) def setShowProgress(b: Boolean): Unit = showProgressHolder.set(b) def showProgress: Boolean = showProgressHolder.get private[sbt] trait Properties { @@ -166,7 +166,7 @@ object ConsoleAppender { case _ => LogOption.Auto } - private[this] val generateId: AtomicInteger = new AtomicInteger + private val generateId: AtomicInteger = new AtomicInteger /** * A new `ConsoleAppender` that writes to standard output. @@ -391,7 +391,7 @@ class ConsoleAppender( override private[sbt] val properties: Properties, override private[sbt] val suppressedMessage: SuppressedTraceContext => Option[String] ) extends Appender { - private[this] val log4j = new AtomicReference[XAppender](null) + private val log4j = new AtomicReference[XAppender](null) override private[sbt] lazy val toLog4J = log4j.get match { case null => log4j.synchronized { diff --git a/internal/util-logging/src/main/scala/sbt/internal/util/ConsoleOut.scala b/internal/util-logging/src/main/scala/sbt/internal/util/ConsoleOut.scala index 386bc0308..012a38c2e 100644 --- a/internal/util-logging/src/main/scala/sbt/internal/util/ConsoleOut.scala +++ b/internal/util-logging/src/main/scala/sbt/internal/util/ConsoleOut.scala @@ -35,7 +35,7 @@ object ConsoleOut { private[sbt] def getGlobalProxy: ConsoleOut = Proxy.proxy.get private object Proxy extends ConsoleOut { private[ConsoleOut] val proxy = new AtomicReference[ConsoleOut](systemOut) - private[this] def get: ConsoleOut = proxy.get + private def get: ConsoleOut = proxy.get def set(proxy: ConsoleOut): Unit = this.proxy.set(proxy) override val lockObject: AnyRef = proxy override def print(s: String): Unit = get.print(s) @@ -49,7 +49,7 @@ object ConsoleOut { (cur, prev) => cur.contains(s) && prev.contains(s) /** Move to beginning of previous line and clear the line. */ - private[this] final val OverwriteLine = "\u001B[A\r\u001B[2K" + private final val OverwriteLine = "\u001B[A\r\u001B[2K" /** * ConsoleOut instance that is backed by System.out. It overwrites the previously printed line if @@ -60,8 +60,8 @@ object ConsoleOut { */ def systemOutOverwrite(f: (String, String) => Boolean): ConsoleOut = new ConsoleOut { val lockObject: PrintStream = System.out - private[this] var last: Option[String] = None - private[this] val current = new java.lang.StringBuffer + private var last: Option[String] = None + private val current = new java.lang.StringBuffer def print(s: String): Unit = synchronized { current.append(s); () } def println(s: String): Unit = synchronized { current.append(s); println() } def println(): Unit = synchronized { @@ -113,7 +113,7 @@ object ConsoleOut { } } - private[this] val consoleOutPerTerminal = new ConcurrentHashMap[Terminal, ConsoleOut] + private val consoleOutPerTerminal = new ConcurrentHashMap[Terminal, ConsoleOut] def terminalOut(terminal: Terminal): ConsoleOut = consoleOutPerTerminal.get(terminal) match { case null => val res = new ConsoleOut { diff --git a/internal/util-logging/src/main/scala/sbt/internal/util/EscHelpers.scala b/internal/util-logging/src/main/scala/sbt/internal/util/EscHelpers.scala index 278c4b1c7..baf06467e 100644 --- a/internal/util-logging/src/main/scala/sbt/internal/util/EscHelpers.scala +++ b/internal/util-logging/src/main/scala/sbt/internal/util/EscHelpers.scala @@ -70,7 +70,7 @@ object EscHelpers { sb.toString } - private[this] def nextESC(s: String, start: Int, sb: java.lang.StringBuilder): Unit = { + private def nextESC(s: String, start: Int, sb: java.lang.StringBuilder): Unit = { val escIndex = s.indexOf(ESC, start) if (escIndex < 0) { sb.append(s, start, s.length) @@ -89,8 +89,8 @@ object EscHelpers { nextESC(s, next, sb) } } - private[this] val esc = 1 - private[this] val csi = 2 + private val esc = 1 + private val csi = 2 def cursorPosition(s: String): Int = { val bytes = s.getBytes var i = 0 @@ -248,7 +248,7 @@ object EscHelpers { * Skips the escape sequence starting at `i-1`. `i` should be positioned at the character after * the ESC that starts the sequence. */ - private[this] def skipESC(s: String, i: Int): Int = { + private def skipESC(s: String, i: Int): Int = { if (i >= s.length) { i } else if (isEscapeTerminator(s.charAt(i))) { diff --git a/internal/util-logging/src/main/scala/sbt/internal/util/JLine3.scala b/internal/util-logging/src/main/scala/sbt/internal/util/JLine3.scala index d6e216365..88dbdcb41 100644 --- a/internal/util-logging/src/main/scala/sbt/internal/util/JLine3.scala +++ b/internal/util-logging/src/main/scala/sbt/internal/util/JLine3.scala @@ -29,9 +29,9 @@ import java.util.concurrent.LinkedBlockingQueue private[sbt] object JLine3 { private[util] val initialAttributes = new AtomicReference[Attributes] - private[this] val forceWindowsJansiHolder = new AtomicBoolean(false) + private val forceWindowsJansiHolder = new AtomicBoolean(false) private[sbt] def forceWindowsJansi(): Unit = forceWindowsJansiHolder.set(true) - private[this] def windowsJansi(): org.jline.terminal.Terminal = { + private def windowsJansi(): org.jline.terminal.Terminal = { val provider = new JansiTerminalProvider val termType = sys.props.get("org.jline.terminal.type").orElse(sys.env.get("TERM")).orNull provider.winSysTerminal( @@ -95,7 +95,7 @@ private[sbt] object JLine3 { } res } - private[this] def wrapTerminal(term: Terminal): JTerminal = { + private def wrapTerminal(term: Terminal): JTerminal = { new AbstractTerminal( term.name, "nocapabilities", @@ -225,7 +225,7 @@ private[sbt] object JLine3 { } // We need to set the ENABLE_PROCESS_INPUT flag for ctrl+c to be treated as a signal in windows // https://docs.microsoft.com/en-us/windows/console/setconsolemode - private[this] val ENABLE_PROCESS_INPUT = 1 + private val ENABLE_PROCESS_INPUT = 1 private[util] def setEnableProcessInput(): Unit = if (Util.isWindows) { WindowsSupport.setConsoleMode(WindowsSupport.getConsoleMode | ENABLE_PROCESS_INPUT) } @@ -274,15 +274,15 @@ private[sbt] object JLine3 { ) result.asScala.toMap } - private[this] val iflagMap: Map[String, InputFlag] = + private val iflagMap: Map[String, InputFlag] = InputFlag.values.map(f => f.name.toLowerCase -> f).toMap - private[this] val oflagMap: Map[String, Attributes.OutputFlag] = + private val oflagMap: Map[String, Attributes.OutputFlag] = Attributes.OutputFlag.values.map(f => f.name.toLowerCase -> f).toMap - private[this] val cflagMap: Map[String, Attributes.ControlFlag] = + private val cflagMap: Map[String, Attributes.ControlFlag] = Attributes.ControlFlag.values.map(f => f.name.toLowerCase -> f).toMap - private[this] val lflagMap: Map[String, LocalFlag] = + private val lflagMap: Map[String, LocalFlag] = LocalFlag.values.map(f => f.name.toLowerCase -> f).toMap - private[this] val charMap: Map[String, Attributes.ControlChar] = + private val charMap: Map[String, Attributes.ControlChar] = Attributes.ControlChar.values().map(f => f.name.toLowerCase -> f).toMap private[sbt] def setMode(term: Terminal, canonical: Boolean, echo: Boolean): Unit = { val prev = attributesFromMap(term.getAttributes) diff --git a/internal/util-logging/src/main/scala/sbt/internal/util/LoggerWriter.scala b/internal/util-logging/src/main/scala/sbt/internal/util/LoggerWriter.scala index 8068c22a0..f134296b8 100644 --- a/internal/util-logging/src/main/scala/sbt/internal/util/LoggerWriter.scala +++ b/internal/util-logging/src/main/scala/sbt/internal/util/LoggerWriter.scala @@ -22,8 +22,8 @@ class LoggerWriter( def this(delegate: Logger, level: Level.Value) = this(delegate, Some(level)) def this(delegate: Logger) = this(delegate, None) - private[this] val buffer = new StringBuilder - private[this] val lines = new collection.mutable.ListBuffer[String] + private val buffer = new StringBuilder + private val lines = new collection.mutable.ListBuffer[String] override def close() = flush() @@ -48,7 +48,7 @@ class LoggerWriter( process() } - private[this] def process(): Unit = { + private def process(): Unit = { val i = buffer.indexOf(nl) if (i >= 0) { log(buffer.substring(0, i)) @@ -57,7 +57,7 @@ class LoggerWriter( } } - private[this] def log(s: String): Unit = unbufferedLevel match { + private def log(s: String): Unit = unbufferedLevel match { case None => lines += s; () case Some(level) => delegate.log(level, s) diff --git a/internal/util-logging/src/main/scala/sbt/internal/util/MultiLogger.scala b/internal/util-logging/src/main/scala/sbt/internal/util/MultiLogger.scala index 9e1240433..2e9d9d73a 100644 --- a/internal/util-logging/src/main/scala/sbt/internal/util/MultiLogger.scala +++ b/internal/util-logging/src/main/scala/sbt/internal/util/MultiLogger.scala @@ -16,7 +16,7 @@ import scala.annotation.nowarn class MultiLogger(delegates: List[AbstractLogger]) extends BasicLogger { @deprecated("No longer used.", "1.0.0") override lazy val ansiCodesSupported = delegates exists supported - @nowarn private[this] def supported = (_: AbstractLogger).ansiCodesSupported + @nowarn private def supported = (_: AbstractLogger).ansiCodesSupported override def setLevel(newLevel: Level.Value): Unit = { super.setLevel(newLevel) @@ -41,7 +41,7 @@ class MultiLogger(delegates: List[AbstractLogger]) extends BasicLogger { def control(event: ControlEvent.Value, message: => String): Unit = delegates.foreach(_.control(event, message)) - private[this] def dispatch(event: LogEvent): Unit = { + private def dispatch(event: LogEvent): Unit = { for (d <- delegates) { d.log(event) } diff --git a/internal/util-logging/src/main/scala/sbt/internal/util/ProgressState.scala b/internal/util-logging/src/main/scala/sbt/internal/util/ProgressState.scala index bab631e55..45253491e 100644 --- a/internal/util-logging/src/main/scala/sbt/internal/util/ProgressState.scala +++ b/internal/util-logging/src/main/scala/sbt/internal/util/ProgressState.scala @@ -47,16 +47,16 @@ private[sbt] final class ProgressState( padding.set(0) currentLineBytes.set(new ArrayBuffer[Byte]) } - private[this] val lineBuffer = new ArrayBlockingQueue[String](300) + private val lineBuffer = new ArrayBlockingQueue[String](300) private[util] def getLines: Seq[String] = lineBuffer.asScala.toVector - private[this] def appendLine(line: String) = while (!lineBuffer.offer(line)) { lineBuffer.poll } + private def appendLine(line: String) = while (!lineBuffer.offer(line)) { lineBuffer.poll } private[util] def clearBytes(): Unit = { val pad = padding.get if (currentLineBytes.get.isEmpty && pad > 0) padding.decrementAndGet() currentLineBytes.set(new ArrayBuffer[Byte]) } - private[this] val lineSeparatorBytes: Array[Byte] = System.lineSeparator.getBytes("UTF-8") + private val lineSeparatorBytes: Array[Byte] = System.lineSeparator.getBytes("UTF-8") private[util] def addBytes(terminal: Terminal, bytes: Seq[Byte]): Unit = { val previous: ArrayBuffer[Byte] = currentLineBytes.get val padding = this.padding.get @@ -86,9 +86,9 @@ private[sbt] final class ProgressState( prefix.getBytes ++ terminal.prompt.render().getBytes("UTF-8") } else Array.empty } - private[this] val cleanPrompt = + private val cleanPrompt = (DeleteLine + ClearScreenAfterCursor + CursorLeft1000).getBytes("UTF-8") - private[this] val clearScreenBytes = ClearScreenAfterCursor.getBytes("UTF-8") + private val clearScreenBytes = ClearScreenAfterCursor.getBytes("UTF-8") private[util] def write( terminal: Terminal, bytes: Array[Byte], diff --git a/internal/util-logging/src/main/scala/sbt/internal/util/Prompt.scala b/internal/util-logging/src/main/scala/sbt/internal/util/Prompt.scala index 0ef6c0ec8..ccd45801d 100644 --- a/internal/util-logging/src/main/scala/sbt/internal/util/Prompt.scala +++ b/internal/util-logging/src/main/scala/sbt/internal/util/Prompt.scala @@ -19,7 +19,7 @@ private[sbt] sealed trait Prompt { private[sbt] object Prompt { private[sbt] case class AskUser(override val mkPrompt: () => String) extends Prompt { - private[this] val bytes = new LinkedBlockingQueue[Byte] + private val bytes = new LinkedBlockingQueue[Byte] def write(b: Array[Byte]): Unit = b.foreach(bytes.put) override def render(): String = { val res = new String(bytes.asScala.toArray, "UTF-8") diff --git a/internal/util-logging/src/main/scala/sbt/internal/util/Terminal.scala b/internal/util-logging/src/main/scala/sbt/internal/util/Terminal.scala index b255910e7..ead919534 100644 --- a/internal/util-logging/src/main/scala/sbt/internal/util/Terminal.scala +++ b/internal/util-logging/src/main/scala/sbt/internal/util/Terminal.scala @@ -168,7 +168,7 @@ trait Terminal extends AutoCloseable { private[sbt] def withRawOutput[R](f: => R): R private[sbt] def restore(): Unit = {} private[sbt] def progressState: ProgressState - private[this] val promptHolder: AtomicReference[Prompt] = new AtomicReference(Prompt.Batch) + private val promptHolder: AtomicReference[Prompt] = new AtomicReference(Prompt.Batch) private[sbt] final def prompt: Prompt = promptHolder.get private[sbt] final def setPrompt(newPrompt: Prompt): Unit = if (prompt != Prompt.NoPrompt) promptHolder.set(newPrompt) @@ -231,14 +231,14 @@ object Terminal { // Disable noisy jline log spam if (System.getProperty("sbt.jline.verbose", "false") != "true") jline.internal.Log.setOutput(new PrintStream(_ => {}, false)) - private[this] val isCI = System.getProperty("sbt.ci", "") == "true" || + private val isCI = System.getProperty("sbt.ci", "") == "true" || sys.env.contains("BUILD_NUMBER") || sys.env.contains("CI") def consoleLog(string: String): Unit = { try Terminal.console.printStream.println(s"[info] $string") catch { case _: IOException => } } - private[this] val writeLock = new AnyRef + private val writeLock = new AnyRef def withWriteLock[A](f: => A): A = { writeLock.synchronized { f @@ -340,7 +340,7 @@ object Terminal { */ private[sbt] def restore(): Unit = console.toJLine.restore() - private[this] val hasProgress: AtomicBoolean = new AtomicBoolean(false) + private val hasProgress: AtomicBoolean = new AtomicBoolean(false) private[sbt] def parseLogOption(s: String): Option[Boolean] = s.toLowerCase match { @@ -358,7 +358,7 @@ object Terminal { * 3. -Dsbt.colour=always/auto/never/true/false 4. * -Dsbt.log.format=always/auto/never/true/false */ - private[this] lazy val logFormatEnabled: Option[Boolean] = { + private lazy val logFormatEnabled: Option[Boolean] = { sys.props.get("sbt.log.noformat") match { case Some(_) => Some(!java.lang.Boolean.getBoolean("sbt.log.noformat")) case _ => sys.props.get("sbt.log.format").flatMap(parseLogOption) @@ -366,10 +366,10 @@ object Terminal { } private[sbt] lazy val isAnsiSupported: Boolean = logFormatEnabled.getOrElse(useColorDefault) - private[this] val isDumb = Some("dumb") == sys.env.get("TERM") - private[this] def isDumbTerminal = isDumb || System.getProperty("jline.terminal", "") == "none" - private[this] val hasConsole = Option(java.lang.System.console).isDefined - private[this] def useColorDefault: Boolean = { + private val isDumb = Some("dumb") == sys.env.get("TERM") + private def isDumbTerminal = isDumb || System.getProperty("jline.terminal", "") == "none" + private val hasConsole = Option(java.lang.System.console).isDefined + private def useColorDefault: Boolean = { // This approximates that both stdin and stdio are connected, // so by default color will be turned off for pipes and redirects. props @@ -380,7 +380,7 @@ object Terminal { .getOrElse(true) && ((hasConsole && !isDumbTerminal) || isCI || Util.isEmacs) ) } - private[this] lazy val isColorEnabledProp: Option[Boolean] = + private lazy val isColorEnabledProp: Option[Boolean] = sys.props.get("sbt.color").orElse(sys.props.get("sbt.colour")).flatMap(parseLogOption) private[sbt] lazy val isColorEnabled = useColorDefault @@ -388,7 +388,7 @@ object Terminal { if (isColorEnabled && doRed) Console.RED + str + Console.RESET else str - private[this] def hasVirtualIO = System.getProperty("sbt.io.virtual", "") == "true" || !isCI + private def hasVirtualIO = System.getProperty("sbt.io.virtual", "") == "true" || !isCI private[sbt] def canPollSystemIn: Boolean = hasConsole && !isDumbTerminal && hasVirtualIO /** @@ -442,7 +442,7 @@ object Terminal { } else f } - private[this] object ProxyTerminal extends Terminal { + private object ProxyTerminal extends Terminal { private def t: Terminal = { val current = activeTerminal.get // if the activeTerminal is yet to be initialized on use, @@ -529,13 +529,13 @@ object Terminal { out.flush() } } - private[this] val originalOut = new LinePrintStream(System.out) - private[this] val originalErr = System.err - private[this] val originalIn = System.in + private val originalOut = new LinePrintStream(System.out) + private val originalErr = System.err + private val originalIn = System.in private[sbt] class WriteableInputStream(in: InputStream, name: String) extends SimpleInputStream with AutoCloseable { - private[this] val isRaw = new AtomicBoolean(false) + private val isRaw = new AtomicBoolean(false) final def write(bytes: Int*): Unit = buffer.synchronized { bytes.foreach(b => buffer.put(b)) } @@ -546,12 +546,12 @@ object Terminal { case _ => } } - private[this] val executor = + private val executor = Executors.newSingleThreadExecutor(r => new Thread(r, s"sbt-$name-input-reader")) - private[this] val buffer = new LinkedBlockingQueue[Integer] - private[this] val closed = new AtomicBoolean(false) - private[this] val readQueue = new LinkedBlockingQueue[Unit] - private[this] val readThread = new AtomicReference[Thread] + private val buffer = new LinkedBlockingQueue[Integer] + private val closed = new AtomicBoolean(false) + private val readQueue = new LinkedBlockingQueue[Unit] + private val readThread = new AtomicReference[Thread] /* * Starts a loop that fills a buffer with bytes from stdin. We only read from * the underlying stream when the buffer is empty and there is an active reader. @@ -563,7 +563,7 @@ object Terminal { * by setting the terminal to raw mode, which the input stream makes it non blocking, * but this approach only works on posix platforms. */ - private[this] val runnable: Runnable = () => { + private val runnable: Runnable = () => { @tailrec def impl(): Unit = { val _ = readQueue.take val b = in.read @@ -610,13 +610,13 @@ object Terminal { () } } - private[this] def nonBlockingIn(term: org.jline.terminal.Terminal): WriteableInputStream = { + private def nonBlockingIn(term: org.jline.terminal.Terminal): WriteableInputStream = { val in = if (Util.isNonCygwinWindows) new WindowsInputStream(term, originalIn) else originalIn new WriteableInputStream(in, "console") } - private[this] val inputStream = new AtomicReference[InputStream](System.in) - private[this] def withOut[T](f: => T): T = { + private val inputStream = new AtomicReference[InputStream](System.in) + private def withOut[T](f: => T): T = { try { System.setOut(proxyPrintStream) System.setErr(proxyErrorStream) @@ -626,7 +626,7 @@ object Terminal { System.setErr(originalErr) } } - private[this] def withIn[T](f: => T): T = + private def withIn[T](f: => T): T = try { inputStream.set(proxyInputStream) System.setIn(proxyInputStream) @@ -634,7 +634,7 @@ object Terminal { } finally System.setIn(originalIn) private[sbt] def withPrintStream[T](f: PrintStream => T): T = console.withPrintStream(f) - private[this] val attached = new AtomicBoolean(true) + private val attached = new AtomicBoolean(true) private[sbt] val NullTerminal = new DefaultTerminal(nullInputStream, _ => (), _ => ()) private[sbt] val SimpleTerminal = new DefaultTerminal(originalIn, originalOut, originalErr) @@ -645,7 +645,7 @@ object Terminal { * Terminal.console method returns this terminal and the ConsoleChannel delegates its terminal * method to it. */ - private[this] val consoleTerminalHolder: AtomicReference[Terminal] = + private val consoleTerminalHolder: AtomicReference[Terminal] = new AtomicReference(SimpleTerminal) /** @@ -654,7 +654,7 @@ object Terminal { * to change the terminal during task evaluation. This allows us to route System.in and System.out * through the terminal's input and output streams. */ - private[this] val activeTerminal = new AtomicReference[Terminal](consoleTerminalHolder.get) + private val activeTerminal = new AtomicReference[Terminal](consoleTerminalHolder.get) /** * The boot input stream allows a remote client to forward input to the sbt process while it is @@ -662,7 +662,7 @@ object Terminal { * bootInputStreamHolder if it is non-null as well as from the normal process console io (assuming * there is console io). */ - private[this] val bootInputStreamHolder = new AtomicReference[InputStream] + private val bootInputStreamHolder = new AtomicReference[InputStream] /** * The boot output stream allows sbt to relay the bytes written to stdout to one or more remote @@ -670,7 +670,7 @@ object Terminal { * TerminalConsole is updated to write to value of bootOutputStreamHolder when it is non-null as * well as the normal process console output stream. */ - private[this] val bootOutputStreamHolder = new AtomicReference[OutputStream] + private val bootOutputStreamHolder = new AtomicReference[OutputStream] private[sbt] def setBootStreams( bootInputStream: InputStream, bootOutputStream: OutputStream @@ -690,8 +690,8 @@ object Terminal { } } } - private[this] object proxyInputStream extends SimpleInputStream { - private[this] val isScripted = System.getProperty("sbt.scripted", "false") == "true" + private object proxyInputStream extends SimpleInputStream { + private val isScripted = System.getProperty("sbt.scripted", "false") == "true" /* * This is to handle the case when a remote client starts sbt and the build fails. * We need to be able to consume input bytes from the remote client, but they @@ -755,8 +755,8 @@ object Terminal { case stream => stream.available() + activeTerminal.get().inputStream.available() } } - private[this] object proxyOutputStream extends OutputStream { - private[this] def os: OutputStream = activeTerminal.get().outputStream + private object proxyOutputStream extends OutputStream { + private def os: OutputStream = activeTerminal.get().outputStream def write(byte: Int): Unit = { os.write(byte) os.flush() @@ -769,22 +769,22 @@ object Terminal { } override def flush(): Unit = os.flush() } - private[this] val proxyPrintStream = new LinePrintStream(proxyOutputStream) { + private val proxyPrintStream = new LinePrintStream(proxyOutputStream) { override def toString: String = s"proxyPrintStream($proxyOutputStream)" } - private[this] object proxyErrorOutputStream extends OutputStream { - private[this] def os: OutputStream = activeTerminal.get().errorStream + private object proxyErrorOutputStream extends OutputStream { + private def os: OutputStream = activeTerminal.get().errorStream def write(byte: Int): Unit = os.write(byte) override def write(bytes: Array[Byte]): Unit = write(bytes, 0, bytes.length) override def write(bytes: Array[Byte], offset: Int, len: Int): Unit = os.write(bytes, offset, len) override def flush(): Unit = os.flush() } - private[this] object proxyErrorStream extends PrintStream(proxyErrorOutputStream, true) - private[this] lazy val isWindows = + private object proxyErrorStream extends PrintStream(proxyErrorOutputStream, true) + private lazy val isWindows = System.getProperty("os.name", "").toLowerCase(Locale.ENGLISH).indexOf("windows") >= 0 - private[this] object WrappedSystemIn extends SimpleInputStream { - private[this] val in = proxyInputStream + private object WrappedSystemIn extends SimpleInputStream { + private val in = proxyInputStream override def available(): Int = if (attached.get) in.available() else 0 override def read(): Int = synchronized { if (attached.get) { @@ -826,7 +826,7 @@ object Terminal { } private[sbt] def startedByRemoteClient = props.isDefined - private[this] def newConsoleTerminal(): Terminal = { + private def newConsoleTerminal(): Terminal = { val system = JLine3.system new ConsoleTerminal(nonBlockingIn(system), originalOut, system) } @@ -839,7 +839,7 @@ object Terminal { // translate explicit class names to type in order to support // older Scala, since it shaded classes but not the system property - private[this] def fixTerminalProperty(): Unit = { + private def fixTerminalProperty(): Unit = { val terminalProperty = "jline.terminal" val newValue = if (!isAnsiSupported && System.getProperty("sbt.io.virtual", "") == "false") "none" @@ -886,7 +886,7 @@ object Terminal { out: OutputStream, private[util] val system: org.jline.terminal.Terminal, ) extends TerminalImpl(in, out, originalErr, "console0") { - private[this] val rawMode = new AtomicBoolean(false) + private val rawMode = new AtomicBoolean(false) if (Util.isWindows && hasConsole) { // It is necessary to enter and exit raw mode in order to get the windows // console to echo input. @@ -977,11 +977,11 @@ object Terminal { override private[sbt] val name: String ) extends Terminal { self => private[sbt] def getSizeImpl: (Int, Int) - private[this] val sizeRefreshPeriod = 1.second - private[this] val size = + private val sizeRefreshPeriod = 1.second + private val size = new AtomicReference[((Int, Int), Deadline)](((1, 1), Deadline.now - 1.day)) - private[this] def setSize() = size.set((Try(getSizeImpl).getOrElse((1, 1)), Deadline.now)) - private[this] def getSize = size.get match { + private def setSize() = size.set((Try(getSizeImpl).getOrElse((1, 1)), Deadline.now)) + private def getSize = size.get match { case (s, d) if (d + sizeRefreshPeriod).isOverdue() => setSize() size.get._1 @@ -989,7 +989,7 @@ object Terminal { } override def getWidth: Int = getSize._1 override def getHeight: Int = getSize._2 - private[this] val rawMode = new AtomicBoolean(false) + private val rawMode = new AtomicBoolean(false) def throwIfClosed[R](f: => R): R = if (isStopped.get) throw new ClosedChannelException else f override def getLastLine: Option[String] = progressState.currentLine override def getLines: Seq[String] = progressState.getLines @@ -1042,7 +1042,7 @@ object Terminal { override def inputStream: InputStream = in private[sbt] def write(bytes: Int*): Unit = in.write(bytes: _*) - private[this] val isStopped = new AtomicBoolean(false) + private val isStopped = new AtomicBoolean(false) override def getLineHeightAndWidth(line: String): (Int, Int) = getWidth match { case width if width > 0 => @@ -1057,7 +1057,7 @@ object Terminal { try f finally rawMode.set(false) } - private[this] val rawPrintStream: PrintStream = new LinePrintStream(combinedOutputStream) + private val rawPrintStream: PrintStream = new LinePrintStream(combinedOutputStream) override def withPrintStream[T](f: PrintStream => T): T = writeLock.synchronized(f(rawPrintStream)) diff --git a/internal/util-logging/src/main/scala/sbt/internal/util/WindowsInputStream.scala b/internal/util-logging/src/main/scala/sbt/internal/util/WindowsInputStream.scala index 541c60627..4c1477fff 100644 --- a/internal/util-logging/src/main/scala/sbt/internal/util/WindowsInputStream.scala +++ b/internal/util-logging/src/main/scala/sbt/internal/util/WindowsInputStream.scala @@ -139,7 +139,7 @@ private[util] class WindowsInputStream(term: org.jline.terminal.Terminal, in: In sb.toString().getBytes() } } - private[this] val raw: InputStream = new SimpleInputStream { + private val raw: InputStream = new SimpleInputStream { val buffer = new LinkedBlockingQueue[Integer] @tailrec override def read(): Int = { @@ -151,7 +151,7 @@ private[util] class WindowsInputStream(term: org.jline.terminal.Terminal, in: In } } } - private[this] val isRaw = new AtomicBoolean(true) + private val isRaw = new AtomicBoolean(true) private[sbt] def setRawMode(toggle: Boolean): Unit = isRaw.set(toggle) override def read(): Int = if (isRaw.get) raw.read() else in.read() } diff --git a/internal/util-logging/src/main/scala/sbt/util/Logger.scala b/internal/util-logging/src/main/scala/sbt/util/Logger.scala index 03616b7f1..fe6e0aa86 100644 --- a/internal/util-logging/src/main/scala/sbt/util/Logger.scala +++ b/internal/util-logging/src/main/scala/sbt/util/Logger.scala @@ -80,7 +80,7 @@ object Logger { case _ => wrapXLogger(lg) } - private[this] def wrapXLogger(lg: xLogger): Logger = new Logger { + private def wrapXLogger(lg: xLogger): Logger = new Logger { import InterfaceUtil.toSupplier override def debug(msg: Supplier[String]): Unit = lg.debug(msg) override def warn(msg: Supplier[String]): Unit = lg.warn(msg) diff --git a/internal/util-logging/src/main/scala/sbt/util/LoggerContext.scala b/internal/util-logging/src/main/scala/sbt/util/LoggerContext.scala index af74d861c..ea6b515c9 100644 --- a/internal/util-logging/src/main/scala/sbt/util/LoggerContext.scala +++ b/internal/util-logging/src/main/scala/sbt/util/LoggerContext.scala @@ -58,8 +58,8 @@ object LoggerContext { } def appenders: Seq[Appender] = consoleAppenders.get.map(_._1) } - private[this] val loggers = new ConcurrentHashMap[String, Log] - private[this] val closed = new AtomicBoolean(false) + private val loggers = new ConcurrentHashMap[String, Log] + private val closed = new AtomicBoolean(false) override def logger( name: String, channelName: Option[String], diff --git a/internal/util-logging/src/test/scala/Escapes.scala b/internal/util-logging/src/test/scala/Escapes.scala index fd92660de..3d81163a7 100644 --- a/internal/util-logging/src/test/scala/Escapes.scala +++ b/internal/util-logging/src/test/scala/Escapes.scala @@ -42,7 +42,7 @@ object Escapes extends Properties("Escapes") { !hasEscapeSequence(removed) } - private[this] final val ecs = ESC.toString + private final val ecs = ESC.toString private val partialEscapeSequences = Gen.oneOf(Gen const ecs, Gen const ecs ++ "[", Gen.choose('@', '_').map(ecs :+ _)) @@ -104,7 +104,7 @@ object Escapes extends Properties("Escapes") { else s"ESC ($content) (${terminator.toInt})" } - private[this] def noEscape(s: String): String = s.replace(ESC, ' ') + private def noEscape(s: String): String = s.replace(ESC, ' ') lazy val genEscapeSequence: Gen[EscapeSequence] = oneOf(genKnownSequence, genTwoCharacterSequence, genArbitraryEscapeSequence) diff --git a/internal/util-logic/src/main/scala/sbt/internal/util/logic/Logic.scala b/internal/util-logic/src/main/scala/sbt/internal/util/logic/Logic.scala index 706c7a587..ca99ef320 100644 --- a/internal/util-logic/src/main/scala/sbt/internal/util/logic/Logic.scala +++ b/internal/util-logic/src/main/scala/sbt/internal/util/logic/Logic.scala @@ -135,7 +135,7 @@ object Logic { * an atom is proved but no clauses prove it. This isn't necessarily a problem, but the main sbt * use cases expects a proven atom to have at least one clause satisfied. */ - private[this] def checkOverlap( + private def checkOverlap( clauses: Clauses, initialFacts: Set[Atom] ): Option[InitialOverlap] = { @@ -144,7 +144,7 @@ object Logic { if (initialOverlap.nonEmpty) Some(new InitialOverlap(initialOverlap)) else None } - private[this] def checkContradictions( + private def checkContradictions( pos: Set[Atom], neg: Set[Atom] ): Option[InitialContradictions] = { @@ -152,7 +152,7 @@ object Logic { if (contradictions.nonEmpty) Some(new InitialContradictions(contradictions)) else None } - private[this] def checkAcyclic(clauses: Clauses): Option[CyclicNegation] = { + private def checkAcyclic(clauses: Clauses): Option[CyclicNegation] = { val deps = dependencyMap(clauses) // println(s"deps = $deps") // println(s"graph(deps) = ${graph(deps)}") @@ -160,7 +160,7 @@ object Logic { if (cycle.nonEmpty) Some(new CyclicNegation(cycle)) else None } - private[this] def graph(deps: Map[Atom, Set[Literal]]) = new Dag.DirectedSignedGraph[Atom] { + private def graph(deps: Map[Atom, Set[Literal]]) = new Dag.DirectedSignedGraph[Atom] { type Arrow = Literal def nodes: List[Atom] = deps.keys.toList def dependencies(a: Atom) = deps.getOrElse(a, Set.empty).toList @@ -177,7 +177,7 @@ object Logic { .mkString("{\n", "\n", "\n}") } - private[this] def dependencyMap(clauses: Clauses): Map[Atom, Set[Literal]] = + private def dependencyMap(clauses: Clauses): Map[Atom, Set[Literal]] = clauses.clauses.foldLeft(Map.empty[Atom, Set[Literal]]) { case (m, Clause(formula, heads)) => val deps = literals(formula) heads.foldLeft(m) { (n, head) => @@ -220,7 +220,7 @@ object Logic { } /** Separates a sequence of literals into `(pos, neg)` atom sequences. */ - private[this] def separate(lits: Seq[Literal]): (Seq[Atom], Seq[Atom]) = + private def separate(lits: Seq[Literal]): (Seq[Atom], Seq[Atom]) = Util.separate(lits) { case a: Atom => Left(a) case Negated(n) => Right(n) @@ -230,16 +230,16 @@ object Logic { * Finds clauses that have no body and thus prove their head. Returns `(, )`. */ - private[this] def findProven(c: Clauses): (Set[Atom], List[Clause]) = { + private def findProven(c: Clauses): (Set[Atom], List[Clause]) = { val (proven, unproven) = c.clauses.partition(_.body == True) (proven.flatMap(_.head).toSet, unproven) } - private[this] def keepPositive(lits: Set[Literal]): Set[Atom] = + private def keepPositive(lits: Set[Literal]): Set[Atom] = lits.collect { case a: Atom => a }.toSet // precondition: factsToProcess contains no contradictions - @tailrec private[this] def reduce0( + @tailrec private def reduce0( clauses: Clauses, factsToProcess: Set[Literal], state: Matched @@ -265,7 +265,7 @@ object Logic { * Finds negated atoms under the negation as failure rule and returns them. This should be called * only after there are no more known atoms to be substituted. */ - private[this] def inferFailure(clauses: Clauses): Set[Literal] = { + private def inferFailure(clauses: Clauses): Set[Literal] = { /* At this point, there is at least one clause and one of the following is the case as the result of the acyclic negation rule: i. there is at least one variable that occurs in a clause body but not in the head of a @@ -289,7 +289,7 @@ object Logic { } } - private[this] def negated(atoms: Set[Atom]): Set[Literal] = atoms.map(a => (Negated(a): Literal)) + private def negated(atoms: Set[Atom]): Set[Literal] = atoms.map(a => (Negated(a): Literal)) /** * Computes the set of atoms in `clauses` that directly or transitively take a negated atom as @@ -317,13 +317,13 @@ object Logic { } /** Computes the `(positive, negative)` literals in `formula`. */ - private[this] def directDeps(formula: Formula): (Seq[Atom], Seq[Atom]) = + private def directDeps(formula: Formula): (Seq[Atom], Seq[Atom]) = Util.separate(literals(formula).toSeq) { case Negated(a) => Right(a) case a: Atom => Left(a) } - private[this] def literals(formula: Formula): Set[Literal] = formula match { + private def literals(formula: Formula): Set[Literal] = formula match { case And(lits) => lits case l: Literal => Set(l) case True => Set.empty diff --git a/internal/util-position/src/main/scala-2/sbt/internal/util/SourcePositionMacro.scala b/internal/util-position/src/main/scala-2/sbt/internal/util/SourcePositionMacro.scala index 9c025164b..ad1a9401b 100644 --- a/internal/util-position/src/main/scala-2/sbt/internal/util/SourcePositionMacro.scala +++ b/internal/util-position/src/main/scala-2/sbt/internal/util/SourcePositionMacro.scala @@ -34,7 +34,7 @@ final class SourcePositionMacro(val c: blackbox.Context) { } else reify { NoPosition } } - private[this] def ownerSource(path: String, name: String): String = { + private def ownerSource(path: String, name: String): String = { @tailrec def inEmptyPackage(s: Symbol): Boolean = s != NoSymbol && ( s.owner == c.mirror.EmptyPackage @@ -49,5 +49,5 @@ final class SourcePositionMacro(val c: blackbox.Context) { } } - private[this] def constant[T: WeakTypeTag](t: T): Expr[T] = c.Expr[T](Literal(Constant(t))) + private def constant[T: WeakTypeTag](t: T): Expr[T] = c.Expr[T](Literal(Constant(t))) } diff --git a/internal/util-scripted/src/main/scala/sbt/internal/scripted/ScriptedTests.scala b/internal/util-scripted/src/main/scala/sbt/internal/scripted/ScriptedTests.scala index 52c08c70a..17e6b3200 100644 --- a/internal/util-scripted/src/main/scala/sbt/internal/scripted/ScriptedTests.scala +++ b/internal/util-scripted/src/main/scala/sbt/internal/scripted/ScriptedTests.scala @@ -210,7 +210,7 @@ final class ListTests(baseDirectory: File, accept: ScriptedTest => Boolean, log: listTests(group).map(ScriptedTest(groupName, _)) } } - private[this] def listTests(group: File): Seq[String] = { + private def listTests(group: File): Seq[String] = { val groupName = group.getName val allTests = list(group, filter).sortBy(_.getName) if (allTests.isEmpty) { diff --git a/launcher-package/integration-test/src/test/scala/InheritInput.scala b/launcher-package/integration-test/src/test/scala/InheritInput.scala index d8304926d..6d150d881 100644 --- a/launcher-package/integration-test/src/test/scala/InheritInput.scala +++ b/launcher-package/integration-test/src/test/scala/InheritInput.scala @@ -9,9 +9,9 @@ private[sbt] object InheritInput { case _ => false } - private[this] val pbClass = Class.forName("java.lang.ProcessBuilder") - private[this] val redirectClass = pbClass.getClasses find (_.getSimpleName == "Redirect") + private val pbClass = Class.forName("java.lang.ProcessBuilder") + private val redirectClass = pbClass.getClasses find (_.getSimpleName == "Redirect") - private[this] val redirectInput = redirectClass map (pbClass.getMethod("redirectInput", _)) - private[this] val inherit = redirectClass map (_ getField "INHERIT" get null) + private val redirectInput = redirectClass map (pbClass.getMethod("redirectInput", _)) + private val inherit = redirectClass map (_ getField "INHERIT" get null) } diff --git a/launcher-package/integration-test/src/test/scala/ProcessImpl.scala b/launcher-package/integration-test/src/test/scala/ProcessImpl.scala index dc67e3c44..b53998a39 100644 --- a/launcher-package/integration-test/src/test/scala/ProcessImpl.scala +++ b/launcher-package/integration-test/src/test/scala/ProcessImpl.scala @@ -77,14 +77,14 @@ object BasicIO { try { transferFullyImpl(in, out) } catch { case _: InterruptedException => () } - private[this] def appendLine(buffer: Appendable): String => Unit = + private def appendLine(buffer: Appendable): String => Unit = line => { buffer.append(line) buffer.append(Newline) } - private[this] def transferFullyImpl(in: InputStream, out: OutputStream): Unit = { + private def transferFullyImpl(in: InputStream, out: OutputStream): Unit = { val continueCount = 1 //if(in.isInstanceOf[PipedInputStream]) 1 else 0 val buffer = new Array[Byte](BufferSize) def read(): Unit = { @@ -124,7 +124,7 @@ private[sbt] abstract class AbstractProcessBuilder extends ProcessBuilder with S def run(log: ProcessLogger): Process = run(log, false) def run(log: ProcessLogger, connectInput: Boolean): Process = run(BasicIO(log, connectInput)) - private[this] def getString(log: Option[ProcessLogger], withIn: Boolean): String = + private def getString(log: Option[ProcessLogger], withIn: Boolean): String = { val buffer = new StringBuffer val code = this ! BasicIO(buffer, log, withIn) @@ -140,7 +140,7 @@ private[sbt] abstract class AbstractProcessBuilder extends ProcessBuilder with S def lines_! : Stream[String] = lines(false, false, None) def lines_!(log: ProcessLogger): Stream[String] = lines(false, false, Some(log)) - private[this] def lines(withInput: Boolean, nonZeroException: Boolean, log: Option[ProcessLogger]): Stream[String] = + private def lines(withInput: Boolean, nonZeroException: Boolean, log: Option[ProcessLogger]): Stream[String] = { val streamed = Streamed[String](nonZeroException) val process = run(new ProcessIO(BasicIO.input(withInput), BasicIO.processFully(streamed.process), BasicIO.getErr(log), BasicIO.inheritInput(withInput))) @@ -172,14 +172,14 @@ private[sbt] class FileBuilder(base: File) extends FilePartialBuilder with SinkP } private abstract class BasicBuilder extends AbstractProcessBuilder { - protected[this] def checkNotThis(a: ProcessBuilder) = require(a != this, "Compound process '" + a + "' cannot contain itself.") + protected def checkNotThis(a: ProcessBuilder) = require(a != this, "Compound process '" + a + "' cannot contain itself.") final def run(io: ProcessIO): Process = { val p = createProcess(io) p.start() p } - protected[this] def createProcess(io: ProcessIO): BasicProcess + protected def createProcess(io: ProcessIO): BasicProcess } private abstract class BasicProcess extends Process { def start(): Unit @@ -204,9 +204,9 @@ private abstract class CompoundProcess extends BasicProcess { } /** Start and block until the exit value is available and then return it in Some. Return None if destroyed (use 'run')*/ - protected[this] def runAndExitValue(): Option[Int] + protected def runAndExitValue(): Option[Int] - protected[this] def runInterruptible[T](action: => T)(destroyImpl: => Unit): Option[T] = + protected def runInterruptible[T](action: => T)(destroyImpl: => Unit): Option[T] = { try { Some(action) } catch { case _: InterruptedException => destroyImpl; None } @@ -232,7 +232,7 @@ private class SequenceProcessBuilder(first: ProcessBuilder, second: ProcessBuild } private class SequentialProcess(a: ProcessBuilder, b: ProcessBuilder, io: ProcessIO, evaluateSecondProcess: Int => Boolean) extends CompoundProcess { - protected[this] override def runAndExitValue() = + protected override def runAndExitValue() = { val first = a.run(io) runInterruptible(first.exitValue)(first.destroy()) flatMap @@ -250,7 +250,7 @@ private class OrProcess(a: ProcessBuilder, b: ProcessBuilder, io: ProcessIO) ext private class ProcessSequence(a: ProcessBuilder, b: ProcessBuilder, io: ProcessIO) extends SequentialProcess(a, b, io, ignore => true) private class PipedProcesses(a: ProcessBuilder, b: ProcessBuilder, defaultIO: ProcessIO, toError: Boolean, exitCode: (Int, Int) => Int) extends CompoundProcess { - protected[this] override def runAndExitValue() = + protected override def runAndExitValue() = { val currentSource = new SyncVar[Option[InputStream]] val pipeOut = new PipedOutputStream @@ -333,7 +333,7 @@ private[sbt] class DummyProcessBuilder(override val toString: String, exitValue: * The implementation of `exitValue` waits until these threads die before returning. */ private class DummyProcess(action: => Int) extends Process { - private[this] val exitCode = Future(action) + private val exitCode = Future(action) override def exitValue() = exitCode() override def destroy(): Unit = () } diff --git a/launcher-package/integration-test/src/test/scala/SyncVar.scala b/launcher-package/integration-test/src/test/scala/SyncVar.scala index 5754e6da0..e5c7294c5 100644 --- a/launcher-package/integration-test/src/test/scala/SyncVar.scala +++ b/launcher-package/integration-test/src/test/scala/SyncVar.scala @@ -2,8 +2,8 @@ package sbt.internal // minimal copy of scala.concurrent.SyncVar since that version deprecated put and unset private[sbt] final class SyncVar[A] { - private[this] var isDefined: Boolean = false - private[this] var value: Option[A] = None + private var isDefined: Boolean = false + private var value: Option[A] = None /** Waits until a value is set and then gets it. Does not clear the value */ def get: A = synchronized { diff --git a/main-actions/src/main/scala/sbt/ForkTests.scala b/main-actions/src/main/scala/sbt/ForkTests.scala index 150667e13..b13711a34 100755 --- a/main-actions/src/main/scala/sbt/ForkTests.scala +++ b/main-actions/src/main/scala/sbt/ForkTests.scala @@ -77,7 +77,7 @@ private[sbt] object ForkTests { apply(runners, tests, config, classpath, converter, fork, log, tag -> 1) } - private[this] def mainTestTask( + private def mainTestTask( runners: Map[TestFramework, Runner], opts: ProcessedOptions, classpath: Seq[HashedVirtualFileRef], @@ -191,7 +191,7 @@ private[sbt] object ForkTests { } } - private[this] def forkFingerprint(f: Fingerprint): Fingerprint with Serializable = + private def forkFingerprint(f: Fingerprint): Fingerprint with Serializable = f match { case s: SubclassFingerprint => new ForkMain.SubclassFingerscan(s) case a: AnnotatedFingerprint => new ForkMain.AnnotatedFingerscan(a) diff --git a/main-actions/src/main/scala/sbt/Tests.scala b/main-actions/src/main/scala/sbt/Tests.scala index 12593c0e1..ce0e9057d 100644 --- a/main-actions/src/main/scala/sbt/Tests.scala +++ b/main-actions/src/main/scala/sbt/Tests.scala @@ -335,7 +335,7 @@ object Tests { ) } - private[this] def distinctBy[T, K](in: Seq[T])(f: T => K): Seq[T] = { + private def distinctBy[T, K](in: Seq[T])(f: T => K): Seq[T] = { val seen = new collection.mutable.HashSet[K] in.filter(t => seen.add(f(t))) } diff --git a/main-command/src/main/scala/sbt/BasicCommandStrings.scala b/main-command/src/main/scala/sbt/BasicCommandStrings.scala index 154f43d74..c3939a958 100644 --- a/main-command/src/main/scala/sbt/BasicCommandStrings.scala +++ b/main-command/src/main/scala/sbt/BasicCommandStrings.scala @@ -73,7 +73,7 @@ $HelpCommand Help(brief, detailed) } - private[this] def logLevelDetail(level: Level.Value): String = + private def logLevelDetail(level: Level.Value): String = s"""$level Sets the global logging level to $level. diff --git a/main-command/src/main/scala/sbt/BasicCommands.scala b/main-command/src/main/scala/sbt/BasicCommands.scala index afece5131..6ec2d0412 100644 --- a/main-command/src/main/scala/sbt/BasicCommands.scala +++ b/main-command/src/main/scala/sbt/BasicCommands.scala @@ -74,12 +74,12 @@ object BasicCommands { def early: Command = Command.arb(earlyParser, earlyHelp)((s, other) => other :: s) - private[this] def levelParser: Parser[String] = + private def levelParser: Parser[String] = Iterator(Level.Debug, Level.Info, Level.Warn, Level.Error) map (l => token(l.toString) ) reduce (_ | _) - private[this] def addPluginSbtFileParser: Parser[File] = { + private def addPluginSbtFileParser: Parser[File] = { token(AddPluginSbtFileCommand) ~> (":" | "=" | Space.map(_.toString)) ~> (StringBasic).examples( "/some/extra.sbt" ) map { @@ -87,7 +87,7 @@ object BasicCommands { } } - private[this] def addPluginSbtFileStringParser: Parser[String] = { + private def addPluginSbtFileStringParser: Parser[String] = { token( token(AddPluginSbtFileCommand) ~ (":" | "=" | Space.map(_.toString)) ~ (StringBasic) .examples("/some/extra.sbt") map { case s1 ~ s2 ~ s3 => @@ -96,14 +96,14 @@ object BasicCommands { ) } - private[this] def earlyParser: State => Parser[String] = (s: State) => { + private def earlyParser: State => Parser[String] = (s: State) => { val p1 = token(EarlyCommand + "(") flatMap (_ => otherCommandParser(s) <~ token(")")) val p2 = (token("-") | token("--")) flatMap (_ => levelParser) val p3 = (token("-") | token("--")) flatMap (_ => addPluginSbtFileStringParser) p1 | p2 | p3 } - private[this] def earlyHelp = Help(EarlyCommand, EarlyCommandBrief, EarlyCommandDetailed) + private def earlyHelp = Help(EarlyCommand, EarlyCommandBrief, EarlyCommandDetailed) /** * Adds additional *.sbt to the plugin build. @@ -158,7 +158,7 @@ object BasicCommands { @deprecated("No longer public", "1.1.1") def completionsParser(state: State): Parser[String] = completionsParser - private[this] def completionsParser: Parser[String] = { + private def completionsParser: Parser[String] = { val notQuoted = (NotQuoted ~ any.*) map { case (nq, s) => nq + s } val quotedOrUnquotedSingleArgument = Space ~> (StringVerbatim | StringEscapable | notQuoted) token((quotedOrUnquotedSingleArgument ?? "").examples("", " ")) @@ -351,7 +351,7 @@ object BasicCommands { def callParser: Parser[(Seq[String], Seq[String])] = token(Space) ~> ((classpathOptionParser ?? nilSeq) ~ rep1sep(className, token(Space))) - private[this] def className: Parser[String] = { + private def className: Parser[String] = { val base = StringBasic & not('-' ~> any.*, "Class name cannot start with '-'.") def single(s: String) = Completions.single(Completion.displayOnly(s)) val compl = TokenCompletions.fixed((seen, _) => @@ -360,10 +360,10 @@ object BasicCommands { token(base, compl) } - private[this] def classpathOptionParser: Parser[Seq[String]] = + private def classpathOptionParser: Parser[Seq[String]] = token(("-cp" | "-classpath") ~> Space) ~> classpathStrings <~ token(Space) - private[this] def classpathStrings: Parser[Seq[String]] = + private def classpathStrings: Parser[Seq[String]] = token(StringBasic.map(s => IO.pathSplit(s).toSeq), "") def exit: Command = Command.command(TerminateAction, exitBrief, exitBrief) { s => @@ -507,7 +507,7 @@ object BasicCommands { System.err.println("Invalid alias name '" + name + "'.") s.fail } - private[this] def addAlias0(s: State, name: String, value: String): State = + private def addAlias0(s: State, name: String, value: String): State = s.copy(definedCommands = newAlias(name, value) +: s.definedCommands) def removeAliases(s: State): State = removeTagged(s, CommandAliasKey) diff --git a/main-command/src/main/scala/sbt/Command.scala b/main-command/src/main/scala/sbt/Command.scala index 0d811899a..a94ae0d59 100644 --- a/main-command/src/main/scala/sbt/Command.scala +++ b/main-command/src/main/scala/sbt/Command.scala @@ -156,17 +156,17 @@ object Command { arbs.map(_.parser(state)).foldLeft(simpleParser(simple)(state))(_ | _) } - private[this] def separateCommands( + private def separateCommands( cmds: Seq[Command] ): (Seq[SimpleCommand], Seq[ArbitraryCommand]) = Util.separate(cmds) { case s: SimpleCommand => Left(s); case a: ArbitraryCommand => Right(a) } - private[this] def apply1[A, B, C](f: (A, B) => C, a: A): B => () => C = b => () => f(a, b) + private def apply1[A, B, C](f: (A, B) => C, a: A): B => () => C = b => () => f(a, b) def simpleParser(cmds: Seq[SimpleCommand]): State => Parser[() => State] = simpleParser(cmds.map(sc => (sc.name, argParser(sc))).toMap) - private[this] def argParser(sc: SimpleCommand): State => Parser[() => State] = { + private def argParser(sc: SimpleCommand): State => Parser[() => State] = { def usageError = s"${sc.name} usage:" + Help.message(sc.help0, None) s => (Parser.softFailure(usageError, definitive = true): Parser[() => State]) | sc.parser(s) diff --git a/main-command/src/main/scala/sbt/State.scala b/main-command/src/main/scala/sbt/State.scala index 3a1983951..834d89329 100644 --- a/main-command/src/main/scala/sbt/State.scala +++ b/main-command/src/main/scala/sbt/State.scala @@ -373,7 +373,7 @@ object State { else applyOnFailure(s, remaining, s.copy(remainingCommands = remaining)) } - private[this] def applyOnFailure(s: State, remaining: List[Exec], noHandler: => State): State = + private def applyOnFailure(s: State, remaining: List[Exec], noHandler: => State): State = s.onFailure match { case Some(c) => s.copy(remainingCommands = c +: remaining, onFailure = None) case None => noHandler @@ -437,13 +437,13 @@ object State { s.put(BasicKeys.extendedClassLoaderCache, cache) .put(BasicKeys.classLoaderCache, new IncClassLoaderCache(cache)) } - private[this] def newClassLoaderCache = + private def newClassLoaderCache = new ClassLoaderCache(s.configuration.provider.scalaProvider) } import ExceptionCategory._ - private[this] def handleException(t: Throwable, s: State, log: Logger): State = { + private def handleException(t: Throwable, s: State, log: Logger): State = { ExceptionCategory(t) match { case AlreadyHandled => () case m: MessageOnly => log.error(m.message) diff --git a/main-command/src/main/scala/sbt/Watched.scala b/main-command/src/main/scala/sbt/Watched.scala index 9b5f7e632..5c654f4f4 100644 --- a/main-command/src/main/scala/sbt/Watched.scala +++ b/main-command/src/main/scala/sbt/Watched.scala @@ -130,7 +130,7 @@ object Watched { }.label("Watched.projectOnWatchMessage") @deprecated("This method is not used and may be removed in a future version of sbt", "1.3.0") - private[this] class AWatched extends Watched + private class AWatched extends Watched @deprecated("This method is not used and may be removed in a future version of sbt", "1.3.0") def multi(base: Watched, paths: Seq[Watched]): Watched = diff --git a/main-command/src/main/scala/sbt/internal/CommandChannel.scala b/main-command/src/main/scala/sbt/internal/CommandChannel.scala index 7d9eb94d1..6f47a493d 100644 --- a/main-command/src/main/scala/sbt/internal/CommandChannel.scala +++ b/main-command/src/main/scala/sbt/internal/CommandChannel.scala @@ -76,10 +76,10 @@ abstract class CommandChannel { @deprecated("Use the variant that takes the logShutdown parameter", "1.4.0") def shutdown(): Unit = shutdown(true) def name: String - private[this] val level = new AtomicReference[Level.Value](Level.Info) + private val level = new AtomicReference[Level.Value](Level.Info) private[sbt] final def setLevel(l: Level.Value): Unit = level.set(l) private[sbt] final def logLevel: Level.Value = level.get - private[this] def setLevel(value: Level.Value, cmd: String): Boolean = { + private def setLevel(value: Level.Value, cmd: String): Boolean = { level.set(value) append(Exec(cmd, Some(Exec.newExecId), Some(CommandSource(name)))) } diff --git a/main-command/src/main/scala/sbt/internal/classpath/ClassLoaderCache.scala b/main-command/src/main/scala/sbt/internal/classpath/ClassLoaderCache.scala index a46803ed1..ba7553229 100644 --- a/main-command/src/main/scala/sbt/internal/classpath/ClassLoaderCache.scala +++ b/main-command/src/main/scala/sbt/internal/classpath/ClassLoaderCache.scala @@ -34,7 +34,7 @@ private[sbt] class ClassLoaderCache( val parent: ClassLoader, private val miniProvider: Option[(File, ClassLoader)] ) extends AbstractClassLoaderCache { - private[this] val parentHolder = new AtomicReference(parent) + private val parentHolder = new AtomicReference(parent) def commonParent = parentHolder.get() def setParent(parent: ClassLoader): Unit = parentHolder.set(parent) def this(commonParent: ClassLoader) = this(commonParent, None) @@ -73,11 +73,11 @@ private[sbt] class ClassLoaderCache( override def hashCode(): Int = (fileStamps.hashCode * 31) ^ parent.hashCode override def toString: String = s"Key(${fileStamps mkString ","}, $parent)" } - private[this] val delegate = + private val delegate = new java.util.concurrent.ConcurrentHashMap[Key, Reference[ClassLoader]]() - private[this] val referenceQueue = new ReferenceQueue[ClassLoader] + private val referenceQueue = new ReferenceQueue[ClassLoader] - private[this] def clearExpiredLoaders(): Unit = lock.synchronized { + private def clearExpiredLoaders(): Unit = lock.synchronized { val clear = (k: Key, ref: Reference[ClassLoader]) => { ref.get() match { case w: WrappedLoader => w.invalidate() @@ -98,7 +98,7 @@ private[sbt] class ClassLoaderCache( } delegate.forEach((k, v) => if (isInvalidated(k.parent)) clear(k, v)) } - private[this] class CleanupThread(private[this] val id: Int) + private class CleanupThread(private val id: Int) extends Thread(s"classloader-cache-cleanup-$id") { setDaemon(true) start() @@ -149,15 +149,15 @@ private[sbt] class ClassLoaderCache( * fairly uncommon for sbt to run out of file descriptors. * */ - private[this] val metaspaceIsLimited = + private val metaspaceIsLimited = ManagementFactory.getMemoryPoolMXBeans.asScala .exists(b => (b.getName == "Metaspace") && (b.getUsage.getMax > 0)) - private[this] val mkReference: (Key, ClassLoader) => Reference[ClassLoader] = + private val mkReference: (Key, ClassLoader) => Reference[ClassLoader] = if (metaspaceIsLimited) { (_, cl) => (new SoftReference[ClassLoader](cl, referenceQueue): Reference[ClassLoader]) } else ClassLoaderReference.apply - private[this] val cleanupThread = new CleanupThread(ClassLoaderCache.threadID.getAndIncrement()) - private[this] val lock = new Object + private val cleanupThread = new CleanupThread(ClassLoaderCache.threadID.getAndIncrement()) + private val lock = new Object private def close(classLoader: ClassLoader): Unit = classLoader match { case a: AutoCloseable => a.close() @@ -197,7 +197,7 @@ private[sbt] class ClassLoaderCache( val key = new Key(files) get(key, mkLoader) } - private[this] def get(key: Key, f: () => ClassLoader): ClassLoader = { + private def get(key: Key, f: () => ClassLoader): ClassLoader = { scalaProviderKey match { case Some(k) if k == key => k.toClassLoader case _ => diff --git a/main-command/src/main/scala/sbt/internal/client/NetworkClient.scala b/main-command/src/main/scala/sbt/internal/client/NetworkClient.scala index 806a47f15..5fdf0f9cc 100644 --- a/main-command/src/main/scala/sbt/internal/client/NetworkClient.scala +++ b/main-command/src/main/scala/sbt/internal/client/NetworkClient.scala @@ -152,14 +152,14 @@ class NetworkClient( } } - private[this] val stdinBytes = new LinkedBlockingQueue[Integer] - private[this] val inLock = new Object - private[this] val inputThread = new AtomicReference[RawInputThread] - private[this] val exitClean = new AtomicBoolean(true) - private[this] val sbtProcess = new AtomicReference[Process](null) + private val stdinBytes = new LinkedBlockingQueue[Integer] + private val inLock = new Object + private val inputThread = new AtomicReference[RawInputThread] + private val exitClean = new AtomicBoolean(true) + private val sbtProcess = new AtomicReference[Process](null) private class ConnectionRefusedException(t: Throwable) extends Throwable(t) private class ServerFailedException extends Exception - private[this] def startInputThread(): Unit = inputThread.get match { + private def startInputThread(): Unit = inputThread.get match { case null => inputThread.set(new RawInputThread) case _ => } @@ -769,16 +769,16 @@ class NetworkClient( } } - private[this] val contHandler: () => Unit = () => { + private val contHandler: () => Unit = () => { if (Terminal.console.getLastLine.nonEmpty) printStream.print(ConsoleAppender.DeleteLine + Terminal.console.getLastLine.get) } - private[this] def withSignalHandler[R](handler: () => Unit, sig: String)(f: => R): R = { + private def withSignalHandler[R](handler: () => Unit, sig: String)(f: => R): R = { val registration = Signals.register(handler, sig) try f finally registration.remove() } - private[this] val cancelled = new AtomicBoolean(false) + private val cancelled = new AtomicBoolean(false) def run(): Int = withSignalHandler(contHandler, Signals.CONT) { @@ -980,7 +980,7 @@ class NetworkClient( case t: Throwable => t.printStackTrace(); throw t } - private[this] class RawInputThread extends Thread("sbt-read-input-thread") with AutoCloseable { + private class RawInputThread extends Thread("sbt-read-input-thread") with AutoCloseable { setDaemon(true) start() val stopped = new AtomicBoolean(false) diff --git a/main-command/src/main/scala/sbt/internal/server/Server.scala b/main-command/src/main/scala/sbt/internal/server/Server.scala index 4edcf3d9f..2e8390c0e 100644 --- a/main-command/src/main/scala/sbt/internal/server/Server.scala +++ b/main-command/src/main/scala/sbt/internal/server/Server.scala @@ -54,9 +54,9 @@ private[sbt] object Server { val running = new AtomicBoolean(false) val p: Promise[Unit] = Promise[Unit]() val ready: Future[Unit] = p.future - private[this] val rand = new SecureRandom - private[this] var token: String = nextToken - private[this] val serverSocketHolder = new AtomicReference[ServerSocket] + private val rand = new SecureRandom + private var token: String = nextToken + private val serverSocketHolder = new AtomicReference[ServerSocket] val serverThread = new Thread("sbt-socket-server") { override def run(): Unit = { @@ -154,7 +154,7 @@ private[sbt] object Server { } /** Generates 128-bit non-negative integer, and represent it as decimal string. */ - private[this] def nextToken: String = { + private def nextToken: String = { new BigInteger(128, rand).toString } @@ -173,7 +173,7 @@ private[sbt] object Server { } } - private[this] def writeTokenfile(): Unit = { + private def writeTokenfile(): Unit = { import JsonProtocol._ val uri = connection.shortName @@ -189,7 +189,7 @@ private[sbt] object Server { } /** Set the permission of the file such that the only the owner can read/write it. */ - private[this] def ownerOnly(file: File): Unit = { + private def ownerOnly(file: File): Unit = { def acl(owner: UserPrincipal) = { val builder = AclEntry.newBuilder builder.setPrincipal(owner) @@ -208,7 +208,7 @@ private[sbt] object Server { } // This file exists through the lifetime of the server. - private[this] def writePortfile(): Unit = { + private def writePortfile(): Unit = { import JsonProtocol._ val uri = connection.shortName diff --git a/main-command/src/main/scala/sbt/internal/ui/UITask.scala b/main-command/src/main/scala/sbt/internal/ui/UITask.scala index 883cab252..bab58fa5a 100644 --- a/main-command/src/main/scala/sbt/internal/ui/UITask.scala +++ b/main-command/src/main/scala/sbt/internal/ui/UITask.scala @@ -25,11 +25,11 @@ import scala.annotation.tailrec private[sbt] trait UITask extends Runnable with AutoCloseable { private[sbt] val channel: CommandChannel private[sbt] def reader: UITask.Reader - private[this] final def handleInput(s: Either[String, String]): Boolean = s match { + private final def handleInput(s: Either[String, String]): Boolean = s match { case Left(m) => channel.onFastTrackTask(m) case Right(cmd) => channel.onCommand(cmd) } - private[this] val isStopped = new AtomicBoolean(false) + private val isStopped = new AtomicBoolean(false) override def run(): Unit = { @tailrec def impl(): Unit = if (!isStopped.get) { val res = reader.readLine() @@ -94,7 +94,7 @@ private[sbt] object UITask { override def close(): Unit = closed.set(true) } } - private[this] def history(s: State): Option[File] = + private def history(s: State): Option[File] = s.get(historyPath).getOrElse(Some(new File(s.baseDir, ".history"))) private[sbt] def shellPrompt(terminal: Terminal, s: State): String = s.get(sbt.BasicKeys.shellPrompt) match { diff --git a/main-command/src/main/scala/sbt/internal/ui/UserThread.scala b/main-command/src/main/scala/sbt/internal/ui/UserThread.scala index 4debe3d7d..1b9711fd9 100644 --- a/main-command/src/main/scala/sbt/internal/ui/UserThread.scala +++ b/main-command/src/main/scala/sbt/internal/ui/UserThread.scala @@ -19,15 +19,15 @@ import sbt.internal.util.JoinThread._ import sbt.internal.util.{ ConsoleAppender, ProgressEvent, ProgressState, Prompt } private[sbt] class UserThread(val channel: CommandChannel) extends AutoCloseable { - private[this] val uiThread = new AtomicReference[(UITask, Thread)] + private val uiThread = new AtomicReference[(UITask, Thread)] private[sbt] final def onProgressEvent(pe: ProgressEvent): Unit = { lastProgressEvent.set(pe) ProgressState.updateProgressState(pe, channel.terminal) } - private[this] val executor = + private val executor = Executors.newSingleThreadExecutor(r => new Thread(r, s"sbt-$name-ui-thread")) - private[this] val lastProgressEvent = new AtomicReference[ProgressEvent] - private[this] val isClosed = new AtomicBoolean(false) + private val lastProgressEvent = new AtomicReference[ProgressEvent] + private val isClosed = new AtomicBoolean(false) private[sbt] def reset(state: State): Unit = if (!isClosed.get) { uiThread.synchronized { diff --git a/main-settings/src/main/scala/sbt/Def.scala b/main-settings/src/main/scala/sbt/Def.scala index 608e82e3e..e9a19c34d 100644 --- a/main-settings/src/main/scala/sbt/Def.scala +++ b/main-settings/src/main/scala/sbt/Def.scala @@ -229,9 +229,9 @@ object Def extends BuildSyntax with Init[Scope] with InitializeImplicits: else if (s1 == GlobalScope) Some(s2) // s2 is more specific else super.intersect(s1, s2) - private[this] def definedSettingString(s: Setting[_]): String = + private def definedSettingString(s: Setting[_]): String = s"derived setting ${s.key.key.label}${positionString(s)}" - private[this] def positionString(s: Setting[_]): String = + private def positionString(s: Setting[_]): String = s.positionString match { case None => ""; case Some(pos) => s" defined at $pos" } /** diff --git a/main-settings/src/main/scala/sbt/InputTask.scala b/main-settings/src/main/scala/sbt/InputTask.scala index 9009d6e64..117c0a3c0 100644 --- a/main-settings/src/main/scala/sbt/InputTask.scala +++ b/main-settings/src/main/scala/sbt/InputTask.scala @@ -137,10 +137,10 @@ object InputTask: * The affected InputTask construction methods are all deprecated and so it is better to keep complete * compatibility. Because the AttributeKey is local, it uses object equality and the manifest is not used. */ - private[this] def localKey[T]: AttributeKey[T] = + private def localKey[T]: AttributeKey[T] = AttributeKey.local[Unit].asInstanceOf[AttributeKey[T]] - private[this] def subResultForDummy[I](dummyKey: AttributeKey[Task[I]], dummyTask: Task[I]) = + private def subResultForDummy[I](dummyKey: AttributeKey[Task[I]], dummyTask: Task[I]) = new (ScopedKey ~> Option) { def apply[T](sk: ScopedKey[T]) = if (sk.key eq dummyKey) { @@ -151,7 +151,7 @@ object InputTask: None } - private[this] def dummyTask[I]: (AttributeKey[Option[I]], Task[I]) = { + private def dummyTask[I]: (AttributeKey[Option[I]], Task[I]) = { val key = localKey[Option[I]] val f: () => I = () => sys.error(s"Internal sbt error: InputTask stub was not substituted properly.") @@ -159,7 +159,7 @@ object InputTask: (key, t) } - private[this] def subForDummy[I, T]( + private def subForDummy[I, T]( marker: AttributeKey[Option[I]], value: I, task: Task[T] diff --git a/main-settings/src/main/scala/sbt/Plugins.scala b/main-settings/src/main/scala/sbt/Plugins.scala index c814282aa..6fe00406e 100644 --- a/main-settings/src/main/scala/sbt/Plugins.scala +++ b/main-settings/src/main/scala/sbt/Plugins.scala @@ -274,10 +274,10 @@ object Plugins extends PluginsFunctions { s"Cycles in plugin requirements cannot involve excludes. The problematic cycle is: ${literalsString(cn.cycle)}" } - private[this] def literalsString(lits: Seq[Literal]): String = + private def literalsString(lits: Seq[Literal]): String = lits map { case Atom(l) => l; case Negated(Atom(l)) => l } mkString (", ") - private[this] def duplicateProvidesError(byAtom: Seq[(Atom, AutoPlugin)]): Unit = { + private def duplicateProvidesError(byAtom: Seq[(Atom, AutoPlugin)]): Unit = { val dupsByAtom = Map(byAtom.groupBy(_._1).toSeq.map { case (k, v) => k -> v.map(_._2) }: _*) @@ -289,7 +289,7 @@ object Plugins extends PluginsFunctions { throw AutoPluginException(message) } - private[this] def exclusionConflictError( + private def exclusionConflictError( requested: Plugins, selected: Seq[AutoPlugin], conflicting: Seq[AutoPlugin] @@ -390,7 +390,7 @@ ${listConflicts(conflicting)}""") case _: Basic => false case Empty => false } - private[this] def flattenConvert(n: Plugins): Seq[Literal] = n match { + private def flattenConvert(n: Plugins): Seq[Literal] = n match { case And(ns) => convertAll(ns) case b: Basic => convertBasic(b) :: Nil case Empty => Nil @@ -401,16 +401,16 @@ ${listConflicts(conflicting)}""") case Empty => Nil } - private[this] def convert(n: Plugins): Formula = n match { + private def convert(n: Plugins): Formula = n match { case And(ns) => convertAll(ns).reduce[Formula](_ && _) case b: Basic => convertBasic(b) case Empty => Formula.True } - private[this] def convertBasic(b: Basic): Literal = b match { + private def convertBasic(b: Basic): Literal = b match { case Exclude(n) => !convertBasic(n) case a: AutoPlugin => Atom(a.label) } - private[this] def convertAll(ns: Seq[Basic]): Seq[Literal] = ns map convertBasic + private def convertAll(ns: Seq[Basic]): Seq[Literal] = ns map convertBasic /** True if the trigger clause `n` is satisfied by `model`. */ def satisfied(n: Plugins, model: Set[AutoPlugin]): Boolean = @@ -453,7 +453,7 @@ ${listConflicts(conflicting)}""") } /** Debugging method to time how long it takes to run various compilation tasks. */ - private[this] def timed[T](label: String, log: Logger)(t: => T): T = { + private def timed[T](label: String, log: Logger)(t: => T): T = { val start = System.nanoTime val result = t val elapsed = System.nanoTime - start diff --git a/main-settings/src/main/scala/sbt/Previous.scala b/main-settings/src/main/scala/sbt/Previous.scala index b0c41dca5..782ec74ff 100644 --- a/main-settings/src/main/scala/sbt/Previous.scala +++ b/main-settings/src/main/scala/sbt/Previous.scala @@ -24,14 +24,14 @@ import scala.util.control.NonFatal * `referenced` provides the `Format` to use for each key. */ private[sbt] final class Previous(streams: Streams, referenced: IMap[Previous.Key, Referenced]) { - private[this] var map = IMap.empty[Previous.Key, ReferencedValue] + private var map = IMap.empty[Previous.Key, ReferencedValue] // We can't use mapValues to transform the map because mapValues is lazy and evaluates the // transformation function every time a value is fetched from the map, defeating the entire // purpose of ReferencedValue. for case referenced.TPair(k, v) <- referenced.toTypedSeq do map = map.put(k, new ReferencedValue(v)) - private[this] final class ReferencedValue[T](referenced: Referenced[T]) { + private final class ReferencedValue[T](referenced: Referenced[T]) { lazy val previousValue: Option[T] = referenced.read(streams) } @@ -100,7 +100,7 @@ object Previous { /** Records references to previous task value. This should be completely populated after settings finish loading. */ private[sbt] final class References { - private[this] var map = IMap.empty[Key, Referenced] + private var map = IMap.empty[Key, Referenced] @deprecated("unused", "1.3.0") def recordReference[T](key: ScopedKey[Task[T]], format: JsonFormat[T]): Unit = diff --git a/main-settings/src/main/scala/sbt/Project.scala b/main-settings/src/main/scala/sbt/Project.scala index 372b29df3..54203f419 100644 --- a/main-settings/src/main/scala/sbt/Project.scala +++ b/main-settings/src/main/scala/sbt/Project.scala @@ -84,7 +84,7 @@ sealed trait ProjectDefinition[PR <: ProjectReference] { s"Project(${fields.mkString(", ")})" } - private[this] def ifNonEmpty[T](label: String, ts: Iterable[T]): List[String] = + private def ifNonEmpty[T](label: String, ts: Iterable[T]): List[String] = if (ts.isEmpty) Nil else s"$label: $ts" :: Nil } @@ -325,7 +325,7 @@ object Project: def validProjectID(id: String): Option[String] = DefaultParsers.parse(id, DefaultParsers.ID).left.toOption - private[this] def validProjectIDStart(id: String): Boolean = + private def validProjectIDStart(id: String): Boolean = DefaultParsers.parse(id, DefaultParsers.IDStart).isRight def fillTaskAxis(scoped: ScopedKey[_]): ScopedKey[_] = @@ -381,7 +381,7 @@ object Project: validProjectID(refined).toLeft(refined) } - private[this] def normalizeBase(s: String) = + private def normalizeBase(s: String) = s.toLowerCase(Locale.ENGLISH).replaceAll("""\W+""", "-") private[sbt] enum LoadAction: diff --git a/main-settings/src/main/scala/sbt/Scope.scala b/main-settings/src/main/scala/sbt/Scope.scala index 0f29f16f5..7ffa65779 100644 --- a/main-settings/src/main/scala/sbt/Scope.scala +++ b/main-settings/src/main/scala/sbt/Scope.scala @@ -395,7 +395,7 @@ object Scope: .toMap new DelegateIndex0(pDelegates) } - private[this] def delegateIndex(ref: ProjectRef, confs: Seq[ConfigKey])( + private def delegateIndex(ref: ProjectRef, confs: Seq[ConfigKey])( projectInherit: ProjectRef => Seq[ProjectRef], configInherit: (ResolvedReference, ConfigKey) => Seq[ConfigKey] ): ProjectDelegates = { diff --git a/main-settings/src/main/scala/sbt/Structure.scala b/main-settings/src/main/scala/sbt/Structure.scala index 3d52545db..78f5c995c 100644 --- a/main-settings/src/main/scala/sbt/Structure.scala +++ b/main-settings/src/main/scala/sbt/Structure.scala @@ -123,7 +123,7 @@ sealed abstract class SettingKey[A1] inline def make[A2](other: Initialize[A2])(f: (A1, A2) => A1): Setting[A1] = set(this.zipWith(other)(f)) - protected[this] inline def make[A2](other: Initialize[A2], source: SourcePosition)( + protected inline def make[A2](other: Initialize[A2], source: SourcePosition)( f: (A1, A2) => A1 ): Setting[A1] = set0(this.zipWith(other)(f), source) @@ -371,7 +371,7 @@ object Scoped: nonLocal(tasks.toSeq.asInstanceOf[Seq[AnyInitTask]], Def.triggeredBy) def runBefore[A2](tasks: Initialize[Task[A2]]*): Initialize[Task[A1]] = nonLocal(tasks.toSeq.asInstanceOf[Seq[AnyInitTask]], Def.runBefore) - private[this] def nonLocal( + private def nonLocal( tasks: Seq[AnyInitTask], key: AttributeKey[Seq[Task[_]]] ): Initialize[Task[A1]] = @@ -504,10 +504,10 @@ object Scoped: private def convert[Ret](f: Fun[Id, Ret]): Tup => Ret = convertK(f).asInstanceOf - private[this] val inputs: Tuple.Map[Tup, App] = + private val inputs: Tuple.Map[Tup, App] = keys.transform { [A] => (fa: Taskable[A]) => fa.toTask } - private[this] def onTasks[A1](f: Tuple.Map[Tup, Task] => Task[A1]): App[A1] = + private def onTasks[A1](f: Tuple.Map[Tup, Task] => Task[A1]): App[A1] = Def.app[Tuple.Map[Tup, Task], Task[A1]](inputs.asInstanceOf)(f) def flatMapN[T](f: Fun[Id, Task[T]]): App[T] = onTasks(_.flatMapN(convert(f))) diff --git a/main-settings/src/main/scala/sbt/std/InputTaskMacro.scala b/main-settings/src/main/scala/sbt/std/InputTaskMacro.scala index 08ee3f126..66dfb382d 100644 --- a/main-settings/src/main/scala/sbt/std/InputTaskMacro.scala +++ b/main-settings/src/main/scala/sbt/std/InputTaskMacro.scala @@ -23,7 +23,7 @@ object InputTaskMacro: // def inputTaskDynMacroImpl[A1: Type](t: c.Expr[Initialize[Task[A1]]])(using qctx: Quotes): c.Expr[Initialize[InputTask[A1]]] = // inputTaskDynMacro0[A1](c)(t) - private[this] def inputTaskMacro0[A1: Type](tree: Expr[A1])(using + private def inputTaskMacro0[A1: Type](tree: Expr[A1])(using qctx: Quotes ): Expr[Def.Initialize[InputTask[A1]]] = // println(s"tree = ${tree.show}") @@ -36,7 +36,7 @@ object InputTaskMacro: '{ InputTask.make($pt) } } - private[this] def iInitializeMacro[F1[_]: Type, A1: Type](tree: Expr[A1])( + private def iInitializeMacro[F1[_]: Type, A1: Type](tree: Expr[A1])( f: Expr[A1] => Expr[F1[A1]] )(using qctx: Quotes): Expr[Def.Initialize[F1[A1]]] = import qctx.reflect.* @@ -99,7 +99,7 @@ object InputTaskMacro: val cond = conditionInputTaskTree(tree.asTerm).asExprOf[A1] convert1.contMapN[A1, Def.Initialize, F1](cond, convert1.appExpr, None, inner) - private[this] def iParserMacro[F1[_]: Type, A1: Type](tree: Expr[A1])( + private def iParserMacro[F1[_]: Type, A1: Type](tree: Expr[A1])( f: Expr[A1] => Expr[F1[A1]] )(using qctx: Quotes): Expr[State => Parser[F1[A1]]] = import qctx.reflect.* @@ -107,11 +107,11 @@ object InputTaskMacro: val inner: convert1.TermTransform[F1] = (in: Term) => f(in.asExprOf[A1]).asTerm convert1.contMapN[A1, ParserInstance.F1, F1](tree, convert1.appExpr, None, inner) - private[this] def iTaskMacro[A1: Type](tree: Expr[A1])(using qctx: Quotes): Expr[Task[A1]] = + private def iTaskMacro[A1: Type](tree: Expr[A1])(using qctx: Quotes): Expr[Task[A1]] = val convert1 = new TaskConvert(qctx, 2000) convert1.contMapN[A1, Task, Id](tree, convert1.appExpr, None) /* - private[this] def inputTaskDynMacro0[A1: Type]( + private def inputTaskDynMacro0[A1: Type]( expr: Expr[Def.Initialize[Task[A1]]] )(using qctx: Quotes): Expr[Def.Initialize[InputTask[A1]]] = { import qctx.reflect.{ Apply => ApplyTree, * } diff --git a/main-settings/src/main/scala/sbt/std/InputWrapper.scala b/main-settings/src/main/scala/sbt/std/InputWrapper.scala index 6e7a86758..f1a7c9e0a 100644 --- a/main-settings/src/main/scala/sbt/std/InputWrapper.scala +++ b/main-settings/src/main/scala/sbt/std/InputWrapper.scala @@ -68,7 +68,7 @@ object InputWrapper: ) def `wrapPrevious_\u2603\u2603`[T](@deprecated("unused", "") in: Any): T = implDetailError - private[this] def implDetailError = + private def implDetailError = sys.error("This method is an implementation detail and should not be referenced.") /* diff --git a/main-settings/src/main/scala/sbt/std/Instances.scala b/main-settings/src/main/scala/sbt/std/Instances.scala index e9f5cae3e..6a57ec725 100644 --- a/main-settings/src/main/scala/sbt/std/Instances.scala +++ b/main-settings/src/main/scala/sbt/std/Instances.scala @@ -30,7 +30,7 @@ end InitializeInstance object ParserInstance: type F1[x] = State => Parser[x] // import sbt.internal.util.Classes.Applicative - // private[this] implicit val parserApplicative: Applicative[M] = new Applicative[M] { + // private implicit val parserApplicative: Applicative[M] = new Applicative[M] { // def apply[S, T](f: M[S => T], v: M[S]): M[A1] = s => (f(s) ~ v(s)) map { case (a, b) => a(b) } // def pure[S](s: => S) = const(Parser.success(s)) // def map[S, T](f: S => T, v: M[S]) = s => v(s).map(f) diff --git a/main-settings/src/main/scala/sbt/std/TaskMacro.scala b/main-settings/src/main/scala/sbt/std/TaskMacro.scala index 08278bacf..4643030fc 100644 --- a/main-settings/src/main/scala/sbt/std/TaskMacro.scala +++ b/main-settings/src/main/scala/sbt/std/TaskMacro.scala @@ -168,7 +168,7 @@ object TaskMacro: report.errorAndAbort(s"Append.Value[${Type.show[A1]}, ${Type.show[A2]}] missing") /* - private[this] def transformMacroImpl[A](using qctx: Quotes)(init: Expr[A])( + private def transformMacroImpl[A](using qctx: Quotes)(init: Expr[A])( newName: String ): qctx.reflect.Term = { import qctx.reflect.* @@ -194,7 +194,7 @@ object TaskMacro: else '{ NoPosition } /* - private[this] def settingSource(c: blackbox.Context, path: String, name: String): String = { + private def settingSource(c: blackbox.Context, path: String, name: String): String = { @tailrec def inEmptyPackage(s: c.Symbol): Boolean = s != c.universe.NoSymbol && ( s.owner == c.mirror.EmptyPackage || s.owner == c.mirror.EmptyPackageClass || inEmptyPackage( s.owner @@ -207,7 +207,7 @@ object TaskMacro: } } - private[this] def constant[A1: c.TypeTag](c: blackbox.Context, t: T): c.Expr[A1] = { + private def constant[A1: c.TypeTag](c: blackbox.Context, t: T): c.Expr[A1] = { import c.universe._ c.Expr[A1](Literal(Constant(t))) } diff --git a/main-settings/src/test/scala/sbt/std/TaskConfigSpec.scala b/main-settings/src/test/scala/sbt/std/TaskConfigSpec.scala index 09c311a2b..c39e4db57 100644 --- a/main-settings/src/test/scala/sbt/std/TaskConfigSpec.scala +++ b/main-settings/src/test/scala/sbt/std/TaskConfigSpec.scala @@ -30,9 +30,9 @@ class TaskConfigSpec extends funsuite.FixtureAnyFunSuite with fixture.TestDataFi assert(errorMessage.contains(errorSnippet), userMessage) } private class CachingToolbox(implicit td: TestData) { - private[this] val m = scala.reflect.runtime.currentMirror - private[this] var _infos: List[FrontEnd#Info] = Nil - private[this] val frontEnd = new FrontEnd { + private val m = scala.reflect.runtime.currentMirror + private var _infos: List[FrontEnd#Info] = Nil + private val frontEnd = new FrontEnd { override def display(info: Info): Unit = _infos ::= info def interactive(): Unit = {} } diff --git a/main/src/main/scala/sbt/BuildPaths.scala b/main/src/main/scala/sbt/BuildPaths.scala index e6a97985b..bcef8cee8 100644 --- a/main/src/main/scala/sbt/BuildPaths.scala +++ b/main/src/main/scala/sbt/BuildPaths.scala @@ -68,7 +68,7 @@ object BuildPaths { def getZincDirectory(state: State, globalBase: File): File = fileSetting(globalZincDirectory, GlobalZincProperty, defaultGlobalZinc(globalBase))(state) - private[this] def fileSetting(stateKey: AttributeKey[File], property: String, default: File)( + private def fileSetting(stateKey: AttributeKey[File], property: String, default: File)( state: State ): File = getFileSetting(stateKey, property, default)(state) @@ -108,13 +108,13 @@ object BuildPaths { def defaultVersionedGlobalBase(sbtVersion: String): File = defaultGlobalBase / sbtVersion def defaultGlobalBase = Path.userHome / ConfigDirectoryName - private[this] def binarySbtVersion(state: State): String = + private def binarySbtVersion(state: State): String = sbt.internal.librarymanagement.cross.CrossVersionUtil .binarySbtVersion(state.configuration.provider.id.version) - private[this] def defaultStaging(globalBase: File) = globalBase / "staging" - private[this] def defaultGlobalPlugins(globalBase: File) = globalBase / PluginsDirectoryName - private[this] def defaultDependencyBase(globalBase: File) = globalBase / "dependency" - private[this] def defaultGlobalZinc(globalBase: File) = globalBase / "zinc" + private def defaultStaging(globalBase: File) = globalBase / "staging" + private def defaultGlobalPlugins(globalBase: File) = globalBase / PluginsDirectoryName + private def defaultDependencyBase(globalBase: File) = globalBase / "dependency" + private def defaultGlobalZinc(globalBase: File) = globalBase / "zinc" def configurationSources(base: File): Seq[File] = (base * (GlobFilter("*.sbt") - ".sbt")) diff --git a/main/src/main/scala/sbt/Defaults.scala b/main/src/main/scala/sbt/Defaults.scala index 104778c41..5e0c9eba6 100644 --- a/main/src/main/scala/sbt/Defaults.scala +++ b/main/src/main/scala/sbt/Defaults.scala @@ -739,7 +739,7 @@ object Defaults extends BuildCommon { console / classpathOptions := ClasspathOptionsUtil.replNoboot(scalaVersion.value), ) // must be a val: duplication detected by object identity - private[this] lazy val compileBaseGlobal: Seq[Setting[_]] = globalDefaults( + private lazy val compileBaseGlobal: Seq[Setting[_]] = globalDefaults( Seq( auxiliaryClassFiles :== Nil, incOptions := IncOptions.of(), @@ -1059,7 +1059,7 @@ object Defaults extends BuildCommon { mainBgRunTaskForConfig(This) ) ++ inTask(run)(runnerSettings ++ newRunnerSettings) ++ compileIncrementalTaskSettings - private[this] lazy val configGlobal = globalDefaults( + private lazy val configGlobal = globalDefaults( Seq( initialCommands :== "", cleanupCommands :== "", @@ -1173,7 +1173,7 @@ object Defaults extends BuildCommon { else Def.task(None) } - private[this] def noToolConfiguration(autoInstance: Boolean): String = { + private def noToolConfiguration(autoInstance: Boolean): String = { val pre = "Missing Scala tool configuration from the 'update' report. " val post = if (autoInstance) @@ -1308,7 +1308,7 @@ object Defaults extends BuildCommon { ) } - private[this] def testDefaults = + private def testDefaults = Defaults.globalDefaults( Seq( testFrameworks :== sbt.TestFrameworks.All, @@ -1449,7 +1449,7 @@ object Defaults extends BuildCommon { ) ) - private[this] def closeableTestLogger(manager: Streams, baseKey: Scoped, buffered: Boolean)( + private def closeableTestLogger(manager: Streams, baseKey: Scoped, buffered: Boolean)( tdef: TestDefinition ): TestLogger.PerTest = { val scope = baseKey.scope @@ -1510,7 +1510,7 @@ object Defaults extends BuildCommon { def inputTests(key: InputKey[_]): Initialize[InputTask[Unit]] = inputTests0.mapReferenced(Def.mapScope((s) => s.rescope(key.key))) - private[this] lazy val inputTests0: Initialize[InputTask[Unit]] = { + private lazy val inputTests0: Initialize[InputTask[Unit]] = { val parser = loadForParser(definedTestNames)((s, i) => testOnlyParser(s, i getOrElse Nil)) ParserGen(parser).flatMapTask { case ((selected, frameworkOptions)) => val s = streams.value @@ -2050,7 +2050,7 @@ object Defaults extends BuildCommon { /** Implements `cleanFiles` task. */ private[sbt] def cleanFilesTask: Initialize[Task[Vector[File]]] = Def.task { Vector.empty[File] } - private[this] def termWrapper(canonical: Boolean, echo: Boolean): (() => Unit) => (() => Unit) = + private def termWrapper(canonical: Boolean, echo: Boolean): (() => Unit) => (() => Unit) = (f: () => Unit) => () => { val term = ITerminal.get @@ -2352,7 +2352,7 @@ object Defaults extends BuildCommon { def mainBgRunTask = mainBgRunTaskForConfig(Select(Runtime)) def mainBgRunMainTask = mainBgRunMainTaskForConfig(Select(Runtime)) - private[this] def mainBgRunTaskForConfig(c: ScopeAxis[ConfigKey]) = + private def mainBgRunTaskForConfig(c: ScopeAxis[ConfigKey]) = bgRun := bgRunTask( exportedProductJars, This / c / This / fullClasspathAsJars, @@ -2361,7 +2361,7 @@ object Defaults extends BuildCommon { run / runner ).evaluated - private[this] def mainBgRunMainTaskForConfig(c: ScopeAxis[ConfigKey]) = + private def mainBgRunMainTaskForConfig(c: ScopeAxis[ConfigKey]) = bgRunMain := bgRunMainTask( exportedProductJars, This / c / This / fullClasspathAsJars, @@ -2403,10 +2403,10 @@ object Defaults extends BuildCommon { println() } - private[this] def exported(w: PrintWriter, command: String): Seq[String] => Unit = + private def exported(w: PrintWriter, command: String): Seq[String] => Unit = args => w.println((command +: args).mkString(" ")) - private[this] def exported(s: TaskStreams, command: String): Seq[String] => Unit = { + private def exported(s: TaskStreams, command: String): Seq[String] => Unit = { val w = s.text(ExportStream) try exported(w, command) finally w.close() // workaround for #937 @@ -2547,7 +2547,7 @@ object Defaults extends BuildCommon { } } - private[this] def compileIncrementalTaskImpl( + private def compileIncrementalTaskImpl( task: BspCompileTask, s: TaskStreams, ci: Inputs, @@ -2817,7 +2817,7 @@ object Defaults extends BuildCommon { // 1. runnerSettings is added unscoped via JvmPlugin. // 2. In addition it's added scoped to run task. lazy val runnerSettings: Seq[Setting[_]] = Seq(runnerTask, forkOptions := forkOptionsTask.value) - private[this] lazy val newRunnerSettings: Seq[Setting[_]] = + private lazy val newRunnerSettings: Seq[Setting[_]] = Seq(runner := ClassLoaders.runner.value, forkOptions := forkOptionsTask.value) lazy val baseTasks: Seq[Setting[_]] = projectTasks ++ packageBase @@ -2936,7 +2936,7 @@ object Classpaths { update.value ) ) - private[this] def classpaths: Seq[Setting[_]] = + private def classpaths: Seq[Setting[_]] = Seq( externalDependencyClasspath := concat(unmanagedClasspath, managedClasspath).value, dependencyClasspath := concat(internalDependencyClasspath, externalDependencyClasspath).value, @@ -3025,20 +3025,20 @@ object Classpaths { internalDependencyPicklePath := ClasspathImpl.internalDependencyPicklePathTask.value, exportedPickles := ClasspathImpl.exportedPicklesTask.value, ) - private[this] def exportVirtualClasspath( + private def exportVirtualClasspath( s: Setting[Task[Classpath]] ): Setting[Task[Classpath]] = s.mapInitialize(init => Def.task { exportVirtualClasspath(streams.value, init.value) }) - private[this] def exportClasspath( + private def exportClasspath( s: Setting[Task[Seq[Attributed[File]]]] ): Setting[Task[Seq[Attributed[File]]]] = s.mapInitialize(init => Def.task { exportClasspath(streams.value, init.value) }) - private[this] def exportVirtualClasspath(s: TaskStreams, cp: Classpath): Classpath = + private def exportVirtualClasspath(s: TaskStreams, cp: Classpath): Classpath = val w = s.text(ExportStream) try w.println(data(cp).toString) finally w.close() // workaround for #937 cp - private[this] def exportClasspath( + private def exportClasspath( s: TaskStreams, cp: Seq[Attributed[File]] ): Seq[Attributed[File]] = @@ -3094,7 +3094,7 @@ object Classpaths { ): Initialize[Seq[T]] = pkgTasks.map(pkg => (pkg.scope / pkg / key)).join - private[this] def publishGlobalDefaults = + private def publishGlobalDefaults = Defaults.globalDefaults( Seq( publishMavenStyle :== true, @@ -3220,7 +3220,7 @@ object Classpaths { publishM2 := publishOrSkip(publishM2Configuration, publishM2 / skip).value ) - private[this] def baseGlobalDefaults = + private def baseGlobalDefaults = Defaults.globalDefaults( Seq( conflictWarning :== ConflictWarning.default("global"), @@ -3785,7 +3785,7 @@ object Classpaths { .withConflictManager(conflictManager.value) } - private[this] def sbtClassifiersGlobalDefaults = + private def sbtClassifiersGlobalDefaults = Defaults.globalDefaults( Seq( (updateSbtClassifiers / transitiveClassifiers) ~= (_.filter(_ != DocClassifier)) @@ -4594,7 +4594,7 @@ object Classpaths { val plugins = compilerPlugins(pluginClasspath, isDotty) plugins.map("-Xplugin:" + _.toAbsolutePath.toString).toSeq - private[this] lazy val internalCompilerPluginClasspath: Initialize[Task[Classpath]] = + private lazy val internalCompilerPluginClasspath: Initialize[Task[Classpath]] = (Def .task { (thisProjectRef.value, settingsData.value, buildDependencies.value, streams.value) }) .flatMapTask { case (ref, data, deps, s) => @@ -4676,35 +4676,35 @@ object Classpaths { base / "target" / "coursier-temp" } - private[this] def mavenCompatible(ivyRepo: xsbti.IvyRepository): Boolean = + private def mavenCompatible(ivyRepo: xsbti.IvyRepository): Boolean = try { ivyRepo.mavenCompatible } catch { case _: NoSuchMethodError => false } - private[this] def skipConsistencyCheck(ivyRepo: xsbti.IvyRepository): Boolean = + private def skipConsistencyCheck(ivyRepo: xsbti.IvyRepository): Boolean = try { ivyRepo.skipConsistencyCheck } catch { case _: NoSuchMethodError => false } - private[this] def descriptorOptional(ivyRepo: xsbti.IvyRepository): Boolean = + private def descriptorOptional(ivyRepo: xsbti.IvyRepository): Boolean = try { ivyRepo.descriptorOptional } catch { case _: NoSuchMethodError => false } // for forward-compatibility with launcher.jar prior to 1.3.11 - private[this] def mavenRepoAllowInsecureProtocol(mavenRepo: xsbti.MavenRepository): Boolean = + private def mavenRepoAllowInsecureProtocol(mavenRepo: xsbti.MavenRepository): Boolean = try { mavenRepo.allowInsecureProtocol } catch { case _: NoSuchMethodError => false } // for forward-compatibility with launcher.jar prior to 1.3.11 - private[this] def allowInsecureProtocol(ivyRepo: xsbti.IvyRepository): Boolean = + private def allowInsecureProtocol(ivyRepo: xsbti.IvyRepository): Boolean = try { ivyRepo.allowInsecureProtocol } catch { case _: NoSuchMethodError => false } @nowarn - private[this] def bootRepository(repo: xsbti.Repository): Resolver = { + private def bootRepository(repo: xsbti.Repository): Resolver = { import xsbti.Predefined repo match { case m: xsbti.MavenRepository => @@ -4970,7 +4970,7 @@ trait BuildExtra extends BuildCommon with DefExtra { } trait DefExtra { - private[this] val ts: TaskSequential = new TaskSequential {} + private val ts: TaskSequential = new TaskSequential {} implicit def toTaskSequential(@deprecated("unused", "") d: Def.type): TaskSequential = ts } diff --git a/main/src/main/scala/sbt/EvaluateTask.scala b/main/src/main/scala/sbt/EvaluateTask.scala index fed53f3e6..bb9255160 100644 --- a/main/src/main/scala/sbt/EvaluateTask.scala +++ b/main/src/main/scala/sbt/EvaluateTask.scala @@ -133,7 +133,7 @@ object EvaluateTaskConfig { minForcegcInterval ) - private[this] case class DefaultEvaluateTaskConfig( + private case class DefaultEvaluateTaskConfig( restrictions: Seq[Tags.Rule], checkCycles: Boolean, progressReporter: ExecuteProgress, @@ -423,7 +423,7 @@ object EvaluateTask { } } - private[this] def contextDisplay(state: State, highlight: Boolean) = + private def contextDisplay(state: State, highlight: Boolean) = Project.showContextKey(state, if (highlight) Some(RED) else None) def suppressedMessage(key: ScopedKey[_])(implicit display: Show[ScopedKey[_]]): String = @@ -563,7 +563,7 @@ object EvaluateTask { } } - private[this] def storeValuesForPrevious( + private def storeValuesForPrevious( results: RMap[TaskId, Result], state: State, streams: Streams diff --git a/main/src/main/scala/sbt/Extracted.scala b/main/src/main/scala/sbt/Extracted.scala index 798b106dd..72dd0abb6 100644 --- a/main/src/main/scala/sbt/Extracted.scala +++ b/main/src/main/scala/sbt/Extracted.scala @@ -46,7 +46,7 @@ final case class Extracted( def getOpt[T](key: TaskKey[T]): Option[Task[T]] = structure.data.get(inCurrent(key.scope), key.key) - private[this] def inCurrent(scope: Scope): Scope = + private def inCurrent(scope: Scope): Scope = if scope.project == This then scope.rescope(currentRef) else scope @@ -113,7 +113,7 @@ final case class Extracted( show = Aggregation.defaultShow(state, false), ) - private[this] def resolve[K <: Scoped.ScopingSetting[K] with Scoped](key: K): K = + private def resolve[K <: Scoped.ScopingSetting[K] with Scoped](key: K): K = Scope.resolveScope(GlobalScope, currentRef.build, rootProject)(key.scope) / key private def getOrError[T](scope: Scope, key: AttributeKey[_], value: Option[T])(implicit @@ -144,7 +144,7 @@ final case class Extracted( def appendWithoutSession(settings: Seq[Setting[_]], state: State): State = appendImpl(settings, state, session.original) - private[this] def appendImpl( + private def appendImpl( settings: Seq[Setting[_]], state: State, sessionSettings: Seq[Setting[_]], diff --git a/main/src/main/scala/sbt/Main.scala b/main/src/main/scala/sbt/Main.scala index 31b1c49d5..488c2a7f0 100644 --- a/main/src/main/scala/sbt/Main.scala +++ b/main/src/main/scala/sbt/Main.scala @@ -213,19 +213,19 @@ object StandardMain { // The access to the pool should be thread safe because lazy val instantiation is thread safe // and pool is only referenced directly in closeRunnable after the executionContext is sure // to have been instantiated - private[this] var pool: Option[ForkJoinPool] = None + private var pool: Option[ForkJoinPool] = None private[sbt] lazy val executionContext: ExecutionContext = ExecutionContext.fromExecutor({ val p = new ForkJoinPool pool = Some(p) p }) - private[this] val closeRunnable = () => { + private val closeRunnable = () => { exchange.shutdown() pool.foreach(_.shutdownNow()) } - private[this] val isShutdown = new AtomicBoolean(false) + private val isShutdown = new AtomicBoolean(false) def runManaged(s: State): xsbti.MainResult = { val hook = ShutdownHooks.add(closeRunnable) try { @@ -245,7 +245,7 @@ object StandardMain { ConsoleOut.systemOutOverwrite(ConsoleOut.overwriteContaining("Resolving ")) ConsoleOut.setGlobalProxy(console) - private[this] def initialGlobalLogging(file: Option[File]): GlobalLogging = { + private def initialGlobalLogging(file: Option[File]): GlobalLogging = { def createTemp(attempt: Int = 0): File = Retry { file.foreach(f => if (!f.exists()) IO.createDirectory(f)) File.createTempFile("sbt-global-log", ".log", file.orNull) @@ -372,7 +372,7 @@ object BuiltinCommands { } def setLogLevel = Command.arb(const(logLevelParser), logLevelHelp)(LogManager.setGlobalLogLevel) - private[this] def logLevelParser: Parser[Level.Value] = + private def logLevelParser: Parser[Level.Value] = oneOf(Level.values.toSeq.map(v => v.toString ^^^ v)) // This parser schedules the default boot commands unless overridden by an alias @@ -437,13 +437,13 @@ object BuiltinCommands { |""".stripMargin.format(name, ver, about, name, name, scalaVer) } - private[this] def selectScalaVersion(sv: Option[String], si: ScalaInstance): String = + private def selectScalaVersion(sv: Option[String], si: ScalaInstance): String = sv match { case Some(si.version) => si.version case _ => si.actualVersion } - private[this] def quiet[T](t: => T): Option[T] = + private def quiet[T](t: => T): Option[T] = try Some(t) catch case _: Exception => None @@ -564,7 +564,7 @@ object BuiltinCommands { def continuous: Command = Continuous.continuous - private[this] def loadedEval(s: State, arg: String): Unit = { + private def loadedEval(s: State, arg: String): Unit = { val extracted = Project.extract(s) import extracted._ val result = @@ -572,7 +572,7 @@ object BuiltinCommands { s.log.info(s"ans: ${result.tpe} = ${result.getValue(currentLoader)}") } - private[this] def rawEval(s: State, arg: String): Unit = { + private def rawEval(s: State, arg: String): Unit = { val app = s.configuration.provider val classpath = app.mainClasspath ++ app.scalaProvider.jars val result = Load @@ -735,7 +735,7 @@ object BuiltinCommands { def exportCommand: Command = Command(ExportCommand, exportBrief, exportDetailed)(exportParser)((_, f) => f()) - private[this] def lastImpl(s: State, sks: AnyKeys, sid: Option[String]): State = { + private def lastImpl(s: State, sks: AnyKeys, sid: Option[String]): State = { val (str, _, display) = extractLast(s) Output.last(sks, str.streams(s), printLast, sid)(using display) keepLastLog(s) @@ -866,12 +866,12 @@ object BuiltinCommands { doLoadFailed(s, loadArg) } - private[this] def deprecationWarningText(oldCommand: String, newCommand: String) = { + private def deprecationWarningText(oldCommand: String, newCommand: String) = { s"The `$oldCommand` command is deprecated in favor of `$newCommand` and will be removed in a later version" } @tailrec - private[this] def doLoadFailed(s: State, loadArg: String): State = { + private def doLoadFailed(s: State, loadArg: String): State = { s.log.warn("Project loading failed: (r)etry, (q)uit, (l)ast, or (i)gnore? (default: r)") val result: Int = try @@ -907,10 +907,10 @@ object BuiltinCommands { loadProjectCommands(arg) ::: s ) - private[this] def loadProjectParser: State => Parser[String] = + private def loadProjectParser: State => Parser[String] = _ => matched(Project.loadActionParser) - private[this] def loadProjectCommand(command: String, arg: String): String = + private def loadProjectCommand(command: String, arg: String): String = s"$command $arg".trim def loadProjectImpl: Command = @@ -1189,7 +1189,7 @@ object BuiltinCommands { notifyUsersAboutShell(state); state } - private[this] def skipWelcomeFile(state: State, version: String) = { + private def skipWelcomeFile(state: State, version: String) = { val base = BuildPaths.getGlobalBase(state).toPath base.resolve("preferences").resolve(version).resolve(SkipBannerFileName) } @@ -1207,11 +1207,11 @@ object BuiltinCommands { state.put(bannerHasBeenShown, true) } else state } - private[this] val bannerHasBeenShown = + private val bannerHasBeenShown = AttributeKey[Boolean]("banner-has-been-shown", Int.MaxValue) - private[this] val SkipBannerFileName = "skip-banner" - private[this] val SkipBanner = "skipBanner" - private[this] def skipBanner: Command = Command.command(SkipBanner)(skipBanner) + private val SkipBannerFileName = "skip-banner" + private val SkipBanner = "skipBanner" + private def skipBanner: Command = Command.command(SkipBanner)(skipBanner) private def skipBanner(state: State): State = { val skipFile = skipWelcomeFile(state, sbtVersion(state)) try Files.createFile(skipFile) diff --git a/main/src/main/scala/sbt/MainLoop.scala b/main/src/main/scala/sbt/MainLoop.scala index fac42e605..12f6a5279 100644 --- a/main/src/main/scala/sbt/MainLoop.scala +++ b/main/src/main/scala/sbt/MainLoop.scala @@ -130,7 +130,7 @@ object MainLoop { } // /** Transfers logging and trace levels from the old global loggers to the new ones. */ - // private[this] def transferLevels(state: State, logging: GlobalLogging): Unit = { + // private def transferLevels(state: State, logging: GlobalLogging): Unit = { // val old = state.globalLogging // Logger.transferLevels(old.backed, logging.backed) // (old.full, logging.full) match { // well, this is a hack @@ -334,14 +334,14 @@ object MainLoop { def logFullException(e: Throwable, log: Logger): Unit = State.logFullException(e, log) - private[this] type ExitCode = Option[Long] - private[this] object ExitCode { + private type ExitCode = Option[Long] + private object ExitCode { def apply(n: Long): ExitCode = Option(n) val Success: ExitCode = ExitCode(0) val Unknown: ExitCode = None } - private[this] def exitCode(state: State, prevState: State): ExitCode = { + private def exitCode(state: State, prevState: State): ExitCode = { exitCodeFromStateNext(state) match { case ExitCode.Success => exitCodeFromStateOnFailure(state, prevState) case x => x @@ -350,7 +350,7 @@ object MainLoop { // State's "next" field indicates the next action for the command processor to take // we'll use that to determine if the command failed - private[this] def exitCodeFromStateNext(state: State): ExitCode = { + private def exitCodeFromStateNext(state: State): ExitCode = { state.next match { case State.Continue => ExitCode.Success case State.ClearGlobalLog => ExitCode.Success @@ -371,7 +371,7 @@ object MainLoop { // the shell command specifies an onFailure so that if an exception is thrown // it's handled by executing the shell again, instead of the state failing // so we also use that to indicate that the execution failed - private[this] def exitCodeFromStateOnFailure(state: State, prevState: State): ExitCode = + private def exitCodeFromStateOnFailure(state: State, prevState: State): ExitCode = if ( prevState.onFailure.isDefined && state.onFailure.isEmpty && state.currentCommand.fold(true)(_.commandLine != StashOnFailure) diff --git a/main/src/main/scala/sbt/ProjectExtra.scala b/main/src/main/scala/sbt/ProjectExtra.scala index 296eb5dc9..f8d62ec3e 100755 --- a/main/src/main/scala/sbt/ProjectExtra.scala +++ b/main/src/main/scala/sbt/ProjectExtra.scala @@ -73,7 +73,7 @@ sealed trait Project extends ProjectDefinition[ProjectReference] with CompositeP ): Project = copy2(id, base, aggregate, dependencies, settings, configurations) - private[this] def copy2( + private def copy2( id: String = id, base: File = base, aggregate: Seq[ProjectReference] = aggregate, @@ -515,7 +515,7 @@ trait ProjectExtra extends Scoped.Syntax: private[sbt] def showUses(defs: Seq[ScopedKey[_]])(using display: Show[ScopedKey[_]]): String = showKeys(defs) - private[this] def showKeys(s: Seq[ScopedKey[_]])(using display: Show[ScopedKey[_]]): String = + private def showKeys(s: Seq[ScopedKey[_]])(using display: Show[ScopedKey[_]]): String = s.map(display.show).sorted.mkString("\n\t", "\n\t", "\n\n") private[sbt] def definitions(structure: BuildStructure, actual: Boolean, key: AttributeKey[_])( diff --git a/main/src/main/scala/sbt/Resolvers.scala b/main/src/main/scala/sbt/Resolvers.scala index e4b6d7356..beb361026 100644 --- a/main/src/main/scala/sbt/Resolvers.scala +++ b/main/src/main/scala/sbt/Resolvers.scala @@ -165,14 +165,14 @@ object Resolvers { new File(base, last) } - private[this] def shortName(uri: URI): Option[String] = + private def shortName(uri: URI): Option[String] = Option(uri.withoutMarkerScheme.getPath).flatMap { _.split("/").map(_.trim).filterNot(_.isEmpty).lastOption } - private[this] def normalizeDirectoryName(name: String): String = + private def normalizeDirectoryName(name: String): String = dropExtensions(name).toLowerCase(Locale.ENGLISH).replaceAll("""\W+""", "-") - private[this] def dropExtensions(name: String): String = name.takeWhile(_ != '.') + private def dropExtensions(name: String): String = name.takeWhile(_ != '.') } diff --git a/main/src/main/scala/sbt/ScopeFilter.scala b/main/src/main/scala/sbt/ScopeFilter.scala index 730d56333..c6d9a9756 100644 --- a/main/src/main/scala/sbt/ScopeFilter.scala +++ b/main/src/main/scala/sbt/ScopeFilter.scala @@ -230,7 +230,7 @@ object ScopeFilter { } /** Constructs a Data instance from the list of static scopes and the project relationships. */ - private[this] val getData: Initialize[Data] = + private val getData: Initialize[Data] = Def.setting { val build = Keys.loadedBuild.value val scopes = Keys.allScopes.value @@ -248,7 +248,7 @@ object ScopeFilter { new Data(build.units, resolve, scopes) } - private[this] def getDependencies( + private def getDependencies( structure: Map[URI, LoadedBuildUnit], classpath: Boolean, aggregate: Boolean @@ -260,7 +260,7 @@ object ScopeFilter { (if (aggregate) p.aggregate else Nil) } - private[this] def byDeps( + private def byDeps( ref: ProjectReference, transitive: Boolean, includeRoot: Boolean, @@ -282,14 +282,14 @@ object ScopeFilter { private def inProjects(projects: ProjectReference*): ProjectFilter = inResolvedProjects(data => projects.map(data.resolve)) - private[this] def inResolvedProjects(projects: Data => Seq[ProjectRef]): ProjectFilter = + private def inResolvedProjects(projects: Data => Seq[ProjectRef]): ProjectFilter = selectAxis(data => projects(data).toSet) - private[this] def zeroAxis[T]: AxisFilter[T] = new AxisFilter[T] { + private def zeroAxis[T]: AxisFilter[T] = new AxisFilter[T] { private[sbt] def apply(data: Data): ScopeAxis[T] => Boolean = _ == Zero } - private[this] def selectAny[T]: AxisFilter[T] = selectAxis(const(const(true))) - private[this] def selectAxis[T](f: Data => T => Boolean): AxisFilter[T] = new AxisFilter[T] { + private def selectAny[T]: AxisFilter[T] = selectAxis(const(const(true))) + private def selectAxis[T](f: Data => T => Boolean): AxisFilter[T] = new AxisFilter[T] { private[sbt] def apply(data: Data): ScopeAxis[T] => Boolean = { val g = f(data) _ match { diff --git a/main/src/main/scala/sbt/ScriptedPlugin.scala b/main/src/main/scala/sbt/ScriptedPlugin.scala index 5113798c5..5ebfd6316 100644 --- a/main/src/main/scala/sbt/ScriptedPlugin.scala +++ b/main/src/main/scala/sbt/ScriptedPlugin.scala @@ -183,7 +183,7 @@ object ScriptedPlugin extends AutoPlugin { ) } - private[this] def getJars(config: Configuration): Initialize[Task[PathFinder]] = Def.task { + private def getJars(config: Configuration): Initialize[Task[PathFinder]] = Def.task { val converter = Keys.fileConverter.value PathFinder( Classpaths diff --git a/main/src/main/scala/sbt/Tags.scala b/main/src/main/scala/sbt/Tags.scala index fc63cde86..253b3a938 100644 --- a/main/src/main/scala/sbt/Tags.scala +++ b/main/src/main/scala/sbt/Tags.scala @@ -41,30 +41,30 @@ object Tags { def &&(r: Rule): Rule = new And(this, r) def unary_- : Rule = new Not(this) } - private[this] final class Custom(f: TagMap => Boolean) extends Rule { + private final class Custom(f: TagMap => Boolean) extends Rule { def apply(m: TagMap) = f(m) } - private[this] final class Single(tag: Tag, max: Int) extends Rule { + private final class Single(tag: Tag, max: Int) extends Rule { checkMax(max) def apply(m: TagMap) = getInt(m, tag) <= max override def toString = "Limit " + tag.name + " to " + max } - private[this] final class Sum(tags: Seq[Tag], max: Int) extends Rule { + private final class Sum(tags: Seq[Tag], max: Int) extends Rule { checkMax(max) def apply(m: TagMap) = tags.foldLeft(0)((sum, t) => sum + getInt(m, t)) <= max override def toString = tags.mkString("Limit sum of ", ", ", " to " + max) } - private[this] final class Or(a: Rule, b: Rule) extends Rule { + private final class Or(a: Rule, b: Rule) extends Rule { def apply(m: TagMap) = a(m) || b(m) } - private[this] final class And(a: Rule, b: Rule) extends Rule { + private final class And(a: Rule, b: Rule) extends Rule { def apply(m: TagMap) = a(m) && b(m) } - private[this] final class Not(a: Rule) extends Rule { + private final class Not(a: Rule) extends Rule { def apply(m: TagMap) = !a(m) } - private[this] def checkMax(max: Int): Unit = assert(max >= 1, "Limit must be at least 1.") + private def checkMax(max: Int): Unit = assert(max >= 1, "Limit must be at least 1.") /** Converts a sequence of rules into a function that identifies whether a set of tasks are allowed to execute concurrently based on their merged tags. */ def predicate(rules: Seq[Rule]): TagMap => Boolean = m => { diff --git a/main/src/main/scala/sbt/coursierint/LMCoursier.scala b/main/src/main/scala/sbt/coursierint/LMCoursier.scala index 0838b90aa..3e5fd18ca 100644 --- a/main/src/main/scala/sbt/coursierint/LMCoursier.scala +++ b/main/src/main/scala/sbt/coursierint/LMCoursier.scala @@ -36,7 +36,7 @@ import sbt.io.syntax._ import xsbti.AppConfiguration object LMCoursier { - private[this] val credentialRegistry: ConcurrentHashMap[(String, String), IvyCredentials] = + private val credentialRegistry: ConcurrentHashMap[(String, String), IvyCredentials] = new ConcurrentHashMap def defaultCacheLocation: File = { diff --git a/main/src/main/scala/sbt/internal/APIMappings.scala b/main/src/main/scala/sbt/internal/APIMappings.scala index 25666839f..91a81c1b8 100644 --- a/main/src/main/scala/sbt/internal/APIMappings.scala +++ b/main/src/main/scala/sbt/internal/APIMappings.scala @@ -36,7 +36,7 @@ private[sbt] object APIMappings { extractFromID(entry.data, mid, log) } - private[this] def extractFromID( + private def extractFromID( entry: HashedVirtualFileRef, mid: ModuleID, log: Logger @@ -46,7 +46,7 @@ private[sbt] object APIMappings { u <- parseURL(urlString, entry, log) yield (entry, u) - private[this] def parseURL(s: String, forEntry: HashedVirtualFileRef, log: Logger): Option[URL] = + private def parseURL(s: String, forEntry: HashedVirtualFileRef, log: Logger): Option[URL] = try Some(new URI(s).toURL) catch { diff --git a/main/src/main/scala/sbt/internal/AbstractTaskProgress.scala b/main/src/main/scala/sbt/internal/AbstractTaskProgress.scala index 5de66abf3..e6f1e2b15 100644 --- a/main/src/main/scala/sbt/internal/AbstractTaskProgress.scala +++ b/main/src/main/scala/sbt/internal/AbstractTaskProgress.scala @@ -19,10 +19,10 @@ import scala.concurrent.duration._ private[sbt] abstract class AbstractTaskExecuteProgress extends ExecuteProgress { import AbstractTaskExecuteProgress.Timer - private[this] val showScopedKey = Def.showShortKey(None) - private[this] val anonOwners = new ConcurrentHashMap[TaskId[_], TaskId[_]] - private[this] val calledBy = new ConcurrentHashMap[TaskId[_], TaskId[_]] - private[this] val timings = new ConcurrentHashMap[TaskId[_], Timer] + private val showScopedKey = Def.showShortKey(None) + private val anonOwners = new ConcurrentHashMap[TaskId[_], TaskId[_]] + private val calledBy = new ConcurrentHashMap[TaskId[_], TaskId[_]] + private val timings = new ConcurrentHashMap[TaskId[_], Timer] private[sbt] def timingsByName: mutable.Map[String, AtomicLong] = { val result = new ConcurrentHashMap[String, AtomicLong] timings.forEach { (task, timing) => @@ -102,7 +102,7 @@ private[sbt] abstract class AbstractTaskExecuteProgress extends ExecuteProgress } } - private[this] val taskNameCache = new ConcurrentHashMap[TaskId[_], String] + private val taskNameCache = new ConcurrentHashMap[TaskId[_], String] protected def taskName(t: TaskId[_]): String = taskNameCache.get(t) match { case null => val name = taskName0(t) @@ -110,7 +110,7 @@ private[sbt] abstract class AbstractTaskExecuteProgress extends ExecuteProgress name case name => name } - private[this] def taskName0(t: TaskId[_]): String = { + private def taskName0(t: TaskId[_]): String = { def definedName(node: Task[_]): Option[String] = node.info.name.orElse(TaskName.transformNode(node).map(showScopedKey.show)) def inferredName(t: Task[_]): Option[String] = nameDelegate(t) map taskName diff --git a/main/src/main/scala/sbt/internal/Act.scala b/main/src/main/scala/sbt/internal/Act.scala index 9ef84da34..c71029432 100644 --- a/main/src/main/scala/sbt/internal/Act.scala +++ b/main/src/main/scala/sbt/internal/Act.scala @@ -215,7 +215,7 @@ object Act { case Seq(single) => success(single) case multi => failure("Ambiguous keys: " + showAmbiguous(keys(multi))) } - private[this] def keys(ss: Seq[ParsedKey]): Seq[ScopedKey[_]] = ss.map(_.key) + private def keys(ss: Seq[ParsedKey]): Seq[ScopedKey[_]] = ss.map(_.key) def selectByConfig(ss: Seq[ParsedKey]): Seq[ParsedKey] = ss match { case Seq() => Nil @@ -476,7 +476,7 @@ object Act { def actParser(s: State): Parser[() => State] = requireSession(s, actParser0(s)) - private[this] def actParser0(state: State): Parser[() => State] = + private def actParser0(state: State): Parser[() => State] = val extracted = Project.extract(state) import extracted.{ showKey, structure } actionParser.flatMap: action => @@ -530,10 +530,10 @@ object Act { case _ => true } - private[this] final class ActAction - private[this] final val ShowAction, MultiAction, SingleAction, PrintAction = new ActAction + private final class ActAction + private final val ShowAction, MultiAction, SingleAction, PrintAction = new ActAction - private[this] def actionParser: Parser[ActAction] = + private def actionParser: Parser[ActAction] = token( ((ShowCommand ^^^ ShowAction) | (PrintCommand ^^^ PrintAction) | @@ -576,7 +576,7 @@ object Act { KeyValue(key, value) } } - private[this] def anyKeyValues( + private def anyKeyValues( structure: BuildStructure, keys: Seq[ScopedKey[_]] ): Seq[KeyValue[_]] = @@ -586,7 +586,7 @@ object Act { } } - private[this] def getValue[T]( + private def getValue[T]( data: Settings[Scope], scope: Scope, key: AttributeKey[T] diff --git a/main/src/main/scala/sbt/internal/Aggregation.scala b/main/src/main/scala/sbt/internal/Aggregation.scala index 4a2a8e727..fd96ddaad 100644 --- a/main/src/main/scala/sbt/internal/Aggregation.scala +++ b/main/src/main/scala/sbt/internal/Aggregation.scala @@ -250,10 +250,9 @@ object Aggregation { } // this is a hack to avoid duplicating method implementations - private[this] def castToAny[F[_]]: [a] => F[a] => F[Any] = [a] => - (fa: F[a]) => fa.asInstanceOf[F[Any]] + private def castToAny[F[_]]: [a] => F[a] => F[Any] = [a] => (fa: F[a]) => fa.asInstanceOf[F[Any]] - private[this] def maps[T, S](vs: Values[T])(f: T => S): Values[S] = + private def maps[T, S](vs: Values[T])(f: T => S): Values[S] = vs map { case KeyValue(k, v) => KeyValue(k, f(v)) } def projectAggregates[Proj]( diff --git a/main/src/main/scala/sbt/internal/BuildLoader.scala b/main/src/main/scala/sbt/internal/BuildLoader.scala index 6d6f1d749..7fae1e78e 100644 --- a/main/src/main/scala/sbt/internal/BuildLoader.scala +++ b/main/src/main/scala/sbt/internal/BuildLoader.scala @@ -62,7 +62,7 @@ final class MultiHandler[S, T]( } } - private[this] def warn(baseMessage: String, log: Logger, matching: Seq[(URI, T)]): Unit = { + private def warn(baseMessage: String, log: Logger, matching: Seq[(URI, T)]): Unit = { log.warn(baseMessage) log.debug("Non-root build resolvers defined in:") log.debug(matching.map(_._1).mkString("\n\t")) @@ -233,7 +233,7 @@ final class BuildLoader( val mgmt = config.pluginManagement copyWithNewPM(mgmt.copy(overrides = mgmt.overrides ++ overrides)) } - private[this] def copyWithNewPM(newpm: PluginManagement): BuildLoader = { + private def copyWithNewPM(newpm: PluginManagement): BuildLoader = { val newConfig = config.copy(pluginManagement = newpm) new BuildLoader(fail, state, newConfig, resolvers, builders, transformer, full, transformAll) } diff --git a/main/src/main/scala/sbt/internal/BuildStructure.scala b/main/src/main/scala/sbt/internal/BuildStructure.scala index e9e998dd1..fa2ece153 100644 --- a/main/src/main/scala/sbt/internal/BuildStructure.scala +++ b/main/src/main/scala/sbt/internal/BuildStructure.scala @@ -59,11 +59,11 @@ final class BuildStructure( def allProjectRefs(build: URI): Seq[ProjectRef] = eachProject(build, p => ProjectRef(build, p.id)) /** Foreach project in each build apply the specified function. */ - private[this] def eachBuild[A](f: (URI, ResolvedProject) => A): Seq[A] = + private def eachBuild[A](f: (URI, ResolvedProject) => A): Seq[A] = units.iterator.flatMap { case (build, unit) => unit.projects.map(f(build, _)) }.toIndexedSeq /** Foreach project in the specified build apply the specified function. */ - private[this] def eachProject[A](build: URI, f: ResolvedProject => A): Seq[A] = + private def eachProject[A](build: URI, f: ResolvedProject => A): Seq[A] = units.get(build).iterator.flatMap(_.projects).map(f).toIndexedSeq } @@ -204,7 +204,7 @@ final class DetectedPlugins( BuildUtil.importAll(autoImports(topLevelAutoPluginAutoImports)) ++ BuildUtil.importNamesRoot(autoPlugins.map(_.name).filter(nonTopLevelPlugin)) - private[this] lazy val (autoPluginAutoImports, topLevelAutoPluginAutoImports) = + private lazy val (autoPluginAutoImports, topLevelAutoPluginAutoImports) = autoPlugins .flatMap { case DetectedAutoPlugin(name, _, hasAutoImport) => if (hasAutoImport) Some(name) else None @@ -222,9 +222,9 @@ final class DetectedPlugins( Plugins.deducer(detected)(ps0, log) } - private[this] def autoImports(pluginNames: Seq[String]) = pluginNames.map(_ + ".autoImport") + private def autoImports(pluginNames: Seq[String]) = pluginNames.map(_ + ".autoImport") - private[this] def nonTopLevelPlugin(name: String) = name.contains('.') + private def nonTopLevelPlugin(name: String) = name.contains('.') } /** diff --git a/main/src/main/scala/sbt/internal/ClassLoaders.scala b/main/src/main/scala/sbt/internal/ClassLoaders.scala index cf47bc325..290deee6f 100644 --- a/main/src/main/scala/sbt/internal/ClassLoaders.scala +++ b/main/src/main/scala/sbt/internal/ClassLoaders.scala @@ -33,7 +33,7 @@ private[sbt] object ClassLoaders { private implicit class SeqFileOps(val files: Seq[File]) extends AnyVal { def urls: Array[URL] = files.toArray.map(_.toURI.toURL) } - private[this] val interfaceLoader = classOf[sbt.testing.Framework].getClassLoader + private val interfaceLoader = classOf[sbt.testing.Framework].getClassLoader /* * Get the class loader for a test task. The configuration could be IntegrationTest or Test. */ @@ -139,7 +139,7 @@ private[sbt] object ClassLoaders { } } - private[this] def extendedClassLoaderCache: Def.Initialize[Task[ClassLoaderCache]] = Def.task { + private def extendedClassLoaderCache: Def.Initialize[Task[ClassLoaderCache]] = Def.task { val errorMessage = "Tried to extract classloader cache for uninitialized state." state.value .get(BasicKeys.extendedClassLoaderCache) @@ -252,7 +252,7 @@ private[sbt] object ClassLoaders { ): Def.Initialize[Task[Seq[HashedVirtualFileRef]]] = Def.task(data(key.value).filter(_.id.endsWith(".jar"))) - private[this] def modifiedTimes(stamps: Seq[(Path, FileStamp)]): Seq[(File, Long)] = stamps.map { + private def modifiedTimes(stamps: Seq[(Path, FileStamp)]): Seq[(File, Long)] = stamps.map { case (p, LastModified(lm)) => p.toFile -> lm case (p, _) => val f = p.toFile diff --git a/main/src/main/scala/sbt/internal/ClasspathImpl.scala b/main/src/main/scala/sbt/internal/ClasspathImpl.scala index 6861873ad..b277e8d32 100644 --- a/main/src/main/scala/sbt/internal/ClasspathImpl.scala +++ b/main/src/main/scala/sbt/internal/ClasspathImpl.scala @@ -76,7 +76,7 @@ private[sbt] object ClasspathImpl { .put(Keys.configurationStr, config.name) } - private[this] def trackedExportedProductsImplTask( + private def trackedExportedProductsImplTask( track: TrackLevel ): Initialize[Task[Seq[(HashedVirtualFileRef, VirtualFile)]]] = Def.taskIf { @@ -87,7 +87,7 @@ private[sbt] object ClasspathImpl { else trackedNonJarProductsImplTask(track).value } - private[this] def trackedNonJarProductsImplTask( + private def trackedNonJarProductsImplTask( track: TrackLevel ): Initialize[Task[Seq[(HashedVirtualFileRef, VirtualFile)]]] = Def @@ -118,7 +118,7 @@ private[sbt] object ClasspathImpl { } } - private[this] def trackedJarProductsImplTask( + private def trackedJarProductsImplTask( track: TrackLevel ): Initialize[Task[Seq[(HashedVirtualFileRef, VirtualFile)]]] = (Def diff --git a/main/src/main/scala/sbt/internal/Clean.scala b/main/src/main/scala/sbt/internal/Clean.scala index de8524e9c..b2a035cd9 100644 --- a/main/src/main/scala/sbt/internal/Clean.scala +++ b/main/src/main/scala/sbt/internal/Clean.scala @@ -36,7 +36,7 @@ private[sbt] object Clean { FileTreeView.default, tryDelete((_: String) => {}) ) - private[this] def deleteContents( + private def deleteContents( path: Path, exclude: Path => Boolean, view: FileTreeView.Nio[FileAttributes], @@ -56,7 +56,7 @@ private[sbt] object Clean { deleteRecursive(path) } - private[this] def cleanFilter(scope: Scope): Def.Initialize[Task[Path => Boolean]] = Def.task { + private def cleanFilter(scope: Scope): Def.Initialize[Task[Path => Boolean]] = Def.task { val excludes = (scope / cleanKeepFiles).value.map { // This mimics the legacy behavior of cleanFilesTask case f if f.isDirectory => Glob(f, AnyPath) @@ -64,7 +64,7 @@ private[sbt] object Clean { } ++ (scope / cleanKeepGlobs).value (p: Path) => excludes.exists(_.matches(p)) } - private[this] def cleanDelete(scope: Scope): Def.Initialize[Task[Path => Unit]] = Def.task { + private def cleanDelete(scope: Scope): Def.Initialize[Task[Path => Unit]] = Def.task { // Don't use a regular logger because the logger actually writes to the target directory. val debug = (scope / logLevel).?.value.orElse(state.value.get(logLevel.key)) match { case Some(Level.Debug) => @@ -153,7 +153,7 @@ private[sbt] object Clean { case _ => Nil end ToSeqPath - private[this] implicit class ToSeqPathOps[T](val t: T) extends AnyVal { + private implicit class ToSeqPathOps[T](val t: T) extends AnyVal { def toSeqPath(implicit toSeqPath: ToSeqPath[T]): Seq[Path] = toSeqPath(t) } @@ -179,7 +179,7 @@ private[sbt] object Clean { } .tag(Tags.Clean) - private[this] def tryDelete(debug: String => Unit): Path => Unit = path => { + private def tryDelete(debug: String => Unit): Path => Unit = path => { try { debug(s"clean -- deleting file $path") Files.deleteIfExists(path) diff --git a/main/src/main/scala/sbt/internal/CommandExchange.scala b/main/src/main/scala/sbt/internal/CommandExchange.scala index 8569bb474..019d3d05e 100644 --- a/main/src/main/scala/sbt/internal/CommandExchange.scala +++ b/main/src/main/scala/sbt/internal/CommandExchange.scala @@ -57,8 +57,8 @@ private[sbt] final class CommandExchange { private val channelBufferLock = new AnyRef {} private val fastTrackChannelQueue = new LinkedBlockingQueue[FastTrackTask] private val nextChannelId: AtomicInteger = new AtomicInteger(0) - private[this] val lastState = new AtomicReference[State] - private[this] val currentExecRef = new AtomicReference[Exec] + private val lastState = new AtomicReference[State] + private val currentExecRef = new AtomicReference[Exec] private[sbt] def hasServer = server.isDefined addConsoleChannel() @@ -174,7 +174,7 @@ private[sbt] final class CommandExchange { catch { case _: InterruptedException => } } - private[this] def mkAskUser( + private def mkAskUser( name: String, ): (State, CommandChannel) => UITask = { (state, channel) => ContinuousCommands @@ -455,7 +455,7 @@ private[sbt] final class CommandExchange { commandQueue.add(exit) () } - private[this] def cancel(e: Exec): Unit = { + private def cancel(e: Exec): Unit = { if (e.commandLine.startsWith("console")) { val terminal = Terminal.get terminal.write(13, 13, 13, 4) @@ -465,12 +465,12 @@ private[sbt] final class CommandExchange { } } - private[this] class FastTrackThread + private class FastTrackThread extends Thread("sbt-command-exchange-fastTrack") with AutoCloseable { setDaemon(true) start() - private[this] val isStopped = new AtomicBoolean(false) + private val isStopped = new AtomicBoolean(false) override def run(): Unit = { def exit(mt: FastTrackTask): Unit = { mt.channel.shutdown(false) @@ -516,5 +516,5 @@ private[sbt] final class CommandExchange { } private[sbt] def channelForName(channelName: String): Option[CommandChannel] = channels.find(_.name == channelName) - private[this] val fastTrackThread = new FastTrackThread + private val fastTrackThread = new FastTrackThread } diff --git a/main/src/main/scala/sbt/internal/Continuous.scala b/main/src/main/scala/sbt/internal/Continuous.scala index ab2b47464..bfd03bc91 100644 --- a/main/src/main/scala/sbt/internal/Continuous.scala +++ b/main/src/main/scala/sbt/internal/Continuous.scala @@ -140,7 +140,7 @@ private[sbt] object Continuous extends DeprecatedContinuous { 10000 ) - private[this] val continuousParser: State => Parser[(Int, Seq[String])] = { + private val continuousParser: State => Parser[(Int, Seq[String])] = { def toInt(s: String): Int = Try(s.toInt).getOrElse(0) // This allows us to re-enter the watch with the previous count. @@ -215,7 +215,7 @@ private[sbt] object Continuous extends DeprecatedContinuous { } // This is defined so we can assign a task key to a command to parse the WatchSettings. - private[this] val globalWatchSettingKey = + private val globalWatchSettingKey = taskKey[Unit]("Internal task key. Not actually used.").withRank(KeyRanks.Invisible) private def parseCommand(command: String, state: State): Seq[ScopedKey[_]] = { // Collect all of the scoped keys that are used to delegate the multi commands. These are @@ -456,12 +456,12 @@ private[sbt] object Continuous extends DeprecatedContinuous { override def debug(msg: Any): Unit = l.debug(msg.toString) } - private[this] val observers: Observers[Event] = new Observers - private[this] val repo = getRepository(state) - private[this] val handles = new java.util.ArrayList[AutoCloseable] + private val observers: Observers[Event] = new Observers + private val repo = getRepository(state) + private val handles = new java.util.ArrayList[AutoCloseable] handles.add(repo.addObserver(observers)) - private[this] val eventMonitorObservers = new Observers[Event] - private[this] val configHandle: AutoCloseable = + private val eventMonitorObservers = new Observers[Event] + private val configHandle: AutoCloseable = observers.addObserver { e => // We only want to create one event per actual source file event. It doesn't matter // which of the config inputs triggers the event because they all will be used in @@ -486,8 +486,8 @@ private[sbt] object Continuous extends DeprecatedContinuous { } } - private[this] val antiEntropyWindow = configs.map(_.watchSettings.antiEntropy).max - private[this] val monitor = FileEventMonitor.antiEntropy( + private val antiEntropyWindow = configs.map(_.watchSettings.antiEntropy).max + private val monitor = FileEventMonitor.antiEntropy( eventMonitorObservers, antiEntropyWindow, logger, @@ -495,7 +495,7 @@ private[sbt] object Continuous extends DeprecatedContinuous { retentionPeriod ) - private[this] val antiEntropyPollPeriod = + private val antiEntropyPollPeriod = configs.map(_.watchSettings.antiEntropyPollPeriod).max override def poll(duration: Duration, filter: Event => Boolean): Seq[Event] = { monitor.poll(duration, filter) match { @@ -664,7 +664,7 @@ private[sbt] object Continuous extends DeprecatedContinuous { ) } - private[this] class WatchExecutor(name: String) extends AutoCloseable { + private class WatchExecutor(name: String) extends AutoCloseable { val id = new AtomicInteger(0) val threads = new java.util.Vector[Thread] val closed = new AtomicBoolean(false) @@ -1202,7 +1202,7 @@ private[sbt] object ContinuousCommands { "", Int.MaxValue ) - private[this] val watchStates = + private val watchStates = AttributeKey[Map[String, ContinuousState]]("sbt-watch-states", Int.MaxValue) private[sbt] val runWatch = networkExecPrefix + "runWatch" private[sbt] val preWatch = networkExecPrefix + "preWatch" @@ -1210,13 +1210,13 @@ private[sbt] object ContinuousCommands { private[sbt] val stopWatch = networkExecPrefix + "stopWatch" private[sbt] val failWatch = networkExecPrefix + "failWatch" private[sbt] val waitWatch = networkExecPrefix + "waitWatch" - private[this] def noComplete[T](p: Parser[T]): Parser[T] = p.examples() - private[this] val space = noComplete(Space) - private[this] def cmdParser(s: String): Parser[String] = noComplete(matched(s)) <~ space - private[this] def channelParser: Parser[String] = + private def noComplete[T](p: Parser[T]): Parser[T] = p.examples() + private val space = noComplete(Space) + private def cmdParser(s: String): Parser[String] = noComplete(matched(s)) <~ space + private def channelParser: Parser[String] = noComplete(matched(charClass(c => c.isLetterOrDigit || c == '-').+)) - private[this] val stashedRepo = AttributeKey[FileTreeRepository[FileAttributes]]( + private val stashedRepo = AttributeKey[FileTreeRepository[FileAttributes]]( "stashed-file-tree-repository", "", Int.MaxValue @@ -1301,7 +1301,7 @@ private[sbt] object ContinuousCommands { throw new IllegalStateException(msg) } } - private[this] def watchCommand( + private def watchCommand( name: String )(updateState: (String, State) => State): Command = Command.arb { state => @@ -1322,7 +1322,7 @@ private[sbt] object ContinuousCommands { state.get(watchStates).exists(_.contains(channel.name)) private[sbt] def isPending(state: State, channel: CommandChannel): Boolean = state.get(watchStates).exists(_.get(channel.name).exists(_.pending)) - private[this] class WatchUITask( + private class WatchUITask( override private[sbt] val channel: CommandChannel, cs: ContinuousState, state: State @@ -1363,7 +1363,7 @@ private[sbt] object ContinuousCommands { } } @inline - private[this] def watchState(state: State, channel: String): ContinuousState = + private def watchState(state: State, channel: String): ContinuousState = state.get(watchStates).flatMap(_.get(channel)) match { case None => throw new IllegalStateException(s"no watch state for $channel") case Some(s) => s @@ -1386,7 +1386,7 @@ private[sbt] object ContinuousCommands { } cs.afterCommand(postState) } - private[this] val exitWatchShared = (error: Boolean) => + private val exitWatchShared = (error: Boolean) => (channel: String, state: State) => state.get(watchStates).flatMap(_.get(channel)) match { case Some(cs) => @@ -1415,9 +1415,9 @@ private[sbt] object ContinuousCommands { * Creates a FileTreeRepository where it is safe to call close without inadvertently cancelling * still active watches. */ - private[this] def localRepo[T](r: FileTreeRepository[T]): FileTreeRepository[T] = + private def localRepo[T](r: FileTreeRepository[T]): FileTreeRepository[T] = new FileTreeRepository[T] { - private[this] val closeables = ConcurrentHashMap.newKeySet[AutoCloseable] + private val closeables = ConcurrentHashMap.newKeySet[AutoCloseable] override def addObserver(observer: Observer[FileEvent[T]]): AutoCloseable = { val ac = r.addObserver(observer) val safeCloseable: AutoCloseable = () => diff --git a/main/src/main/scala/sbt/internal/DefaultBackgroundJobService.scala b/main/src/main/scala/sbt/internal/DefaultBackgroundJobService.scala index 0380f86b0..c5f19c50e 100644 --- a/main/src/main/scala/sbt/internal/DefaultBackgroundJobService.scala +++ b/main/src/main/scala/sbt/internal/DefaultBackgroundJobService.scala @@ -533,7 +533,7 @@ private[sbt] class DefaultBackgroundJobService( } private[sbt] object DefaultBackgroundJobService { - private[this] val backgroundJobServices = new ConcurrentHashMap[File, DefaultBackgroundJobService] + private val backgroundJobServices = new ConcurrentHashMap[File, DefaultBackgroundJobService] private[sbt] def shutdown(): Unit = { backgroundJobServices.values.forEach(_.shutdown()) backgroundJobServices.clear() diff --git a/main/src/main/scala/sbt/internal/DeprecatedContinuous.scala b/main/src/main/scala/sbt/internal/DeprecatedContinuous.scala index 8ca30fb20..2b92dc696 100644 --- a/main/src/main/scala/sbt/internal/DeprecatedContinuous.scala +++ b/main/src/main/scala/sbt/internal/DeprecatedContinuous.scala @@ -29,7 +29,7 @@ private[internal] trait DeprecatedContinuous { protected def watchState(globs: Seq[Glob], count: Int): WS = { WS.empty(globs).withCount(count) } - private[this] val legacyWatchState = + private val legacyWatchState = AttributeKey[AtomicReference[WS]]("legacy-watch-state", Int.MaxValue) private[sbt] def addLegacyWatchSetting(state: State): State = { val legacyState = new AtomicReference[WS](WS.empty(Nil).withCount(1)) diff --git a/main/src/main/scala/sbt/internal/GCMonitor.scala b/main/src/main/scala/sbt/internal/GCMonitor.scala index 999b40d77..4ac4961d1 100644 --- a/main/src/main/scala/sbt/internal/GCMonitor.scala +++ b/main/src/main/scala/sbt/internal/GCMonitor.scala @@ -24,7 +24,7 @@ trait GCMonitorBase { protected val queue = new LinkedBlockingQueue[(FiniteDuration, Long)] protected val queueScala = queue.asScala - private[this] val lastWarned = new AtomicReference(Deadline(Int.MinValue.millis)) + private val lastWarned = new AtomicReference(Deadline(Int.MinValue.millis)) protected def emitWarning(total: Long, over: Option[Long]): Unit diff --git a/main/src/main/scala/sbt/internal/GlobalPlugin.scala b/main/src/main/scala/sbt/internal/GlobalPlugin.scala index 9cac57c26..2f5ab96f2 100644 --- a/main/src/main/scala/sbt/internal/GlobalPlugin.scala +++ b/main/src/main/scala/sbt/internal/GlobalPlugin.scala @@ -45,7 +45,7 @@ object GlobalPlugin { injectInternalClasspath(Runtime, gp.internalClasspath), injectInternalClasspath(Compile, gp.internalClasspath) ) - private[this] def injectInternalClasspath( + private def injectInternalClasspath( config: Configuration, cp: Def.Classpath, ): Setting[_] = diff --git a/main/src/main/scala/sbt/internal/InMemoryCacheStore.scala b/main/src/main/scala/sbt/internal/InMemoryCacheStore.scala index 714c3544f..0f7b3572d 100644 --- a/main/src/main/scala/sbt/internal/InMemoryCacheStore.scala +++ b/main/src/main/scala/sbt/internal/InMemoryCacheStore.scala @@ -20,9 +20,9 @@ import sbt.util.{ CacheStore, CacheStoreFactory, DirectoryStoreFactory } import sjsonnew.{ JsonReader, JsonWriter } private[sbt] object InMemoryCacheStore { - private[this] class InMemoryCacheStore(maxSize: Long) extends AutoCloseable { - private[this] val weigher: Weigher[Path, (Any, Long, Int)] = { case (_, (_, _, size)) => size } - private[this] val files: Cache[Path, (Any, Long, Int)] = Caffeine + private class InMemoryCacheStore(maxSize: Long) extends AutoCloseable { + private val weigher: Weigher[Path, (Any, Long, Int)] = { case (_, (_, _, size)) => size } + private val files: Cache[Path, (Any, Long, Int)] = Caffeine .newBuilder() .maximumWeight(maxSize) .weigher(weigher) @@ -51,7 +51,7 @@ private[sbt] object InMemoryCacheStore { } } - private[this] class CacheStoreImpl(path: Path, store: InMemoryCacheStore, cacheStore: CacheStore) + private class CacheStoreImpl(path: Path, store: InMemoryCacheStore, cacheStore: CacheStore) extends CacheStore { override def delete(): Unit = cacheStore.delete() override def read[T]()(implicit reader: JsonReader[T]): T = { @@ -84,7 +84,7 @@ private[sbt] object InMemoryCacheStore { cacheStore.close() } } - private[this] def factory( + private def factory( store: InMemoryCacheStore, path: Path ): CacheStoreFactory = { @@ -99,8 +99,8 @@ private[sbt] object InMemoryCacheStore { private[sbt] trait CacheStoreFactoryFactory extends AutoCloseable { def apply(path: Path): CacheStoreFactory } - private[this] class CacheStoreFactoryFactoryImpl(size: Long) extends CacheStoreFactoryFactory { - private[this] val storeRef = new AtomicReference[InMemoryCacheStore] + private class CacheStoreFactoryFactoryImpl(size: Long) extends CacheStoreFactoryFactory { + private val storeRef = new AtomicReference[InMemoryCacheStore] override def close(): Unit = Option(storeRef.get).foreach(_.close()) def apply( path: Path, @@ -121,7 +121,7 @@ private[sbt] object InMemoryCacheStore { factory(store, path) } } - private[this] object DirectoryFactory extends CacheStoreFactoryFactory { + private object DirectoryFactory extends CacheStoreFactoryFactory { override def apply( path: Path, ): CacheStoreFactory = new DirectoryStoreFactory(path.toFile) diff --git a/main/src/main/scala/sbt/internal/InstallSbtn.scala b/main/src/main/scala/sbt/internal/InstallSbtn.scala index 59e5bbcad..3e56f6f55 100644 --- a/main/src/main/scala/sbt/internal/InstallSbtn.scala +++ b/main/src/main/scala/sbt/internal/InstallSbtn.scala @@ -99,13 +99,13 @@ private[sbt] object InstallSbtn { } () } - private[this] def downloadRelease(term: Terminal, version: String, location: Path): Unit = { + private def downloadRelease(term: Terminal, version: String, location: Path): Unit = { val zip = s"https://github.com/sbt/sbt/releases/download/v$version/sbt-$version.zip" val url = new URI(zip).toURL term.printStream.println(s"downloading $zip to $location") transfer(url.openStream(), location) } - private[this] def transfer(inputStream: InputStream, path: Path): Unit = + private def transfer(inputStream: InputStream, path: Path): Unit = try { val os = new FileOutputStream(path.toFile) try { @@ -119,7 +119,7 @@ private[sbt] object InstallSbtn { while bytesRead > 0 do impl() } finally os.close() } finally inputStream.close() - private[this] def getShell(term: Terminal): String = { + private def getShell(term: Terminal): String = { term.printStream.print(s"""Setup sbtn for shell: | [1] bash | [2] fish @@ -138,12 +138,12 @@ private[sbt] object InstallSbtn { case _ => "none" } } - private[this] def downloadCompletion(completion: String, version: String, target: Path): Unit = { + private def downloadCompletion(completion: String, version: String, target: Path): Unit = { Files.createDirectories(target.getParent) val comp = s"https://raw.githubusercontent.com/sbt/sbt/v$version/client/completions/$completion" transfer(new URI(comp).toURL.openStream, target) } - private[this] def setupShell( + private def setupShell( shell: String, baseDirectory: Path, term: Terminal, @@ -195,7 +195,7 @@ private[sbt] object InstallSbtn { term.printStream.println() } } - private[this] def setupBash(baseDirectory: Path, term: Terminal): Unit = + private def setupBash(baseDirectory: Path, term: Terminal): Unit = setupShell( "bash", baseDirectory, @@ -204,20 +204,20 @@ private[sbt] object InstallSbtn { bin => s"export PATH=$$PATH:$bin", completions => s"source $completions/sbtn.bash" ) - private[this] def setupZsh(baseDirectory: Path, term: Terminal): Unit = { + private def setupZsh(baseDirectory: Path, term: Terminal): Unit = { val comp = (completions: Path) => { "# The following two lines were added by the sbt installSbtn task:\n" + s"fpath=($$fpath $completions)\nautoload -Uz compinit; compinit" } setupShell("zsh", baseDirectory, term, userHome / ".zshrc", bin => s"path=($$path $bin)", comp) } - private[this] def setupFish(baseDirectory: Path, term: Terminal): Unit = { + private def setupFish(baseDirectory: Path, term: Terminal): Unit = { val comp = (completions: Path) => s"source $completions/sbtn.fish" val path = (bin: Path) => s"set PATH $$PATH $bin" val config = userHome / ".config" / "fish" / "config.fish" setupShell("fish", baseDirectory, term, config, path, comp) } - private[this] def setupPowershell(baseDirectory: Path, term: Terminal): Unit = { + private def setupPowershell(baseDirectory: Path, term: Terminal): Unit = { val comp = (completions: Path) => s""". "$completions\\sbtn.ps1"""" val path = (bin: Path) => s"""$$env:Path += ";$bin"""" import scala.sys.process._ @@ -232,7 +232,7 @@ private[sbt] object InstallSbtn { } } } - private[this] val shellCompletions = Map( + private val shellCompletions = Map( "bash" -> "sbtn.bash", "fish" -> "sbtn.fish", "powershell" -> "sbtn.ps1", diff --git a/main/src/main/scala/sbt/internal/IvyConsole.scala b/main/src/main/scala/sbt/internal/IvyConsole.scala index 5ab6aed19..c32b8c99a 100644 --- a/main/src/main/scala/sbt/internal/IvyConsole.scala +++ b/main/src/main/scala/sbt/internal/IvyConsole.scala @@ -86,7 +86,7 @@ object IvyConsole { case _ => acc.copy(managed = parseManaged(arg, log) ++ acc.managed) } - private[this] def parseResolver(arg: String): MavenRepository = { + private def parseResolver(arg: String): MavenRepository = { val Array(name, url) = arg.split(" at ") MavenRepository(name.trim, url.trim) } diff --git a/main/src/main/scala/sbt/internal/JarClassPath.scala b/main/src/main/scala/sbt/internal/JarClassPath.scala index 9d93e6736..ae0c46619 100644 --- a/main/src/main/scala/sbt/internal/JarClassPath.scala +++ b/main/src/main/scala/sbt/internal/JarClassPath.scala @@ -15,7 +15,7 @@ import sbt.io.IO private[internal] object JarClassPath { class Snapshot private[internal] (val file: File, val lastModified: Long) extends Comparable[JarClassPath.Snapshot] { - private[this] val _hash = (file.hashCode * 31) ^ java.lang.Long.valueOf(lastModified).hashCode() + private val _hash = (file.hashCode * 31) ^ java.lang.Long.valueOf(lastModified).hashCode() def this(file: File) = this(file, IO.getModifiedTimeOrZero(file)) override def equals(obj: Any): Boolean = obj match { case that: JarClassPath.Snapshot => @@ -29,7 +29,7 @@ private[internal] object JarClassPath { } } private[internal] final class JarClassPath(val jars: Seq[File]) { - private[this] def isSnapshot(file: File): Boolean = file.getName contains "-SNAPSHOT" + private def isSnapshot(file: File): Boolean = file.getName contains "-SNAPSHOT" private val jarSet = jars.toSet val (snapshotJars, regularJars) = jars.partition(isSnapshot) private val snapshots = snapshotJars.map(new JarClassPath.Snapshot(_)) @@ -41,7 +41,7 @@ private[internal] final class JarClassPath(val jars: Seq[File]) { // The memoization is because codacy isn't smart enough to identify that // `override lazy val hashCode: Int = jarSet.hashCode` does actually override hashCode and it // complains that equals and hashCode were not implemented together. - private[this] lazy val _hashCode: Int = jarSet.hashCode + private lazy val _hashCode: Int = jarSet.hashCode override def hashCode: Int = _hashCode override def toString: String = s"JarClassPath(\n jars =\n ${regularJars.mkString(",\n ")}" + diff --git a/main/src/main/scala/sbt/internal/KeyIndex.scala b/main/src/main/scala/sbt/internal/KeyIndex.scala index a2b72ea14..5c098cfb9 100644 --- a/main/src/main/scala/sbt/internal/KeyIndex.scala +++ b/main/src/main/scala/sbt/internal/KeyIndex.scala @@ -54,7 +54,7 @@ object KeyIndex { } } - private[this] def base( + private def base( projects: Map[URI, Set[String]], configurations: Map[String, Seq[Configuration]] ): ExtendableKeyIndex = { @@ -273,7 +273,7 @@ private[sbt] final class KeyIndex0(val data: BuildIndex) extends ExtendableKeyIn case Some(BuildRef(uri)) => (Some(uri), None) case _ => (None, None) } - private[this] def optConfigs(project: Option[ResolvedReference]): Seq[Option[String]] = + private def optConfigs(project: Option[ResolvedReference]): Seq[Option[String]] = None +: (configs(project).toSeq.map(some[String])) def addAggregated(scoped: ScopedKey[_], extra: BuildUtil[_]): ExtendableKeyIndex = @@ -284,11 +284,11 @@ private[sbt] final class KeyIndex0(val data: BuildIndex) extends ExtendableKeyIn def add(scoped: ScopedKey[_]): ExtendableKeyIndex = if (validID(scoped.key.label)) add0(scoped) else this - private[this] def add0(scoped: ScopedKey[_]): ExtendableKeyIndex = { + private def add0(scoped: ScopedKey[_]): ExtendableKeyIndex = { val (build, project) = parts(scoped.scope.project.toOption) add1(build, project, scoped.scope.config, scoped.scope.task, scoped.key) } - private[this] def add1( + private def add1( uri: Option[URI], id: Option[String], config: ScopeAxis[ConfigKey], diff --git a/main/src/main/scala/sbt/internal/LayeredClassLoaders.scala b/main/src/main/scala/sbt/internal/LayeredClassLoaders.scala index 276366227..4a0613242 100644 --- a/main/src/main/scala/sbt/internal/LayeredClassLoaders.scala +++ b/main/src/main/scala/sbt/internal/LayeredClassLoaders.scala @@ -46,9 +46,9 @@ private[internal] final class ReverseLookupClassLoaderHolder( val allowZombies: Boolean, val logger: Logger ) extends URLClassLoader(Array.empty, null) { - private[this] val cached: AtomicReference[ReverseLookupClassLoader] = new AtomicReference - private[this] val closed = new AtomicBoolean(false) - private[this] val urls = classpath.map(_.toURI.toURL).toArray + private val cached: AtomicReference[ReverseLookupClassLoader] = new AtomicReference + private val closed = new AtomicBoolean(false) + private val urls = classpath.map(_.toURI.toURL).toArray /** * Get a classloader. If there is a loader available in the cache, it will use that loader, @@ -109,10 +109,10 @@ private[internal] trait NativeLoader extends AutoCloseable { private[internal] def setTempDir(file: File): Unit = {} } private[internal] class NativeLookup extends NativeLoader { - private[this] val mapped = new ConcurrentHashMap[String, String] - private[this] val searchPaths = + private val mapped = new ConcurrentHashMap[String, String] + private val searchPaths = sys.props.get("java.library.path").map(IO.parseClasspath).getOrElse(Nil) - private[this] val tempDir = new AtomicReference(new File("/dev/null")) + private val tempDir = new AtomicReference(new File("/dev/null")) override def close(): Unit = setTempDir(new File("/dev/null")) @@ -135,23 +135,23 @@ private[internal] class NativeLookup extends NativeLoader { tempDir.set(file) } - private[this] def deleteNativeLibs(): Unit = { + private def deleteNativeLibs(): Unit = { mapped.values().forEach(NativeLibs.delete) mapped.clear() } - private[this] def findLibrary0(name: String): String = { + private def findLibrary0(name: String): String = { val mappedName = System.mapLibraryName(name) val search = searchPaths.to(LazyList).flatMap(relativeLibrary(mappedName)) search.headOption.map(copy).orNull } - private[this] def relativeLibrary(mappedName: String)(base: File): Seq[File] = { + private def relativeLibrary(mappedName: String)(base: File): Seq[File] = { val f = new File(base, mappedName) if (f.isFile) f :: Nil else Nil } - private[this] def copy(f: File): String = { + private def copy(f: File): String = { val target = new File(tempDir.get(), f.getName) IO.copyFile(f, target) target.getAbsolutePath @@ -159,7 +159,7 @@ private[internal] class NativeLookup extends NativeLoader { } private[internal] object NativeLibs { - private[this] val nativeLibs = new java.util.HashSet[File].asScala + private val nativeLibs = new java.util.HashSet[File].asScala ShutdownHooks.add(() => { nativeLibs.foreach(IO.delete) IO.deleteIfEmpty(nativeLibs.map(_.getParentFile).toSet) diff --git a/main/src/main/scala/sbt/internal/LibraryManagement.scala b/main/src/main/scala/sbt/internal/LibraryManagement.scala index c1c233494..df1b40836 100644 --- a/main/src/main/scala/sbt/internal/LibraryManagement.scala +++ b/main/src/main/scala/sbt/internal/LibraryManagement.scala @@ -173,7 +173,7 @@ private[sbt] object LibraryManagement { handler((extraInputHash, settings, withoutClock)) } - private[this] def fileUptodate(file0: String, stamps: Map[String, Long], log: Logger): Boolean = { + private def fileUptodate(file0: String, stamps: Map[String, Long], log: Logger): Boolean = { val file = File(file0) val exists = file.exists // https://github.com/sbt/sbt/issues/5292 warn the user that the file is missing since this indicates @@ -216,7 +216,7 @@ private[sbt] object LibraryManagement { .withConfigurations(if (confs) m.configurations else None) .branch(m.branchName) - private[this] def transformDetails( + private def transformDetails( ur: UpdateReport, includeCallers: Boolean, includeDetails: Boolean diff --git a/main/src/main/scala/sbt/internal/LintUnused.scala b/main/src/main/scala/sbt/internal/LintUnused.scala index 91ccd3b2a..745b719d6 100644 --- a/main/src/main/scala/sbt/internal/LintUnused.scala +++ b/main/src/main/scala/sbt/internal/LintUnused.scala @@ -173,7 +173,7 @@ object LintUnused { }).sortBy(_._2) } - private[this] case class UnusedKey( + private case class UnusedKey( scoped: ScopedKey[_], positions: Vector[SourcePosition], data: Option[ScopedKeyData[_]] diff --git a/main/src/main/scala/sbt/internal/Load.scala b/main/src/main/scala/sbt/internal/Load.scala index bbe238308..ee0a38365 100755 --- a/main/src/main/scala/sbt/internal/Load.scala +++ b/main/src/main/scala/sbt/internal/Load.scala @@ -862,7 +862,7 @@ private[sbt] object Load { new BuildUnit(uri, normBase, loadedDefs, plugs, converter) } - private[this] def autoID( + private def autoID( localBase: File, context: PluginManagement.Context, existingIDs: Seq[String] @@ -883,15 +883,15 @@ private[sbt] object Load { if (existingIDs.contains(tryID)) BuildDef.defaultID(localBase) else tryID } - private[this] def autoIDError(base: File, reason: String): String = + private def autoIDError(base: File, reason: String): String = "Could not derive root project ID from directory " + base.getAbsolutePath + ":\n" + reason + "\nRename the directory or explicitly define a root project." - private[this] def projectsFromBuild(b: BuildDef, base: File): Seq[Project] = + private def projectsFromBuild(b: BuildDef, base: File): Seq[Project] = b.projectDefinitions(base).map(resolveBase(base)) // Lame hackery to keep track of our state. - private[this] case class LoadedProjects( + private case class LoadedProjects( projects: Seq[Project], generatedConfigClassFiles: Seq[Path], ) @@ -926,7 +926,7 @@ private[sbt] object Load { * @param extraSbtFiles * @return The completely resolved/updated sequence of projects defined, with all settings expanded. */ - private[this] def loadTransitive( + private def loadTransitive( newProjects: Seq[Project], buildBase: File, plugins: LoadedPlugins, @@ -1097,7 +1097,7 @@ private[sbt] object Load { LoadedProjects(acc, generatedConfigClassFiles) end loadTransitive - private[this] def translateAutoPluginException( + private def translateAutoPluginException( e: AutoPluginException, project: Project ): AutoPluginException = @@ -1112,7 +1112,7 @@ private[sbt] object Load { * @param sbtFiles Any sbt file loaded during this discovery (used later to complete the project). * @param generatedFiles Any .class file that was generated when compiling/discovering these projects. */ - private[this] case class DiscoveredProjects( + private case class DiscoveredProjects( root: Option[Project], nonRoot: Seq[Project], sbtFiles: Seq[VirtualFile], @@ -1189,7 +1189,7 @@ private[sbt] object Load { .prefixConfigs(autoConfigs: _*) } - private[this] def expandCommonSettingsPerBase( + private def expandCommonSettingsPerBase( directory: File, memoSettings: mutable.Map[VirtualFile, LoadedSbtFile], extraSbtFiles: Seq[VirtualFile], @@ -1228,7 +1228,7 @@ private[sbt] object Load { * @param eval A mechanism of executing/running scala code. * @param memoSettings A recording of all files we've parsed. */ - private[this] def discoverProjects( + private def discoverProjects( auto: AddSettings, projectBase: File, extraSbtFiles: Seq[VirtualFile], @@ -1353,7 +1353,7 @@ private[sbt] object Load { ) ) - private[this] def removeEntries( + private def removeEntries( cp: Def.Classpath, remove: Def.Classpath ): Def.Classpath = diff --git a/main/src/main/scala/sbt/internal/LogManager.scala b/main/src/main/scala/sbt/internal/LogManager.scala index 2768b92f2..f804f6509 100644 --- a/main/src/main/scala/sbt/internal/LogManager.scala +++ b/main/src/main/scala/sbt/internal/LogManager.scala @@ -300,7 +300,7 @@ object LogManager { // This is the default implementation for the relay appender val defaultRelay: Unit => ConsoleAppender = _ => defaultRelayImpl - private[this] lazy val defaultRelayImpl: ConsoleAppender = new RelayAppender("Relay0") + private lazy val defaultRelayImpl: ConsoleAppender = new RelayAppender("Relay0") private[sbt] def settingsLogger(state: State): Def.Setting[_] = // strict to avoid retaining a reference to `state` @@ -308,10 +308,10 @@ object LogManager { // construct a Logger that delegates to the global logger, but only holds a weak reference // this is an approximation to the ideal that would invalidate the delegate after loading completes - private[this] def globalWrapper(s: State): Logger = + private def globalWrapper(s: State): Logger = new Logger { - private[this] val ref = new java.lang.ref.WeakReference(s.globalLogging.full) - private[this] def slog: Logger = + private val ref = new java.lang.ref.WeakReference(s.globalLogging.full) + private def slog: Logger = Option(ref.get) getOrElse sys.error("Settings logger used after project was loaded.") override val ansiCodesSupported = ITerminal.isAnsiSupported diff --git a/main/src/main/scala/sbt/internal/PluginDiscovery.scala b/main/src/main/scala/sbt/internal/PluginDiscovery.scala index adffe815c..0e31ff607 100644 --- a/main/src/main/scala/sbt/internal/PluginDiscovery.scala +++ b/main/src/main/scala/sbt/internal/PluginDiscovery.scala @@ -168,7 +168,7 @@ object PluginDiscovery: loadModules[A](data, names, loader) DetectedModules(namesAndValues) - private[this] def loadModules[A: reflect.ClassTag]( + private def loadModules[A: reflect.ClassTag]( data: PluginData, names: Seq[String], loader: ClassLoader @@ -181,7 +181,7 @@ object PluginDiscovery: case e: LinkageError => incompatiblePlugins(data, e) } - private[this] def incompatiblePlugins(data: PluginData, t: LinkageError): Nothing = { + private def incompatiblePlugins(data: PluginData, t: LinkageError): Nothing = { val evicted = data.report.toList.flatMap(_.configurations.flatMap(_.evicted)) val evictedModules = evicted.map { id => (id.organization, id.name) diff --git a/main/src/main/scala/sbt/internal/PluginManagement.scala b/main/src/main/scala/sbt/internal/PluginManagement.scala index 77a31f24a..cf1a6af62 100644 --- a/main/src/main/scala/sbt/internal/PluginManagement.scala +++ b/main/src/main/scala/sbt/internal/PluginManagement.scala @@ -75,7 +75,7 @@ object PluginManagement { ModuleID(m.organization, m.name, m.revision).withCrossVersion(m.crossVersion) final class PluginClassLoader(p: ClassLoader) extends URLClassLoader(Array(), p) { - private[this] val urlSet = + private val urlSet = new collection.mutable.HashSet[URI] // remember: don't use hashCode/equals on URL def add(urls: Seq[URL]): Unit = synchronized { for (url <- urls) diff --git a/main/src/main/scala/sbt/internal/PluginsDebug.scala b/main/src/main/scala/sbt/internal/PluginsDebug.scala index ac29e518a..cdd410a87 100644 --- a/main/src/main/scala/sbt/internal/PluginsDebug.scala +++ b/main/src/main/scala/sbt/internal/PluginsDebug.scala @@ -50,7 +50,7 @@ private[sbt] class PluginsDebug( activePrefix + debugDeactivated(notFoundKey, deactivated) } - private[this] def debugDeactivated( + private def debugDeactivated( notFoundKey: String, deactivated: Seq[EnableDeactivated] ): String = { @@ -113,7 +113,7 @@ private[sbt] class PluginsDebug( s"$prefix$keysString$confsString\n$toActivate" } - private[this] def multi(strs: Seq[String]): String = + private def multi(strs: Seq[String]): String = strs.mkString(if (strs.lengthCompare(4) > 0) "\n\t" else ", ") } @@ -163,7 +163,7 @@ private[sbt] object PluginsDebug { .toMap } - private[this] def availableAutoPlugins(build: LoadedBuildUnit): Seq[AutoPlugin] = + private def availableAutoPlugins(build: LoadedBuildUnit): Seq[AutoPlugin] = build.unit.plugins.detected.autoPlugins map { _.value } def help(plugin: AutoPlugin, s: State): String = { @@ -293,7 +293,7 @@ private[sbt] object PluginsDebug { else enableDeactivated(context, plugin) - private[this] def enableDeactivated(context: Context, plugin: AutoPlugin): PluginEnable = { + private def enableDeactivated(context: Context, plugin: AutoPlugin): PluginEnable = { // deconstruct the context val initialModel = context.enabled.toSet val initial = flatten(context.initial) @@ -382,20 +382,20 @@ private[sbt] object PluginsDebug { } } - private[this] def includeAll[T <: Basic](basic: Set[T]): Plugins = And(basic.toList) - private[this] def excludeAll(plugins: Set[AutoPlugin]): Plugins = + private def includeAll[T <: Basic](basic: Set[T]): Plugins = And(basic.toList) + private def excludeAll(plugins: Set[AutoPlugin]): Plugins = And(plugins.map(p => Exclude(p)).toList) - private[this] def excludes(bs: Seq[Basic]): Set[AutoPlugin] = + private def excludes(bs: Seq[Basic]): Set[AutoPlugin] = bs.collect { case Exclude(b) => b }.toSet - private[this] def plugins(bs: Seq[Basic]): Set[AutoPlugin] = + private def plugins(bs: Seq[Basic]): Set[AutoPlugin] = bs.collect { case n: AutoPlugin => n }.toSet // If there is a model that includes `plugin`, it includes at least what is returned by this method. // This is the list of plugins that must be included as well as list of plugins that must not be present. // It might not be valid, such as if there are contradictions or if there are cycles that are unsatisfiable. // The actual model might be larger, since other plugins might be enabled by the selected plugins. - private[this] def minimalModel(plugin: AutoPlugin): Seq[Basic] = + private def minimalModel(plugin: AutoPlugin): Seq[Basic] = Dag.topologicalSortUnchecked(plugin: Basic) { case _: Exclude => Nil case ap: AutoPlugin => Plugins.flatten(ap.requires) :+ plugin @@ -440,66 +440,66 @@ private[sbt] object PluginsDebug { available.foldLeft(empty)((r, p) => r + (p, extractDefinedKeys(allSettings(p)))) } - private[this] def excludedError(transitive: Boolean, dependencies: List[AutoPlugin]): String = + private def excludedError(transitive: Boolean, dependencies: List[AutoPlugin]): String = str(dependencies)(excludedPluginError(transitive), excludedPluginsError(transitive)) - private[this] def excludedPluginError(transitive: Boolean)(dependency: AutoPlugin) = + private def excludedPluginError(transitive: Boolean)(dependency: AutoPlugin) = s"Required ${transitiveString(transitive)}dependency ${dependency.label} was excluded." - private[this] def excludedPluginsError(transitive: Boolean)(dependencies: List[AutoPlugin]) = + private def excludedPluginsError(transitive: Boolean)(dependencies: List[AutoPlugin]) = s"Required ${transitiveString(transitive)}dependencies were excluded:\n\t${labels(dependencies) .mkString("\n\t")}" - private[this] def transitiveString(transitive: Boolean) = + private def transitiveString(transitive: Boolean) = if (transitive) "(transitive) " else "" - private[this] def required(plugins: List[AutoPlugin]): String = + private def required(plugins: List[AutoPlugin]): String = str(plugins)(requiredPlugin, requiredPlugins) - private[this] def requiredPlugin(plugin: AutoPlugin) = + private def requiredPlugin(plugin: AutoPlugin) = s"Required plugin ${plugin.label} not present." - private[this] def requiredPlugins(plugins: List[AutoPlugin]) = + private def requiredPlugins(plugins: List[AutoPlugin]) = s"Required plugins not present:\n\t${plugins.map(_.label).mkString("\n\t")}" - private[this] def str[A](list: List[A])(f: A => String, fs: List[A] => String): String = + private def str[A](list: List[A])(f: A => String, fs: List[A] => String): String = list match { case Nil => "" case single :: Nil => f(single) case _ => fs(list) } - private[this] def willAdd(base: AutoPlugin, plugins: List[AutoPlugin]): String = + private def willAdd(base: AutoPlugin, plugins: List[AutoPlugin]): String = str(plugins)(willAddPlugin(base), willAddPlugins(base)) - private[this] def willAddPlugin(base: AutoPlugin)(plugin: AutoPlugin) = + private def willAddPlugin(base: AutoPlugin)(plugin: AutoPlugin) = s"Enabling ${base.label} will also enable ${plugin.label}" - private[this] def willAddPlugins(base: AutoPlugin)(plugins: List[AutoPlugin]) = + private def willAddPlugins(base: AutoPlugin)(plugins: List[AutoPlugin]) = s"Enabling ${base.label} will also enable:\n\t${labels(plugins).mkString("\n\t")}" - private[this] def willRemove(base: AutoPlugin, plugins: List[AutoPlugin]): String = + private def willRemove(base: AutoPlugin, plugins: List[AutoPlugin]): String = str(plugins)(willRemovePlugin(base), willRemovePlugins(base)) - private[this] def willRemovePlugin(base: AutoPlugin)(plugin: AutoPlugin) = + private def willRemovePlugin(base: AutoPlugin)(plugin: AutoPlugin) = s"Enabling ${base.label} will disable ${plugin.label}" - private[this] def willRemovePlugins(base: AutoPlugin)(plugins: List[AutoPlugin]) = + private def willRemovePlugins(base: AutoPlugin)(plugins: List[AutoPlugin]) = s"Enabling ${base.label} will disable:\n\t${labels(plugins).mkString("\n\t")}" - private[this] def labels(plugins: List[AutoPlugin]): List[String] = + private def labels(plugins: List[AutoPlugin]): List[String] = plugins.map(_.label) - private[this] def needToDeactivate(deactivate: List[DeactivatePlugin]): String = + private def needToDeactivate(deactivate: List[DeactivatePlugin]): String = str(deactivate)(deactivate1, deactivateN) - private[this] def deactivateN(plugins: List[DeactivatePlugin]): String = + private def deactivateN(plugins: List[DeactivatePlugin]): String = plugins.map(deactivateString).mkString("These plugins need to be deactivated:\n\t", "\n\t", "") - private[this] def deactivate1(deactivate: DeactivatePlugin): String = + private def deactivate1(deactivate: DeactivatePlugin): String = s"Need to deactivate ${deactivateString(deactivate)}" - private[this] def deactivateString(d: DeactivatePlugin): String = { + private def deactivateString(d: DeactivatePlugin): String = { val removePluginsString: String = d.removeOneOf.toList match { case Nil => "" @@ -509,10 +509,10 @@ private[sbt] object PluginsDebug { s"${d.plugin.label}: directly exclude it${removePluginsString}" } - private[this] def pluginImpossible(plugin: AutoPlugin, contradictions: Set[AutoPlugin]): String = + private def pluginImpossible(plugin: AutoPlugin, contradictions: Set[AutoPlugin]): String = str(contradictions.toList)(pluginImpossible1(plugin), pluginImpossibleN(plugin)) - private[this] def pluginImpossible1(plugin: AutoPlugin)(contradiction: AutoPlugin): String = { + private def pluginImpossible1(plugin: AutoPlugin)(contradiction: AutoPlugin): String = { val s1 = s"There is no way to enable plugin ${plugin.label}." val s2 = s"It (or its dependencies) requires plugin ${contradiction.label} to both be present and absent." @@ -520,7 +520,7 @@ private[sbt] object PluginsDebug { s"$s1 $s2 $s3" } - private[this] def pluginImpossibleN( + private def pluginImpossibleN( plugin: AutoPlugin )(contradictions: List[AutoPlugin]): String = { val s1 = s"There is no way to enable plugin ${plugin.label}." diff --git a/main/src/main/scala/sbt/internal/SessionSettings.scala b/main/src/main/scala/sbt/internal/SessionSettings.scala index 6e690c048..9b419c935 100755 --- a/main/src/main/scala/sbt/internal/SessionSettings.scala +++ b/main/src/main/scala/sbt/internal/SessionSettings.scala @@ -88,10 +88,10 @@ final case class SessionSettings( */ def clearExtraSettings: SessionSettings = copy(append = Map.empty, rawAppend = Nil) - private[this] def merge(map: SessionMap): Seq[Setting[_]] = + private def merge(map: SessionMap): Seq[Setting[_]] = map.values.toSeq.flatten[SessionSetting].map(_._1) - private[this] def modify( + private def modify( map: SessionMap, onSeq: Seq[SessionSetting] => Seq[SessionSetting], ): SessionMap = { diff --git a/main/src/main/scala/sbt/internal/SettingCompletions.scala b/main/src/main/scala/sbt/internal/SettingCompletions.scala index 4688cf03f..7b16a260b 100644 --- a/main/src/main/scala/sbt/internal/SettingCompletions.scala +++ b/main/src/main/scala/sbt/internal/SettingCompletions.scala @@ -86,7 +86,7 @@ private[sbt] object SettingCompletions { setResult(newSession, r, append) } - private[this] def setResult( + private def setResult( session: SessionSettings, r: Relation[ScopedKey[_], ScopedKey[_]], redefined: Seq[Setting[_]], @@ -97,7 +97,7 @@ private[sbt] object SettingCompletions { new SetResult(session, summary(true), summary(false)) } - private[this] def setSummary( + private def setSummary( redefined: Set[ScopedKey[_]], affected: Set[ScopedKey[_]], verbose: Boolean, @@ -206,7 +206,7 @@ private[sbt] object SettingCompletions { scope(allScopes, definedScopes, context) } - private[this] def scope( + private def scope( allScopes: Seq[Scope], definedScopes: Seq[Scope], context: ResolvedProject, @@ -258,10 +258,10 @@ private[sbt] object SettingCompletions { token(Space) ~> token(optionallyQuoted(identifier), completions) } - private[this] def fixedCompletions(f: (String, Int) => Set[Completion]): TokenCompletions = + private def fixedCompletions(f: (String, Int) => Set[Completion]): TokenCompletions = TokenCompletions.fixed((s, l) => Completions(f(s, l))) - private[this] def scalaID[T](keyMap: Map[String, T], label: String): Parser[T] = { + private def scalaID[T](keyMap: Map[String, T], label: String): Parser[T] = { val identifier = Act.filterStrings(ScalaID, keyMap.keySet, label) map keyMap optionallyQuoted(identifier) } diff --git a/main/src/main/scala/sbt/internal/ShutdownHooks.scala b/main/src/main/scala/sbt/internal/ShutdownHooks.scala index 411d42095..6bd53982c 100644 --- a/main/src/main/scala/sbt/internal/ShutdownHooks.scala +++ b/main/src/main/scala/sbt/internal/ShutdownHooks.scala @@ -14,13 +14,13 @@ import java.util.concurrent.atomic.{ AtomicBoolean, AtomicInteger } import scala.util.control.NonFatal private[sbt] object ShutdownHooks extends AutoCloseable { - private[this] val idGenerator = new AtomicInteger(0) - private[this] val hooks = new ConcurrentHashMap[Int, () => Unit] - private[this] val ranHooks = new AtomicBoolean(false) - private[this] val thread = new Thread("shutdown-hooks-run-all") { + private val idGenerator = new AtomicInteger(0) + private val hooks = new ConcurrentHashMap[Int, () => Unit] + private val ranHooks = new AtomicBoolean(false) + private val thread = new Thread("shutdown-hooks-run-all") { override def run(): Unit = runAll() } - private[this] val runtime = Runtime.getRuntime + private val runtime = Runtime.getRuntime runtime.addShutdownHook(thread) private[sbt] def add[R](task: () => R): AutoCloseable = { val id = idGenerator.getAndIncrement() diff --git a/main/src/main/scala/sbt/internal/SysProp.scala b/main/src/main/scala/sbt/internal/SysProp.scala index fa24f7e81..e7e384795 100644 --- a/main/src/main/scala/sbt/internal/SysProp.scala +++ b/main/src/main/scala/sbt/internal/SysProp.scala @@ -202,8 +202,8 @@ object SysProp { def serverUseJni = getOrFalse("sbt.ipcsocket.jni") - private[this] def file(value: String): File = new File(value) - private[this] def home: File = file(sys.props("user.home")) + private def file(value: String): File = new File(value) + private def home: File = file(sys.props("user.home")) /** * Operating system specific cache directory, similar to Coursier cache. @@ -253,11 +253,11 @@ object SysProp { runtimeDirectory.resolve("ipcsocket").toString ) } - private[this] lazy val getOrUpdateSwovalTmpDir: String => String = + private lazy val getOrUpdateSwovalTmpDir: String => String = getOrUpdateSysProp("swoval.tmpdir")(_) - private[this] lazy val getOrUpdateIpcSocketTmpDir: String => String = + private lazy val getOrUpdateIpcSocketTmpDir: String => String = getOrUpdateSysProp("sbt.ipcsocket.tmpdir")(_) - private[this] def getOrUpdateSysProp(key: String)(value: String): String = { + private def getOrUpdateSysProp(key: String)(value: String): String = { val newVal = sys.props.getOrElse(key, value) sys.props += (key -> newVal) newVal @@ -271,7 +271,7 @@ object SysProp { * A deterministic hash is appended in the directory name as "/tmp/.sbt1234ABCD/" * to avoid collision between multiple users in a shared server environment. */ - private[this] def runtimeDirectory: Path = { + private def runtimeDirectory: Path = { val hashValue = java.lang.Long.toHexString(HashUtil.farmHash(home.toString.getBytes("UTF-8"))) val halfhash = hashValue.take(8) diff --git a/main/src/main/scala/sbt/internal/TaskProgress.scala b/main/src/main/scala/sbt/internal/TaskProgress.scala index f9550e0b1..87dc035b9 100644 --- a/main/src/main/scala/sbt/internal/TaskProgress.scala +++ b/main/src/main/scala/sbt/internal/TaskProgress.scala @@ -29,14 +29,14 @@ private[sbt] class TaskProgress( ) extends AbstractTaskExecuteProgress with ExecuteProgress with AutoCloseable { - private[this] val lastTaskCount = new AtomicInteger(0) - private[this] val reportLoop = new AtomicReference[AutoCloseable] - private[this] val active = new ConcurrentHashMap[TaskId[_], AutoCloseable] - private[this] val nextReport = new AtomicReference(Deadline.now) - private[this] val scheduler = + private val lastTaskCount = new AtomicInteger(0) + private val reportLoop = new AtomicReference[AutoCloseable] + private val active = new ConcurrentHashMap[TaskId[_], AutoCloseable] + private val nextReport = new AtomicReference(Deadline.now) + private val scheduler = Executors.newSingleThreadScheduledExecutor(r => new Thread(r, "sbt-progress-report-scheduler")) - private[this] val pending = new java.util.Vector[java.util.concurrent.Future[_]] - private[this] val closed = new AtomicBoolean(false) + private val pending = new java.util.Vector[java.util.concurrent.Future[_]] + private val closed = new AtomicBoolean(false) private def schedule[R](duration: FiniteDuration, recurring: Boolean)(f: => R): AutoCloseable = if (!closed.get) { val cancelled = new AtomicBoolean(false) @@ -63,7 +63,7 @@ private[sbt] class TaskProgress( logger.debug("tried to call schedule on closed TaskProgress") () => () } - private[this] val executor = + private val executor = Executors.newSingleThreadExecutor(r => new Thread(r, "sbt-task-progress-report-thread")) override def close(): Unit = if (closed.compareAndSet(false, true)) { Option(reportLoop.getAndSet(null)).foreach(_.close()) @@ -83,7 +83,7 @@ private[sbt] class TaskProgress( override protected def clearTimings: Boolean = true override def initial(): Unit = () - private[this] def doReport(): Unit = { + private def doReport(): Unit = { val runnable: Runnable = () => { if (nextReport.get.isOverdue) { report() @@ -141,7 +141,7 @@ private[sbt] class TaskProgress( // send an empty progress report to clear out the previous report appendProgress(ProgressEvent("Info", Vector(), Some(lastTaskCount.get), None, None)) } - private[this] val skipReportTasks = + private val skipReportTasks = Set( "installSbtn", "run", @@ -156,13 +156,13 @@ private[sbt] class TaskProgress( "streams", "streams-manager", ) - private[this] val hiddenTasks = Set( + private val hiddenTasks = Set( "compileEarly", "pickleProducts", ) - private[this] def appendProgress(event: ProgressEvent): Unit = + private def appendProgress(event: ProgressEvent): Unit = StandardMain.exchange.updateProgress(event) - private[this] def report(): Unit = { + private def report(): Unit = { val (currentTasks, skip) = filter(timings(active.keySet, threshold.toMicros)) val ltc = lastTaskCount.get if (currentTasks.nonEmpty || ltc != 0) { @@ -190,7 +190,7 @@ private[sbt] class TaskProgress( } } - private[this] def getShortName(task: TaskId[_]): String = { + private def getShortName(task: TaskId[_]): String = { val name = taskName(task) name.lastIndexOf('/') match { case -1 => name @@ -201,7 +201,7 @@ private[sbt] class TaskProgress( } } - private[this] def filter( + private def filter( tasks: Vector[(TaskId[_], Long)] ): (Vector[(TaskId[_], Long)], Boolean) = { tasks.foldLeft((Vector.empty[(TaskId[_], Long)], false)) { diff --git a/main/src/main/scala/sbt/internal/TaskTimings.scala b/main/src/main/scala/sbt/internal/TaskTimings.scala index e636b218a..73f7c261f 100644 --- a/main/src/main/scala/sbt/internal/TaskTimings.scala +++ b/main/src/main/scala/sbt/internal/TaskTimings.scala @@ -36,10 +36,10 @@ private[sbt] final class TaskTimings(reportOnShutdown: Boolean, logger: Logger) ConsoleOut.systemOut.println(message) } ) - private[this] var start = 0L - private[this] val threshold = SysProp.taskTimingsThreshold - private[this] val omitPaths = SysProp.taskTimingsOmitPaths - private[this] val (unit, divider) = SysProp.taskTimingsUnit + private var start = 0L + private val threshold = SysProp.taskTimingsThreshold + private val omitPaths = SysProp.taskTimingsOmitPaths + private val (unit, divider) = SysProp.taskTimingsUnit if (reportOnShutdown) { start = System.nanoTime @@ -60,9 +60,9 @@ private[sbt] final class TaskTimings(reportOnShutdown: Boolean, logger: Logger) override def stop(): Unit = () - private[this] val reFilePath = raw"\{[^}]+\}".r + private val reFilePath = raw"\{[^}]+\}".r - private[this] def report() = { + private def report() = { val total = divide(System.nanoTime - start) logger.info(s"Total time: $total $unit") val times = timingsByName.toSeq @@ -82,7 +82,7 @@ private[sbt] final class TaskTimings(reportOnShutdown: Boolean, logger: Logger) } } - private[this] def divide(time: Long) = (1L to divider.toLong).fold(time) { (a, b) => + private def divide(time: Long) = (1L to divider.toLong).fold(time) { (a, b) => a / 10L } } diff --git a/main/src/main/scala/sbt/internal/TaskTraceEvent.scala b/main/src/main/scala/sbt/internal/TaskTraceEvent.scala index f4c34266b..a5a054fe0 100644 --- a/main/src/main/scala/sbt/internal/TaskTraceEvent.scala +++ b/main/src/main/scala/sbt/internal/TaskTraceEvent.scala @@ -24,8 +24,8 @@ import sjsonnew.support.scalajson.unsafe.CompactPrinter */ private[sbt] final class TaskTraceEvent extends AbstractTaskExecuteProgress with ExecuteProgress { import AbstractTaskExecuteProgress.Timer - private[this] var start = 0L - private[this] val console = ConsoleOut.systemOut + private var start = 0L + private val console = ConsoleOut.systemOut override def initial(): Unit = () override def afterReady(task: TaskId[?]): Unit = () @@ -36,13 +36,13 @@ private[sbt] final class TaskTraceEvent extends AbstractTaskExecuteProgress with start = System.nanoTime ShutdownHooks.add(() => report()) - private[this] def report() = { + private def report() = { if (anyTimings) { writeTraceEvent() } } - private[this] def writeTraceEvent(): Unit = { + private def writeTraceEvent(): Unit = { // import java.time.{ ZonedDateTime, ZoneOffset } // import java.time.format.DateTimeFormatter // val fileName = "build-" + ZonedDateTime diff --git a/main/src/main/scala/sbt/internal/VirtualFileValueCache.scala b/main/src/main/scala/sbt/internal/VirtualFileValueCache.scala index fd3121c13..6836e1b0b 100644 --- a/main/src/main/scala/sbt/internal/VirtualFileValueCache.scala +++ b/main/src/main/scala/sbt/internal/VirtualFileValueCache.scala @@ -50,13 +50,13 @@ object VirtualFileValueCache { new VirtualFileValueCache0[A](stamp, f)(using Equiv.universal) } -private[this] final class VirtualFileValueCache0[A]( +private final class VirtualFileValueCache0[A]( getStamp: VirtualFile => XStamp, make: VirtualFile => A )(implicit equiv: Equiv[XStamp] ) extends VirtualFileValueCache[A] { - private[this] val backing = new ConcurrentHashMap[VirtualFile, VirtualFileCache] + private val backing = new ConcurrentHashMap[VirtualFile, VirtualFileCache] def clear(): Unit = backing.clear() def get = file => { @@ -65,8 +65,8 @@ private[this] final class VirtualFileValueCache0[A]( (if (cache eq null) ifAbsent else cache).get() } - private[this] final class VirtualFileCache(file: VirtualFile) { - private[this] var stampedValue: Option[(XStamp, A)] = None + private final class VirtualFileCache(file: VirtualFile) { + private var stampedValue: Option[(XStamp, A)] = None def get(): A = synchronized { val latest = getStamp(file) stampedValue match { @@ -75,7 +75,7 @@ private[this] final class VirtualFileValueCache0[A]( } } - private[this] def update(stamp: XStamp): A = { + private def update(stamp: XStamp): A = { val value = make(file) stampedValue = Some((stamp, value)) value diff --git a/main/src/main/scala/sbt/internal/WatchTransitiveDependencies.scala b/main/src/main/scala/sbt/internal/WatchTransitiveDependencies.scala index cfc0e832e..7729b4061 100644 --- a/main/src/main/scala/sbt/internal/WatchTransitiveDependencies.scala +++ b/main/src/main/scala/sbt/internal/WatchTransitiveDependencies.scala @@ -234,7 +234,7 @@ private[sbt] object WatchTransitiveDependencies { } case _ => accumulator.toIndexedSeq } - private[this] def isGlobKey(key: ScopedKey[_]): Boolean = key.key match { + private def isGlobKey(key: ScopedKey[_]): Boolean = key.key match { case fileInputs.key | watchTriggers.key => true case _ => false } diff --git a/main/src/main/scala/sbt/internal/librarymanagement/IvyXml.scala b/main/src/main/scala/sbt/internal/librarymanagement/IvyXml.scala index 3723f0415..b6872e23f 100644 --- a/main/src/main/scala/sbt/internal/librarymanagement/IvyXml.scala +++ b/main/src/main/scala/sbt/internal/librarymanagement/IvyXml.scala @@ -217,7 +217,7 @@ object IvyXml { "makeIvyXmlConfiguration" ) - private[this] def getPubConf(method: String): List[TaskKey[PublishConfiguration]] = + private def getPubConf(method: String): List[TaskKey[PublishConfiguration]] = try { val cls = sbt.Keys.getClass val m = cls.getMethod(method) diff --git a/main/src/main/scala/sbt/internal/server/Definition.scala b/main/src/main/scala/sbt/internal/server/Definition.scala index 8768f5871..041b6dc47 100644 --- a/main/src/main/scala/sbt/internal/server/Definition.scala +++ b/main/src/main/scala/sbt/internal/server/Definition.scala @@ -162,7 +162,7 @@ private[sbt] object Definition { Converter.fromJson[TextDocumentPositionParams](jsonDefinition).toOption } - private[this] val AnalysesKey = "lsp.definition.analyses.key" + private val AnalysesKey = "lsp.definition.analyses.key" private[server] type Analyses = Set[((String, Boolean, Boolean), Option[Analysis])] private def storeAnalysis( diff --git a/main/src/main/scala/sbt/internal/server/NetworkChannel.scala b/main/src/main/scala/sbt/internal/server/NetworkChannel.scala index 303501344..6af553be7 100644 --- a/main/src/main/scala/sbt/internal/server/NetworkChannel.scala +++ b/main/src/main/scala/sbt/internal/server/NetworkChannel.scala @@ -87,12 +87,12 @@ final class NetworkChannel( private var initialized = false private val pendingRequests: mutable.Map[String, JsonRpcRequestMessage] = mutable.Map() - private[this] val inputBuffer = new LinkedBlockingQueue[Int]() - private[this] val pendingWrites = new LinkedBlockingQueue[(Array[Byte], Boolean)]() - private[this] val attached = new AtomicBoolean(false) - private[this] val alive = new AtomicBoolean(true) + private val inputBuffer = new LinkedBlockingQueue[Int]() + private val pendingWrites = new LinkedBlockingQueue[(Array[Byte], Boolean)]() + private val attached = new AtomicBoolean(false) + private val alive = new AtomicBoolean(true) private[sbt] def isInteractive = interactive.get - private[this] val interactive = new AtomicBoolean(false) + private val interactive = new AtomicBoolean(false) private[sbt] def setInteractive(id: String, value: Boolean) = { terminalHolder.getAndSet(new NetworkTerminal) match { case null => @@ -111,7 +111,7 @@ final class NetworkChannel( } private[sbt] def write(byte: Byte) = inputBuffer.add(byte.toInt) - private[this] val terminalHolder = new AtomicReference[Terminal](Terminal.NullTerminal) + private val terminalHolder = new AtomicReference[Terminal](Terminal.NullTerminal) override private[sbt] def terminal: Terminal = terminalHolder.get override val userThread: UserThread = new UserThread(this) @@ -338,7 +338,7 @@ final class NetworkChannel( /* * Do writes on a background thread because otherwise the client socket can get blocked. */ - private[this] val writeThread = new Thread( + private val writeThread = new Thread( () => { @tailrec def impl(): Unit = { val (event, delimit) = @@ -653,7 +653,7 @@ final class NetworkChannel( ) } - private[this] lazy val inputStream: InputStream = new Terminal.SimpleInputStream { + private lazy val inputStream: InputStream = new Terminal.SimpleInputStream { override def read(): Int = { import sjsonnew.BasicJsonProtocol._ try { @@ -668,27 +668,27 @@ final class NetworkChannel( } override def available(): Int = inputBuffer.size } - private[this] lazy val writeableInputStream: Terminal.WriteableInputStream = + private lazy val writeableInputStream: Terminal.WriteableInputStream = new Terminal.WriteableInputStream(inputStream, name) import sjsonnew.BasicJsonProtocol._ import scala.jdk.CollectionConverters.* - private[this] val outputBuffer = new LinkedBlockingQueue[Byte] - private[this] val flushExecutor = Executors.newSingleThreadScheduledExecutor(r => + private val outputBuffer = new LinkedBlockingQueue[Byte] + private val flushExecutor = Executors.newSingleThreadScheduledExecutor(r => new Thread(r, s"$name-output-buffer-timer-thread") ) - private[this] def forceFlush(): Unit = + private def forceFlush(): Unit = Util.ignoreResult(flushExecutor.shutdownNow()) doFlush() - private[this] def doFlush() = { + private def doFlush() = { val list = new java.util.ArrayList[Byte] outputBuffer.synchronized(outputBuffer.drainTo(list)) if (!list.isEmpty) jsonRpcNotify(Serialization.systemOut, list.asScala.toSeq) } - private[this] lazy val outputStream: OutputStream with AutoCloseable = new OutputStream + private lazy val outputStream: OutputStream with AutoCloseable = new OutputStream with AutoCloseable { /* * We buffer calls to flush to the remote client so that it is called at most @@ -701,7 +701,7 @@ final class NetworkChannel( * probably long enough to catch each burst but short enough to not introduce * noticeable latency. */ - private[this] val flushFuture = new AtomicReference[java.util.concurrent.Future[_]] + private val flushFuture = new AtomicReference[java.util.concurrent.Future[_]] override def close(): Unit = { forceFlush() } @@ -733,8 +733,8 @@ final class NetworkChannel( write(java.util.Arrays.copyOfRange(b, off, off + len)) } } - private[this] lazy val errorStream: OutputStream = new OutputStream { - private[this] val buffer = new LinkedBlockingQueue[Byte] + private lazy val errorStream: OutputStream = new OutputStream { + private val buffer = new LinkedBlockingQueue[Byte] override def write(b: Int): Unit = buffer.synchronized { buffer.put(b.toByte) } @@ -752,10 +752,10 @@ final class NetworkChannel( } private class NetworkTerminal extends TerminalImpl(writeableInputStream, outputStream, errorStream, name) { term => - private[this] val pending = new AtomicBoolean(false) - private[this] val closed = new AtomicBoolean(false) - private[this] val properties = new AtomicReference[TerminalPropertiesResponse] - private[this] val lastUpdate = new AtomicReference[Deadline] + private val pending = new AtomicBoolean(false) + private val closed = new AtomicBoolean(false) + private val properties = new AtomicReference[TerminalPropertiesResponse] + private val lastUpdate = new AtomicReference[Deadline] private def empty = TerminalPropertiesResponse(0, 0, false, false, false, false) def getProperties(block: Boolean): Unit = { if (alive.get) { @@ -802,7 +802,7 @@ final class NetworkChannel( None ) } - private[this] def waitForPending(f: TerminalPropertiesResponse => Boolean): Boolean = { + private def waitForPending(f: TerminalPropertiesResponse => Boolean): Boolean = { if (closed.get || !isAttached) false else withThread( @@ -813,7 +813,7 @@ final class NetworkChannel( false ) } - private[this] val blockedThreads = ConcurrentHashMap.newKeySet[Thread] + private val blockedThreads = ConcurrentHashMap.newKeySet[Thread] override private[sbt] val progressState: ProgressState = new ProgressState( 1, StandardMain.exchange @@ -917,7 +917,7 @@ final class NetworkChannel( try queue.take catch { case _: InterruptedException => } } - private[this] def setRawMode(toggle: Boolean): Unit = { + private def setRawMode(toggle: Boolean): Unit = { if (!closed.get || false) { val raw = TerminalSetRawModeCommand(toggle) val queue = VirtualTerminal.setTerminalRawMode( diff --git a/main/src/main/scala/sbt/internal/server/VirtualTerminal.scala b/main/src/main/scala/sbt/internal/server/VirtualTerminal.scala index 7423ce5a9..0648078f6 100644 --- a/main/src/main/scala/sbt/internal/server/VirtualTerminal.scala +++ b/main/src/main/scala/sbt/internal/server/VirtualTerminal.scala @@ -47,21 +47,21 @@ import sbt.protocol.{ import sbt.protocol.codec.JsonProtocol._ object VirtualTerminal { - private[this] val pendingTerminalProperties = + private val pendingTerminalProperties = new ConcurrentHashMap[(String, String), ArrayBlockingQueue[TerminalPropertiesResponse]]() - private[this] val pendingTerminalCapabilities = + private val pendingTerminalCapabilities = new ConcurrentHashMap[(String, String), ArrayBlockingQueue[TerminalCapabilitiesResponse]] - private[this] val pendingTerminalAttributes = + private val pendingTerminalAttributes = new ConcurrentHashMap[(String, String), ArrayBlockingQueue[TerminalAttributesResponse]] - private[this] val pendingTerminalSetAttributes = + private val pendingTerminalSetAttributes = new ConcurrentHashMap[(String, String), ArrayBlockingQueue[Unit]] - private[this] val pendingTerminalSetSize = + private val pendingTerminalSetSize = new ConcurrentHashMap[(String, String), ArrayBlockingQueue[Unit]] - private[this] val pendingTerminalGetSize = + private val pendingTerminalGetSize = new ConcurrentHashMap[(String, String), ArrayBlockingQueue[TerminalGetSizeResponse]] - private[this] val pendingTerminalSetEcho = + private val pendingTerminalSetEcho = new ConcurrentHashMap[(String, String), ArrayBlockingQueue[Unit]] - private[this] val pendingTerminalSetRawMode = + private val pendingTerminalSetRawMode = new ConcurrentHashMap[(String, String), ArrayBlockingQueue[Unit]] private[sbt] def sendTerminalPropertiesQuery( channelName: String, diff --git a/main/src/main/scala/sbt/nio/CheckBuildSources.scala b/main/src/main/scala/sbt/nio/CheckBuildSources.scala index 83522f849..a8cf3dabc 100644 --- a/main/src/main/scala/sbt/nio/CheckBuildSources.scala +++ b/main/src/main/scala/sbt/nio/CheckBuildSources.scala @@ -45,12 +45,12 @@ import scala.io.AnsiColor * the build files if the poll interval has elapsed. */ private[sbt] class CheckBuildSources extends AutoCloseable { - private[this] val repository = new AtomicReference[FileTreeRepository[FileAttributes]] - private[this] val pollingPeriod = new AtomicReference[FiniteDuration] - private[this] val sources = new AtomicReference[Seq[Glob]](Nil) - private[this] val needUpdate = new AtomicBoolean(true) - private[this] val lastPolled = new AtomicReference[SDeadline](SDeadline.now) - private[this] val previousStamps = new AtomicReference[Seq[(Path, FileStamp)]] + private val repository = new AtomicReference[FileTreeRepository[FileAttributes]] + private val pollingPeriod = new AtomicReference[FiniteDuration] + private val sources = new AtomicReference[Seq[Glob]](Nil) + private val needUpdate = new AtomicBoolean(true) + private val lastPolled = new AtomicReference[SDeadline](SDeadline.now) + private val previousStamps = new AtomicReference[Seq[(Path, FileStamp)]] private[sbt] def fileTreeRepository: Option[FileTreeRepository[FileAttributes]] = Option(repository.get) private def getStamps(force: Boolean) = { diff --git a/main/src/main/scala/sbt/nio/FileStamp.scala b/main/src/main/scala/sbt/nio/FileStamp.scala index 6e8ddaf3a..05f00d374 100644 --- a/main/src/main/scala/sbt/nio/FileStamp.scala +++ b/main/src/main/scala/sbt/nio/FileStamp.scala @@ -100,7 +100,7 @@ object FileStamp { case 0 => None case l => Some(LastModified(l)) } - private[this] class FileHashImpl(val xstamp: XStamp) extends Hash(xstamp.toString) + private class FileHashImpl(val xstamp: XStamp) extends Hash(xstamp.toString) private[sbt] sealed abstract case class Hash private[sbt] (hex: String) extends FileStamp private[sbt] final case class LastModified private[sbt] (time: Long) extends FileStamp private[sbt] final case class Error(exception: IOException) extends FileStamp @@ -253,7 +253,7 @@ object FileStamp { } private[sbt] class Cache { - private[this] val underlying = new ConcurrentHashMap[Path, Either[FileStamp, FileStamp]] + private val underlying = new ConcurrentHashMap[Path, Either[FileStamp, FileStamp]] /** * Invalidate the cache entry, but don't re-stamp the file until it's actually used diff --git a/main/src/main/scala/sbt/nio/Keys.scala b/main/src/main/scala/sbt/nio/Keys.scala index 168996fa9..122eac1b9 100644 --- a/main/src/main/scala/sbt/nio/Keys.scala +++ b/main/src/main/scala/sbt/nio/Keys.scala @@ -78,7 +78,7 @@ object Keys { val watchDeletionQuarantinePeriod = settingKey[FiniteDuration]( "Period for which deletion events will be quarantined. This is to prevent spurious builds when a file is updated with a rename which manifests as a file deletion followed by a file creation. The higher this value is set, the longer the delay will be between a file deletion and a build trigger but the less likely it is for a spurious trigger." ).withRank(DSetting) - private[this] val forceTriggerOnAnyChangeMessage = + private val forceTriggerOnAnyChangeMessage = "Force the watch process to rerun the current task(s) if any relevant source change is " + "detected regardless of whether or not the underlying file has actually changed." @@ -182,7 +182,7 @@ object Keys { taskKey[Seq[Path]]("The dependency classpath for a task.").withRank(Invisible) private[sbt] val compileOutputs = taskKey[Seq[Path]]("Compilation outputs").withRank(Invisible) - private[this] val hasCheckedMetaBuildMsg = + private val hasCheckedMetaBuildMsg = "Indicates whether or not we have called the checkBuildSources task. This is to avoid warning " + "user about build source changes if the build sources were changed while sbt was shutdown. " + " When that occurs, the previous cache reflects the state of the old build files, but by " + diff --git a/main/src/main/scala/sbt/nio/Settings.scala b/main/src/main/scala/sbt/nio/Settings.scala index b4cc96a72..e68ee9905 100644 --- a/main/src/main/scala/sbt/nio/Settings.scala +++ b/main/src/main/scala/sbt/nio/Settings.scala @@ -68,7 +68,7 @@ private[sbt] object Settings { * @return the injected settings */ @nowarn - private[this] def maybeAddOutputsAndFileStamps( + private def maybeAddOutputsAndFileStamps( setting: Def.Setting[_], fileOutputScopes: Set[Scope] ): List[Def.Setting[_]] = { @@ -144,7 +144,7 @@ private[sbt] object Settings { * @tparam T the generic type of the task (needed for type checking because [[Task]] is invariant) * @return the setting with the task definition */ - private[this] def addTaskDefinition[T](setting: Def.Setting[Task[T]]): Def.Setting[Task[T]] = + private def addTaskDefinition[T](setting: Def.Setting[Task[T]]): Def.Setting[Task[T]] = setting.mapInit((sk, task) => Task(task.info.set(taskDefinitionKey, sk), task.work)) /** @@ -174,8 +174,8 @@ private[sbt] object Settings { }) :: fileStamps(scopedKey) :: allFilesImpl(scope) :: changedInputFilesImpl(scope) } - private[this] val seqClass = classOf[Seq[_]] - private[this] val pathClass = classOf[Path] + private val seqClass = classOf[Seq[_]] + private val pathClass = classOf[Path] private val fileClass = classOf[File] private val virtualFileRefClass = classOf[VirtualFileRef] @@ -186,7 +186,7 @@ private[sbt] object Settings { * @param scope the key whose file inputs we are seeking * @return a task definition that retrieves all of the input paths scoped to the input key. */ - private[this] def allFilesImpl(scope: Scope): Def.Setting[_] = { + private def allFilesImpl(scope: Scope): Def.Setting[_] = { addTaskDefinition(scope / Keys.allInputFiles := { val filter = (scope / fileInputIncludeFilter).value && !(scope / fileInputExcludeFilter).value @@ -205,7 +205,7 @@ private[sbt] object Settings { * @param scope the scope corresponding to the task whose fileInputs we are seeking * @return a task definition that retrieves the changed input files scoped to the key. */ - private[this] def changedInputFilesImpl(scope: Scope): List[Def.Setting[_]] = + private def changedInputFilesImpl(scope: Scope): List[Def.Setting[_]] = changedFilesImpl(scope, changedInputFiles, inputFileStamps) :: (scope / watchForceTriggerOnAnyChange := { (scope / watchForceTriggerOnAnyChange).?.value match { @@ -214,7 +214,7 @@ private[sbt] object Settings { } }) :: Nil - private[this] def changedFilesImpl( + private def changedFilesImpl( scope: Scope, changeKey: TaskKey[Seq[(Path, FileStamp)] => FileChanges], stampKey: TaskKey[Seq[(Path, FileStamp)]] @@ -325,7 +325,7 @@ private[sbt] object Settings { } @nowarn - private[this] def outputsAndStamps[T: JsonFormat: ToSeqPath]( + private def outputsAndStamps[T: JsonFormat: ToSeqPath]( taskKey: TaskKey[T] ): List[Def.Setting[_]] = { val scope = taskKey.scope.rescope(taskKey.key) @@ -333,7 +333,7 @@ private[sbt] object Settings { allOutputPathsImpl(scope) :: outputFileStampsImpl(scope) :: cleanImpl(taskKey) :: changes } - private[this] def allOutputPathsImpl(scope: Scope): Def.Setting[_] = + private def allOutputPathsImpl(scope: Scope): Def.Setting[_] = addTaskDefinition(scope / allOutputFiles := { val filter = (scope / fileOutputIncludeFilter).value && !(scope / fileOutputExcludeFilter).value @@ -359,7 +359,7 @@ private[sbt] object Settings { } }) - private[this] def outputFileStampsImpl(scope: Scope): Def.Setting[_] = + private def outputFileStampsImpl(scope: Scope): Def.Setting[_] = addTaskDefinition(scope / outputFileStamps := { val stamper: Path => Option[FileStamp] = (scope / outputFileStamper).value match { case LastModified => FileStamp.lastModified diff --git a/main/src/main/scala/sbt/nio/Watch.scala b/main/src/main/scala/sbt/nio/Watch.scala index ab32086ac..af23a081a 100644 --- a/main/src/main/scala/sbt/nio/Watch.scala +++ b/main/src/main/scala/sbt/nio/Watch.scala @@ -50,10 +50,10 @@ object Watch { */ def occurredAt: FiniteDuration } - private[this] val formatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss.SSS") - private[this] val timeZone = ZoneId.systemDefault - private[this] val timeZoneName = timeZone.getDisplayName(TextStyle.SHORT, Locale.getDefault) - private[this] implicit class DurationOps(val d: Duration) extends AnyVal { + private val formatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss.SSS") + private val timeZone = ZoneId.systemDefault + private val timeZoneName = timeZone.getDisplayName(TextStyle.SHORT, Locale.getDefault) + private implicit class DurationOps(val d: Duration) extends AnyVal { def finite: FiniteDuration = d match { case f: FiniteDuration => f case _ => new FiniteDuration(Long.MaxValue, TimeUnit.MILLISECONDS) diff --git a/main/src/test/scala/TagsTest.scala b/main/src/test/scala/TagsTest.scala index 071a69515..585302069 100644 --- a/main/src/test/scala/TagsTest.scala +++ b/main/src/test/scala/TagsTest.scala @@ -47,6 +47,6 @@ object TagsTest extends Properties("Tags") { excl(etag)(tm) } - private[this] def excl(tag: Tag): TagMap => Boolean = predicate(exclusive(tag) :: Nil) + private def excl(tag: Tag): TagMap => Boolean = predicate(exclusive(tag) :: Nil) } diff --git a/main/src/test/scala/sbt/internal/InstallSbtnSpec.scala b/main/src/test/scala/sbt/internal/InstallSbtnSpec.scala index a5d6b8cdc..0d7cbd0e8 100644 --- a/main/src/test/scala/sbt/internal/InstallSbtnSpec.scala +++ b/main/src/test/scala/sbt/internal/InstallSbtnSpec.scala @@ -26,7 +26,7 @@ class InstallSbtnSpec extends AnyFlatSpec { () } } - private[this] val term = new Terminal { + private val term = new Terminal { def getHeight: Int = 0 def getWidth: Int = 0 def inputStream: InputStream = () => -1 diff --git a/run/src/main/scala/sbt/Fork.scala b/run/src/main/scala/sbt/Fork.scala index 0e2356fb7..abf6effa3 100644 --- a/run/src/main/scala/sbt/Fork.scala +++ b/run/src/main/scala/sbt/Fork.scala @@ -82,7 +82,7 @@ final class Fork(val commandName: String, val runnerClass: Option[String]) { case out: CustomOutput => (process #> out.output).run(connectInput = false) } } - private[this] def makeOptions( + private def makeOptions( jvmOptions: Seq[String], bootJars: Iterable[File], arguments: Seq[String] @@ -105,26 +105,26 @@ object Fork { val scalac = new Fork(JavaCommandName, Some(ScalacMainClass)) private val ClasspathEnvKey = "CLASSPATH" - private[this] val ClasspathOptionLong = "-classpath" - private[this] val ClasspathOptionShort = "-cp" - private[this] def isClasspathOption(s: String) = + private val ClasspathOptionLong = "-classpath" + private val ClasspathOptionShort = "-cp" + private def isClasspathOption(s: String) = s == ClasspathOptionLong || s == ClasspathOptionShort /** * Maximum length of classpath string before passing the classpath in an environment variable * instead of an option. */ - private[this] val MaxConcatenatedOptionLength = 5000 + private val MaxConcatenatedOptionLength = 5000 private def fitClasspath(options: Seq[String]): (Option[String], Seq[String]) = if (Util.isWindows && optionsTooLong(options)) convertClasspathToEnv(options) else (None, options) - private[this] def optionsTooLong(options: Seq[String]): Boolean = + private def optionsTooLong(options: Seq[String]): Boolean = options.mkString(" ").length > MaxConcatenatedOptionLength - private[this] def convertClasspathToEnv(options: Seq[String]): (Option[String], Seq[String]) = { + private def convertClasspathToEnv(options: Seq[String]): (Option[String], Seq[String]) = { val (preCP, cpAndPost) = options.span(opt => !isClasspathOption(opt)) val postCP = cpAndPost.drop(2) val classpathOption = cpAndPost.drop(1).headOption diff --git a/run/src/main/scala/sbt/OutputStrategy.scala b/run/src/main/scala/sbt/OutputStrategy.scala index ccd54e103..26b7e710b 100644 --- a/run/src/main/scala/sbt/OutputStrategy.scala +++ b/run/src/main/scala/sbt/OutputStrategy.scala @@ -38,7 +38,7 @@ object OutputStrategy { override def toString: String = { "BufferedOutput(" + logger + ")" } - private[this] def copy(logger: Logger = logger): BufferedOutput = { + private def copy(logger: Logger = logger): BufferedOutput = { new BufferedOutput(logger) } def withLogger(logger: Logger): BufferedOutput = { @@ -64,7 +64,7 @@ object OutputStrategy { override def toString: String = { "LoggedOutput(" + logger + ")" } - private[this] def copy(logger: Logger = logger): LoggedOutput = { + private def copy(logger: Logger = logger): LoggedOutput = { new LoggedOutput(logger) } def withLogger(logger: Logger): LoggedOutput = { @@ -92,7 +92,7 @@ object OutputStrategy { override def toString: String = { "CustomOutput(" + output + ")" } - private[this] def copy(output: OutputStream = output): CustomOutput = { + private def copy(output: OutputStream = output): CustomOutput = { new CustomOutput(output) } def withOutput(output: OutputStream): CustomOutput = { diff --git a/run/src/main/scala/sbt/TrapExit.scala b/run/src/main/scala/sbt/TrapExit.scala index d12f3d873..49ef8392a 100644 --- a/run/src/main/scala/sbt/TrapExit.scala +++ b/run/src/main/scala/sbt/TrapExit.scala @@ -43,7 +43,7 @@ object TrapExit { @deprecated("TrapExit feature is removed; just call the function instead", "1.6.0") def uninstallManager(previous: Any): Unit = () - private[this] def runUnmanaged(execute: => Unit, log: Logger): Int = { + private def runUnmanaged(execute: => Unit, log: Logger): Int = { log.warn("Managed execution not possible: security manager not installed.") try { execute; 0 diff --git a/run/src/test/scala/sbt/ForkTest.scala b/run/src/test/scala/sbt/ForkTest.scala index 51799f77a..4a2ad0125 100644 --- a/run/src/test/scala/sbt/ForkTest.scala +++ b/run/src/test/scala/sbt/ForkTest.scala @@ -64,7 +64,7 @@ object ForkTest extends Properties("Fork") { } } - private[this] def trimClasspath(cp: String): String = + private def trimClasspath(cp: String): String = if (cp.length > MaximumClasspathLength) { val lastEntryI = cp.lastIndexOf(File.pathSeparatorChar.toInt, MaximumClasspathLength) if (lastEntryI > 0) diff --git a/sbt-app/src/test/scala/sbt/IllegalReferenceSpec.scala b/sbt-app/src/test/scala/sbt/IllegalReferenceSpec.scala index b9981d9f4..24a4c081c 100644 --- a/sbt-app/src/test/scala/sbt/IllegalReferenceSpec.scala +++ b/sbt-app/src/test/scala/sbt/IllegalReferenceSpec.scala @@ -41,9 +41,9 @@ class IllegalReferenceSpec extends funsuite.FixtureAnyFunSuite with fixture.Test assert(errorMessage.contains(errorSnippet), userMessage) } private class CachingToolbox(implicit td: TestData) { - private[this] val m = scala.reflect.runtime.currentMirror - private[this] var _infos: List[FrontEnd#Info] = Nil - private[this] val frontEnd = new FrontEnd { + private val m = scala.reflect.runtime.currentMirror + private var _infos: List[FrontEnd#Info] = Nil + private val frontEnd = new FrontEnd { override def display(info: Info): Unit = _infos ::= info def interactive(): Unit = {} } diff --git a/scripted-sbt/src/main/scala/sbt/scriptedtest/SbtHandler.scala b/scripted-sbt/src/main/scala/sbt/scriptedtest/SbtHandler.scala index 1888ffa4f..d8c145399 100644 --- a/scripted-sbt/src/main/scala/sbt/scriptedtest/SbtHandler.scala +++ b/scripted-sbt/src/main/scala/sbt/scriptedtest/SbtHandler.scala @@ -41,7 +41,7 @@ final class SbtHandler(remoteSbtCreator: RemoteSbtCreator) extends StatementHand case None => onNewSbtInstance(f) } - private[this] def onNewSbtInstance(f: (Process, IPC.Server) => Unit): Option[SbtInstance] = { + private def onNewSbtInstance(f: (Process, IPC.Server) => Unit): Option[SbtInstance] = { val server = IPC.unmanagedServer val p = try newRemote(server) diff --git a/scripted-sbt/src/main/scala/sbt/scriptedtest/ScriptedTests.scala b/scripted-sbt/src/main/scala/sbt/scriptedtest/ScriptedTests.scala index d6f0532ab..ed4c6c92f 100644 --- a/scripted-sbt/src/main/scala/sbt/scriptedtest/ScriptedTests.scala +++ b/scripted-sbt/src/main/scala/sbt/scriptedtest/ScriptedTests.scala @@ -162,7 +162,7 @@ final class ScriptedTests( } } - private[this] val windowsExclude: (((String, String), File)) => Boolean = + private val windowsExclude: (((String, String), File)) => Boolean = if (scala.util.Properties.isWin) { case (testName, _) => testName match { case ("classloader-cache", "jni") => true // no native lib is built for windows @@ -561,7 +561,7 @@ class ScriptedRunner { ) @nowarn - private[this] def run( + private def run( baseDir: File, bufferLog: Boolean, tests: Array[String], @@ -700,7 +700,7 @@ private[sbt] final class ListTests( } .toSeq - private[this] def listTests(group: File): Set[String] = { + private def listTests(group: File): Set[String] = { val groupName = group.getName val allTests = IO.listFiles(group, filter) if (allTests.isEmpty) { diff --git a/server-test/src/test/scala/testpkg/ClientTest.scala b/server-test/src/test/scala/testpkg/ClientTest.scala index e5a4a3c7d..63aed2afb 100644 --- a/server-test/src/test/scala/testpkg/ClientTest.scala +++ b/server-test/src/test/scala/testpkg/ClientTest.scala @@ -44,7 +44,7 @@ class ClientTest extends AbstractServerTest { } else -1 } } - private[this] def background[R](f: => R): R = { + private def background[R](f: => R): R = { val result = new LinkedBlockingQueue[R] val thread = new Thread("client-bg-thread") { setDaemon(true) diff --git a/tasks-standard/src/main/scala/sbt/std/Streams.scala b/tasks-standard/src/main/scala/sbt/std/Streams.scala index 84f0a1ea2..7586b6af5 100644 --- a/tasks-standard/src/main/scala/sbt/std/Streams.scala +++ b/tasks-standard/src/main/scala/sbt/std/Streams.scala @@ -74,7 +74,7 @@ sealed trait TaskStreams[Key] { /** Creates a Logger that logs to stream with ID `sid`. */ def log(sid: String): ManagedLogger - private[this] def getID(s: Option[String]) = s getOrElse default + private def getID(s: Option[String]) = s getOrElse default } sealed trait ManagedStreams[Key] extends TaskStreams[Key] { def open(): Unit @@ -96,14 +96,14 @@ trait Streams[Key] { } trait CloseableStreams[Key] extends Streams[Key] with java.io.Closeable object Streams { - private[this] val closeQuietly = (c: Closeable) => + private val closeQuietly = (c: Closeable) => try { c.close() } catch { case _: IOException => () } - private[this] val streamLocks = new ConcurrentHashMap[File, AnyRef]() + private val streamLocks = new ConcurrentHashMap[File, AnyRef]() def closeable[Key](delegate: Streams[Key]): CloseableStreams[Key] = new CloseableStreams[Key] { - private[this] val streams = new collection.mutable.HashMap[Key, ManagedStreams[Key]] + private val streams = new collection.mutable.HashMap[Key, ManagedStreams[Key]] def apply(key: Key): ManagedStreams[Key] = synchronized { @@ -156,8 +156,8 @@ object Streams { ): Streams[Key] = new Streams[Key] { def apply(a: Key): ManagedStreams[Key] = new ManagedStreams[Key] { - private[this] var opened: List[Closeable] = nil - private[this] var closed = false + private var opened: List[Closeable] = nil + private var closed = false def getInput(a: Key, sid: String = default): Input = make(a, sid)(f => new FileInput(f)) diff --git a/tasks/src/main/scala/sbt/ConcurrentRestrictions.scala b/tasks/src/main/scala/sbt/ConcurrentRestrictions.scala index 7ed701941..3d8b19bc7 100644 --- a/tasks/src/main/scala/sbt/ConcurrentRestrictions.scala +++ b/tasks/src/main/scala/sbt/ConcurrentRestrictions.scala @@ -53,7 +53,7 @@ import java.util.concurrent.{ Executor, Executors, ExecutorCompletionService } import annotation.tailrec object ConcurrentRestrictions { - private[this] val completionServices = new java.util.WeakHashMap[CompletionService, Boolean] + private val completionServices = new java.util.WeakHashMap[CompletionService, Boolean] def cancelAll() = completionServices.keySet.asScala.toVector.foreach { case a: AutoCloseable => a.close() case _ => @@ -118,7 +118,7 @@ object ConcurrentRestrictions { def valid(g: TagMap) = validF(g) } - private[this] def merge(m: TagMap, a: TaskId[?])( + private def merge(m: TagMap, a: TaskId[?])( f: (Int, Int) => Int ): TagMap = { val base = merge(m, a.tags)(f) @@ -126,7 +126,7 @@ object ConcurrentRestrictions { update(un, All, 1)(f) } - private[this] def update[A, B](m: Map[A, B], a: A, b: B)(f: (B, B) => B): Map[A, B] = { + private def update[A, B](m: Map[A, B], a: A, b: B)(f: (B, B) => B): Map[A, B] = { val newb = (m get a) match { case Some(bv) => f(bv, b) @@ -134,10 +134,10 @@ object ConcurrentRestrictions { } m.updated(a, newb) } - private[this] def merge[A, B](m: Map[A, B], n: Map[A, B])(f: (B, B) => B): Map[A, B] = + private def merge[A, B](m: Map[A, B], n: Map[A, B])(f: (B, B) => B): Map[A, B] = n.foldLeft(m) { case (acc, (a, b)) => update(acc, a, b)(f) } - private[this] val poolID = new AtomicInteger(1) + private val poolID = new AtomicInteger(1) /** * Constructs a CompletionService suitable for backing task execution based on the provided @@ -220,28 +220,28 @@ object ConcurrentRestrictions { new CompletionService with CancelSentiels with AutoCloseable { completionServices.put(this, true) - private[this] val closed = new AtomicBoolean(false) + private val closed = new AtomicBoolean(false) override def close(): Unit = if (closed.compareAndSet(false, true)) { completionServices.remove(this) () } /** Backing service used to manage execution on threads once all constraints are satisfied. */ - private[this] val jservice = new ExecutorCompletionService[Completed](backing) + private val jservice = new ExecutorCompletionService[Completed](backing) /** The description of the currently running tasks, used by `tags` to manage restrictions. */ - private[this] var tagState = tags.empty + private var tagState = tags.empty /** The number of running tasks. */ - private[this] var running = 0 + private var running = 0 /** * Tasks that cannot be run yet because they cannot execute concurrently with the currently * running tasks. */ - private[this] val pending = new LinkedList[Enqueue] + private val pending = new LinkedList[Enqueue] - private[this] val sentinels: mutable.ListBuffer[JFuture[_]] = mutable.ListBuffer.empty + private val sentinels: mutable.ListBuffer[JFuture[_]] = mutable.ListBuffer.empty def cancelSentinels(): Unit = { sentinels.toList foreach { s => @@ -271,7 +271,7 @@ object ConcurrentRestrictions { } () } - private[this] def submitValid(node: TaskId[?], work: () => Completed): Unit = { + private def submitValid(node: TaskId[?], work: () => Completed): Unit = { running += 1 val wrappedWork = () => try work() @@ -279,7 +279,7 @@ object ConcurrentRestrictions { CompletionService.submitFuture(wrappedWork, jservice) () } - private[this] def cleanup(node: TaskId[?]): Unit = synchronized { + private def cleanup(node: TaskId[?]): Unit = synchronized { running -= 1 tagState = tags.remove(tagState, node) if (!tags.valid(tagState)) { @@ -290,11 +290,11 @@ object ConcurrentRestrictions { } submitValid(new LinkedList) } - private[this] def errorAddingToIdle() = + private def errorAddingToIdle() = warn("Invalid restriction: adding a node to an idle system must be allowed.") /** Submits pending tasks that are now allowed to executed. */ - @tailrec private[this] def submitValid(tried: Queue[Enqueue]): Unit = + @tailrec private def submitValid(tried: Queue[Enqueue]): Unit = if (pending.isEmpty) { if (!tried.isEmpty) { if (running == 0) errorAddingToIdle() diff --git a/tasks/src/main/scala/sbt/Execute.scala b/tasks/src/main/scala/sbt/Execute.scala index b6cc3bca2..2ecafb563 100644 --- a/tasks/src/main/scala/sbt/Execute.scala +++ b/tasks/src/main/scala/sbt/Execute.scala @@ -63,20 +63,20 @@ private[sbt] final class Execute( )(using view: NodeView) { import Execute.* - private[this] val forward = taskMap[IDSet[TaskId[?]]] - private[this] val reverse = taskMap[Iterable[TaskId[?]]] - private[this] val callers = taskPMap[[X] =>> IDSet[TaskId[X]]] - private[this] val state = taskMap[State] - private[this] val viewCache = taskPMap[Node] - private[this] val results = taskPMap[Result] + private val forward = taskMap[IDSet[TaskId[?]]] + private val reverse = taskMap[Iterable[TaskId[?]]] + private val callers = taskPMap[[X] =>> IDSet[TaskId[X]]] + private val state = taskMap[State] + private val viewCache = taskPMap[Node] + private val results = taskPMap[Result] - private[this] val getResult: [A] => TaskId[A] => Result[A] = [A] => + private val getResult: [A] => TaskId[A] => Result[A] = [A] => (a: TaskId[A]) => view.inline1(a) match case Some(v) => Result.Value(v()) case None => results(a) - private[this] type State = State.Value - private[this] object State extends Enumeration { + private type State = State.Value + private object State extends Enumeration { val Pending, Running, Calling, Done = Value } import State.{ Pending, Running, Calling, Done } @@ -305,7 +305,7 @@ private[sbt] final class Execute( } } } - private[this] def rewrap[A]( + private def rewrap[A]( rawResult: Either[Incomplete, Either[TaskId[A], A]] ): Either[TaskId[A], Result[A]] = rawResult match { diff --git a/testing/src/main/scala/sbt/JUnitXmlTestsListener.scala b/testing/src/main/scala/sbt/JUnitXmlTestsListener.scala index bd5819cc1..fe6fb51f5 100644 --- a/testing/src/main/scala/sbt/JUnitXmlTestsListener.scala +++ b/testing/src/main/scala/sbt/JUnitXmlTestsListener.scala @@ -242,12 +242,12 @@ class JUnitXmlTestsListener(val targetDir: File, legacyTestReport: Boolean, logg // Here we normalize the name to ensure that it's a nicer filename, rather than // contort the user into not using spaces. - private[this] def normalizeName(s: String) = s.replaceAll("""\s+""", "-") + private def normalizeName(s: String) = s.replaceAll("""\s+""", "-") /** * Format the date, without milliseconds or the timezone, per the JUnit spec. */ - private[this] def formatISO8601DateTime(d: LocalDateTime): String = + private def formatISO8601DateTime(d: LocalDateTime): String = d.truncatedTo(ChronoUnit.SECONDS).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) private def writeSuite(): Unit = { diff --git a/testing/src/main/scala/sbt/TestFramework.scala b/testing/src/main/scala/sbt/TestFramework.scala index 4a5f47304..071c05f81 100644 --- a/testing/src/main/scala/sbt/TestFramework.scala +++ b/testing/src/main/scala/sbt/TestFramework.scala @@ -239,7 +239,7 @@ object TestFramework { ) } - private[this] def order( + private def order( mapped: Map[String, TestFunction], inputs: Vector[TestDefinition] ): Vector[(String, TestFunction)] = @@ -295,7 +295,7 @@ object TestFramework { val endTask = (result: TestResult) => foreachListenerSafe(_.doComplete(result)) (startTask, order(testTasks, ordered), endTask) } - private[this] def withContextLoader[T](loader: ClassLoader)(eval: => T): T = { + private def withContextLoader[T](loader: ClassLoader)(eval: => T): T = { val oldLoader = Thread.currentThread.getContextClassLoader Thread.currentThread.setContextClassLoader(loader) try { diff --git a/util-collection/src/main/scala/sbt/internal/util/Attributes.scala b/util-collection/src/main/scala/sbt/internal/util/Attributes.scala index eaf34b8f1..8d72a2b29 100644 --- a/util-collection/src/main/scala/sbt/internal/util/Attributes.scala +++ b/util-collection/src/main/scala/sbt/internal/util/Attributes.scala @@ -119,7 +119,7 @@ object AttributeKey { private[sbt] def copyWithRank[A](a: AttributeKey[A], rank: Int): AttributeKey[A] = make(a.label, a.description, a.extend, rank)(using a.tag, a.optJsonWriter) - private[this] def make[A: KeyTag: OptJsonWriter]( + private def make[A: KeyTag: OptJsonWriter]( name: String, description0: Option[String], extend0: Seq[AttributeKey[_]], diff --git a/util-collection/src/main/scala/sbt/internal/util/IDSet.scala b/util-collection/src/main/scala/sbt/internal/util/IDSet.scala index 5b7c71242..663ded067 100644 --- a/util-collection/src/main/scala/sbt/internal/util/IDSet.scala +++ b/util-collection/src/main/scala/sbt/internal/util/IDSet.scala @@ -37,8 +37,8 @@ object IDSet { } def create[T]: IDSet[T] = new IDSet[T] { - private[this] val backing = new java.util.IdentityHashMap[T, AnyRef] - private[this] val Dummy: AnyRef = "" + private val backing = new java.util.IdentityHashMap[T, AnyRef] + private val Dummy: AnyRef = "" def apply(t: T) = contains(t) def contains(t: T) = backing.containsKey(t) diff --git a/util-collection/src/main/scala/sbt/internal/util/INode.scala b/util-collection/src/main/scala/sbt/internal/util/INode.scala index bec3bfa15..c870ea1ab 100644 --- a/util-collection/src/main/scala/sbt/internal/util/INode.scala +++ b/util-collection/src/main/scala/sbt/internal/util/INode.scala @@ -28,14 +28,14 @@ abstract class EvaluateSettings[ScopeType]: import EvaluationState.* - private[this] val complete = new LinkedBlockingQueue[Option[Throwable]] - private[this] val static = PMap.empty[ScopedKey, INode] - private[this] val allScopes: Set[ScopeType] = compiledSettings.map(_.key.scope).toSet + private val complete = new LinkedBlockingQueue[Option[Throwable]] + private val static = PMap.empty[ScopedKey, INode] + private val allScopes: Set[ScopeType] = compiledSettings.map(_.key.scope).toSet - private[this] def getStatic[A](key: ScopedKey[A]): INode[A] = + private def getStatic[A](key: ScopedKey[A]): INode[A] = static.get(key).getOrElse { sys.error("Illegal reference to key " + key) } - private[this] val transform: [A] => Initialize[A] => INode[A] = [A] => + private val transform: [A] => Initialize[A] => INode[A] = [A] => (fa: Initialize[A]) => fa match case k: Keyed[s, A] => single(getStatic(k.scopedKey), k.transform) @@ -52,7 +52,7 @@ abstract class EvaluateSettings[ScopeType]: case Some(i) => single[s, A](transform(i), x => o.f(Some(x))) case StaticScopes => strictConstant(allScopes) - private[this] lazy val roots: Seq[INode[_]] = compiledSettings.flatMap { cs => + private lazy val roots: Seq[INode[_]] = compiledSettings.flatMap { cs => (cs.settings map { s => val t = transform(s.init) static(s.key) = t @@ -60,8 +60,8 @@ abstract class EvaluateSettings[ScopeType]: }): Seq[INode[_]] } - private[this] val running = new AtomicInteger - private[this] val cancel = new AtomicBoolean(false) + private val running = new AtomicInteger + private val cancel = new AtomicBoolean(false) def run(implicit delegates: ScopeType => Seq[ScopeType]): Settings[ScopeType] = { assert(running.get() == 0, "Already running") @@ -75,46 +75,46 @@ abstract class EvaluateSettings[ScopeType]: getResults(delegates) } - private[this] def getResults(implicit delegates: ScopeType => Seq[ScopeType]) = + private def getResults(implicit delegates: ScopeType => Seq[ScopeType]) = static.toTypedSeq.foldLeft(empty) { case (ss, static.TPair(key, node)) => if key.key.isLocal then ss else ss.set(key.scope, key.key, node.get) } - private[this] lazy val getValue: [A] => INode[A] => A = [A] => (fa: INode[A]) => fa.get + private lazy val getValue: [A] => INode[A] => A = [A] => (fa: INode[A]) => fa.get - private[this] def submitEvaluate(node: INode[_]) = submit(node.evaluate()) + private def submitEvaluate(node: INode[_]) = submit(node.evaluate()) - private[this] def submitCallComplete[A](node: BindNode[_, A], value: A) = + private def submitCallComplete[A](node: BindNode[_, A], value: A) = submit(node.callComplete(value)) - private[this] def submit(work: => Unit): Unit = + private def submit(work: => Unit): Unit = startWork() executor.execute(() => if !cancel.get() then run0(work)) - private[this] def run0(work: => Unit): Unit = + private def run0(work: => Unit): Unit = try { work } catch { case e: Throwable => complete.put(Some(e)) } workComplete() - private[this] def startWork(): Unit = { running.incrementAndGet(); () } + private def startWork(): Unit = { running.incrementAndGet(); () } - private[this] def workComplete(): Unit = + private def workComplete(): Unit = if running.decrementAndGet() == 0 then complete.put(None) - private[this] sealed abstract class INode[A1]: - private[this] var state: EvaluationState = New - private[this] var value: A1 = _ - private[this] val blocking = new collection.mutable.ListBuffer[INode[_]] - private[this] var blockedOn: Int = 0 - private[this] val calledBy = new collection.mutable.ListBuffer[BindNode[_, A1]] + private sealed abstract class INode[A1]: + private var state: EvaluationState = New + private var value: A1 = _ + private val blocking = new collection.mutable.ListBuffer[INode[_]] + private var blockedOn: Int = 0 + private val calledBy = new collection.mutable.ListBuffer[BindNode[_, A1]] override def toString(): String = getClass.getName + " (state=" + state + ",blockedOn=" + blockedOn + ",calledBy=" + calledBy.size + ",blocking=" + blocking.size + "): " + keyString - private[this] def keyString = + private def keyString = static.toSeq .flatMap { case (key, value) => if (value eq this) init.showFullKey.show(key) :: Nil else Nil @@ -142,7 +142,7 @@ abstract class EvaluateSettings[ScopeType]: final def isCalling: Boolean = synchronized { state == Calling } final def registerIfNew(): Unit = synchronized { if (state == New) register() } - private[this] def register(): Unit = { + private def register(): Unit = { assert(state == New, "Already registered and: " + toString) val deps = dependsOn blockedOn = deps.size - deps.count(_.doneOrBlock(this)) @@ -201,15 +201,15 @@ abstract class EvaluateSettings[ScopeType]: protected def evaluate0(): Unit end INode - private[this] def strictConstant[A1](v: A1): INode[A1] = constant(() => v) + private def strictConstant[A1](v: A1): INode[A1] = constant(() => v) - private[this] def constant[A1](f: () => A1): INode[A1] = + private def constant[A1](f: () => A1): INode[A1] = MixedNode[EmptyTuple, A1](EmptyTuple, _ => f()) - private[this] def single[A1, A2](in: INode[A1], f: A1 => A2): INode[A2] = + private def single[A1, A2](in: INode[A1], f: A1 => A2): INode[A2] = MixedNode[Tuple1[A1], A2](Tuple1(in), { case Tuple1(a) => f(a) }) - private[this] final class BindNode[A1, A2](in: INode[A1], f: A1 => INode[A2]) extends INode[A2]: + private final class BindNode[A1, A2](in: INode[A1], f: A1 => INode[A2]) extends INode[A2]: protected def dependsOn: Seq[INode[_]] = in :: Nil protected def evaluate0(): Unit = makeCall(this, f(in.get)) def callComplete(value: A2): Unit = synchronized { @@ -218,14 +218,13 @@ abstract class EvaluateSettings[ScopeType]: } end BindNode - private[this] final class MixedNode[Tup <: Tuple, A1](in: Tuple.Map[Tup, INode], f: Tup => A1) + private final class MixedNode[Tup <: Tuple, A1](in: Tuple.Map[Tup, INode], f: Tup => A1) extends INode[A1]: import TupleMapExtension.* protected override def dependsOn: Seq[INode[_]] = in.toList0 protected override def evaluate0(): Unit = setValue(f(in.unmap(getValue))) - private[this] final class UniformNode[A1, A2](in: List[INode[A1]], f: List[A1] => A2) - extends INode[A2]: + private final class UniformNode[A1, A2](in: List[INode[A1]], f: List[A1] => A2) extends INode[A2]: protected override def dependsOn: Seq[INode[_]] = in protected override def evaluate0(): Unit = setValue(f(in.map(_.get))) diff --git a/util-collection/src/main/scala/sbt/internal/util/PMap.scala b/util-collection/src/main/scala/sbt/internal/util/PMap.scala index 1b40355bb..f74131d07 100644 --- a/util-collection/src/main/scala/sbt/internal/util/PMap.scala +++ b/util-collection/src/main/scala/sbt/internal/util/PMap.scala @@ -117,8 +117,8 @@ class DelegatingPMap[K[_], V[_]](backing: mutable.Map[K[Any], V[Any]]) def values = backing.values.asInstanceOf[Iterable[V[Any]]] def isEmpty = backing.isEmpty - private[this] def cast[A](v: V[Any]): V[A] = v.asInstanceOf[V[A]] - private[this] def cast[A](o: Option[V[Any]]): Option[V[A]] = o map cast[A] + private def cast[A](v: V[Any]): V[A] = v.asInstanceOf[V[A]] + private def cast[A](o: Option[V[Any]]): Option[V[A]] = o map cast[A] override def toString = backing.toString } diff --git a/util-collection/src/main/scala/sbt/internal/util/Settings.scala b/util-collection/src/main/scala/sbt/internal/util/Settings.scala index a4fb63f6b..e9e6f281c 100644 --- a/util-collection/src/main/scala/sbt/internal/util/Settings.scala +++ b/util-collection/src/main/scala/sbt/internal/util/Settings.scala @@ -108,7 +108,7 @@ trait Init[ScopeType]: def flatMap[A1, A2](in: Initialize[A1])(f: A1 => Initialize[A2]): Initialize[A2] = Bind(f, in) - private[this] def map[A1, A2](in: Initialize[A1])(f: A1 => A2): Initialize[A2] = + private def map[A1, A2](in: Initialize[A1])(f: A1 => A2): Initialize[A2] = Apply[Tuple1[A1], A2](x => f(x(0)), Tuple1(in)) def app[Tup <: Tuple, A2](inputs: Tuple.Map[Tup, Initialize])(f: Tup => A2): Initialize[A2] = @@ -160,8 +160,8 @@ trait Init[ScopeType]: private[sbt] def defaultSettings(ss: Seq[Setting[_]]): Seq[Setting[_]] = ss.map(s => defaultSetting(s)) - private[this] final val nextID = new java.util.concurrent.atomic.AtomicLong - private[this] final def nextDefaultID(): Long = nextID.incrementAndGet() + private final val nextID = new java.util.concurrent.atomic.AtomicLong + private final def nextDefaultID(): Long = nextID.incrementAndGet() def empty(implicit delegates: ScopeType => Seq[ScopeType]): Settings[ScopeType] = Settings0(Map.empty, delegates) @@ -177,7 +177,7 @@ trait Init[ScopeType]: def mapScope(f: ScopeType => ScopeType): MapScoped = [a] => (k: ScopedKey[a]) => k.copy(scope = f(k.scope)) - private[this] def applyDefaults(ss: Seq[Setting[_]]): Seq[Setting[_]] = { + private def applyDefaults(ss: Seq[Setting[_]]): Seq[Setting[_]] = { val result = new java.util.LinkedHashSet[Setting[_]] val others = new java.util.ArrayList[Setting[_]] ss.foreach { @@ -311,7 +311,7 @@ trait Init[ScopeType]: else throw Uninitialized(sMap.keys.toSeq, delegates, undefined.asScala.toList, false) } - private[this] def delegateForKey[A1]( + private def delegateForKey[A1]( sMap: ScopedMap, k: ScopedKey[A1], scopes: Seq[ScopeType], @@ -322,7 +322,7 @@ trait Init[ScopeType]: val definedAt = skeys.find(sk => (selfRefOk || ref.key != sk) && (sMap contains sk)) definedAt.toRight(Undefined(ref, k)) - private[this] def applyInits(ordered: Seq[Compiled[_]])(implicit + private def applyInits(ordered: Seq[Compiled[_]])(implicit delegates: ScopeType => Seq[ScopeType] ): Settings[ScopeType] = val x = @@ -360,7 +360,7 @@ trait Init[ScopeType]: u.referencedKey ) + " from " + refString + sourceString + derivedString + guessedString - private[this] def parenPosString(s: Setting[_]): String = + private def parenPosString(s: Setting[_]): String = s.positionString match { case None => ""; case Some(s) => " (" + s + ")" } def guessIntendedScope( @@ -475,7 +475,7 @@ trait Init[ScopeType]: def exists(f: ScopeType => Boolean): Boolean end Delegates - private[this] def mkDelegates(delegates: ScopeType => Seq[ScopeType]): ScopeType => Delegates = { + private def mkDelegates(delegates: ScopeType => Seq[ScopeType]): ScopeType => Delegates = { val delegateMap = new java.util.concurrent.ConcurrentHashMap[ScopeType, Delegates] s => delegateMap.get(s) match { @@ -511,8 +511,8 @@ trait Init[ScopeType]: else if (delegates(s2).contains(s1)) Some(s2) // s2 is more specific else None - private[this] def deriveAndLocal(init: Seq[Setting[_]], delegates: ScopeType => Delegates)( - implicit scopeLocal: ScopeLocal + private def deriveAndLocal(init: Seq[Setting[_]], delegates: ScopeType => Delegates)(implicit + scopeLocal: ScopeLocal ): Seq[Setting[_]] = { import collection.mutable @@ -659,7 +659,7 @@ trait Init[ScopeType]: def zipWith[A2, U](o: Initialize[A2])(f: (A1, A2) => U): Initialize[U] = zipTupled(o)(f.tupled) - private[this] def zipTupled[A2, U](o: Initialize[A2])(f: ((A1, A2)) => U): Initialize[U] = + private def zipTupled[A2, U](o: Initialize[A2])(f: ((A1, A2)) => U): Initialize[U] = Apply[(A1, A2), U](f, (this, o)) /** A fold on the static attributes of this and nested Initializes. */ @@ -724,7 +724,7 @@ trait Init[ScopeType]: override def toString = "setting(" + key + ") at " + pos - protected[this] def make[A2]( + protected def make[A2]( key: ScopedKey[A2], init: Initialize[A2], pos: SourcePosition @@ -783,25 +783,25 @@ trait Init[ScopeType]: val id = _id end DefaultSetting - private[this] def handleUndefined[A](vr: ValidatedInit[A]): Initialize[A] = vr match + private def handleUndefined[A](vr: ValidatedInit[A]): Initialize[A] = vr match case Left(undefs) => throw new RuntimeUndefined(undefs) case Right(x) => x - private[this] lazy val getValidatedK = [A] => (fa: ValidatedInit[A]) => handleUndefined(fa) + private lazy val getValidatedK = [A] => (fa: ValidatedInit[A]) => handleUndefined(fa) // mainly for reducing generated class count - private[this] def validateKeyReferencedK( + private def validateKeyReferencedK( g: ValidateKeyRef ): [A] => Initialize[A] => ValidatedInit[A] = [A] => (fa: Initialize[A]) => (fa.validateKeyReferenced(g)) - private[this] def mapReferencedK(g: MapScoped): [A] => Initialize[A] => Initialize[A] = [A] => + private def mapReferencedK(g: MapScoped): [A] => Initialize[A] => Initialize[A] = [A] => (fa: Initialize[A]) => (fa.mapReferenced(g)) - private[this] def mapConstantK(g: MapConstant): [A] => Initialize[A] => Initialize[A] = [A] => + private def mapConstantK(g: MapConstant): [A] => Initialize[A] => Initialize[A] = [A] => (fa: Initialize[A]) => (fa.mapConstant(g)) - private[this] def evaluateK(g: Settings[ScopeType]): [A] => Initialize[A] => A = [A] => + private def evaluateK(g: Settings[ScopeType]): [A] => Initialize[A] => A = [A] => (fa: Initialize[A]) => (fa.evaluate(g)) - private[this] def deps(ls: List[Initialize[_]]): Seq[ScopedKey[_]] = + private def deps(ls: List[Initialize[_]]): Seq[ScopedKey[_]] = ls.flatMap(_.dependencies) /** @@ -834,7 +834,7 @@ trait Init[ScopeType]: init end Keyed - private[this] final class GetValue[S, A1](val scopedKey: ScopedKey[S], val transform: S => A1) + private final class GetValue[S, A1](val scopedKey: ScopedKey[S], val transform: S => A1) extends Keyed[S, A1] /** @@ -920,7 +920,7 @@ trait Init[ScopeType]: f(a.flatMap { i => trapBadRef(evaluateK(ss)(i)) }) // proper solution is for evaluate to be deprecated or for external use only and a new internal method returning Either be used - private[this] def trapBadRef[A](run: => A): Option[A] = + private def trapBadRef[A](run: => A): Option[A] = try Some(run) catch { case _: InvalidReference => None } diff --git a/util-tracking/src/main/scala/sbt/util/Tracked.scala b/util-tracking/src/main/scala/sbt/util/Tracked.scala index 00c6bff49..789e6032a 100644 --- a/util-tracking/src/main/scala/sbt/util/Tracked.scala +++ b/util-tracking/src/main/scala/sbt/util/Tracked.scala @@ -412,7 +412,7 @@ class Difference( private def abs(files: Set[File]) = files.map(_.getAbsoluteFile) - private[this] def apply[T](files: Set[File], lastFilesInfo: Set[style.F])( + private def apply[T](files: Set[File], lastFilesInfo: Set[style.F])( f: ChangeReport[File] => T )(extractFiles: T => Set[File]): T = { val lastFiles = raw(lastFilesInfo)