<commit_before>/*
 * sbt
 * Copyright 2011 - 2017, Lightbend, Inc.
 * Copyright 2008 - 2010, <NAME>
 * Licensed under BSD-3-Clause license (see LICENSE)
 */

package sbt
package internal

import java.io.IOException
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.atomic._
import scala.collection.mutable.ListBuffer
import scala.annotation.tailrec
import BasicKeys.{
  serverHost,
  serverPort,
  serverAuthentication,
  serverConnectionType,
  serverLogLevel,
  logLevel
}
import java.net.Socket
import sjsonnew.JsonFormat
import sjsonnew.shaded.scalajson.ast.unsafe._
import scala.concurrent.Await
import scala.concurrent.duration.Duration
import scala.util.{ Success, Failure, Try }
import sbt.io.syntax._
import sbt.io.{ Hash, IO }
import sbt.internal.server._
import sbt.internal.langserver.{ LogMessageParams, MessageType }
import sbt.internal.util.{ StringEvent, ObjectEvent, MainAppender }
import sbt.internal.util.codec.JValueFormats
import sbt.protocol.{ EventMessage, ExecStatusEvent }
import sbt.util.{ Level, Logger, LogExchange }

/**
 * The command exchange merges multiple command channels (e.g. network and console),
 * and acts as the central multiplexing point.
 * Instead of blocking on JLine.readLine, the server command will block on
 * this exchange, which could serve command request from either of the channel.
 */
private[sbt] final class CommandExchange {
  private val autoStartServer =
    sys.props get "sbt.server.autostart" forall (_.toLowerCase == "true")

  private var server: Option[ServerInstance] = None
  private val firstInstance: AtomicBoolean = new AtomicBoolean(true)
  private var consoleChannel: Option[ConsoleChannel] = None
  private val commandQueue: ConcurrentLinkedQueue[Exec] = new ConcurrentLinkedQueue()
  private val channelBuffer: ListBuffer[CommandChannel] = new ListBuffer()
  private val channelBufferLock = new AnyRef {}
  private val nextChannelId: AtomicInteger = new AtomicInteger(0)
  private lazy val jsonFormat = new sjsonnew.BasicJsonProtocol with JValueFormats {}

  def channels: List[CommandChannel] = channelBuffer.toList
  def subscribe(c: CommandChannel): Unit = channelBufferLock.synchronized(channelBuffer.append(c))

  // periodically move all messages from all the channels
  @tailrec def blockUntilNextExec: Exec = {
    @tailrec def slurpMessages(): Unit =
      channels.foldLeft(Option.empty[Exec]) { _ orElse _.poll } match {
        case None => ()
        case Some(x) =>
          commandQueue.add(x)
          slurpMessages
      }
    slurpMessages()
    Option(commandQueue.poll) match {
      case Some(x) => x
      case None =>
        Thread.sleep(50)
        blockUntilNextExec
    }
  }

  def run(s: State): State = {
    if (consoleChannel.isEmpty) {
      val console0 = new ConsoleChannel("console0")
      consoleChannel = Some(console0)
      subscribe(console0)
    }
    if (autoStartServer) runServer(s)
    else s
  }

  private def newNetworkName: String = s"network-${nextChannelId.incrementAndGet()}"

  /**
   * Check if a server instance is running already, and start one if it isn't.
   */
  private[sbt] def runServer(s: State): State = {
    lazy val port = s.get(serverPort).getOrElse(5001)
    lazy val host = s.get(serverHost).getOrElse("127.0.0.1")
    lazy val auth: Set[ServerAuthentication] =
      s.get(serverAuthentication).getOrElse(Set(ServerAuthentication.Token))
    lazy val connectionType = s.get(serverConnectionType).getOrElse(ConnectionType.Tcp)
    lazy val level = s.get(serverLogLevel).orElse(s.get(logLevel)).getOrElse(Level.Warn)

    def onIncomingSocket(socket: Socket, instance: ServerInstance): Unit = {
      val name = newNetworkName
      s.log.info(s"new client connected: $name")
      val logger: Logger = {
        val log = LogExchange.logger(name, None, None)
        LogExchange.unbindLoggerAppenders(name)
        val appender = MainAppender.defaultScreen(s.globalLogging.console)
        LogExchange.bindLoggerAppenders(name, List(appender -> level))
        log
      }
      val channel =
        new NetworkChannel(name, socket, Project structure s, auth, instance, logger)
      subscribe(channel)
    }
    if (server.isEmpty && firstInstance.get) {
      val portfile = (new File(".")).getAbsoluteFile / "project" / "target" / "active.json"<commit_msg>Use State to pick the port file<commit_after>/*
 * sbt
 * Copyright 2011 - 2017, Lightbend, Inc.
 * Copyright 2008 - 2010, <NAME>
 * Licensed under BSD-3-Clause license (see LICENSE)
 */

package sbt
package internal

import java.io.IOException
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.atomic._
import scala.collection.mutable.ListBuffer
import scala.annotation.tailrec
import BasicKeys.{
  serverHost,
  serverPort,
  serverAuthentication,
  serverConnectionType,
  serverLogLevel,
  logLevel
}
import java.net.Socket
import sjsonnew.JsonFormat
import sjsonnew.shaded.scalajson.ast.unsafe._
import scala.concurrent.Await
import scala.concurrent.duration.Duration
import scala.util.{ Success, Failure, Try }
import sbt.io.syntax._
import sbt.io.{ Hash, IO }
import sbt.internal.server._
import sbt.internal.langserver.{ LogMessageParams, MessageType }
import sbt.internal.util.{ StringEvent, ObjectEvent, MainAppender }
import sbt.internal.util.codec.JValueFormats
import sbt.protocol.{ EventMessage, ExecStatusEvent }
import sbt.util.{ Level, Logger, LogExchange }

/**
 * The command exchange merges multiple command channels (e.g. network and console),
 * and acts as the central multiplexing point.
 * Instead of blocking on JLine.readLine, the server command will block on
 * this exchange, which could serve command request from either of the channel.
 */
private[sbt] final class CommandExchange {
  private val autoStartServer =
    sys.props get "sbt.server.autostart" forall (_.toLowerCase == "true")

  private var server: Option[ServerInstance] = None
  private val firstInstance: AtomicBoolean = new AtomicBoolean(true)
  private var consoleChannel: Option[ConsoleChannel] = None
  private val commandQueue: ConcurrentLinkedQueue[Exec] = new ConcurrentLinkedQueue()
  private val channelBuffer: ListBuffer[CommandChannel] = new ListBuffer()
  private val channelBufferLock = new AnyRef {}
  private val nextChannelId: AtomicInteger = new AtomicInteger(0)
  private lazy val jsonFormat = new sjsonnew.BasicJsonProtocol with JValueFormats {}

  def channels: List[CommandChannel] = channelBuffer.toList
  def subscribe(c: CommandChannel): Unit = channelBufferLock.synchronized(channelBuffer.append(c))

  // periodically move all messages from all the channels
  @tailrec def blockUntilNextExec: Exec = {
    @tailrec def slurpMessages(): Unit =
      channels.foldLeft(Option.empty[Exec]) { _ orElse _.poll } match {
        case None => ()
        case Some(x) =>
          commandQueue.add(x)
          slurpMessages
      }
    slurpMessages()
    Option(commandQueue.poll) match {
      case Some(x) => x
      case None =>
        Thread.sleep(50)
        blockUntilNextExec
    }
  }

  def run(s: State): State = {
    if (consoleChannel.isEmpty) {
      val console0 = new ConsoleChannel("console0")
      consoleChannel = Some(console0)
      subscribe(console0)
    }
    if (autoStartServer) runServer(s)
    else s
  }

  private def newNetworkName: String = s"network-${nextChannelId.incrementAndGet()}"

  /**
   * Check if a server instance is running already, and start one if it isn't.
   */
  private[sbt] def runServer(s: State): State = {
    lazy val port = s.get(serverPort).getOrElse(5001)
    lazy val host = s.get(serverHost).getOrElse("127.0.0.1")
    lazy val auth: Set[ServerAuthentication] =
      s.get(serverAuthentication).getOrElse(Set(ServerAuthentication.Token))
    lazy val connectionType = s.get(serverConnectionType).getOrElse(ConnectionType.Tcp)
    lazy val level = s.get(serverLogLevel).orElse(s.get(logLevel)).getOrElse(Level.Warn)

    def onIncomingSocket(socket: Socket, instance: ServerInstance): Unit = {
      val name = newNetworkName
      s.log.info(s"new client connected: $name")
      val logger: Logger = {
        val log = LogExchange.logger(name, None, None)
        LogExchange.unbindLoggerAppenders(name)
        val appender = MainAppender.defaultScreen(s.globalLogging.console)
        LogExchange.bindLoggerAppenders(name, List(appender -> level))
        log
      }
      val channel =
        new NetworkChannel(name, socket, Project structure s, auth, instance, logger)
      subscribe(channel)
    }
    if (server.isEmpty && firstInstance.get) {
      val portfile = s.baseDir / "project" / "target" / "active.json"
{'fraction_non_alphanumeric': 0.09790129151291513, 'fraction_numerical': 0.007841328413284132, 'mean_word_length': 3.8861971830985915, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3745604', 'n_tokens_mistral': 2600, 'n_tokens_neox': 2509, 'n_words': 688}