Skip to content

Commit

Permalink
Run scalafmtAll
Browse files Browse the repository at this point in the history
  • Loading branch information
lenguyenthanh committed Jul 5, 2023
1 parent db6d309 commit 77ff4f6
Show file tree
Hide file tree
Showing 618 changed files with 2,325 additions and 2,558 deletions.
4 changes: 2 additions & 2 deletions app/Lila.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package lila.app

import java.io._
import java.io.*

import play.api.{ Application, Environment, Play, Configuration, Mode }
import play.core.server.{ RealServerProcess, ServerProcess, Server, ServerStartException, ServerConfig }
Expand Down Expand Up @@ -96,7 +96,7 @@ object Lila:
val address = configuration.getOptional[String]("play.server.http.address").getOrElse("0.0.0.0")

val mode =
if (configuration.getOptional[String]("play.mode").contains("prod")) Mode.Prod
if configuration.getOptional[String]("play.mode").contains("prod") then Mode.Prod
else Mode.Dev

ServerConfig(rootDir, httpPort, address, mode, process.properties, configuration)
9 changes: 4 additions & 5 deletions app/LoggerConfigurator.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ package lila.app
import java.io.File
import java.net.URL

import ch.qos.logback.classic._
import ch.qos.logback.classic.*
import ch.qos.logback.classic.jul.LevelChangePropagator
import ch.qos.logback.classic.util.ContextInitializer
import ch.qos.logback.core.util._
import ch.qos.logback.core.util.*
import org.slf4j.{ LoggerFactory, ILoggerFactory }
import org.slf4j.bridge._
import org.slf4j.bridge.*

private object LoggerConfigurator:

Expand All @@ -20,7 +20,7 @@ private object LoggerConfigurator:
new File(sys.props.get("logger.file").getOrElse("conf/logger.dev.xml")).toURI.toURL
)

def configure(properties: Map[String, String], configUrl: URL): Unit = {
def configure(properties: Map[String, String], configUrl: URL): Unit =
// Touching LoggerContext is not thread-safe, and so if you run several
// application tests at the same time (spec2 / scalatest with "new WithApplication()")
// then you will see NullPointerException as the array list loggerContextListenerList
Expand Down Expand Up @@ -71,7 +71,6 @@ private object LoggerConfigurator:

StatusPrinter.printIfErrorsOccured(ctx)
// }
}

def shutdown(): Unit =
val ctx = loggerFactory.asInstanceOf[LoggerContext]
Expand Down
4 changes: 2 additions & 2 deletions app/controllers/Api.scala
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ final class Api(
val result =
if csv then csvDownload(lila.tournament.TournamentCsv(source))
else jsonDownload(source.map(lila.tournament.JsonView.playerResultWrites.writes))
result.pipe(asAttachment(env.api.gameApiV2.filename(tour, if (csv) "csv" else "ndjson")))
result.pipe(asAttachment(env.api.gameApiV2.filename(tour, if csv then "csv" else "ndjson")))
}

def tournamentTeams(id: TourId) = Anon:
Expand Down Expand Up @@ -306,7 +306,7 @@ final class Api(
transform: String => Option[Id]
)(f: Set[Id] => Result): Result =
val ids = req.body.split(',').view.filter(_.nonEmpty).flatMap(s => transform(s.trim)).toSet
if (ids.size > max) JsonBadRequest(jsonError(s"Too many ids: ${ids.size}, expected up to $max"))
if ids.size > max then JsonBadRequest(jsonError(s"Too many ids: ${ids.size}, expected up to $max"))
else f(ids)

val cloudEval =
Expand Down
9 changes: 4 additions & 5 deletions app/controllers/Auth.scala
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ final class Auth(
def authenticate = OpenBody:
NoCrawlers:
Firewall:
def redirectTo(url: String) = if (HTTPRequest isXhr ctx.req) Ok(s"ok:$url") else Redirect(url)
def redirectTo(url: String) = if HTTPRequest isXhr ctx.req then Ok(s"ok:$url") else Redirect(url)
val referrer = get("referrer").filterNot(env.api.referrerRedirect.sillyLoginReferrers)
api.loginForm
.bindFromRequest()
Expand Down Expand Up @@ -204,7 +204,7 @@ final class Auth(
ctx: Context
): Funit =
garbageCollect(user)(email)
if (sendWelcomeEmail) env.mailer.automaticEmail.welcomeEmail(user, email)
if sendWelcomeEmail then env.mailer.automaticEmail.welcomeEmail(user, email)
env.mailer.automaticEmail.welcomePM(user)
env.pref.api.saveNewUserPrefs(user, ctx.req)

Expand Down Expand Up @@ -382,7 +382,7 @@ final class Auth(
def magicLinkApply = OpenBody:
Firewall:
env.security.hcaptcha.verify() flatMap { captcha =>
if (captcha.ok)
if captcha.ok then
forms.magicLink flatMap {
_.form
.bindFromRequest()
Expand All @@ -401,8 +401,7 @@ final class Auth(
}
)
}
else
renderMagicLink(none, fail = true) map { BadRequest(_) }
else renderMagicLink(none, fail = true) map { BadRequest(_) }
}

def magicLinkSent = Open:
Expand Down
2 changes: 1 addition & 1 deletion app/controllers/Challenge.scala
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ final class Challenge(
_ map { game =>
env.lilaCookie.cookie(
AnonCookie.name,
game.player(if (owner) c.finalColor else !c.finalColor).id.value,
game.player(if owner then c.finalColor else !c.finalColor).id.value,
maxAge = AnonCookie.maxAge.some,
httpOnly = false.some
)
Expand Down
6 changes: 3 additions & 3 deletions app/controllers/Clas.scala
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import views.*
import lila.app.{ given, * }

import lila.clas.ClasInvite
import lila.clas.Clas.{ Id => ClasId }
import lila.clas.Clas.{ Id as ClasId }

final class Clas(env: Env, authC: Auth) extends LilaController(env):

Expand Down Expand Up @@ -107,7 +107,7 @@ final class Clas(env: Env, authC: Auth) extends LilaController(env):
else
Found(env.clas.api.clas.byId(id)): clas =>
env.clas.api.student.activeWithUsers(clas) flatMap { students =>
if (students.exists(_.student is me)) forStudent(clas, students)
if students.exists(_.student is me) then forStudent(clas, students)
else orDefault(ctx)
}
}
Expand Down Expand Up @@ -173,7 +173,7 @@ final class Clas(env: Env, authC: Auth) extends LilaController(env):
env.clas.api.student.activeWithUsers(clas) flatMap { students =>
Reasonable(clas, students, "notify"):
val url = routes.Clas.show(clas.id.value).url
val full = if (text contains url) text else s"$text\n\n${env.net.baseUrl}$url"
val full = if text contains url then text else s"$text\n\n${env.net.baseUrl}$url"
env.msg.api
.multiPost(Source(students.map(_.user.id)), full)
.addEffect: nb =>
Expand Down
4 changes: 2 additions & 2 deletions app/controllers/Dasher.scala
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,12 @@ final class Dasher(env: Env)(using ws: StandaloneWSClient) extends LilaControlle

private def translations(using Context) =
lila.i18n.JsDump.keysToObject(
if (ctx.isAnon) translationsAnon else translationsAuth,
if ctx.isAnon then translationsAnon else translationsAuth,
ctx.lang
) ++ lila.i18n.JsDump.keysToObject(
// the language settings should never be in a totally foreign language
List(trans.language),
if (I18nLangPicker.allFromRequestHeaders(ctx.req).has(ctx.lang)) ctx.lang
if I18nLangPicker.allFromRequestHeaders(ctx.req).has(ctx.lang) then ctx.lang
else I18nLangPicker.bestFromRequestHeaders(ctx.req) | enLang
)

Expand Down
2 changes: 1 addition & 1 deletion app/controllers/Editor.scala
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ final class Editor(env: Env) extends LilaController(env):
else editorUrl(get("fen").fold(Fen.write(game.chess))(Fen.Epd.clean), game.variant)

private[controllers] def editorUrl(fen: Fen.Epd, variant: Variant): String =
if (fen == Fen.initial && variant.standard) routes.Editor.index.url
if fen == Fen.initial && variant.standard then routes.Editor.index.url
else
val params = variant.exotic so s"?variant=${variant.key}"
routes.Editor.load(lila.common.String.underscoreFen(fen)).url + params
4 changes: 2 additions & 2 deletions app/controllers/Export.scala
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ final class Export(env: Env) extends LilaController(env):
g.fen,
Theme(theme).name,
PieceSet.get(piece).name
) pipe stream(cacheSeconds = if (g.game.finishedOrAborted) 3600 * 24 else 10)
) pipe stream(cacheSeconds = if g.game.finishedOrAborted then 3600 * 24 else 10)
}

def legacyGameThumbnail(id: GameId, theme: Option[String], piece: Option[String]) = Anon:
Expand All @@ -47,7 +47,7 @@ final class Export(env: Env) extends LilaController(env):
def gameThumbnail(id: GameId, theme: Option[String], piece: Option[String]) =
exportImageOf(env.game.gameRepo game id) { game =>
env.game.gifExport.gameThumbnail(game, Theme(theme).name, PieceSet.get(piece).name) pipe
stream(cacheSeconds = if (game.finishedOrAborted) 3600 * 24 else 10)
stream(cacheSeconds = if game.finishedOrAborted then 3600 * 24 else 10)
}

def puzzleThumbnail(id: PuzzleId, theme: Option[String], piece: Option[String]) =
Expand Down
4 changes: 2 additions & 2 deletions app/controllers/ForumController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import play.api.mvc.*
import lila.app.{ given, * }
import lila.forum.ForumTopic

private[controllers] trait ForumController { self: LilaController =>
private[controllers] trait ForumController:
self: LilaController =>

protected def categApi = env.forum.categApi
protected def topicApi = env.forum.topicApi
Expand Down Expand Up @@ -55,4 +56,3 @@ private[controllers] trait ForumController { self: LilaController =>
else Forbidden("You cannot moderate this forum")
}
}
}
4 changes: 2 additions & 2 deletions app/controllers/ForumPost.scala
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,8 @@ final class ForumPost(env: Env) extends LilaController(env) with ForumController
topic <- topicRepo.forUser(me.some).byId(post.topicId)
reason <- reasonOpt.filter(MsgPreset.forumDeletion.presets.contains)
preset =
if (isGranted(_.ModerateForum)) MsgPreset.forumDeletion.byModerator
else if (topic.exists(_ isUblogAuthor me))
if isGranted(_.ModerateForum) then MsgPreset.forumDeletion.byModerator
else if topic.exists(_ isUblogAuthor me) then
MsgPreset.forumDeletion.byBlogAuthor(me.username)
else MsgPreset.forumDeletion.byTeamLeader(categId)
do env.msg.api.systemPost(userId, preset(reason))
Expand Down
5 changes: 3 additions & 2 deletions app/controllers/Game.scala
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ final class Game(env: Env, apiC: => Api) extends LilaController(env):
case None => NotFound
case Some(game) =>
val config = GameApiV2.OneConfig(
format = if (HTTPRequest acceptsJson req) GameApiV2.Format.JSON else GameApiV2.Format.PGN,
format = if HTTPRequest acceptsJson req then GameApiV2.Format.JSON else GameApiV2.Format.PGN,
imported = getBool("imported"),
flags = requestPgnFlags(extended = true),
playerFile = get("players")
Expand Down Expand Up @@ -72,7 +72,8 @@ final class Game(env: Env, apiC: => Api) extends LilaController(env):
color = get("color") flatMap chess.Color.fromName,
analysed = getBoolOpt("analysed"),
flags = requestPgnFlags(extended = false),
sort = if (get("sort") has "dateAsc") GameApiV2.GameSort.DateAsc else GameApiV2.GameSort.DateDesc,
sort =
if get("sort") has "dateAsc" then GameApiV2.GameSort.DateAsc else GameApiV2.GameSort.DateDesc,
perSecond = MaxPerSecond(ctx.me match
case Some(m) if m is lila.user.User.explorerId => env.apiExplorerGamesPerSecond.get()
case Some(m) if m is user.id => 60
Expand Down
2 changes: 1 addition & 1 deletion app/controllers/I18n.scala
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ final class I18n(env: Env) extends LilaController(env):
val pageUrl = new java.net.URI(str).parseServerAuthority().toURL()
val path = pageUrl.getPath
val query = pageUrl.getQuery
if (query == null) path
if query == null then path
else path + "?" + query
catch case _: Exception => routes.Lobby.home.url
if ctx.isAnon
Expand Down
2 changes: 1 addition & 1 deletion app/controllers/Main.scala
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ final class Main(
def captchaCheck(id: GameId) = Open:
import makeTimeout.long
env.hub.captcher.actor ? ValidCaptcha(id, ~get("solution")) map { case valid: Boolean =>
Ok(if (valid) 1 else 0)
Ok(if valid then 1 else 0)
}

def webmasters = Open:
Expand Down
6 changes: 3 additions & 3 deletions app/controllers/Mod.scala
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ final class Mod(
case _ if Granter(_.BoostHunter) => ModDomain.Boost
case _ => ModDomain.Admin
,
room = if (report.isSpontaneous) "Spontaneous inquiry" else report.room.name
room = if report.isSpontaneous then "Spontaneous inquiry" else report.room.name
) inject NoContent
}
}
Expand Down Expand Up @@ -301,10 +301,10 @@ final class Mod(
.flashFailure(s"Currently processed by ${mod.name}")
case _ =>
val f =
if (isAppeal) env.report.api.inquiries.appeal
if isAppeal then env.report.api.inquiries.appeal
else env.report.api.inquiries.spontaneous
f(Suspect(user)) inject {
if (isAppeal) Redirect(s"${appeal.routes.Appeal.show(user.username)}#appeal-actions")
if isAppeal then Redirect(s"${appeal.routes.Appeal.show(user.username)}#appeal-actions")
else redirect(user.username, mod = true)
}
}
Expand Down
7 changes: 3 additions & 4 deletions app/controllers/Opening.scala
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,9 @@ final class Opening(env: Env) extends LilaController(env):
case None => Redirect(routes.Opening.index(key.some))
case Some(page) =>
val query = page.query.query
if (query.key.isEmpty) Redirect(routes.Opening.index(key.some))
else if (query.key != key)
Redirect(routes.Opening.byKeyAndMoves(query.key, moves))
else if (moves.nonEmpty && page.query.pgnUnderscored != moves && !getBool("r"))
if query.key.isEmpty then Redirect(routes.Opening.index(key.some))
else if query.key != key then Redirect(routes.Opening.byKeyAndMoves(query.key, moves))
else if moves.nonEmpty && page.query.pgnUnderscored != moves && !getBool("r") then
Redirect:
s"${routes.Opening.byKeyAndMoves(query.key, page.query.pgnUnderscored)}?r=1"
else
Expand Down
5 changes: 2 additions & 3 deletions app/controllers/Puzzle.scala
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ final class Puzzle(env: Env, apiC: => Api) extends LilaController(env):
"voted" -> round.vote
)
else
(data.replayDays, angle.asTheme) match {
(data.replayDays, angle.asTheme) match
case (Some(replayDays), Some(theme)) =>
for
_ <- env.puzzle.replay.onComplete(round, replayDays, angle)
Expand All @@ -187,12 +187,11 @@ final class Puzzle(env: Env, apiC: => Api) extends LilaController(env):
"round" -> env.puzzle.jsonView.roundJson.web(round, perf)(using me),
"next" -> nextJson
)
}
yield json
}
case None =>
env.puzzle.finisher.incPuzzlePlays(id)
if (mobileBc) fuccess(Json.obj("user" -> false))
if mobileBc then fuccess(Json.obj("user" -> false))
else
nextPuzzleForMe(angle, data.color map some)
.flatMap:
Expand Down
3 changes: 1 addition & 2 deletions app/controllers/RelayRound.scala
Original file line number Diff line number Diff line change
Expand Up @@ -95,11 +95,10 @@ final class RelayRound(
val sc =
if rt.round.sync.ongoing then
env.study.chapterRepo relaysAndTagsByStudyId rt.round.studyId flatMap { chapters =>
chapters.find(_.looksAlive) orElse chapters.headOption match {
chapters.find(_.looksAlive) orElse chapters.headOption match
case Some(chapter) =>
env.study.api.byIdWithChapterOrFallback(rt.round.studyId, chapter.id)
case None => env.study.api byIdWithChapter rt.round.studyId
}
}
else env.study.api byIdWithChapter rt.round.studyId
sc orNotFound { doShow(rt, _) }
Expand Down
6 changes: 3 additions & 3 deletions app/controllers/Report.scala
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ final class Report(
}

private def onInquiryStart(inquiry: ReportModel): Result =
if (inquiry.isRecentComm) Redirect(controllers.routes.Mod.communicationPrivate(inquiry.user))
else if (inquiry.isComm) Redirect(controllers.routes.Mod.communicationPublic(inquiry.user))
if inquiry.isRecentComm then Redirect(controllers.routes.Mod.communicationPrivate(inquiry.user))
else if inquiry.isComm then Redirect(controllers.routes.Mod.communicationPublic(inquiry.user))
else modC.redirect(inquiry.user)

protected[controllers] def onModAction(goTo: Suspect)(using ctx: BodyContext[?], me: Me): Fu[Result] =
Expand Down Expand Up @@ -131,7 +131,7 @@ final class Report(

def form = Auth { _ ?=> _ ?=>
getUserStr("username") so env.user.repo.byId flatMap { user =>
if (user.map(_.id) has UserModel.lichessId) Redirect(controllers.routes.Main.contact)
if user.map(_.id) has UserModel.lichessId then Redirect(controllers.routes.Main.contact)
else
Ok.pageAsync:
val form = env.report.forms.create
Expand Down
2 changes: 1 addition & 1 deletion app/controllers/Round.scala
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ final class Round(
playablePovForReq(pov.game) match
case Some(player) if userTv.isEmpty => renderPlayer(pov withColor player.color)
case _ if pov.game.variant == chess.variant.RacingKings && pov.color.black =>
if (userTv.isDefined) watch(!pov, userTv)
if userTv.isDefined then watch(!pov, userTv)
else Redirect(routes.Round.watcher(pov.gameId, "white"))
case _ =>
negotiateApi(
Expand Down
2 changes: 1 addition & 1 deletion app/controllers/Simul.scala
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ final class Simul(env: Env) extends LilaController(env):

def withdraw(id: SimulId) = Auth { ctx ?=> me ?=>
env.simul.api.removeApplicant(id, me) inject {
if (HTTPRequest isXhr ctx.req) jsonOkResult
if HTTPRequest isXhr ctx.req then jsonOkResult
else Redirect(routes.Simul.show(id))
}
}
Expand Down
2 changes: 1 addition & 1 deletion app/controllers/Storm.scala
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ final class Storm(env: Env) extends LilaController(env):

def apiDashboardOf(username: UserStr, days: Int) = Open:
lila.user.User.validateId(username).so { userId =>
if (days < 0 || days > 365) notFoundJson("Invalid days parameter")
if days < 0 || days > 365 then notFoundJson("Invalid days parameter")
else
((days > 0) so env.storm.dayApi.apiHistory(userId, days)) zip env.storm.highApi.get(userId) map {
case (history, high) => Ok(env.storm.json.apiDashboard(high, history))
Expand Down
4 changes: 2 additions & 2 deletions app/controllers/Streamer.scala
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ final class Streamer(env: Env, apiC: => Api) extends LilaController(env):
BadRequest.page(html.streamer.edit(sws, error, forMod)),
data =>
api.update(sws.streamer, data, isGranted(_.Streamers)) flatMap { change =>
if (change.decline) logApi.streamerDecline(s.user.id)
if change.decline then logApi.streamerDecline(s.user.id)
change.list foreach { logApi.streamerList(s.user.id, _) }
change.tier foreach { logApi.streamerTier(s.user.id, _) }
if data.approval.flatMap(_.quick).isDefined
Expand All @@ -115,7 +115,7 @@ final class Streamer(env: Env, apiC: => Api) extends LilaController(env):
nextId.fold(s"${routes.Streamer.index()}?requests=1"): id =>
s"${routes.Streamer.edit.url}?u=$id"
else
val next = if (sws.streamer is me) "" else s"?u=${sws.user.id}"
val next = if sws.streamer is me then "" else s"?u=${sws.user.id}"
Redirect(s"${routes.Streamer.edit.url}$next")
}
)
Expand Down
Loading

0 comments on commit 77ff4f6

Please sign in to comment.