Skip to content

Commit

Permalink
scalafmt 3.7.7, rewrite
Browse files Browse the repository at this point in the history
  • Loading branch information
ornicar committed Jul 6, 2023
1 parent 7de336b commit 9a71e3f
Show file tree
Hide file tree
Showing 47 changed files with 163 additions and 173 deletions.
6 changes: 4 additions & 2 deletions .scalafmt.conf
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
version = "3.7.6"
version = "3.7.7"
runner.dialect = scala3

align.preset = more
maxColumn = 110
spaces.inImportCurlyBraces = true
rewrite.rules = [SortImports, RedundantParens, SortModifiers]
rewrite.redundantBraces.stringInterpolation = true
docstrings.style = keep // don't format comment

rewrite.scala3.convertToNewSyntax = yes
rewrite.scala3.removeOptionalBraces = yes
2 changes: 1 addition & 1 deletion src/main/scala/Auth.scala
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ final class Auth(mongo: Mongo, seenAt: SeenAtUpdate, config: Config)(using Execu
import Mongo.given

def apply(req: RequestHeader): Future[Option[Success]] =
if (req.flag contains Flag.api) Future successful None
if req.flag contains Flag.api then Future successful None
else
sessionIdFromReq(req) match
case Some(sid) if sid startsWith appealPrefix => Future successful None
Expand Down
4 changes: 2 additions & 2 deletions src/main/scala/Chess.scala
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ object Chess:
then initialDests
else
val sit = chess.Game(req.variant.some, Some(req.fen)).situation
if (sit.playable(false)) json.destString(sit.destinations) else ""
if sit.playable(false) then json.destString(sit.destinations) else ""
,
opening =
if Variant.list.openingSensibleVariants(req.variant)
Expand Down Expand Up @@ -81,7 +81,7 @@ object Chess:
move = move,
fen = fen,
check = game.situation.check,
dests = if (movable) game.situation.destinations else Map.empty,
dests = if movable then game.situation.destinations else Map.empty,
opening =
if game.ply <= 30 && Variant.list.openingSensibleVariants(game.board.variant)
then OpeningDb findByEpdFen fen
Expand Down
33 changes: 17 additions & 16 deletions src/main/scala/Controller.scala
Original file line number Diff line number Diff line change
Expand Up @@ -199,22 +199,23 @@ final class Controller(
def racer(id: Racer.Id, header: RequestHeader) =
WebSocket(header): req =>
Future.successful:
req.user.match {
case Some(u) => Option(Racer.PlayerId.User(u))
case None => auth.sidFromReq(header) map Racer.PlayerId.Anon.apply
}.match
case None => notFound
case Some(pid) =>
endpoint(
name = "racer",
behavior = emit =>
RacerClientActor.start(RoomActor.State(id into RoomId, IsTroll(false)), pid):
Deps(emit, req, services)
,
header,
credits = 30,
interval = 15.seconds
)
req.user
.match
case Some(u) => Option(Racer.PlayerId.User(u))
case None => auth.sidFromReq(header) map Racer.PlayerId.Anon.apply
.match
case None => notFound
case Some(pid) =>
endpoint(
name = "racer",
behavior = emit =>
RacerClientActor.start(RoomActor.State(id into RoomId, IsTroll(false)), pid):
Deps(emit, req, services)
,
header,
credits = 30,
interval = 15.seconds
)

def api(header: RequestHeader) =
val req = Req(header, Sri.random, None).copy(flag = Some(Flag.api))
Expand Down
3 changes: 1 addition & 2 deletions src/main/scala/Fens.scala
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ object Fens:
(_, watched) =>
val turnColor = moveBy.fold(Color.white)(c => !c)
json.value
.match {
.match
case MoveClockRegex(uciS, fenS, wcS, bcS) =>
for
uci <- Uci(uciS)
Expand All @@ -64,7 +64,6 @@ object Fens:
yield Position(uci, Fen.Board(fenS), Some(Clock(wc, bc)), turnColor)
case MoveRegex(uciS, fenS) => Uci(uciS) map { Position(_, Fen.Board(fenS), None, turnColor) }
case _ => None
}
.fold(watched): position =>
val msg = ClientIn.Fen(gameId, position)
watched.clients foreach { _ ! msg }
Expand Down
4 changes: 2 additions & 2 deletions src/main/scala/FriendList.scala
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,12 @@ final class FriendList(

private def update(userId: User.Id, msg: User.Id => ipc.ClientIn)(update: UserMeta => UserMeta) =
graph.tell(userId, update) foreach { (subject, subs) =>
if (subs.nonEmpty) users.tellMany(subs, msg(subject.id))
if subs.nonEmpty then users.tellMany(subs, msg(subject.id))
}

private def updateView(userId: User.Id, msg: UserView => ipc.ClientIn)(update: UserMeta => UserMeta) =
graph.tell(userId, update) foreach { (subject, subs) =>
if (subs.nonEmpty)
if subs.nonEmpty then
userDatas
.get(subject.id)
.foreach:
Expand Down
7 changes: 3 additions & 4 deletions src/main/scala/Lila.scala
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ final class Lila(config: Config)(using Executor):

object currentStatus:
private var value: Status = Status.Online
def setOffline() = { value = Status.Offline }
def setOffline() = value = Status.Offline
def setOnline() =
value = Status.Online
buffer.flush()
Expand All @@ -30,7 +30,7 @@ final class Lila(config: Config)(using Executor):
@annotation.tailrec
def flush(): Unit =
val next = queue.poll()
if (next != null)
if next != null then
connIn.async.publish(next.chan, next.msg)
flush()

Expand Down Expand Up @@ -70,7 +70,7 @@ final class Lila(config: Config)(using Executor):

val connIn = redis.connectPubSub

val emit: Emit[In] = in => {
val emit: Emit[In] = in =>
val msg = in.write
val path = msg.takeWhile(' '.!=)
val chanIn = chan in msg
Expand All @@ -83,7 +83,6 @@ final class Lila(config: Config)(using Executor):
else if in.isInstanceOf[LilaIn.RoomSetVersions]
then connIn.async.publish(chanIn, msg)
else Monitor.redis.drop(chanIn, path)
}

chan
.match
Expand Down
4 changes: 2 additions & 2 deletions src/main/scala/LilaHandler.scala
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ final class LilaHandler(
if allAbsent.sizeIs > 100
then ThreadLocalRandom.shuffle(allAbsent) take 80
else allAbsent
if (absent.nonEmpty) users.tellMany(absent, ClientIn.TourReminder(roomId into Tour.Id, name))
if absent.nonEmpty then users.tellMany(absent, ClientIn.TourReminder(roomId into Tour.Id, name))
}
case LilaBoot => roomBoot(_.idFilter.tour, lila.emit.tour)
case msg => roomHandler(msg)
Expand All @@ -120,7 +120,7 @@ final class LilaHandler(
val versioned = ClientIn.RoundVersioned(version, flags, tpe, data)
History.round.add(gameId, versioned)
publish(_ room gameId, versioned)
if (tpe == "move" || tpe == "drop") Fens.move(gameId, data, flags.moveBy)
if tpe == "move" || tpe == "drop" then Fens.move(gameId, data, flags.moveBy)
case TellRoom(roomId, payload) => publish(_ room roomId, ClientIn.Payload(payload))
case RoundResyncPlayer(fullId) =>
publish(_ room fullId.gameId, ClientIn.RoundResyncPlayer(fullId.playerId))
Expand Down
6 changes: 3 additions & 3 deletions src/main/scala/Monitor.scala
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ final class Monitor(
logger.info(s"lila-ws 3.0 netty native=$native kamon=$useKamon")
logger.info(s"Java version: $version, memory: ${memory}MB")

if (useKamon) kamon.Kamon.init()
if useKamon then kamon.Kamon.init()

scheduler.scheduleWithFixedDelay(5.seconds, 1949.millis) { () => periodicMetrics() }

Expand Down Expand Up @@ -134,7 +134,7 @@ object Monitor:
private val frameLagHistogram = Kamon.timer("round.lag.frame").withoutTags()

def roundFrameLag(millis: Int) =
if (millis > 1 && millis < 99999) frameLagHistogram.record(millis.toLong, TimeUnit.MILLISECONDS)
if millis > 1 && millis < 99999 then frameLagHistogram.record(millis.toLong, TimeUnit.MILLISECONDS)

def time[A](metric: Monitor.type => kamon.metric.Timer)(f: => A): A =
val timer = metric(Monitor).start()
Expand All @@ -145,7 +145,7 @@ object Monitor:
object evalCache:
private val r = Kamon.counter("evalCache.request")
def request(ply: Int, isHit: Boolean) =
r.withTags(TagSet.from(Map("ply" -> (if (ply < 15) ply.toString else "15+"), "hit" -> isHit)))
r.withTags(TagSet.from(Map("ply" -> (if ply < 15 then ply.toString else "15+"), "hit" -> isHit)))
object upgrade:
val count = Kamon.counter("evalCache.upgrade.count").withoutTags()
val members = Kamon.gauge("evalCache.upgrade.members").withoutTags()
Expand Down
7 changes: 3 additions & 4 deletions src/main/scala/RoomCrowd.scala
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,11 @@ final class RoomCrowd(json: CrowdJson, groupedWithin: util.GroupedWithin)(using
def disconnect(roomId: RoomId, user: Option[User.Id]): Unit =
val room = rooms.computeIfPresent(
roomId,
(_, room) => {
(_, room) =>
val newRoom = room disconnect user
if (newRoom.isEmpty) null else newRoom
}
if newRoom.isEmpty then null else newRoom
)
if (room != null) publish(roomId, room)
if room != null then publish(roomId, room)

def getUsers(roomId: RoomId): Set[User.Id] =
Option(rooms get roomId).fold(Set.empty[User.Id])(_.users.keySet)
Expand Down
16 changes: 7 additions & 9 deletions src/main/scala/RoundCrowd.scala
Original file line number Diff line number Diff line change
Expand Up @@ -24,23 +24,21 @@ final class RoundCrowd(
def disconnect(roomId: RoomId, user: Option[User.Id], player: Option[Color]): Unit =
rounds.computeIfPresent(
roomId,
(_, round) => {
(_, round) =>
val newRound = round.disconnect(user, player)
publish(roomId, newRound)
if (newRound.isEmpty) null else newRound
}
if newRound.isEmpty then null else newRound
)

def botOnline(roomId: RoomId, color: Color, online: Boolean): Unit =
rounds.compute(
roomId,
(_, cur) =>
Option(cur).getOrElse(RoundState()).botOnline(color, online) match {
Option(cur).getOrElse(RoundState()).botOnline(color, online) match
case None => cur
case Some(round) =>
publish(roomId, round)
if (round.isEmpty) null else round
}
if round.isEmpty then null else round
)

def getUsers(roomId: RoomId): Set[User.Id] =
Expand Down Expand Up @@ -80,16 +78,16 @@ object RoundCrowd:
):
def connect(user: Option[User.Id], player: Option[Color]) =
copy(
room = if (player.isDefined) room else room connect user,
room = if player.isDefined then room else room connect user,
players = player.fold(players)(c => players.update(c, _ + 1))
)
def disconnect(user: Option[User.Id], player: Option[Color]) =
copy(
room = if (player.isDefined) room else room disconnect user,
room = if player.isDefined then room else room disconnect user,
players = player.fold(players)(c => players.update(c, nb => Math.max(0, nb - 1)))
)
def botOnline(color: Color, online: Boolean): Option[RoundState] = Some:
if (online) connect(None, Some(color))
if online then connect(None, Some(color))
else disconnect(None, Some(color))

def isEmpty = room.isEmpty && players.forall(1 > _)
4 changes: 2 additions & 2 deletions src/main/scala/SeenAtUpdate.scala
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ final class SeenAtUpdate(mongo: Mongo)(using
)
isCoach = userDoc.exists(_.getAsOpt[List[String]]("roles").exists(_ contains "ROLE_COACH"))
_ <-
if (isCoach)
if isCoach then
mongo.coach(
_.update(ordered = false).one(
BSONDocument("_id" -> user),
Expand All @@ -39,7 +39,7 @@ final class SeenAtUpdate(mongo: Mongo)(using
)
else Future successful {}
_ <-
if (userDoc.isDefined && streamers.contains(user))
if userDoc.isDefined && streamers.contains(user) then
mongo.streamer(
_.update(ordered = false).one(
BSONDocument("_id" -> user),
Expand Down
13 changes: 6 additions & 7 deletions src/main/scala/SocialGraph.scala
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ final class SocialGraph(mongo: Mongo, config: Config):
// Try to find an existing or empty slot between hash and
// hash + MaxStride.
val hash = fxhash32(id) & slotsMask
for (s <- hash to (hash + SocialGraph.MaxStride))
for s <- hash to (hash + SocialGraph.MaxStride) do
val slot = s & slotsMask
read(slot) match
case None => throwReturn[Slot](NewSlot(slot))
Expand All @@ -72,7 +72,7 @@ final class SocialGraph(mongo: Mongo, config: Config):
// is lost.
// Do not replace exceptSlot. This can be used so that a followed user
// does not replace its follower.
for (s <- hash to (hash + SocialGraph.MaxStride))
for s <- hash to (hash + SocialGraph.MaxStride) do
val slot = s & slotsMask
read(slot) match
case None => throwReturn[Slot](NewSlot(slot))
Expand All @@ -83,7 +83,7 @@ final class SocialGraph(mongo: Mongo, config: Config):
case _ =>

// The hashtable is full. Overwrite a random entry.
val slot = if (hash != exceptSlot) hash else (hash + 1) & slotsMask
val slot = if hash != exceptSlot then hash else (hash + 1) & slotsMask
freeSlot(slot)

private def freeSlot(leftSlot: Int): NewSlot =
Expand Down Expand Up @@ -118,14 +118,13 @@ final class SocialGraph(mongo: Mongo, config: Config):
graph.readOutgoing(leftSlot) foreach { graph.remove(leftSlot, _) }

(followed map { userId =>
val (rightSlot, info) = findSlot(userId, leftSlot) match {
val (rightSlot, info) = findSlot(userId, leftSlot) match
case NewSlot(rightSlot) =>
write(rightSlot, UserEntry(userId, UserMeta.stale))
rightSlot -> UserEntry(userId, UserMeta.stale)
case ExistingSlot(rightSlot, entry) =>
write(rightSlot, entry)
rightSlot -> UserEntry(userId, entry.meta)
}
graph.add(leftSlot, rightSlot)
info
}).toList
Expand Down Expand Up @@ -155,7 +154,7 @@ final class SocialGraph(mongo: Mongo, config: Config):
case NewSlot(_) =>
None
case ExistingSlot(slot, entry) =>
if (entry.meta.fresh)
if entry.meta.fresh then
write(slot, entry.update(_.withSubscribed(true)))
Some(readFollowed(slot))
else None
Expand Down Expand Up @@ -241,7 +240,7 @@ object SocialGraph:
val freshSubscribed = UserMeta(FRESH | SUBSCRIBED)

extension (flags: UserMeta)
private inline def toggle(flag: Int, on: Boolean) = UserMeta(if (on) flags | flag else flags & ~flag)
private inline def toggle(flag: Int, on: Boolean) = UserMeta(if on then flags | flag else flags & ~flag)
private inline def has(flag: Int): Boolean = (flags & flag) != 0

inline def fresh = flags.has(UserMeta.FRESH)
Expand Down
2 changes: 1 addition & 1 deletion src/main/scala/Tv.scala
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ object Tv:
Bus.publish(_ room RoomId(gameId), cliMsg)
}
}
(if (out.speed <= chess.Speed.Bullet) fast else slow).put(out.gameId.value, true)
(if out.speed <= chess.Speed.Bullet then fast else slow).put(out.gameId.value, true)

def get(gameId: Game.Id): Boolean = get(gameId, fast) || get(gameId, slow)

Expand Down
7 changes: 3 additions & 4 deletions src/main/scala/Users.scala
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,12 @@ final class Users(using scheduler: Scheduler, ec: Executor):
def disconnect(user: User.Id, client: Client): Unit =
users.computeIfPresent(
user,
(_, clients) => {
(_, clients) =>
val newClients = clients - client
if (newClients.isEmpty) {
if newClients.isEmpty then
disconnects add user
null
} else newClients
}
else newClients
)

def tellOne(userId: User.Id, payload: ClientMsg): Unit =
Expand Down
6 changes: 3 additions & 3 deletions src/main/scala/actor/ChallengeClientActor.scala
Original file line number Diff line number Diff line change
Expand Up @@ -41,21 +41,21 @@ object ChallengeClientActor:
Behaviors.same

case ClientCtrl.Broom(oldSeconds) =>
if (state.site.lastPing < oldSeconds) Behaviors.stopped
if state.site.lastPing < oldSeconds then Behaviors.stopped
else
keepAlive challenge state.room.room
Behaviors.same

case ctrl: ClientCtrl => socketControl(state.site, deps, ctrl)

case ClientOut.ChallengePing =>
if (state.owner) services.challengePing(state.room.room)
if state.owner then services.challengePing(state.room.room)
Behaviors.same

// default receive (site)
case msg: ClientOutSite =>
val siteState = globalReceive(state.site, deps, ctx, msg)
if (siteState == state.site) Behaviors.same
if siteState == state.site then Behaviors.same
else apply(state.copy(site = siteState), deps)

case _ =>
Expand Down
Loading

0 comments on commit 9a71e3f

Please sign in to comment.