From 16f0742b23de2e48c250bdcf55ecdf5f680d2016 Mon Sep 17 00:00:00 2001 From: xuwei-k <6b656e6a69@gmail.com> Date: Sun, 15 Jun 2025 15:01:08 +0900 Subject: [PATCH] add sbt-scalafmt plugin. update scalafmt config --- .github/workflows/build-test.yml | 2 +- .scalafmt.conf | 7 +- app/actors/DocumentationActor.scala | 2 +- app/actors/DocumentationLoadingActor.scala | 2 +- app/actors/DocumentationPollingActor.scala | 12 ++-- app/controllers/Application.scala | 33 +++++---- app/controllers/Blog.scala | 8 +-- app/controllers/Modules.scala | 14 ++-- app/controllers/Outreachy.scala | 6 +- app/controllers/Security.scala | 8 +-- .../DocumentationController.scala | 67 +++++++++++-------- app/controllers/documentation/Router.scala | 14 ++-- app/models/PlayExampleProjects.scala | 31 +++++---- app/models/Releases.scala | 7 +- app/models/documentation/Documentation.scala | 4 +- app/models/github/FallbackContributors.scala | 2 +- .../opencollective/FallbackMembers.scala | 2 +- .../opencollective/OpenCollective.scala | 2 +- .../github/ContributorsSummariser.scala | 2 +- app/services/github/GitHub.scala | 4 +- app/services/modules/ModuleDao.scala | 2 +- .../opencollective/MembersSummariser.scala | 2 +- app/services/releases/ReleasesModule.scala | 9 ++- app/utils/GitFileRepository.scala | 2 +- app/utils/Markdown.scala | 2 +- build.sbt | 6 +- project/plugins.sbt | 9 +-- test/controllers/ModulesSpec.scala | 2 +- .../DocumentationControllerSpec.scala | 24 +++---- .../github/ContributorsSummariserSpec.scala | 4 +- test/services/github/GitHubSpec.scala | 2 +- .../GitFileRepositoryPerformanceTest.scala | 8 +-- 32 files changed, 168 insertions(+), 133 deletions(-) diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml index 83733745..73157a80 100644 --- a/.github/workflows/build-test.yml +++ b/.github/workflows/build-test.yml @@ -42,7 +42,7 @@ jobs: cmd: | # Clone generated docs so that we can run some integration tests git clone -o origin https://github.com/playframework/play-generated-docs.git $PWD/data/generated - sbt ++$MATRIX_SCALA test + sbt ++$MATRIX_SCALA scalafmtSbtCheck scalafmtCheckAll test finish: name: Finish diff --git a/.scalafmt.conf b/.scalafmt.conf index cca03577..1aa282ca 100644 --- a/.scalafmt.conf +++ b/.scalafmt.conf @@ -1,7 +1,8 @@ -align = more +runner.dialect = Scala3 +align.preset = more assumeStandardLibraryStripMargin = true -danglingParentheses = true -docstrings = JavaDoc +danglingParentheses.preset = true +docstrings.style = keep maxColumn = 112 project.git = true rewrite.rules = [ AvoidInfix, ExpandImportSelectors, RedundantParens, SortModifiers, PreferCurlyFors ] diff --git a/app/actors/DocumentationActor.scala b/app/actors/DocumentationActor.scala index 67e8739b..59d01fb9 100644 --- a/app/actors/DocumentationActor.scala +++ b/app/actors/DocumentationActor.scala @@ -395,7 +395,7 @@ class DocumentationActor( * Get the translation context for the given language and version. */ def translationContext(lang: Lang, version: Version, translation: Translation): TranslationContext = { - val isDefault = lang == documentation.defaultLang + val isDefault = lang == documentation.defaultLang val defaultAlternative = AlternateTranslation( documentation.defaultLang, true, diff --git a/app/actors/DocumentationLoadingActor.scala b/app/actors/DocumentationLoadingActor.scala index 19776bae..2cfe7333 100644 --- a/app/actors/DocumentationLoadingActor.scala +++ b/app/actors/DocumentationLoadingActor.scala @@ -69,7 +69,7 @@ object DocumentationLoadingActor { val sheets = sortedSheets.flatMap { file => repo.loadFile(s"cheatsheets/$category/$file")(is => Textile.toHTML(IOUtils.toString(is, "utf-8"))) } - val title = CheatSheetHelper.getCategoryTitle(category) + val title = CheatSheetHelper.getCategoryTitle(category) val otherCategories = CheatSheetHelper .listCategoriesAndTitles( repo diff --git a/app/actors/DocumentationPollingActor.scala b/app/actors/DocumentationPollingActor.scala index 550725cb..3cc590cd 100644 --- a/app/actors/DocumentationPollingActor.scala +++ b/app/actors/DocumentationPollingActor.scala @@ -119,7 +119,7 @@ class DocumentationPollingActor( old.flatMap(_.default.byVersion.get(version)) match { // The version hasn't changed, don't rescan case Some(same: TranslationVersion) if same.cacheId == newCacheId => same - case _ => + case _ => implicit val lang = repos.default.config.lang if (old.isDefined) { @@ -144,7 +144,7 @@ class DocumentationPollingActor( // Now for each translation val translations = repos.translations.map { t => // Parse all the versions from tags, branches and the main version - val gitTags = parseVersionsFromRefs(t.repo.allTags).map(v => (v._1, v._2, v._1.name)) + val gitTags = parseVersionsFromRefs(t.repo.allTags).map(v => (v._1, v._2, v._1.name)) val gitBranches = parseVersionsFromRefs( t.repo.allBranches .filter(_._1.matches("""\d+\.\d+\.x""")), @@ -152,7 +152,7 @@ class DocumentationPollingActor( val mainVersion = determineMainVersion(t).map(v => (v._1, v._2, "main")) implicit val lang = t.config.lang - val versions = versionsToTranslations( + val versions = versionsToTranslations( t.repo, gitTags ++ gitBranches ++ mainVersion, defaultTranslation, @@ -184,8 +184,8 @@ class DocumentationPollingActor( .sortBy(_._1) .reverse .map { version => - val baseRepo = repo.fileRepoForHash(version._2) - val aggregateVersion = aggregate.byVersion.get(version._1) + val baseRepo = repo.fileRepoForHash(version._2) + val aggregateVersion = aggregate.byVersion.get(version._1) val (fileRepo, cacheId) = aggregateVersion.fold(baseRepo -> xorHashes(version._2.name, utils.SiteVersion.hash)) { default => new AggregateFileRepository(Seq(baseRepo, default.repo)) -> @@ -195,7 +195,7 @@ class DocumentationPollingActor( old.flatMap(_.byVersion.get(version._1)) match { // The version hasn't changed, don't rescan case Some(same: TranslationVersion) if same.cacheId == cacheId => same - case _ => + case _ => val playDoc = new PlayDoc( markdownRepository = fileRepo, codeRepository = fileRepo, diff --git a/app/controllers/Application.scala b/app/controllers/Application.scala index 7212d818..ee86f776 100644 --- a/app/controllers/Application.scala +++ b/app/controllers/Application.scala @@ -55,11 +55,16 @@ class Application @Inject() ( } .orElse { - if(version.isEmpty || + if ( + version.isEmpty || (version.exists(_.startsWith("2.")) && !version.contains(releases.latest2.version)) || - (version.exists(_.startsWith("3.")) && !version.contains(releases.latest3.version))) { + (version.exists(_.startsWith("3.")) && !version.contains(releases.latest3.version)) + ) { Some( - s"""Play framework ${if(version.isEmpty || version.exists(_.startsWith("3."))) releases.latest3.version else releases.latest2.version} is out! Check it out here.""", + s"""Play framework ${ + if (version.isEmpty || version.exists(_.startsWith("3."))) releases.latest3.version + else releases.latest2.version + } is out! Check it out here.""", ) } else { None @@ -76,7 +81,7 @@ class Application @Inject() ( def widget(version: Option[String]) = Action.async { request => Future.successful( - Ok(views.html.widget(news(version))) + Ok(views.html.widget(news(version))), ) } @@ -84,7 +89,7 @@ class Application @Inject() ( // the URL for SEO purposes only. def download = Action.async { implicit request => Future.successful( - MovedPermanently(routes.Application.gettingStarted.path) + MovedPermanently(routes.Application.gettingStarted.path), ) } @@ -106,7 +111,7 @@ class Application @Inject() ( def allreleases(platform: Option[String] = None) = Action.async { implicit request => val selectedPlatform = Platform(platform.orElse(request.headers.get("User-Agent"))) Future.successful( - Ok(html.allreleases(releases, selectedPlatform)) + Ok(html.allreleases(releases, selectedPlatform)), ) } @@ -161,24 +166,24 @@ class Application @Inject() ( page match { case Some(content) => Future.successful( - Ok(template(request)(Html(content))).withHeaders(CACHE_CONTROL -> "max-age=10000") + Ok(template(request)(Html(content))).withHeaders(CACHE_CONTROL -> "max-age=10000"), ) case None => Future.successful( - notFound + notFound, ) } } def getInvolved = Action.async { implicit request => Future.successful( - Ok(html.getInvolved()) + Ok(html.getInvolved()), ) } def sponsors = Action.async { implicit request => Future.successful( - Ok(html.sponsors()) + Ok(html.sponsors()), ) } @@ -197,15 +202,15 @@ class Application @Inject() ( .replace("-released", "") .replace("-", ".") Future.successful( - MovedPermanently(s"https://github.com/playframework/playframework/releases/tag/$version") + MovedPermanently(s"https://github.com/playframework/playframework/releases/tag/$version"), ) } else if (route.endsWith("/")) { Future.successful( - MovedPermanently("/" + request.path.take(request.path.length - 1).dropWhile(_ == '/')) + MovedPermanently("/" + request.path.take(request.path.length - 1).dropWhile(_ == '/')), ) } else { Future.successful( - notFound + notFound, ) } } @@ -244,7 +249,7 @@ class Application @Inject() ( val sections = byVersion.map { case (v, p) => val TutorialKeyword = "tutorial" // this MUST be in the project keywords for this to work val SeedKeyword = "seed" - val tutorials = p + val tutorials = p .filter(e => e.keywords.contains(TutorialKeyword) && !e.hasParams) .groupBy(byLanguage) .view diff --git a/app/controllers/Blog.scala b/app/controllers/Blog.scala index 210223cc..8c94e7b7 100644 --- a/app/controllers/Blog.scala +++ b/app/controllers/Blog.scala @@ -30,25 +30,25 @@ class Blog @Inject() ( def index() = Action.async { implicit request => Future.successful( - Ok(html.blog.index(blogName)) + Ok(html.blog.index(blogName)), ) } def graal() = Action.async { implicit request => Future.successful( - Ok(html.blog.graal(blogName, "Running Play on GraalVM")) + Ok(html.blog.graal(blogName, "Running Play on GraalVM")), ) } def socketio() = Action.async { implicit request => Future.successful( - Ok(html.blog.socketio(blogName, "Play socket.io support")) + Ok(html.blog.socketio(blogName, "Play socket.io support")), ) } def ossPledgeLaunch() = Action.async { implicit request => Future.successful( - Ok(html.blog.ossPledgeLaunch(blogName, "Celebrating the Launch of the Open Source Pledge")) + Ok(html.blog.ossPledgeLaunch(blogName, "Celebrating the Launch of the Open Source Pledge")), ) } } diff --git a/app/controllers/Modules.scala b/app/controllers/Modules.scala index 010ae5c2..adf025a5 100644 --- a/app/controllers/Modules.scala +++ b/app/controllers/Modules.scala @@ -25,7 +25,7 @@ class Modules @Inject() (modulesLookup: ModulesLookup, moduleDao: ModuleDao, com case Accepts.Json() => import Module.modulesWrites Ok(Json.toJson(moduleDao.findEverything())) - } + }, ) } @@ -33,11 +33,11 @@ class Modules @Inject() (modulesLookup: ModulesLookup, moduleDao: ModuleDao, com modulesLookup.findModule(name, version) match { case Some(zip) => Future.successful( - Ok.sendFile(zip) + Ok.sendFile(zip), ) case None => Future.successful( - PageNotFound + PageNotFound, ) } } @@ -46,11 +46,11 @@ class Modules @Inject() (modulesLookup: ModulesLookup, moduleDao: ModuleDao, com modulesLookup.loadModuleDocumentation(name, version, page) match { case Some(content) => Future.successful( - Ok(views.html.modules.documentation(name, content)) + Ok(views.html.modules.documentation(name, content)), ) case None => Future.successful( - PageNotFound + PageNotFound, ) } } @@ -59,11 +59,11 @@ class Modules @Inject() (modulesLookup: ModulesLookup, moduleDao: ModuleDao, com moduleDao.findById(name) match { case Some((module, releases)) => Future.successful( - Ok(views.html.modules.show(module, releases)) + Ok(views.html.modules.show(module, releases)), ) case None => Future.successful( - PageNotFound + PageNotFound, ) } } diff --git a/app/controllers/Outreachy.scala b/app/controllers/Outreachy.scala index b1508da2..c1809750 100644 --- a/app/controllers/Outreachy.scala +++ b/app/controllers/Outreachy.scala @@ -14,17 +14,17 @@ class Outreachy @Inject() (components: ControllerComponents)(implicit reverseRouter: documentation.ReverseRouter, ) extends AbstractController(components) { - //def outreachy = Action(Redirect(routes.Outreachy.round15)) + // def outreachy = Action(Redirect(routes.Outreachy.round15)) def round10 = Action.async { implicit req => Future.successful( - Ok(views.html.outreachy.round10()) + Ok(views.html.outreachy.round10()), ) } def round15 = Action.async { implicit req => Future.successful( - Ok(views.html.outreachy.round15()) + Ok(views.html.outreachy.round15()), ) } } diff --git a/app/controllers/Security.scala b/app/controllers/Security.scala index 80843873..bfe13cfa 100644 --- a/app/controllers/Security.scala +++ b/app/controllers/Security.scala @@ -37,7 +37,7 @@ class Security @Inject() (environment: Environment, val controllerComponents: Co "Play Framework Security Advisory", Html(Markdown.toHtml(content, link => (link, link))), ), - ).withHeaders(CACHE_CONTROL -> "max-age=10000") + ).withHeaders(CACHE_CONTROL -> "max-age=10000"), ) } finally { is.close() @@ -45,15 +45,15 @@ class Security @Inject() (environment: Environment, val controllerComponents: Co } .getOrElse( Future.successful( - notFound - ) + notFound, + ), ) } } def index = Action.async { implicit req => Future.successful( - Ok(views.html.vulnerabilities()).withHeaders(CACHE_CONTROL -> "max-age=1000") + Ok(views.html.vulnerabilities()).withHeaders(CACHE_CONTROL -> "max-age=1000"), ) } diff --git a/app/controllers/documentation/DocumentationController.scala b/app/controllers/documentation/DocumentationController.scala index 3adfa9fb..5f00f608 100644 --- a/app/controllers/documentation/DocumentationController.scala +++ b/app/controllers/documentation/DocumentationController.scala @@ -83,7 +83,7 @@ class DocumentationController @Inject() ( private def preferredLang(langs: Seq[Lang])(implicit request: RequestHeader) = { val maybeLangFromCookie = request.cookies.get(messages.langCookieName).flatMap(c => Lang.get(c.value)) - val candidateLangs = maybeLangFromCookie match { + val candidateLangs = maybeLangFromCookie match { case Some(cookieLang) => cookieLang +: request.acceptLanguages case None => request.acceptLanguages } @@ -132,10 +132,13 @@ class DocumentationController @Inject() ( def v1Page(lang: Option[Lang], v: String, page: String) = VersionAction(v) { (actor, version) => implicit req => - actorRequest(actor, page, (replyTo: ActorRef[Response[RenderedPage]]) => RenderV1Page(lang, version, etag(req), page, replyTo)) { - case RenderedPage(html, _, _, _, context, cacheId) => - val result = Ok(views.html.documentation.v1(messages, context, page, html)) - cacheable(withLangHeaders(result, page, context), cacheId) + actorRequest( + actor, + page, + (replyTo: ActorRef[Response[RenderedPage]]) => RenderV1Page(lang, version, etag(req), page, replyTo), + ) { case RenderedPage(html, _, _, _, context, cacheId) => + val result = Ok(views.html.documentation.v1(messages, context, page, html)) + cacheable(withLangHeaders(result, page, context), cacheId) } } @@ -163,7 +166,8 @@ class DocumentationController @Inject() ( actorRequest( actor, category, - (replyTo: ActorRef[Response[V1Cheatsheet]]) => RenderV1Cheatsheet(lang, version, etag(req), category, replyTo), + (replyTo: ActorRef[Response[V1Cheatsheet]]) => + RenderV1Cheatsheet(lang, version, etag(req), category, replyTo), ) { case V1Cheatsheet(sheets, title, otherCategories, context, cacheId) => cacheable( Ok(views.html.documentation.cheatsheet(context, title, otherCategories, sheets)), @@ -187,25 +191,28 @@ class DocumentationController @Inject() ( } def page(lang: Option[Lang], v: String, page: String) = VersionAction(v) { (actor, version) => implicit req => - val linkFuture = canonicalLinkHeader(page, version) + val linkFuture = canonicalLinkHeader(page, version) val resultFuture = - actorRequest(actor, page, (replyTo: ActorRef[Response[RenderedPage]]) => RenderPage(lang, version, etag(req), page, replyTo)) { - case RenderedPage(html, sidebarHtml, breadcrumbsHtml, source, context, cacheId) => - val pageTitle = HtmlHelpers.friendlyTitle(page) - val result = Ok( - views.html.documentation - .v2( - messages, - context, - page, - pageTitle, - Some(html), - sidebarHtml, - source, - breadcrumbs = breadcrumbsHtml, - ), - ) - cacheable(withLangHeaders(result, page, context), cacheId) + actorRequest( + actor, + page, + (replyTo: ActorRef[Response[RenderedPage]]) => RenderPage(lang, version, etag(req), page, replyTo), + ) { case RenderedPage(html, sidebarHtml, breadcrumbsHtml, source, context, cacheId) => + val pageTitle = HtmlHelpers.friendlyTitle(page) + val result = Ok( + views.html.documentation + .v2( + messages, + context, + page, + pageTitle, + Some(html), + sidebarHtml, + source, + breadcrumbs = breadcrumbsHtml, + ), + ) + cacheable(withLangHeaders(result, page, context), cacheId) }.flatMap { result => if (result.header.status == NOT_FOUND) { documentationRedirects.redirectFor(page) match { @@ -305,10 +312,10 @@ class DocumentationController @Inject() ( ) = { VersionAction(version) { (actor, version) => implicit req => actor.ask[Response[Resource]](replyTo => message(version, etag(req), replyTo)).map { - case DocsNotFound(context) => pageNotFound(context, resource, Nil) - case DocsNotModified(cacheId) => notModified(cacheId) + case DocsNotFound(context) => pageNotFound(context, resource, Nil) + case DocsNotModified(cacheId) => notModified(cacheId) case Resource(source, size, cacheId) => - val fileName = resource.drop(resource.lastIndexOf('/') + 1) + val fileName = resource.drop(resource.lastIndexOf('/') + 1) val contentDisposition = if (inline) { Nil } else { @@ -351,7 +358,11 @@ class DocumentationController @Inject() ( home: String, ) = { (lang: Option[Lang], v: String, page: String) => VersionAction(v) { (actor, version) => implicit req => - actorRequest(actor, page, (replyTo: ActorRef[Response[PageExists]]) => msg(lang, version, etag(req), page, replyTo)) { + actorRequest( + actor, + page, + (replyTo: ActorRef[Response[PageExists]]) => msg(lang, version, etag(req), page, replyTo), + ) { case PageExists(true, cacheId) => cacheable(TemporaryRedirect(reverseRouter.page(lang, version.name, page)), cacheId) case PageExists(false, cacheId) => diff --git a/app/controllers/documentation/Router.scala b/app/controllers/documentation/Router.scala index cc62d941..05ffe776 100644 --- a/app/controllers/documentation/Router.scala +++ b/app/controllers/documentation/Router.scala @@ -16,8 +16,8 @@ class Router @Inject() (docController: DocumentationController) extends play.api private var _prefix = "/" def withPrefix(prefix: String): Router = { _prefix = prefix; this } - def prefix: String = _prefix - def documentation = Nil + def prefix: String = _prefix + def documentation = Nil private val Language = "^/([A-Za-z]{2}(?:_[A-Za-z]{2})?)((?:/.*)?)$".r @@ -58,9 +58,9 @@ class Router @Inject() (docController: DocumentationController) extends play.api case p"/$version<1\.[^/]+>/cheatsheet/$category" => docController.v1Cheatsheet(lang, version, category) // Other paths - case p"/$version<\d+\.[^/]+>" => docController.home(lang, version) - case p"/$version<\d+\.[^/]+>/" => docController.home(lang, version) - case p"/$version<\d+\.[^/]+>/$page" => docController.page(lang, version, page) + case p"/$version<\d+\.[^/]+>" => docController.home(lang, version) + case p"/$version<\d+\.[^/]+>/" => docController.home(lang, version) + case p"/$version<\d+\.[^/]+>/$page" => docController.page(lang, version, page) case p"/$version<\d+\.[^/]+>/resources/$path*" => docController.resource(lang, version, decodePath(path)) case p"/latest" => docController.latest(lang, "Home") @@ -84,8 +84,8 @@ class ReverseRouter @Inject() (routerProvider: Provider[Router]) { def home(lang: Option[Lang], version: String) = s"${index(lang)}/$version" def page(lang: Option[Lang], version: String, pageFileName: String = "Home") = s"${index(lang)}/$version/$pageFileName" - def api(version: String, path: String) = s"${router.prefix}/$version/api/$path" - def latest(lang: Option[Lang], page: String = "Home") = this.page(lang, "latest", page) + def api(version: String, path: String) = s"${router.prefix}/$version/api/$path" + def latest(lang: Option[Lang], page: String = "Home") = this.page(lang, "latest", page) def cheatsheet(lang: Option[Lang], version: String, category: String) = s"${index(lang)}/$version/cheatsheet/$category" def switch(lang: Option[Lang], version: String, pageFileName: String) = diff --git a/app/models/PlayExampleProjects.scala b/app/models/PlayExampleProjects.scala index 92bd2a23..08d2330b 100644 --- a/app/models/PlayExampleProjects.scala +++ b/app/models/PlayExampleProjects.scala @@ -56,14 +56,14 @@ class PlayExampleProjectsService @Inject() ( configuration: Configuration, ws: WSClient, cache: SyncCacheApi, - environment: Environment + environment: Environment, )(implicit ec: ExecutionContext) { val validPlayVersions: Seq[String] = configuration.get[Seq[String]]("examples.playVersions") private val logger = org.slf4j.LoggerFactory.getLogger(this.getClass) - //private val examplesUrl = configuration.get[String]("examples.apiUrl") + // private val examplesUrl = configuration.get[String]("examples.apiUrl") // NOTE: TTL is really just a safety measure here. // We should re-deploy when we make major changes to projects @@ -92,19 +92,22 @@ class PlayExampleProjectsService @Inject() ( def examples(): Future[Seq[ExampleProject]] = { Future - .sequence(validPlayVersions.map { version => { - lazy val samples: JsValue = - environment - .resourceAsStream(s"playSamples_${version}.json") - .flatMap { is => - try { - Json.fromJson[JsValue](Json.parse(IOUtils.toByteArray(is))).asOpt - } finally { - is.close() + .sequence(validPlayVersions.map { version => + { + lazy val samples: JsValue = + environment + .resourceAsStream(s"playSamples_${version}.json") + .flatMap { is => + try { + Json.fromJson[JsValue](Json.parse(IOUtils.toByteArray(is))).asOpt + } finally { + is.close() + } } - }.getOrElse(JsArray()) - Future.successful(version, samples) - }}) + .getOrElse(JsArray()) + Future.successful(version, samples) + } + }) .map { response => response.flatMap((convertExampleProjects _).tupled) } diff --git a/app/models/Releases.scala b/app/models/Releases.scala index b5596049..b31cff93 100644 --- a/app/models/Releases.scala +++ b/app/models/Releases.scala @@ -17,7 +17,12 @@ object PlayRelease { implicit val releaseReads: Reads[PlayRelease] = Json.reads[PlayRelease] } -case class PlayReleases(latest3: PlayRelease, latest2: PlayRelease, development: Seq[PlayRelease], previous: Seq[PlayRelease]) +case class PlayReleases( + latest3: PlayRelease, + latest2: PlayRelease, + development: Seq[PlayRelease], + previous: Seq[PlayRelease], +) object PlayReleases { implicit val playReleasesReads: Reads[PlayReleases] = Json.reads[PlayReleases] diff --git a/app/models/documentation/Documentation.scala b/app/models/documentation/Documentation.scala index a4600cc7..4fca7834 100644 --- a/app/models/documentation/Documentation.scala +++ b/app/models/documentation/Documentation.scala @@ -83,7 +83,7 @@ case class TranslationVersion( * Release types. Primary use is to identify which versions are stable, and how to sort them. */ sealed abstract class VersionType(val name: String, val order: Int) extends Ordered[VersionType] { - val number = 0 + val number = 0 def compare(that: VersionType) = { val compare1 = order - that.order if (compare1 != 0) compare1 else number - that.number @@ -105,7 +105,7 @@ case class Milestone(override val number: Int) extends VersionType("m", 8 */ case class Version(name: String, era: Int, major: Int, minor: Int, patch: Int, versionType: VersionType) extends Ordered[Version] { - def sameMajor(that: Version) = era == that.era && major == that.major + def sameMajor(that: Version) = era == that.era && major == that.major def earlierMajorThan(that: Version) = { if (era < that.era) true else if (era > that.era) false diff --git a/app/models/github/FallbackContributors.scala b/app/models/github/FallbackContributors.scala index 294be37d..77ce51f3 100644 --- a/app/models/github/FallbackContributors.scala +++ b/app/models/github/FallbackContributors.scala @@ -626,7 +626,7 @@ object FallbackContributors { * Code to generate the code above from a current list of contributors */ def dumpContributors(contributors: Contributors) = { - def option(s: Option[String]) = s.fold("None")("Some(\"" + _ + "\")") + def option(s: Option[String]) = s.fold("None")("Some(\"" + _ + "\")") def formatUser(u: GitHubUser): String = { import u._ // format: off diff --git a/app/models/opencollective/FallbackMembers.scala b/app/models/opencollective/FallbackMembers.scala index e3bd23d4..1c15c43e 100644 --- a/app/models/opencollective/FallbackMembers.scala +++ b/app/models/opencollective/FallbackMembers.scala @@ -48,7 +48,7 @@ object FallbackMembers { * Code to generate the code above from a current list of members */ def dumpMembers(members: Seq[OpenCollectiveMember]) = { - def option(s: Option[String]) = s.fold("None")("Some(\"" + _ + "\")") + def option(s: Option[String]) = s.fold("None")("Some(\"" + _ + "\")") def formatMember(m: OpenCollectiveMember): String = { import m._ // format: off diff --git a/app/models/opencollective/OpenCollective.scala b/app/models/opencollective/OpenCollective.scala index 1fd9d39a..a79796be 100644 --- a/app/models/opencollective/OpenCollective.scala +++ b/app/models/opencollective/OpenCollective.scala @@ -14,7 +14,7 @@ case class OpenCollectiveMember( `type`: String, // USER or ORGANIZATION, role: String, // BACKER, ADMIN or HOST, isActive: Boolean, // true or false - totalAmountDonated: Double,// amount in cent (USD 100.00 = 10000) + totalAmountDonated: Double, // amount in cent (USD 100.00 = 10000) // createdAt: 2021-11-08 14:41, // lastTransactionAt: 2021-11-19 09:16, // lastTransactionAmount: 0, diff --git a/app/services/github/ContributorsSummariser.scala b/app/services/github/ContributorsSummariser.scala index f7fd4ce9..37d988a3 100644 --- a/app/services/github/ContributorsSummariser.scala +++ b/app/services/github/ContributorsSummariser.scala @@ -101,7 +101,7 @@ class CachingContributorsSummariser @Inject() ( actorSystem.scheduler.scheduleWithFixedDelay(0.seconds, 24.hours)(() => { delegate.fetchContributors.onComplete { - case Failure(t) => log.error("Unable to load contributors from GitHub", t) + case Failure(t) => log.error("Unable to load contributors from GitHub", t) case Success(cs) => if (contributors != cs) { val count = diff --git a/app/services/github/GitHub.scala b/app/services/github/GitHub.scala index 907d1def..99792b47 100644 --- a/app/services/github/GitHub.scala +++ b/app/services/github/GitHub.scala @@ -75,7 +75,7 @@ class DefaultGitHub @Inject() (ws: WSClient, config: GitHubConfig)(implicit ec: } object NextLink { - val ParseNext = """.*<([^>]+)>;\s*rel="?next"?.*""".r + val ParseNext = """.*<([^>]+)>;\s*rel="?next"?.*""".r def unapply(response: WSResponse): Option[String] = { response.header("Link").collect { case ParseNext(next) => next @@ -104,7 +104,7 @@ class DefaultGitHub @Inject() (ws: WSClient, config: GitHubConfig)(implicit ec: def loadNext(url: String): Future[Seq[T]] = { authCall(url).get().flatMap { case notOk if notOk.status >= 300 => throw responseFailure(notOk) - case response @ NextLink(next) => + case response @ NextLink(next) => for { nextResults <- loadNext(next) } yield { diff --git a/app/services/modules/ModuleDao.scala b/app/services/modules/ModuleDao.scala index a446df11..b5cecf01 100644 --- a/app/services/modules/ModuleDao.scala +++ b/app/services/modules/ModuleDao.scala @@ -35,7 +35,7 @@ class DbModuleDao @Inject() extends ModuleDao { private val modules: Map[ModuleId, Module] = InMemDatabase.rawModules.toMap // not a Map because ModuleId can be duplicate in this Seq - private val moduleReleases: Seq[(ModuleId, Release)] = InMemDatabase.rawReleases + private val moduleReleases: Seq[(ModuleId, Release)] = InMemDatabase.rawReleases private val releasesByModuleId: Map[ModuleId, Seq[Release]] = moduleReleases.groupBy(_._1).view.mapValues(_.map(_._2)).toMap // left join. Some modules may not have a release. diff --git a/app/services/opencollective/MembersSummariser.scala b/app/services/opencollective/MembersSummariser.scala index 8c2f93ac..8a514237 100644 --- a/app/services/opencollective/MembersSummariser.scala +++ b/app/services/opencollective/MembersSummariser.scala @@ -50,7 +50,7 @@ class CachingMembersSummariser @Inject() ( actorSystem.scheduler.scheduleWithFixedDelay(0.seconds, 24.hours)(() => { delegate.fetchMembers.onComplete { - case Failure(t) => log.error("Unable to load members from OpenCollective", t) + case Failure(t) => log.error("Unable to load members from OpenCollective", t) case Success(ms) => if (members != ms) { val count = members.size diff --git a/app/services/releases/ReleasesModule.scala b/app/services/releases/ReleasesModule.scala index 4d26a88c..47591869 100644 --- a/app/services/releases/ReleasesModule.scala +++ b/app/services/releases/ReleasesModule.scala @@ -23,7 +23,14 @@ class PlayReleasesProvider @Inject() (environment: Environment) extends Provider is.close() } } - .getOrElse(PlayReleases(PlayRelease("unknown", None, Some("unknown"), None, None), PlayRelease("unknown", None, Some("unknown"), None, None), Nil, Nil)) + .getOrElse( + PlayReleases( + PlayRelease("unknown", None, Some("unknown"), None, None), + PlayRelease("unknown", None, Some("unknown"), None, None), + Nil, + Nil, + ), + ) } override def get(): PlayReleases = releases diff --git a/app/utils/GitFileRepository.scala b/app/utils/GitFileRepository.scala index 9d80df40..478b3cd4 100644 --- a/app/utils/GitFileRepository.scala +++ b/app/utils/GitFileRepository.scala @@ -25,7 +25,7 @@ class PlayGitRepository(val gitDir: File, val remote: String = "origin", basePat new GitFileRepository(this, hash, basePath) } - def close(): Unit = repository.close() + def close(): Unit = repository.close() def allTags: Seq[(String, ObjectId)] = git .tagList() diff --git a/app/utils/Markdown.scala b/app/utils/Markdown.scala index 0ec2ede2..3e3f04d5 100644 --- a/app/utils/Markdown.scala +++ b/app/utils/Markdown.scala @@ -7,7 +7,7 @@ object Markdown { def toHtml(markdown: String, link: String => (String, String) = a => (a, a)): String = { val processor = new PegDownProcessor(Extensions.ALL) - val links = new LinkRenderer { + val links = new LinkRenderer { override def render(node: WikiLinkNode) = { val (href, text) = link(node.getText) new LinkRenderer.Rendering(href, text) diff --git a/build.sbt b/build.sbt index 7c767d12..0b11a722 100644 --- a/build.sbt +++ b/build.sbt @@ -1,4 +1,4 @@ -name := "playframework" +name := "playframework" version := "1.0-SNAPSHOT" enablePlugins(PlayScala) @@ -25,7 +25,7 @@ routesGenerator := InjectedRoutesGenerator JsEngineKeys.engineType := JsEngineKeys.EngineType.Node -Assets / StylusKeys.useNib := true +Assets / StylusKeys.useNib := true Assets / StylusKeys.compress := true pipelineStages := Seq(digest, gzip) @@ -49,5 +49,5 @@ Compile / sourceGenerators += Def.task { }.taskValue Compile / managedSourceDirectories += crossTarget.value / "version" -Compile / doc / sources := Seq.empty +Compile / doc / sources := Seq.empty Compile / packageDoc / publishArtifact := false diff --git a/project/plugins.sbt b/project/plugins.sbt index 9061f3d1..d17cdbc9 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -1,4 +1,5 @@ -addSbtPlugin("org.playframework" % "sbt-plugin" % "3.0.8") -addSbtPlugin("com.github.sbt" % "sbt-digest" % "2.1.0") -addSbtPlugin("com.github.sbt" % "sbt-gzip" % "2.0.0") -addSbtPlugin("com.github.sbt" % "sbt-stylus" % "2.0.1") +addSbtPlugin("org.playframework" % "sbt-plugin" % "3.0.8") +addSbtPlugin("com.github.sbt" % "sbt-digest" % "2.1.0") +addSbtPlugin("com.github.sbt" % "sbt-gzip" % "2.0.0") +addSbtPlugin("com.github.sbt" % "sbt-stylus" % "2.0.1") +addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.5.5") diff --git a/test/controllers/ModulesSpec.scala b/test/controllers/ModulesSpec.scala index 1f21dcdf..d8bef964 100644 --- a/test/controllers/ModulesSpec.scala +++ b/test/controllers/ModulesSpec.scala @@ -39,7 +39,7 @@ object ModulesSpec extends PlaySpecification { "as html when the client accepts html" in new WithApplication(app) { override def running() = { val (modules, _, dao) = createModules(this.app) - val result = modules.index("foo")(FakeRequest().withHeaders(ACCEPT -> "text/html")) + val result = modules.index("foo")(FakeRequest().withHeaders(ACCEPT -> "text/html")) status(result) must_== 200 contentType(result) must beSome("text/html") contentAsString(result) must contain("Some Description") diff --git a/test/controllers/documentation/DocumentationControllerSpec.scala b/test/controllers/documentation/DocumentationControllerSpec.scala index 63361e2e..60ba5196 100644 --- a/test/controllers/documentation/DocumentationControllerSpec.scala +++ b/test/controllers/documentation/DocumentationControllerSpec.scala @@ -11,10 +11,10 @@ object DocumentationControllerSpec extends PlaySpecification { override def running(): Unit = { inject[Router] // makes sure generated router.Routes class (in target folder) get initialized, which injects controllers.documentation.Router and calls its withPrefix(...) val reverseRouter: ReverseRouter = inject[ReverseRouter] - val page: String = reverseRouter.page(None, "2.5.x", "Home") + val page: String = reverseRouter.page(None, "2.5.x", "Home") page must beEqualTo("/documentation/2.5.x/Home") val request = FakeRequest("GET", page) - val result = await(route(app, request).get) + val result = await(route(app, request).get) result.header.status must beEqualTo(OK) } } @@ -23,8 +23,8 @@ object DocumentationControllerSpec extends PlaySpecification { override def running(): Unit = { inject[Router] // makes sure router.Routes class get initialized, which injects controllers.documentation.Router and calls its withPrefix(...) val reverseRouter: ReverseRouter = inject[ReverseRouter] - val request = FakeRequest("GET", reverseRouter.page(None, "2.5.x", "Home")) - val result = await(route(app, request).get) + val request = FakeRequest("GET", reverseRouter.page(None, "2.5.x", "Home")) + val result = await(route(app, request).get) result.header.headers.contains("Link") must beTrue } } @@ -36,7 +36,7 @@ object DocumentationControllerSpec extends PlaySpecification { val reverseRouter: ReverseRouter = inject[ReverseRouter] val request = FakeRequest("GET", reverseRouter.switch(None, "2.7.x", "Home")) - val result = route(app, request).get + val result = route(app, request).get redirectLocation(result) must beSome(reverseRouter.page(None, "2.7.x", "Home")) } @@ -49,7 +49,7 @@ object DocumentationControllerSpec extends PlaySpecification { val reverseRouter: ReverseRouter = inject[ReverseRouter] val request = FakeRequest("GET", reverseRouter.switch(None, "2.7.x", "")) - val result = route(app, request).get + val result = route(app, request).get redirectLocation(result) must beSome(reverseRouter.page(None, "2.7.x", "Home")) } @@ -61,9 +61,9 @@ object DocumentationControllerSpec extends PlaySpecification { inject[Router] // makes sure router.Routes class get initialized, which injects controllers.documentation.Router and calls its withPrefix(...) val reverseRouter: ReverseRouter = inject[ReverseRouter] - val page = reverseRouter.switch(None, "2.7.x", "").stripSuffix("/") + val page = reverseRouter.switch(None, "2.7.x", "").stripSuffix("/") val request = FakeRequest("GET", page) - val result = route(app, request).get + val result = route(app, request).get redirectLocation(result) must beSome(reverseRouter.page(None, "2.7.x", "Home")) } @@ -77,7 +77,7 @@ object DocumentationControllerSpec extends PlaySpecification { val reverseRouter: ReverseRouter = inject[ReverseRouter] // When accessing "AkkaCore" (was renamed to "ThreadPools") val request = FakeRequest("GET", reverseRouter.page(None, "2.5.x", "AkkaCore")) - val result = route(app, request).get + val result = route(app, request).get // Then we should be redirected to "ThreadPools" redirectLocation(result) must beSome(reverseRouter.page(None, "2.5.x", "ThreadPools")) @@ -89,7 +89,7 @@ object DocumentationControllerSpec extends PlaySpecification { inject[Router] // makes sure router.Routes class get initialized, which injects controllers.documentation.Router and calls its withPrefix(...) val reverseRouter: ReverseRouter = inject[ReverseRouter] val request = FakeRequest("GET", reverseRouter.page(None, "2.5.x", "PullRequests")) - val result = route(app, request).get + val result = route(app, request).get redirectLocation(result) must beSome( "https://github.com/playframework/.github/blob/main/CONTRIBUTING.md", @@ -102,7 +102,7 @@ object DocumentationControllerSpec extends PlaySpecification { inject[Router] // makes sure router.Routes class get initialized, which injects controllers.documentation.Router and calls its withPrefix(...) val reverseRouter: ReverseRouter = inject[ReverseRouter] val request = FakeRequest("GET", reverseRouter.page(None, "2.5.x", "DoesNotExists")) - val result = route(app, request).get + val result = route(app, request).get redirectLocation(result) must beNone await(result).header.status must beEqualTo(NOT_FOUND) @@ -115,7 +115,7 @@ object DocumentationControllerSpec extends PlaySpecification { val reverseRouter: ReverseRouter = inject[ReverseRouter] // AkkaCore exists for version 2.0 val request = FakeRequest("GET", reverseRouter.page(None, "2.0.x", "AkkaCore")) - val result = route(app, request).get + val result = route(app, request).get redirectLocation(result) must beNone await(result).header.status must beEqualTo(OK) diff --git a/test/services/github/ContributorsSummariserSpec.scala b/test/services/github/ContributorsSummariserSpec.scala index d8497394..40f027bd 100644 --- a/test/services/github/ContributorsSummariserSpec.scala +++ b/test/services/github/ContributorsSummariserSpec.scala @@ -66,7 +66,9 @@ object ContributorsSummariserSpec extends PlaySpecification { Mockito.when(gh.fetchOrganisationMembers(org)).thenReturn(f(Seq(owner, orgMember))) Mockito.when(gh.fetchOrganisationRepos(org)).thenReturn(f(Seq(playRepo, twirlRepo, forkRepo))) - Mockito.when(gh.fetchRepoContributors(playRepo)).thenReturn(f(Seq(contributor2 -> 4, orgMember -> 10, contributor1 -> 3, owner -> 20))) + Mockito + .when(gh.fetchRepoContributors(playRepo)) + .thenReturn(f(Seq(contributor2 -> 4, orgMember -> 10, contributor1 -> 3, owner -> 20))) Mockito.when(gh.fetchRepoContributors(twirlRepo)).thenReturn(f(Seq(contributor1 -> 3, contributor3 -> 1))) val contributors = await(new DefaultContributorsSummariser(gh, config).fetchContributors) diff --git a/test/services/github/GitHubSpec.scala b/test/services/github/GitHubSpec.scala index 3723f8de..172f20f3 100644 --- a/test/services/github/GitHubSpec.scala +++ b/test/services/github/GitHubSpec.scala @@ -74,7 +74,7 @@ object GitHubSpec extends PlaySpecification { def withGitHub[T](block: GitHub => T): T = Server.withRouterFromComponents() { components => { - case Get(p"/orgs/${_}") => components.defaultActionBuilder(Ok.sendResource("github/org.json")) + case Get(p"/orgs/${_}") => components.defaultActionBuilder(Ok.sendResource("github/org.json")) case Get(p"/orgs/${_}/members") => components.defaultActionBuilder(Ok.sendResource("github/orgMembers.json")) case Get(p"/orgs/${_}/teams") => components.defaultActionBuilder(Ok.sendResource("github/teams.json")) diff --git a/test/utils/GitFileRepositoryPerformanceTest.scala b/test/utils/GitFileRepositoryPerformanceTest.scala index 13aff860..63bd03ae 100644 --- a/test/utils/GitFileRepositoryPerformanceTest.scala +++ b/test/utils/GitFileRepositoryPerformanceTest.scala @@ -17,7 +17,7 @@ object GitFileRepositoryPerformanceTest extends App { val basePath = "documentation/manual" // First, find all the files that we might want to look up - val tags = repo.allTags + val tags = repo.allTags val allFiles = tags.flatMap { case (_, ref) => repo.listAllFilesInPath(ref, basePath).map((ref, _)) } @@ -29,7 +29,7 @@ object GitFileRepositoryPerformanceTest extends App { @volatile var running = true val findFileWithNameTiming = new AtomicLong() val loadFileTiming = new AtomicLong() - val tasks = Future.sequence(for (i <- 0 to threads) yield { + val tasks = Future.sequence(for (i <- 0 to threads) yield { Future { var markdownLoaded = 0 @@ -68,8 +68,8 @@ object GitFileRepositoryPerformanceTest extends App { println("Loaded " + loaded + " files in " + seconds + " seconds") println("That's " + (loaded / seconds) + " files a second") - println(s"Total time spent finding markdown files: ${(findFileWithNameTiming.get() / 1000000)}ms") - println(s"Total time spent loading markdown files: ${(loadFileTiming.get() / 1000000)}ms") + println(s"Total time spent finding markdown files: ${findFileWithNameTiming.get() / 1000000}ms") + println(s"Total time spent loading markdown files: ${loadFileTiming.get() / 1000000}ms") } println()