From 6303d1a4a5838719d169b7028c80c87d62b30494 Mon Sep 17 00:00:00 2001 From: Li Haoyi Date: Fri, 5 Dec 2025 05:57:43 +0800 Subject: [PATCH 1/2] fix --- .../artifactory/ArtifactoryHttpApi.scala | 2 +- .../ArtifactoryPublishModule.scala | 4 +- .../artifactory/ArtifactoryPublisher.scala | 6 +- .../mill/contrib/buildinfo/BuildInfo.scala | 6 +- .../codeartifact/CodeArtifactPublisher.scala | 4 +- .../CodeartifactPublishModule.scala | 4 +- .../src/mill/contrib/flyway/ConsoleLog.scala | 2 +- .../mill/contrib/flyway/FlywayModule.scala | 2 +- .../contrib/gitlab/GitlabPublishModule.scala | 8 +- .../mill/contrib/gitlab/GitlabPublisher.scala | 2 +- .../contrib/gitlab/GitlabTokenTests.scala | 2 +- .../playlib/RouteCompilerWorkerModule.scala | 2 +- .../test/controllers/HomeControllerSpec.scala | 2 +- .../test/controllers/HomeControllerSpec.scala | 2 +- .../test/controllers/HomeControllerSpec.scala | 2 +- .../src/mill/contrib/sbom/CycloneDX.scala | 2 +- .../contrib/scalapblib/ScalaPBModule.scala | 2 +- .../contrib/scalapblib/ScalaPBWorkerApi.scala | 2 +- .../scoverage/ScoverageReportWorker.scala | 2 +- .../worker/ScoverageReportWorkerImpl.scala | 8 +- .../src/mill/twirllib/TwirlWorker.scala | 8 +- .../mill/contrib/versionfile/Version.scala | 2 +- .../src/mill/api/daemon/ExecResult.scala | 2 +- .../daemon/src/mill/api/daemon/Logger.scala | 8 +- .../mill/api/daemon/MillURLClassLoader.scala | 4 +- .../daemon/src/mill/api/daemon/Segments.scala | 6 +- .../src/mill/api/daemon/SystemStreams.scala | 4 +- .../api/daemon/internal/MillScalaParser.scala | 2 +- .../api/daemon/internal/TestReporter.scala | 2 +- core/api/src/mill/api/Cross.scala | 4 +- core/api/src/mill/api/Debug.scala | 4 +- core/api/src/mill/api/Discover.scala | 4 +- core/api/src/mill/api/EnclosingClass.scala | 2 +- core/api/src/mill/api/Evaluator.scala | 2 +- core/api/src/mill/api/JsonFormatters.scala | 2 +- core/api/src/mill/api/ModuleCtx.scala | 4 +- core/api/src/mill/api/PathRef.scala | 10 +-- .../api/src/mill/api/SystemStreamsUtils.scala | 20 ++--- core/api/src/mill/api/Task.scala | 6 +- core/api/src/mill/api/TaskCtx.scala | 2 +- .../src/mill/api/internal/Applicative.scala | 4 +- core/api/src/mill/api/internal/Cacher.scala | 2 +- core/api/src/mill/api/internal/Mirrors.scala | 2 +- .../mill/api/internal/OverrideMapping.scala | 2 +- core/api/src/mill/api/internal/Reflect.scala | 2 +- core/api/src/mill/api/internal/WatchSig.scala | 4 +- .../test/src/mill/api/ApplicativeTests.scala | 12 +-- core/api/test/src/mill/api/Opt.scala | 6 +- core/eval/src/mill/eval/EvaluatorImpl.scala | 6 +- core/exec/src/mill/exec/CodeSigUtils.scala | 6 +- core/exec/src/mill/exec/Execution.scala | 12 +-- .../src/mill/exec/ExecutionContexts.scala | 16 ++-- core/exec/src/mill/exec/GroupExecution.scala | 12 +-- core/exec/src/mill/exec/PlanImpl.scala | 4 +- .../test/src/mill/exec/ExecutionTests.scala | 4 +- .../test/src/mill/exec/OverrideTests.scala | 14 ++-- core/exec/test/src/mill/exec/TaskTests.scala | 2 +- .../src/mill/internal/FileLogger.scala | 4 +- .../src/mill/internal/JsonArrayLogger.scala | 4 +- .../internal/LineBufferingOutputStream.scala | 2 +- .../src/mill/internal/MultiLogger.scala | 16 ++-- .../src/mill/internal/PipeStreams.scala | 4 +- .../src/mill/internal/PrefixLogger.scala | 8 +- .../src/mill/internal/PromptLogger.scala | 16 ++-- .../src/mill/internal/ProxyLogger.scala | 2 +- .../src/mill/internal/SimpleLogger.scala | 4 +- core/internal/src/mill/internal/Util.scala | 6 +- .../LineBufferingOutputStreamTests.scala | 24 +++--- .../src/mill/internal/PipeStreamsTests.scala | 14 ++-- .../src/mill/internal/PromptLoggerTests.scala | 20 ++--- .../mill/internal/PromptLoggerUtilTests.scala | 2 +- .../src/mill/internal/TestTerminalTests.scala | 22 +++--- .../test/src/mill/resolve/ErrorTests.scala | 42 +++++----- .../test/src/mill/resolve/ModuleTests.scala | 16 ++-- .../test/src/mill/resolve/ResolveTests.scala | 8 +- .../src/mill/resolve/TypeSelectorTests.scala | 6 +- .../src/MillVersionFrontmatterTests.scala | 2 +- .../src/mill/testkit/IntegrationTests.scala | 2 +- .../2-run-compile-deps/bar/src/Bar.scala | 4 +- .../src/Foo.scala | 2 +- .../spark/3-semi-realistic/src/foo/Foo.scala | 2 +- .../bsp-util/src/BspServerTestUtil.scala | 4 +- .../PublishSonatypeCentralSnapshotTests.scala | 2 +- .../ide/bsp-server/src/BspServerTests.scala | 10 +-- .../src/MultiLevelBuildTests.scala | 2 +- .../src/RunBackgroundTests.scala | 2 +- .../resources/app/src/main/scala/App.scala | 2 +- .../databinding/AndroidDataBindingImpl.scala | 14 ++-- .../hilt/AndroidHiltTransformAsm.scala | 8 +- .../mill/androidlib/keytool/CertUtil.scala | 18 ++--- .../mill/androidlib/keytool/Keystore.scala | 12 +-- .../src/mill/androidlib/keytool/Keytool.scala | 6 +- .../mill/androidlib/keytool/RSAKeyGen.scala | 2 +- .../keytool/test/src/KeytoolTest.scala | 4 +- .../mill/androidlib/AndroidAppModule.scala | 8 +- .../mill/androidlib/AndroidKotlinModule.scala | 2 +- .../mill/androidlib/AndroidLibModule.scala | 6 +- .../mill/androidlib/AndroidSdkModule.scala | 12 +-- .../InstrumentalOutputReportTest.scala | 2 +- .../server/src/mill/server/Server.scala | 6 +- .../src/mill/graphviz/GraphvizTools.scala | 6 +- .../mill/main/gradle/GradleBuildGenMain.scala | 2 +- .../maven/src/mill/main/maven/Modeler.scala | 10 +-- .../maven/src/mill/main/maven/Resolver.scala | 10 +-- libs/init/src/mill/init/InitModule.scala | 2 +- .../test/src/mill/init/InitModuleTests.scala | 18 ++--- .../src/mill/javalib/api/JvmWorkerUtil.scala | 6 +- .../internal/ZincCompilerBridgeProvider.scala | 6 +- .../impl/ClassgraphWorkerImpl.scala | 2 +- .../src/SemanticdbProcessor.scala | 2 +- .../mill/javalib/spotless/converters.scala | 2 +- .../worker/impl/SpringBootToolsImpl.scala | 4 +- libs/javalib/src/mill/javalib/Assembly.scala | 8 +- libs/javalib/src/mill/javalib/Dep.scala | 6 +- .../javalib/src/mill/javalib/JavaModule.scala | 10 +-- .../src/mill/javalib/NativeImageModule.scala | 4 +- .../src/mill/javalib/PublishModule.scala | 14 ++-- libs/javalib/src/mill/javalib/RunModule.scala | 4 +- .../SonatypeCentralPublishModule.scala | 6 +- .../javalib/SonatypeCentralPublisher.scala | 8 +- .../javalib/src/mill/javalib/TestModule.scala | 2 +- .../javalib/checkstyle/CheckstyleModule.scala | 4 +- .../checkstyle/CheckstyleXsltModule.scala | 6 +- .../dependency/versions/VersionsFinder.scala | 6 +- .../mill/javalib/internal/PublishModule.scala | 8 +- .../palantirformat/PalantirFormatModule.scala | 2 +- .../src/mill/javalib/publish/Ivy.scala | 2 +- .../src/mill/javalib/publish/Licence.scala | 2 +- .../src/mill/javalib/publish/Pom.scala | 4 +- .../javalib/publish/SonatypeHelpers.scala | 2 +- .../javalib/publish/SonatypeHttpApi.scala | 10 +-- .../javalib/publish/SonatypePublisher.scala | 6 +- .../spring/boot/SpringBootModule.scala | 2 +- .../mill/javalib/TestModuleUtilTests.scala | 14 ++-- .../src/mill/javalib/publish/IvyTests.scala | 4 +- .../publish/LocalM2PublisherTests.scala | 2 +- .../src/mill/javalib/publish/PomTests.scala | 2 +- .../javalib/testrunner/TestRunnerUtils.scala | 12 +-- .../mill/javalib/worker/JvmWorkerImpl.scala | 2 +- .../javalib/zinc/ForwardingReporter.scala | 6 +- .../mill/javalib/zinc/PositionMapper.scala | 2 +- .../src/mill/javalib/zinc/ZincProblem.scala | 2 +- .../src/mill/javalib/zinc/ZincWorker.scala | 6 +- .../mill/javascriptlib/HelloWorldTests.scala | 4 +- .../kotlinlib/ksp2/worker/KspWorkerImpl.scala | 6 +- .../mill/kotlinlib/KotlinWorkerManager.scala | 2 +- .../mill/kotlinlib/detekt/DetektModule.scala | 8 +- .../mill/kotlinlib/js/KotlinJsModule.scala | 10 +-- .../src/mill/kotlinlib/ksp/KspModule.scala | 2 +- .../mill/kotlinlib/ktfmt/KtfmtModule.scala | 4 +- .../mill/kotlinlib/ktlint/KtlintModule.scala | 2 +- .../kotlinlib/worker/impl/JsCompileImpl.scala | 2 +- .../worker/impl/JvmCompileImpl.scala | 2 +- .../src/mill/pythonlib/PublishModule.scala | 2 +- .../src/mill/pythonlib/HelloWorldTests.scala | 4 +- .../mill/pythonlib/RunBackgroundTests.scala | 2 +- libs/rpc/src/mill/rpc/MillRpcClient.scala | 4 +- libs/rpc/src/mill/rpc/MillRpcServer.scala | 4 +- .../src/mill/scalajslib/api/JsEnvConfig.scala | 24 +++--- .../mill/scalajslib/api/OutputPatterns.scala | 6 +- .../src/mill/scalajslib/api/Report.scala | 4 +- .../scalajslib/worker/ScalaJSWorker.scala | 2 +- .../mill/scalajslib/JarPublishRunTests.scala | 2 +- .../scalajslib/worker/ScalaJSWorkerImpl.scala | 22 +++--- .../src/mill/scalalib/CrossModuleBase.scala | 2 +- .../scalalib/scalafmt/ScalafmtWorker.scala | 2 +- .../resources/hello-world/core/src/Main.scala | 2 +- .../src/DoneMessageFailureFramework.scala | 4 +- .../src/mill/scalalib/HelloWorldTests.scala | 6 +- .../src/mill/scalalib/JavaHomeTests.scala | 4 +- .../scalalib/ScalaAssemblyAppendTests.scala | 6 +- .../scalalib/ScalaAssemblyExcludeTests.scala | 8 +- .../mill/scalalib/ScalaAssemblyTests.scala | 2 +- .../mill/scalalib/ScalaColorOutputTests.scala | 4 +- .../scalalib/ScalaCompilerBridgeTests.scala | 2 +- .../scalalib/TestRunnerScalatestTests.scala | 2 +- .../src/mill/scalalib/TestRunnerTests.scala | 12 +-- .../mill/scalalib/TestRunnerUtestTests.scala | 2 +- .../scalalib/spotless/SpotlessTests.scala | 2 +- .../scalanativelib/ScalaNativeModule.scala | 6 +- .../scalanativelib/api/ScalaNativeApi.scala | 2 +- .../worker/ScalaNativeWorker.scala | 2 +- .../mill/scalanativelib/CompileRunTests.scala | 2 +- .../worker/ScalaNativeWorkerImpl.scala | 4 +- .../mill/tabcomplete/TabCompleteTests.scala | 8 +- libs/util/src/mill/util/Inspect.scala | 4 +- libs/util/src/mill/util/Jvm.scala | 14 ++-- libs/util/src/mill/util/Retry.scala | 4 +- libs/util/src/mill/util/TokenReaders.scala | 6 +- libs/util/src/mill/util/Version.scala | 8 +- libs/util/src/mill/util/VisualizeModule.scala | 4 +- libs/util/test/src/mill/util/JvmTests.scala | 2 +- .../test/src/mill/util/MainModuleTests.scala | 36 ++++----- libs/util/test/src/mill/util/RetryTests.scala | 8 +- runner/bsp/src/mill/bsp/BSP.scala | 2 +- .../worker/BspCompileProblemReporter.scala | 20 ++--- .../src/mill/bsp/worker/BspEvaluators.scala | 8 +- .../src/mill/bsp/worker/BspTestReporter.scala | 12 +-- .../src/mill/bsp/worker/BspWorkerImpl.scala | 2 +- .../src/mill/bsp/worker/MillBspLogger.scala | 2 +- .../src/mill/bsp/worker/MillBuildServer.scala | 76 +++++++++---------- .../mill/bsp/worker/MillJavaBuildServer.scala | 4 +- .../mill/bsp/worker/MillJvmBuildServer.scala | 16 ++-- .../bsp/worker/MillScalaBuildServer.scala | 16 ++-- .../SyntheticRootBspBuildTargetData.scala | 8 +- .../worker/src/mill/bsp/worker/Utils.scala | 10 +-- runner/codesig/src/mill/codesig/CodeSig.scala | 4 +- .../src/mill/codesig/ExternalSummary.scala | 4 +- .../codesig/src/mill/codesig/JvmModel.scala | 8 +- .../src/mill/codesig/LocalSummary.scala | 6 +- .../10-iterator-foreach-scala/src/Hello.scala | 2 +- .../src/Hello.scala | 2 +- .../src/Hello.scala | 4 +- .../src/Hello.scala | 4 +- .../6-classes-misc-scala/src/Hello.scala | 2 +- .../7-manifest-scala/src/Hello.scala | 2 +- .../8-linked-list-scala/src/Hello.scala | 8 +- .../9-array-seq-scala/src/Hello.scala | 2 +- .../realistic/4-actors/src/Hello.scala | 8 +- .../realistic/5-parser/src/Hello.scala | 6 +- runner/codesig/test/src/MethodHashTests.scala | 2 +- runner/codesig/test/src/TestUtil.scala | 2 +- .../src/mill/daemon/MillBuildBootstrap.scala | 2 +- .../src/mill/daemon/MillDaemonMain0.scala | 2 +- runner/daemon/src/mill/daemon/MillMain0.scala | 22 +++--- .../src/mill/daemon/MillScalaParserImpl.scala | 2 +- .../daemon/src/mill/daemon/TailManager.scala | 8 +- runner/daemon/src/mill/daemon/Watching.scala | 2 +- .../src/mill/eclipse/GenEclipseImpl.scala | 2 +- runner/idea/src/mill/idea/GenIdeaImpl.scala | 10 +-- .../src/mill/launcher/ConfigReader.scala | 2 +- .../src/mill/meta/AsmPositionUpdater.scala | 4 +- .../meta/src/mill/meta/FileImportGraph.scala | 2 +- .../src/mill/server/MillDaemonServer.scala | 14 ++-- .../src/mill/server/ClientServerTests.scala | 20 ++--- testkit/src/mill/testkit/BashTokenizer.scala | 4 +- testkit/src/mill/testkit/ExampleTester.scala | 2 +- .../mill/testkit/IntegrationTestSuite.scala | 2 +- .../src/mill/testkit/IntegrationTester.scala | 2 +- testkit/src/mill/testkit/UnitTester.scala | 8 +- 240 files changed, 753 insertions(+), 753 deletions(-) diff --git a/contrib/artifactory/src/mill/contrib/artifactory/ArtifactoryHttpApi.scala b/contrib/artifactory/src/mill/contrib/artifactory/ArtifactoryHttpApi.scala index abebc360df8e..c680a7a35800 100644 --- a/contrib/artifactory/src/mill/contrib/artifactory/ArtifactoryHttpApi.scala +++ b/contrib/artifactory/src/mill/contrib/artifactory/ArtifactoryHttpApi.scala @@ -34,5 +34,5 @@ class ArtifactoryHttpApi( } private def base64(s: String) = - new String(Base64.getEncoder.encode(s.getBytes)) + String(Base64.getEncoder.encode(s.getBytes)) } diff --git a/contrib/artifactory/src/mill/contrib/artifactory/ArtifactoryPublishModule.scala b/contrib/artifactory/src/mill/contrib/artifactory/ArtifactoryPublishModule.scala index 369846cf44e1..67e037f9d5e1 100644 --- a/contrib/artifactory/src/mill/contrib/artifactory/ArtifactoryPublishModule.scala +++ b/contrib/artifactory/src/mill/contrib/artifactory/ArtifactoryPublishModule.scala @@ -29,7 +29,7 @@ trait ArtifactoryPublishModule extends PublishModule { connectTimeout: Int = 5000 ): Command[Unit] = Task.Command { val (artifacts, artifactInfo) = publishArtifacts().withConcretePath - new ArtifactoryPublisher( + ArtifactoryPublisher( artifactoryUri, artifactorySnapshotUri, checkArtifactoryCreds(credentials)(), @@ -64,7 +64,7 @@ object ArtifactoryPublishModule extends ExternalModule { val artifacts = Task.sequence(publishArtifacts.value)().map { case data @ PublishModule.PublishData(_, _) => data.withConcretePath } - new ArtifactoryPublisher( + ArtifactoryPublisher( artifactoryUri, artifactorySnapshotUri, checkArtifactoryCreds(credentials)(), diff --git a/contrib/artifactory/src/mill/contrib/artifactory/ArtifactoryPublisher.scala b/contrib/artifactory/src/mill/contrib/artifactory/ArtifactoryPublisher.scala index 3bee0121f20c..ae5ed9611b79 100644 --- a/contrib/artifactory/src/mill/contrib/artifactory/ArtifactoryPublisher.scala +++ b/contrib/artifactory/src/mill/contrib/artifactory/ArtifactoryPublisher.scala @@ -16,7 +16,7 @@ class ArtifactoryPublisher( private def prepareCreds(credentials: String, repoUri: String): String = { if (credentials.isEmpty) { - val hostname = new URI(repoUri).getHost + val hostname = URI(repoUri).getHost val coursierCreds = CoursierConfig.default().credentials.map(_.get).flatten coursierCreds.find(cred => cred.host == hostname && cred.usernameOpt.isDefined && cred.passwordOpt.isDefined @@ -63,7 +63,7 @@ class ArtifactoryPublisher( payloads: Map[os.SubPath, Array[Byte]], artifacts: Seq[Artifact] ): Unit = { - val api = new ArtifactoryHttpApi( + val api = ArtifactoryHttpApi( credentials = prepareCreds(credentials, repoUri), readTimeout = readTimeout, connectTimeout = connectTimeout @@ -87,7 +87,7 @@ class ArtifactoryPublisher( val errors = publishResults.filterNot(_.is2xx).map { response => s"Code: ${response.statusCode}, message: ${response.text()}" } - throw new RuntimeException( + throw RuntimeException( s"Failed to publish ${artifacts.map(_.id).mkString(", ")} to Artifactory. Errors: \n${errors.mkString("\n")}" ) } diff --git a/contrib/buildinfo/src/mill/contrib/buildinfo/BuildInfo.scala b/contrib/buildinfo/src/mill/contrib/buildinfo/BuildInfo.scala index ba64017a5784..07b30cefddd4 100644 --- a/contrib/buildinfo/src/mill/contrib/buildinfo/BuildInfo.scala +++ b/contrib/buildinfo/src/mill/contrib/buildinfo/BuildInfo.scala @@ -218,7 +218,7 @@ object BuildInfo { | .getResourceAsStream("${buildInfoObjectName}.buildinfo.properties") | | if(buildInfoInputStream == null) - | throw new RuntimeException("Could not load resource ${buildInfoObjectName}.buildinfo.properties") + | throw RuntimeException("Could not load resource ${buildInfoObjectName}.buildinfo.properties") | else try { | buildInfoProperties.load(buildInfoInputStream) | } finally { @@ -269,12 +269,12 @@ object BuildInfo { | try { | buildInfoProperties.load(buildInfoInputStream); | } catch (java.io.IOException e) { - | throw new RuntimeException(e); + | throw RuntimeException(e); | } finally { | try { | buildInfoInputStream.close(); | } catch (java.io.IOException e) { - | throw new RuntimeException(e); + | throw RuntimeException(e); | } | } | } diff --git a/contrib/codeartifact/src/mill/contrib/codeartifact/CodeArtifactPublisher.scala b/contrib/codeartifact/src/mill/contrib/codeartifact/CodeArtifactPublisher.scala index be6875e429ae..ae574adb02bb 100644 --- a/contrib/codeartifact/src/mill/contrib/codeartifact/CodeArtifactPublisher.scala +++ b/contrib/codeartifact/src/mill/contrib/codeartifact/CodeArtifactPublisher.scala @@ -14,7 +14,7 @@ class CodeartifactPublisher( connectTimeout: Int, log: Logger ) { - private val api = new CodeartifactHttpApi( + private val api = CodeartifactHttpApi( credentials, readTimeout = readTimeout, connectTimeout = connectTimeout @@ -112,7 +112,7 @@ class CodeartifactPublisher( val errors = publishResults.filterNot(_.is2xx).map { response => s"Code: ${response.statusCode}, message: ${response.text()}" } - throw new RuntimeException( + throw RuntimeException( s"Failed to publish ${artifacts.map(_.id).mkString(", ")} to AWS Codeartifact. Errors: \n${errors .mkString("\n")}" ) diff --git a/contrib/codeartifact/src/mill/contrib/codeartifact/CodeartifactPublishModule.scala b/contrib/codeartifact/src/mill/contrib/codeartifact/CodeartifactPublishModule.scala index d7011e7b7e15..5d4e1b42f7bf 100644 --- a/contrib/codeartifact/src/mill/contrib/codeartifact/CodeartifactPublishModule.scala +++ b/contrib/codeartifact/src/mill/contrib/codeartifact/CodeartifactPublishModule.scala @@ -25,7 +25,7 @@ trait CodeartifactPublishModule extends PublishModule { val (artifacts, artifactInfo) = publishArtifacts().withConcretePath - new CodeartifactPublisher( + CodeartifactPublisher( codeartifactUri, codeartifactSnapshotUri, credentials, @@ -47,7 +47,7 @@ object CodeartifactPublishModule extends ExternalModule { ) = Task.Command { val artifacts = Task.sequence(publishArtifacts.value)().map(_.withConcretePath) - new CodeartifactPublisher( + CodeartifactPublisher( codeartifactUri, codeartifactSnapshotUri, credentials, diff --git a/contrib/flyway/src/mill/contrib/flyway/ConsoleLog.scala b/contrib/flyway/src/mill/contrib/flyway/ConsoleLog.scala index 518f2cb9b305..ed5799aee59c 100644 --- a/contrib/flyway/src/mill/contrib/flyway/ConsoleLog.scala +++ b/contrib/flyway/src/mill/contrib/flyway/ConsoleLog.scala @@ -56,5 +56,5 @@ class ConsoleLog(val level: ConsoleLog.Level.Level) extends Log { * Log Creator for the Command-Line console. */ class ConsoleLogCreator(val level: ConsoleLog.Level.Level) extends LogCreator { - override def createLogger(clazz: Class[?]): Log = new ConsoleLog(level) + override def createLogger(clazz: Class[?]): Log = ConsoleLog(level) } diff --git a/contrib/flyway/src/mill/contrib/flyway/FlywayModule.scala b/contrib/flyway/src/mill/contrib/flyway/FlywayModule.scala index bb9e1a01e24a..4ddfb45a530a 100644 --- a/contrib/flyway/src/mill/contrib/flyway/FlywayModule.scala +++ b/contrib/flyway/src/mill/contrib/flyway/FlywayModule.scala @@ -49,7 +49,7 @@ trait FlywayModule extends JavaModule { strToOptPair(flyway.USER, flywayUser()) ++ strToOptPair(flyway.PASSWORD, flywayPassword()) - LogFactory.setLogCreator(new ConsoleLogCreator(Level.INFO)) + LogFactory.setLogCreator(ConsoleLogCreator(Level.INFO)) Flyway .configure(jdbcClassloader) diff --git a/contrib/gitlab/src/mill/contrib/gitlab/GitlabPublishModule.scala b/contrib/gitlab/src/mill/contrib/gitlab/GitlabPublishModule.scala index d47d687f2ff9..f6bd7fc4e823 100644 --- a/contrib/gitlab/src/mill/contrib/gitlab/GitlabPublishModule.scala +++ b/contrib/gitlab/src/mill/contrib/gitlab/GitlabPublishModule.scala @@ -39,8 +39,8 @@ trait GitlabPublishModule extends PublishModule { outer => if (skipPublish) { Task.log.info(s"SkipPublish = true, skipping publishing of $artifactInfo") } else { - val uploader = new GitlabUploader(gitlabHeaders()(), readTimeout, connectTimeout) - new GitlabPublisher( + val uploader = GitlabUploader(gitlabHeaders()(), readTimeout, connectTimeout) + GitlabPublisher( uploader.upload, gitlabRepo, Task.log @@ -66,9 +66,9 @@ object GitlabPublishModule extends ExternalModule { val artifacts = Task.sequence(publishArtifacts.value)().map { case data @ PublishModule.PublishData(_, _) => data.withConcretePath } - val uploader = new GitlabUploader(auth, readTimeout, connectTimeout) + val uploader = GitlabUploader(auth, readTimeout, connectTimeout) - new GitlabPublisher( + GitlabPublisher( uploader.upload, repo, Task.log diff --git a/contrib/gitlab/src/mill/contrib/gitlab/GitlabPublisher.scala b/contrib/gitlab/src/mill/contrib/gitlab/GitlabPublisher.scala index 9e3ce51d2f52..e8cc89a8d7ad 100644 --- a/contrib/gitlab/src/mill/contrib/gitlab/GitlabPublisher.scala +++ b/contrib/gitlab/src/mill/contrib/gitlab/GitlabPublisher.scala @@ -55,7 +55,7 @@ class GitlabPublisher( s"Code: ${response.statusCode}, message: ${response.text()}" } // Or just log? Fail later? - throw new RuntimeException( + throw RuntimeException( s"Failed to publish $artifact to Gitlab. Errors: \n${errors.mkString("\n")}" ) } diff --git a/contrib/gitlab/test/src/mill/contrib/gitlab/GitlabTokenTests.scala b/contrib/gitlab/test/src/mill/contrib/gitlab/GitlabTokenTests.scala index c2c2b74deb90..ba1e2060517a 100644 --- a/contrib/gitlab/test/src/mill/contrib/gitlab/GitlabTokenTests.scala +++ b/contrib/gitlab/test/src/mill/contrib/gitlab/GitlabTokenTests.scala @@ -134,7 +134,7 @@ object GitlabTokenTests extends TestSuite { } val repo = ProjectRepository("https://gitlab.local", 10) - val publisher = new GitlabPublisher(uploader, repo, DummyLogger) + val publisher = GitlabPublisher(uploader, repo, DummyLogger) val fakeFile = os.pwd / "dummy.data" os.write(fakeFile, Array[Byte]()) diff --git a/contrib/playlib/src/mill/playlib/RouteCompilerWorkerModule.scala b/contrib/playlib/src/mill/playlib/RouteCompilerWorkerModule.scala index 054400d00208..33976da4eff0 100644 --- a/contrib/playlib/src/mill/playlib/RouteCompilerWorkerModule.scala +++ b/contrib/playlib/src/mill/playlib/RouteCompilerWorkerModule.scala @@ -6,7 +6,7 @@ import mill.api.{Discover, ExternalModule} trait RouteCompilerWorkerModule extends Module { def routeCompilerWorker: Worker[RouteCompilerWorker] = Task.Worker { - new RouteCompilerWorker() + RouteCompilerWorker() } } diff --git a/contrib/playlib/test/resources/playmulti/core/test/controllers/HomeControllerSpec.scala b/contrib/playlib/test/resources/playmulti/core/test/controllers/HomeControllerSpec.scala index 0cb5c9d9061d..745e6a0e1042 100644 --- a/contrib/playlib/test/resources/playmulti/core/test/controllers/HomeControllerSpec.scala +++ b/contrib/playlib/test/resources/playmulti/core/test/controllers/HomeControllerSpec.scala @@ -16,7 +16,7 @@ class HomeControllerSpec extends PlaySpec with GuiceOneAppPerTest with Injecting "HomeController GET" should { "render the index page from a new instance of controller" in { - val controller = new HomeController(stubControllerComponents()) + val controller = HomeController(stubControllerComponents()) val home = controller.index().apply(FakeRequest(GET, "/")) status(home) mustBe OK diff --git a/contrib/playlib/test/resources/playsingle/test/controllers/HomeControllerSpec.scala b/contrib/playlib/test/resources/playsingle/test/controllers/HomeControllerSpec.scala index 0cb5c9d9061d..745e6a0e1042 100644 --- a/contrib/playlib/test/resources/playsingle/test/controllers/HomeControllerSpec.scala +++ b/contrib/playlib/test/resources/playsingle/test/controllers/HomeControllerSpec.scala @@ -16,7 +16,7 @@ class HomeControllerSpec extends PlaySpec with GuiceOneAppPerTest with Injecting "HomeController GET" should { "render the index page from a new instance of controller" in { - val controller = new HomeController(stubControllerComponents()) + val controller = HomeController(stubControllerComponents()) val home = controller.index().apply(FakeRequest(GET, "/")) status(home) mustBe OK diff --git a/contrib/playlib/test/resources/playsingleapi/test/controllers/HomeControllerSpec.scala b/contrib/playlib/test/resources/playsingleapi/test/controllers/HomeControllerSpec.scala index 0cb5c9d9061d..745e6a0e1042 100644 --- a/contrib/playlib/test/resources/playsingleapi/test/controllers/HomeControllerSpec.scala +++ b/contrib/playlib/test/resources/playsingleapi/test/controllers/HomeControllerSpec.scala @@ -16,7 +16,7 @@ class HomeControllerSpec extends PlaySpec with GuiceOneAppPerTest with Injecting "HomeController GET" should { "render the index page from a new instance of controller" in { - val controller = new HomeController(stubControllerComponents()) + val controller = HomeController(stubControllerComponents()) val home = controller.index().apply(FakeRequest(GET, "/")) status(home) mustBe OK diff --git a/contrib/sbom/src/mill/contrib/sbom/CycloneDX.scala b/contrib/sbom/src/mill/contrib/sbom/CycloneDX.scala index a1de9571c79f..0df7d46a15d4 100644 --- a/contrib/sbom/src/mill/contrib/sbom/CycloneDX.scala +++ b/contrib/sbom/src/mill/contrib/sbom/CycloneDX.scala @@ -68,7 +68,7 @@ object CycloneDX { val md = MessageDigest.getInstance("SHA-256") val fileContent = os.read.bytes(f) val digest = md.digest(fileContent) - String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest)) + String.format("%0" + (digest.length << 1) + "x", BigInteger(1, digest)) } case class SbomHeader(serialNumber: UUID, timestamp: Instant) diff --git a/contrib/scalapblib/src/mill/contrib/scalapblib/ScalaPBModule.scala b/contrib/scalapblib/src/mill/contrib/scalapblib/ScalaPBModule.scala index 1a83e4aaf0a0..7f4c0bb29e51 100644 --- a/contrib/scalapblib/src/mill/contrib/scalapblib/ScalaPBModule.scala +++ b/contrib/scalapblib/src/mill/contrib/scalapblib/ScalaPBModule.scala @@ -137,7 +137,7 @@ trait ScalaPBModule extends ScalaModule { val cp = scalaPBProtoClasspath() val dest = Task.dest cp.iterator.foreach { ref => - Using(new ZipInputStream(ref.path.getInputStream)) { zip => + Using(ZipInputStream(ref.path.getInputStream)) { zip => while ({ Option(zip.getNextEntry) match { case None => false diff --git a/contrib/scalapblib/src/mill/contrib/scalapblib/ScalaPBWorkerApi.scala b/contrib/scalapblib/src/mill/contrib/scalapblib/ScalaPBWorkerApi.scala index b62761ed6144..64666ced8bd4 100644 --- a/contrib/scalapblib/src/mill/contrib/scalapblib/ScalaPBWorkerApi.scala +++ b/contrib/scalapblib/src/mill/contrib/scalapblib/ScalaPBWorkerApi.scala @@ -16,6 +16,6 @@ trait ScalaPBWorkerApi { } object ScalaPBWorkerApi extends ExternalModule { - def scalaPBWorker: Task.Worker[ScalaPBWorker] = Task.Worker { new ScalaPBWorker() } + def scalaPBWorker: Task.Worker[ScalaPBWorker] = Task.Worker { ScalaPBWorker() } lazy val millDiscover = Discover[this.type] } diff --git a/contrib/scoverage/src/mill/contrib/scoverage/ScoverageReportWorker.scala b/contrib/scoverage/src/mill/contrib/scoverage/ScoverageReportWorker.scala index f89a45487cd4..01284b8370c0 100644 --- a/contrib/scoverage/src/mill/contrib/scoverage/ScoverageReportWorker.scala +++ b/contrib/scoverage/src/mill/contrib/scoverage/ScoverageReportWorker.scala @@ -104,7 +104,7 @@ object ScoverageReportWorker extends ExternalModule { } def scoverageReportWorker: Task.Worker[ScoverageReportWorker] = - Task.Worker { new ScoverageReportWorker() } + Task.Worker { ScoverageReportWorker() } // TODO: make protected lazy val millDiscover = Discover[this.type] diff --git a/contrib/scoverage/worker2/src/mill/contrib/scoverage/worker/ScoverageReportWorkerImpl.scala b/contrib/scoverage/worker2/src/mill/contrib/scoverage/worker/ScoverageReportWorkerImpl.scala index 9bc887a77774..cfb00fd774ea 100644 --- a/contrib/scoverage/worker2/src/mill/contrib/scoverage/worker/ScoverageReportWorkerImpl.scala +++ b/contrib/scoverage/worker2/src/mill/contrib/scoverage/worker/ScoverageReportWorkerImpl.scala @@ -94,7 +94,7 @@ class ScoverageReportWorkerImpl extends ScoverageReportWorkerApi2 { if (errors.nonEmpty) { // Throw exception with all error messages - throw new RuntimeException( + throw RuntimeException( s"Coverage minimums violated:\n${errors.mkString("\n")}" ) } else { @@ -126,13 +126,13 @@ class ScoverageReportWorkerImpl extends ScoverageReportWorkerApi2 { ScoverageReportWorkerApi2.makeAllDirs(folder) reportType match { case ReportType.Html => - new ScoverageHtmlWriter(sourceFolders, folder.toFile, None) + ScoverageHtmlWriter(sourceFolders, folder.toFile, None) .write(coverage) case ReportType.Xml => - new ScoverageXmlWriter(sourceFolders, folder.toFile, false, None) + ScoverageXmlWriter(sourceFolders, folder.toFile, false, None) .write(coverage) case ReportType.XmlCobertura => - new CoberturaXmlWriter(sourceFolders, folder.toFile, None) + CoberturaXmlWriter(sourceFolders, folder.toFile, None) .write(coverage) case ReportType.Console => ctx.log.info(s"Statement coverage.: ${coverage.statementCoverageFormatted}%") diff --git a/contrib/twirllib/src/mill/twirllib/TwirlWorker.scala b/contrib/twirllib/src/mill/twirllib/TwirlWorker.scala index 0899bf184752..e69b1fd102f4 100644 --- a/contrib/twirllib/src/mill/twirllib/TwirlWorker.scala +++ b/contrib/twirllib/src/mill/twirllib/TwirlWorker.scala @@ -25,7 +25,7 @@ object TwirlWorker { // * the java api uses java collections, manipulating which using reflection is much simpler // // NOTE: When creating the cl classloader with passing the current classloader as the parent: - // val cl = new URLClassLoader(twirlClasspath.map(_.toIO.toURI.toURL).toArray, getClass.getClassLoader) + // val cl = URLClassLoader(twirlClasspath.map(_.toIO.toURI.toURL).toArray, getClass.getClassLoader) // it is possible to cast the default to a Seq[String], construct our own Seq[String], and pass it to the method invoke - // classes will be compatible (the tests passed). // But when run in an actual mill project with this module enabled, there were exceptions like this: @@ -63,7 +63,7 @@ object TwirlWorker { codec: Codec, inclusiveDot: Boolean ): Unit = { - // val twirlImports = new HashSet() + // val twirlImports = HashSet() // imports.foreach(twirlImports.add) val twirlImports = hashSetClass.getConstructor().newInstance().asInstanceOf[Object] val hashSetAddMethod = twirlImports.getClass.getMethod("add", classOf[Object]) @@ -73,7 +73,7 @@ object TwirlWorker { val twirlCodec = codecApplyMethod.invoke(null, charsetForNameMethod.invoke(null, codec.charSet.name())) - // val twirlConstructorAnnotations = new ArrayList() + // val twirlConstructorAnnotations = ArrayList() // constructorAnnotations.foreach(twirlConstructorAnnotations.add) val twirlConstructorAnnotations = arrayListClass.getConstructor().newInstance().asInstanceOf[Object] @@ -169,7 +169,7 @@ object TwirlWorker { private def twirlExtensionClass(name: String, formats: Map[String, String]) = formats.collectFirst { case (ext, klass) if name.endsWith(ext) => klass }.getOrElse { - throw new IllegalStateException( + throw IllegalStateException( s"Unknown twirl extension for file: $name. Known extensions: ${formats.keys.mkString(", ")}" ) } diff --git a/contrib/versionfile/src/mill/contrib/versionfile/Version.scala b/contrib/versionfile/src/mill/contrib/versionfile/Version.scala index 099c3d1d225b..85b1897f05a3 100644 --- a/contrib/versionfile/src/mill/contrib/versionfile/Version.scala +++ b/contrib/versionfile/src/mill/contrib/versionfile/Version.scala @@ -30,7 +30,7 @@ sealed trait Version { case Bump.minor => (major, minor + 1, 0) case Bump.patch => (major, minor, patch + 1) case _ => - throw new RuntimeException(s"Valid arguments for bump are: ${Bump.values.mkString(", ")}") + throw RuntimeException(s"Valid arguments for bump are: ${Bump.values.mkString(", ")}") } this match { diff --git a/core/api/daemon/src/mill/api/daemon/ExecResult.scala b/core/api/daemon/src/mill/api/daemon/ExecResult.scala index 408ebfb8d5e5..ed8aec5403e4 100644 --- a/core/api/daemon/src/mill/api/daemon/ExecResult.scala +++ b/core/api/daemon/src/mill/api/daemon/ExecResult.scala @@ -28,7 +28,7 @@ object ExecResult { try Success(t) catch { case e: Throwable => - Exception(e, new OuterStack(new java.lang.Exception().getStackTrace.toIndexedSeq)) + Exception(e, OuterStack(new java.lang.Exception().getStackTrace.toIndexedSeq)) } } diff --git a/core/api/daemon/src/mill/api/daemon/Logger.scala b/core/api/daemon/src/mill/api/daemon/Logger.scala index b53dffd9c2b7..5306274b0a00 100644 --- a/core/api/daemon/src/mill/api/daemon/Logger.scala +++ b/core/api/daemon/src/mill/api/daemon/Logger.scala @@ -100,10 +100,10 @@ object Logger { object DummyLogger extends Logger { def colored = false - val streams = new SystemStreams( - new PrintStream(_ => ()), - new PrintStream(_ => ()), - new ByteArrayInputStream(Array()) + val streams = SystemStreams( + PrintStream(_ => ()), + PrintStream(_ => ()), + ByteArrayInputStream(Array()) ) def info(s: String) = () diff --git a/core/api/daemon/src/mill/api/daemon/MillURLClassLoader.scala b/core/api/daemon/src/mill/api/daemon/MillURLClassLoader.scala index bd2affceb3bd..8cbfb31e6444 100644 --- a/core/api/daemon/src/mill/api/daemon/MillURLClassLoader.scala +++ b/core/api/daemon/src/mill/api/daemon/MillURLClassLoader.scala @@ -71,7 +71,7 @@ object MillURLClassLoader { private[mill] def addOpenClassloader(label: String) = openClassloaders.synchronized { - // println(s"addOpenClassLoader ${classPath.hashCode}\n " + new Exception().getStackTrace.mkString("\n ")) + // println(s"addOpenClassLoader ${classPath.hashCode}\n " + Exception().getStackTrace.mkString("\n ")) openClassloaders.updateWith(label) { case None => Some(1) @@ -81,7 +81,7 @@ object MillURLClassLoader { private[mill] def removeOpenClassloader(label: String) = openClassloaders.synchronized { - // println(s"removeOpenClassLoader ${classPath.hashCode}\n " + new Exception().getStackTrace.mkString("\n ")) + // println(s"removeOpenClassLoader ${classPath.hashCode}\n " + Exception().getStackTrace.mkString("\n ")) openClassloaders.updateWith(label) { case Some(1) => None case Some(n) => Some(n - 1) diff --git a/core/api/daemon/src/mill/api/daemon/Segments.scala b/core/api/daemon/src/mill/api/daemon/Segments.scala index b65a80c1def4..fae56ecac384 100644 --- a/core/api/daemon/src/mill/api/daemon/Segments.scala +++ b/core/api/daemon/src/mill/api/daemon/Segments.scala @@ -23,7 +23,7 @@ final case class Segments private (value: Seq[Segment]) { def last: Segment.Label = value.last match { case l: Segment.Label => l case _ => - throw new IllegalArgumentException("Segments must end with a Label, but found a Cross.") + throw IllegalArgumentException("Segments must end with a Label, but found a Cross.") } def parts: List[String] = value.flatMap(_.pathSegments).toList @@ -58,7 +58,7 @@ final case class Segments private (value: Seq[Segment]) { object Segments { implicit def ordering: Ordering[Segments] = Ordering.by(_.value) - def apply(): Segments = new Segments(Vector()) - def apply(items: Seq[Segment]): Segments = new Segments(items.toVector) + def apply(): Segments = Segments(Vector()) + def apply(items: Seq[Segment]): Segments = Segments(items.toVector) def labels(values: String*): Segments = Segments(values.map(Segment.Label(_)).toVector) } diff --git a/core/api/daemon/src/mill/api/daemon/SystemStreams.scala b/core/api/daemon/src/mill/api/daemon/SystemStreams.scala index ae41bbba6bf9..f80a7340da10 100644 --- a/core/api/daemon/src/mill/api/daemon/SystemStreams.scala +++ b/core/api/daemon/src/mill/api/daemon/SystemStreams.scala @@ -25,8 +25,8 @@ object SystemStreams { * That means that the logs may appear out of order, jumbling your logs and screwing up * your terminal */ - val original = new SystemStreams(System.out, System.err, System.in) - val current = new DynamicVariable(original) + val original = SystemStreams(System.out, System.err, System.in) + val current = DynamicVariable(original) /** * Used to check whether the system streams are all "original", i,e. they diff --git a/core/api/daemon/src/mill/api/daemon/internal/MillScalaParser.scala b/core/api/daemon/src/mill/api/daemon/internal/MillScalaParser.scala index 298c01567fea..731417536ee7 100644 --- a/core/api/daemon/src/mill/api/daemon/internal/MillScalaParser.scala +++ b/core/api/daemon/src/mill/api/daemon/internal/MillScalaParser.scala @@ -39,5 +39,5 @@ object MillScalaParser { s.patch(start, replacement.padTo(end - start, ' '), end - start) } - val current = new DynamicVariable[MillScalaParser](null) + val current = DynamicVariable[MillScalaParser](null) } diff --git a/core/api/daemon/src/mill/api/daemon/internal/TestReporter.scala b/core/api/daemon/src/mill/api/daemon/internal/TestReporter.scala index db223773917a..f7323dc82fee 100644 --- a/core/api/daemon/src/mill/api/daemon/internal/TestReporter.scala +++ b/core/api/daemon/src/mill/api/daemon/internal/TestReporter.scala @@ -40,7 +40,7 @@ object TestReporter { } def apply(logLevel: LogLevel): TestReporter = - new DefaultImpl(logLevel) + DefaultImpl(logLevel) private final class DefaultImpl(override val logLevel: LogLevel) extends TestReporter { override def logStart(event: Event): Unit = {} diff --git a/core/api/src/mill/api/Cross.scala b/core/api/src/mill/api/Cross.scala index 425276c13a56..504dd1de2dff 100644 --- a/core/api/src/mill/api/Cross.scala +++ b/core/api/src/mill/api/Cross.scala @@ -111,10 +111,10 @@ object Cross { implicit object ByteToPathSegment extends ToSegments[Byte](v => List(v.toString)) implicit object BooleanToPathSegment extends ToSegments[Boolean](v => List(v.toString)) implicit object SubPathToPathSegment extends ToSegments[os.SubPath](v => v.segments.toList) - implicit def SeqToPathSegment[T: ToSegments]: ToSegments[Seq[T]] = new ToSegments[Seq[T]]( + implicit def SeqToPathSegment[T: ToSegments]: ToSegments[Seq[T]] = ToSegments[Seq[T]]( _.flatMap(summon[ToSegments[T]].convert).toList ) - implicit def ListToPathSegment[T: ToSegments]: ToSegments[List[T]] = new ToSegments[List[T]]( + implicit def ListToPathSegment[T: ToSegments]: ToSegments[List[T]] = ToSegments[List[T]]( _.flatMap(summon[ToSegments[T]].convert).toList ) } diff --git a/core/api/src/mill/api/Debug.scala b/core/api/src/mill/api/Debug.scala index b636767386a0..67552c6412d9 100644 --- a/core/api/src/mill/api/Debug.scala +++ b/core/api/src/mill/api/Debug.scala @@ -16,7 +16,7 @@ object Debug { showFieldNames: Boolean = true )(implicit line: sourcecode.Line, fileName: sourcecode.FileName): T = { - val baos = new ByteArrayOutputStream() + val baos = ByteArrayOutputStream() pprint.logTo( x, tag, @@ -25,7 +25,7 @@ object Debug { indent, escapeUnicode, showFieldNames, - new PrintStream(baos) + PrintStream(baos) ) mill.constants.DebugLog.println(baos.toString) x.value diff --git a/core/api/src/mill/api/Discover.scala b/core/api/src/mill/api/Discover.scala index f94df4fc7eec..c3a4717a4cf7 100644 --- a/core/api/src/mill/api/Discover.scala +++ b/core/api/src/mill/api/Discover.scala @@ -155,9 +155,9 @@ object Discover { // the problem of generating a *huge* macro method body that finally exceeds the // JVM's maximum allowed method size '{ - def func() = new ClassInfo( + def func() = ClassInfo( ${ Expr.ofList(entryPoints.toList) }, - ${ Expr.ofList(names.map(s => '{ new TaskInfo(${ Expr(s) }) })) } + ${ Expr.ofList(names.map(s => '{ TaskInfo(${ Expr(s) }) })) } ) (${ classOf(cls) }, func()) diff --git a/core/api/src/mill/api/EnclosingClass.scala b/core/api/src/mill/api/EnclosingClass.scala index adf34a072ccb..abccc0a967db 100644 --- a/core/api/src/mill/api/EnclosingClass.scala +++ b/core/api/src/mill/api/EnclosingClass.scala @@ -26,7 +26,7 @@ object EnclosingClass { val cls = enclosingClass(owner).typeRef val res = - '{ new EnclosingClass(${ Ref(defn.Predef_classOf).appliedToType(cls).asExprOf[Class[?]] }) } + '{ EnclosingClass(${ Ref(defn.Predef_classOf).appliedToType(cls).asExprOf[Class[?]] }) } res } } diff --git a/core/api/src/mill/api/Evaluator.scala b/core/api/src/mill/api/Evaluator.scala index f161613a31db..b4457617a575 100644 --- a/core/api/src/mill/api/Evaluator.scala +++ b/core/api/src/mill/api/Evaluator.scala @@ -135,7 +135,7 @@ object Evaluator { // the EvaluatorTokenReader#read call, which does not accept additional parameters. // Until we migrate our CLI parsing off of Scopt (so we can pass the BaseModule // in directly) we are forced to pass it in via a ThreadLocal - private val currentEvaluator0 = new DynamicVariable[Evaluator](null) + private val currentEvaluator0 = DynamicVariable[Evaluator](null) private[mill] def withCurrentEvaluator[T](ev: Evaluator)(t: => T) = { // Make sure we only put a `EvaluatorProxy` in the `DynamicVariable` rather than a // raw `Evaluator`, and `.close()` it after we're done to `null` out the contents. diff --git a/core/api/src/mill/api/JsonFormatters.scala b/core/api/src/mill/api/JsonFormatters.scala index c8e8836fa75f..758d246caab2 100644 --- a/core/api/src/mill/api/JsonFormatters.scala +++ b/core/api/src/mill/api/JsonFormatters.scala @@ -68,7 +68,7 @@ trait JsonFormatters { "lineNumber" -> ujson.Num(ste.getLineNumber) ), json => - new StackTraceElement( + StackTraceElement( json("declaringClass").str.toString, json("methodName").str.toString, json("fileName").arr.headOption.map(_.str.toString).orNull, diff --git a/core/api/src/mill/api/ModuleCtx.scala b/core/api/src/mill/api/ModuleCtx.scala index 53f78c7b17fc..af4a7b1c92e0 100644 --- a/core/api/src/mill/api/ModuleCtx.scala +++ b/core/api/src/mill/api/ModuleCtx.scala @@ -164,7 +164,7 @@ object ModuleCtx extends LowPriCtx { trait LowPriCtx { // Binary compatibility stub - def dummyInfo: ModuleCtx = throw new Exception(LowPriCtx.errorMessage) + def dummyInfo: ModuleCtx = throw Exception(LowPriCtx.errorMessage) // Dummy `Ctx` available in implicit scope but never actually used. // as it is provided by the codegen. Defined for IDEs to think that one is available @@ -184,6 +184,6 @@ object LowPriCtx { sys.props.contains(mill.constants.EnvVars.MILL_ENABLE_STATIC_CHECKS) ) { report.errorAndAbort(errorMessage) - } else '{ throw new Exception(${ Expr(errorMessage) }) } + } else '{ throw Exception(${ Expr(errorMessage) }) } } } diff --git a/core/api/src/mill/api/PathRef.scala b/core/api/src/mill/api/PathRef.scala index 83bbc3b14cfe..c06d7191db34 100644 --- a/core/api/src/mill/api/PathRef.scala +++ b/core/api/src/mill/api/PathRef.scala @@ -73,7 +73,7 @@ object PathRef { case Revalidate.Once | Revalidate.Always => val changedSig = PathRef.apply(pathRef.path, pathRef.quick).sig if (pathRef.sig != changedSig) { - throw new PathRefValidationException(pathRef) + throw PathRefValidationException(pathRef) } val _ = map.put(mapKey(pathRef), pathRef) } @@ -82,10 +82,10 @@ object PathRef { } private[mill] val validatedPaths: DynamicVariable[ValidatedPaths] = - new DynamicVariable[ValidatedPaths](new ValidatedPaths()) + DynamicVariable[ValidatedPaths](ValidatedPaths()) private[mill] val serializedPaths: DynamicVariable[List[PathRef]] = - new DynamicVariable(null) + DynamicVariable(null) class PathRefValidationException(val pathRef: PathRef) extends RuntimeException(s"Invalid path signature detected: ${pathRef}") @@ -118,7 +118,7 @@ object PathRef { val sig = { val isPosix = path.wrapped.getFileSystem.supportedFileAttributeViews().contains("posix") val digest = MessageDigest.getInstance("MD5") - val digestOut = new DigestOutputStream(DummyOutputStream, digest) + val digestOut = DigestOutputStream(DummyOutputStream, digest) def updateWithInt(value: Int): Unit = { digest.update((value >>> 24).toByte) @@ -171,7 +171,7 @@ object PathRef { java.util.Arrays.hashCode(digest.digest()) } - new PathRef(path, quick, sig, revalidate) + PathRef(path, quick, sig, revalidate) } private[mill] def withSerializedPaths[T](block: => T): (T, Seq[PathRef]) = { diff --git a/core/api/src/mill/api/SystemStreamsUtils.scala b/core/api/src/mill/api/SystemStreamsUtils.scala index 0b7c2ca93bee..46c8828a8e2d 100644 --- a/core/api/src/mill/api/SystemStreamsUtils.scala +++ b/core/api/src/mill/api/SystemStreamsUtils.scala @@ -33,11 +33,11 @@ object SystemStreamsUtils { val inheritOut = if (systemStreams.out eq original.out) os.InheritRaw - else new PumpedProcessOutput(systemStreams.out) + else PumpedProcessOutput(systemStreams.out) val inheritErr = if (systemStreams.err eq original.err) os.InheritRaw - else new PumpedProcessOutput(systemStreams.err) + else PumpedProcessOutput(systemStreams.err) ThreadLocalStreams.current.withValue(systemStreams) { Console.withIn(systemStreams.in) { @@ -133,38 +133,38 @@ object SystemStreamsUtils { private def debugPrintln(s: String) = () private[mill] class DebugDelegateStream(delegate0: mill.api.SystemStreams) extends mill.api.SystemStreams( - new PrintStream(new ThreadLocalStreams.ProxyOutputStream { + PrintStream(new ThreadLocalStreams.ProxyOutputStream { override def delegate(): OutputStream = delegate0.out override def write(b: Array[Byte], off: Int, len: Int): Unit = { - debugPrintln(new String(b, off, len)) + debugPrintln(String(b, off, len)) super.write(b, off, len) } override def write(b: Array[Byte]): Unit = { - debugPrintln(new String(b)) + debugPrintln(String(b)) super.write(b) } override def write(b: Int): Unit = { - debugPrintln(new String(Array(b.toByte))) + debugPrintln(String(Array(b.toByte))) super.write(b) } }), - new PrintStream(new ThreadLocalStreams.ProxyOutputStream { + PrintStream(new ThreadLocalStreams.ProxyOutputStream { override def delegate(): OutputStream = delegate0.err override def write(b: Array[Byte], off: Int, len: Int): Unit = { - debugPrintln(new String(b, off, len)) + debugPrintln(String(b, off, len)) super.write(b, off, len) } override def write(b: Array[Byte]): Unit = { - debugPrintln(new String(b)) + debugPrintln(String(b)) super.write(b) } override def write(b: Int): Unit = { - debugPrintln(new String(Array(b.toByte))) + debugPrintln(String(Array(b.toByte))) super.write(b) } }), diff --git a/core/api/src/mill/api/Task.scala b/core/api/src/mill/api/Task.scala index 732f82053da4..4c9c6f13318c 100644 --- a/core/api/src/mill/api/Task.scala +++ b/core/api/src/mill/api/Task.scala @@ -218,7 +218,7 @@ object Task { @unused t: NamedParameterOnlyDummy = new NamedParameterOnlyDummy, exclusive: Boolean = false, persistent: Boolean = false - ): CommandFactory = new CommandFactory(exclusive = exclusive, persistent = persistent) + ): CommandFactory = CommandFactory(exclusive = exclusive, persistent = persistent) class CommandFactory private[mill] (val exclusive: Boolean, val persistent: Boolean) { inline def apply[T](inline t: Result[T])(using inline w: Writer[T], @@ -286,7 +286,7 @@ object Task { def apply( @unused t: NamedParameterOnlyDummy = new NamedParameterOnlyDummy, persistent: Boolean = false - ): ApplyFactory = new ApplyFactory(persistent) + ): ApplyFactory = ApplyFactory(persistent) class ApplyFactory private[mill] (val persistent: Boolean) { inline def apply[T](inline t: Result[T])(using inline rw: ReadWriter[T], @@ -360,7 +360,7 @@ object Task { def label: String = ctx.segments.value.last match { case Segment.Label(v) => v - case Segment.Cross(_) => throw new IllegalArgumentException( + case Segment.Cross(_) => throw IllegalArgumentException( "Task.Named only support a ctx with a Label segment, but found a Cross." ) } diff --git a/core/api/src/mill/api/TaskCtx.scala b/core/api/src/mill/api/TaskCtx.scala index cae7e48fd3a6..362f240ee95b 100644 --- a/core/api/src/mill/api/TaskCtx.scala +++ b/core/api/src/mill/api/TaskCtx.scala @@ -57,7 +57,7 @@ object TaskCtx { def arg[T](index: Int): T = { if (index >= 0 && index < args.length) args(index).asInstanceOf[T] - else throw new IndexOutOfBoundsException(s"Index $index outside of range 0 - ${args.length}") + else throw IndexOutOfBoundsException(s"Index $index outside of range 0 - ${args.length}") } def fail(msg: String): Nothing = throw Result.Exception(msg) diff --git a/core/api/src/mill/api/internal/Applicative.scala b/core/api/src/mill/api/internal/Applicative.scala index 09959683bcfa..aaf9dc18acd2 100644 --- a/core/api/src/mill/api/internal/Applicative.scala +++ b/core/api/src/mill/api/internal/Applicative.scala @@ -64,7 +64,7 @@ object Applicative { /** The `A` to the `Task[A]`. */ val innerTypeRepr = resultTypeRepr.typeArgs match { case innerTypeRepr :: Nil => innerTypeRepr - case other => throw new IllegalStateException( + case other => throw IllegalStateException( s"Task[_] should have exactly one type parameter, but got ${other.map(_.show)}. " + "This is a bug in mill." ) @@ -171,7 +171,7 @@ object Applicative { } if hasErrors then - '{ throw new RuntimeException("stub implementation - macro expansion had errors") } + '{ throw RuntimeException("stub implementation - macro expansion had errors") } else traverseCtx(exprsList, callback) } diff --git a/core/api/src/mill/api/internal/Cacher.scala b/core/api/src/mill/api/internal/Cacher.scala index 7b5d61d7cd07..d3f2acb5a69b 100644 --- a/core/api/src/mill/api/internal/Cacher.scala +++ b/core/api/src/mill/api/internal/Cacher.scala @@ -79,6 +79,6 @@ private[mill] object Cacher { ) { report.errorAndAbort(errorMessage, Position.ofMacroExpansion) // Use a runtime exception to prevent false error highlighting in IntelliJ - } else '{ throw new Exception(${ Expr(errorMessage) }) } + } else '{ throw Exception(${ Expr(errorMessage) }) } } } diff --git a/core/api/src/mill/api/internal/Mirrors.scala b/core/api/src/mill/api/internal/Mirrors.scala index 4f4a3258b02d..f6eabf1af420 100644 --- a/core/api/src/mill/api/internal/Mirrors.scala +++ b/core/api/src/mill/api/internal/Mirrors.scala @@ -397,7 +397,7 @@ private[mill] object Mirrors { val defaultCase = CaseDef( Wildcard(), None, - '{ throw new IllegalArgumentException(s"Unknown argument ${$arg}") }.asTerm + '{ throw IllegalArgumentException(s"Unknown argument ${$arg}") }.asTerm ) val matchExpr = Match(arg.asTerm, cases :+ defaultCase) matchExpr.asExprOf[Int] diff --git a/core/api/src/mill/api/internal/OverrideMapping.scala b/core/api/src/mill/api/internal/OverrideMapping.scala index 60440d82541c..266dd2b1ad81 100644 --- a/core/api/src/mill/api/internal/OverrideMapping.scala +++ b/core/api/src/mill/api/internal/OverrideMapping.scala @@ -60,7 +60,7 @@ private[mill] object OverrideMapping { taskClassName: String ) = { // StringTokenizer is faster than String#split due to not using regexes - def splitEnclosing(s: String) = new StringTokenizer(s, ".# $") + def splitEnclosing(s: String) = StringTokenizer(s, ".# $") .asIterator() .asScala.map(_.asInstanceOf[String]) .filter(_ != "") diff --git a/core/api/src/mill/api/internal/Reflect.scala b/core/api/src/mill/api/internal/Reflect.scala index 490d4f465d53..cab662baf51b 100644 --- a/core/api/src/mill/api/internal/Reflect.scala +++ b/core/api/src/mill/api/internal/Reflect.scala @@ -133,7 +133,7 @@ private[mill] object Reflect { (name, m.getReturnType, (outer: Any) => m.invoke(outer).asInstanceOf[T]) case (name, m: java.lang.reflect.Field) => (name, m.getType, (outer: Any) => m.get(outer).asInstanceOf[T]) - case other => throw new IllegalArgumentException(s"Unexpected member: $other") + case other => throw IllegalArgumentException(s"Unexpected member: $other") } } diff --git a/core/api/src/mill/api/internal/WatchSig.scala b/core/api/src/mill/api/internal/WatchSig.scala index 21f7fcedd72a..65735abb4cac 100644 --- a/core/api/src/mill/api/internal/WatchSig.scala +++ b/core/api/src/mill/api/internal/WatchSig.scala @@ -9,7 +9,7 @@ private[mill] object WatchSig { def poll(w: Watchable): Long = w match { case Watchable.Path(p, quick, sig) => - new PathRef(os.Path(p), quick, sig, PathRef.Revalidate.Once).recomputeSig() + PathRef(os.Path(p), quick, sig, PathRef.Revalidate.Once).recomputeSig() case Watchable.Value(f, _, _) => try f() catch { case _ => 0 } @@ -17,7 +17,7 @@ private[mill] object WatchSig { def signature(w: Watchable): Long = w match { case Watchable.Path(p, quick, sig) => - new PathRef(os.Path(p), quick, sig, PathRef.Revalidate.Once).sig + PathRef(os.Path(p), quick, sig, PathRef.Revalidate.Once).sig case Watchable.Value(_, sig, _) => sig } diff --git a/core/api/test/src/mill/api/ApplicativeTests.scala b/core/api/test/src/mill/api/ApplicativeTests.scala index ea0da51eea14..522859309e6c 100644 --- a/core/api/test/src/mill/api/ApplicativeTests.scala +++ b/core/api/test/src/mill/api/ApplicativeTests.scala @@ -79,14 +79,14 @@ object ApplicativeTests extends TestSuite { // Although x is defined inside the Opt{...} block, it is also defined // within the LHS of the Applyable#apply call, so it is safe to life it // out into the `zipMap` arguments list. - val res = Opt { "lol " + new Opt(Some("hello").flatMap(x => Some(x))).apply() } + val res = Opt { "lol " + Opt(Some("hello").flatMap(x => Some(x))).apply() } assert(res == Opt.some("lol hello")) } test("upstreamAlwaysEvaluated") { // Whether or not control-flow reaches the Applyable#apply call inside an // Opt{...} block, we always evaluate the LHS of the Applyable#apply // because it gets lifted out of any control flow statements - val counter = new Counter() + val counter = Counter() def up = Opt { "lol " + counter() } val down = Opt { if ("lol".length > 10) up() else "fail" } assert( @@ -97,7 +97,7 @@ object ApplicativeTests extends TestSuite { test("upstreamEvaluatedOnlyOnce") { // Even if control-flow reaches the Applyable#apply call more than once, // it only gets evaluated once due to its lifting out of the Opt{...} block - val counter = new Counter() + val counter = Counter() def up = Opt { "lol " + counter() } def runTwice[T](t: => T) = (t, t) val down = Opt { runTwice(up()) } @@ -109,7 +109,7 @@ object ApplicativeTests extends TestSuite { test("evaluationsInsideLambdasWork") { // This required some fiddling with owner chains inside the macro to get // working, so ensure it doesn't regress - val counter = new Counter() + val counter = Counter() def up = Opt { "hello" + counter() } val down1 = Opt { (() => up())() } val down2 = Opt { Seq(1, 2, 3).map(n => up() * n) } @@ -123,7 +123,7 @@ object ApplicativeTests extends TestSuite { // your Opt{...} call, each one gets evaluated once, even if the LHS of each // apply() call is identical. It's up to the downstream zipMap() // implementation to decide if it wants to dedup them or do other things. - val counter = new Counter() + val counter = Counter() def up = Opt { s"hello${counter()}" } val down = Opt { Seq(1, 2, 3).map(n => n + up() + up()) } assert(down == Opt.some(Seq("1hello1hello2", "2hello1hello2", "3hello1hello2"))) @@ -132,7 +132,7 @@ object ApplicativeTests extends TestSuite { // Every Applyable#apply() within a Opt{...} block evaluates before any // other logic within that block, even if they would happen first in the // normal Scala evaluation order - val counter = new Counter() + val counter = Counter() def up = Opt { counter() } val down = Opt { val res = counter() diff --git a/core/api/test/src/mill/api/Opt.scala b/core/api/test/src/mill/api/Opt.scala index 2d1dc97100a3..4d8b40cedcee 100644 --- a/core/api/test/src/mill/api/Opt.scala +++ b/core/api/test/src/mill/api/Opt.scala @@ -6,8 +6,8 @@ import scala.quoted.* case class Opt[+T](self: Option[T]) extends Applicative.Applyable[Opt, T] object Opt { - def none: Opt[Nothing] = new Opt(None) - def some[T](t: T): Opt[T] = new Opt(Some(t)) + def none: Opt[Nothing] = Opt(None) + def some[T](t: T): Opt[T] = Opt(Some(t)) val injectedCtx = "helloooo" def ctx()(using c: String): String = c @@ -15,7 +15,7 @@ object Opt { def traverseCtx[I, R](xs: Seq[Opt[I]])(f: (Seq[I], String) => Applicative.Id[R]) : Opt[R] = { - new Opt( + Opt( if (xs.exists(_.self.isEmpty)) None else Some(f(xs.map(_.self.get).toVector, Opt.injectedCtx)) ) diff --git a/core/eval/src/mill/eval/EvaluatorImpl.scala b/core/eval/src/mill/eval/EvaluatorImpl.scala index 60a6e7f503c5..eb8521071d47 100644 --- a/core/eval/src/mill/eval/EvaluatorImpl.scala +++ b/core/eval/src/mill/eval/EvaluatorImpl.scala @@ -35,7 +35,7 @@ final class EvaluatorImpl( allowPositionalCommandArgs, selectiveExecution, execution, - new ScriptModuleInit() + ScriptModuleInit() ) override val staticBuildOverrides = execution.staticBuildOverrides @@ -49,7 +49,7 @@ final class EvaluatorImpl( def effectiveThreadCount = execution.effectiveThreadCount override def offline: Boolean = execution.offline - def withBaseLogger(newBaseLogger: Logger): Evaluator = new EvaluatorImpl( + def withBaseLogger(newBaseLogger: Logger): Evaluator = EvaluatorImpl( allowPositionalCommandArgs, selectiveExecution, execution.withBaseLogger(newBaseLogger), @@ -339,7 +339,7 @@ final class EvaluatorImpl( reporter: Int => Option[CompileProblemReporter] = _ => None, selectiveExecution: Boolean = false ): mill.api.Result[Evaluator.Result[Any]] = { - val promptLineLogger = new PrefixLogger( + val promptLineLogger = PrefixLogger( logger0 = baseLogger, key0 = Seq("resolve"), message = "resolve " + scriptArgs.mkString(" ") diff --git a/core/exec/src/mill/exec/CodeSigUtils.scala b/core/exec/src/mill/exec/CodeSigUtils.scala index 885aec30708c..d6181c4707ab 100644 --- a/core/exec/src/mill/exec/CodeSigUtils.scala +++ b/core/exec/src/mill/exec/CodeSigUtils.scala @@ -102,7 +102,7 @@ object CodeSigUtils { val methodClass = methodOpt .nextOption() - .getOrElse(throw new MillException( + .getOrElse(throw MillException( s"Could not detect the parent class of task ${namedTask}. " + s"Please report this at ${BuildInfo.millReportNewIssueUrl} . " )) @@ -123,7 +123,7 @@ object CodeSigUtils { case null => None case m: mill.api.Module => Some((m, m.moduleCtx)) case unknown => - throw new MillException(s"Unknown ctx of task ${namedTask}: $unknown") + throw MillException(s"Unknown ctx of task ${namedTask}: $unknown") } } @@ -131,7 +131,7 @@ object CodeSigUtils { .map(m => constructorHashSignatures.get(m.getClass.getName) match { case Some(Seq((_, hash))) => hash - case Some(multiple) => throw new MillException( + case Some(multiple) => throw MillException( s"Multiple constructors found for module $m: ${multiple.mkString(",")}" ) case None => 0 diff --git a/core/exec/src/mill/exec/Execution.scala b/core/exec/src/mill/exec/Execution.scala index b5bd7aff5c0c..41a4f7f0a388 100644 --- a/core/exec/src/mill/exec/Execution.scala +++ b/core/exec/src/mill/exec/Execution.scala @@ -108,10 +108,10 @@ case class Execution( serialCommandExec: Boolean ): Execution.Results = { os.makeDir.all(outPath) - val failed = new AtomicBoolean(false) - val count = new AtomicInteger(1) - val rootFailedCount = new AtomicInteger(0) // Track only root failures - val planningLogger = new PrefixLogger( + val failed = AtomicBoolean(false) + val count = AtomicInteger(1) + val rootFailedCount = AtomicInteger(0) // Track only root failures + val planningLogger = PrefixLogger( logger0 = baseLogger, key0 = Seq("planning"), message = "planning" @@ -204,7 +204,7 @@ case class Execution( val keySuffix = s"/${indexToTerminal.size}" - val contextLogger = new PrefixLogger( + val contextLogger = PrefixLogger( logger0 = logger, key0 = Seq(countMsg), keySuffix = keySuffix, @@ -280,7 +280,7 @@ case class Execution( // Wrapping the fatal error in a non-fatal exception, so it would be caught by Scala's Future // infrastructure, rather than silently terminating the future and leaving downstream Awaits hanging. case e: Throwable if !scala.util.control.NonFatal(e) => - val nonFatal = new Exception(s"fatal exception occurred: $e", e) + val nonFatal = Exception(s"fatal exception occurred: $e", e) // Set the stack trace of the non-fatal exception to the original exception's stack trace // as it actually indicates the location of the error. nonFatal.setStackTrace(e.getStackTrace) diff --git a/core/exec/src/mill/exec/ExecutionContexts.scala b/core/exec/src/mill/exec/ExecutionContexts.scala index cba7f7bdda9a..23fa8d8008be 100644 --- a/core/exec/src/mill/exec/ExecutionContexts.scala +++ b/core/exec/src/mill/exec/ExecutionContexts.scala @@ -58,7 +58,7 @@ object ExecutionContexts { val submitterPwd = os.dynamicPwdFunction.value val submitterChecker = os.checker.value val submitterStreams = new mill.api.SystemStreams(Console.out, Console.err, System.in) - executor.execute(new PriorityRunnable( + executor.execute(PriorityRunnable( 0, () => os.checker.withValue(submitterChecker) { @@ -108,9 +108,9 @@ object ExecutionContexts { def async[T](dest: Path, key: String, message: String, priority: Int)(t: Logger => T)(using ctx: mill.api.TaskCtx ): Future[T] = { - val logger = new MultiLogger( - new PrefixLogger(ctx.log, Seq(key), ctx.log.keySuffix, message), - new FileLogger(dest / os.up / s"${dest.last}.log", false), + val logger = MultiLogger( + PrefixLogger(ctx.log, Seq(key), ctx.log.keySuffix, message), + FileLogger(dest / os.up / s"${dest.last}.log", false), ctx.log.streams.in ) @@ -124,7 +124,7 @@ object ExecutionContexts { dest } val promise = concurrent.Promise[T] - val runnable = new PriorityRunnable( + val runnable = PriorityRunnable( priority = priority, run0 = () => { val result = scala.util.Try(logger.withPromptLine { @@ -147,7 +147,7 @@ object ExecutionContexts { def createExecutor(threadCount: Int): ThreadPoolExecutor = { val executorIndex = executorCounter.incrementAndGet() val threadCounter = new AtomicInteger - new ThreadPoolExecutor( + ThreadPoolExecutor( threadCount, threadCount, 0, @@ -156,10 +156,10 @@ object ExecutionContexts { // operations reversed, providing elements in a LIFO order. This ensures that // child `fork.async` tasks always take priority over parent tasks, avoiding // large numbers of blocked parent tasks from piling up - new PriorityBlockingQueue[Runnable](), + PriorityBlockingQueue[Runnable](), runnable => { val threadIndex = threadCounter.incrementAndGet() - val t = new Thread( + val t = Thread( runnable, s"execution-contexts-threadpool-$executorIndex-thread-$threadIndex" ) diff --git a/core/exec/src/mill/exec/GroupExecution.scala b/core/exec/src/mill/exec/GroupExecution.scala index cf570c86009c..c17404380cda 100644 --- a/core/exec/src/mill/exec/GroupExecution.scala +++ b/core/exec/src/mill/exec/GroupExecution.scala @@ -451,7 +451,7 @@ trait GroupExecution { case NonFatal(e) => ExecResult.Exception( e, - new OuterStack(new Exception().getStackTrace.toIndexedSeq) + OuterStack(Exception().getStackTrace.toIndexedSeq) ) case e: Throwable => throw e } @@ -539,8 +539,8 @@ trait GroupExecution { logPath match { case None => (logger, None) case Some(path) => - val fileLogger = new FileLogger(path) - val multiLogger = new MultiLogger( + val fileLogger = FileLogger(path) + val multiLogger = MultiLogger( logger, fileLogger, logger.streams.in @@ -663,7 +663,7 @@ object GroupExecution { usedDest = Some(dest.dest) dest.dest - case None => throw new Exception("No `dest` folder available here") + case None => throw Exception("No `dest` folder available here") } } } @@ -731,7 +731,7 @@ object GroupExecution { val isCommand = terminal.isInstanceOf[Task.Command[?]] val isInput = terminal.isInstanceOf[Task.Input[?]] val executionChecker = - new ExecutionChecker(workspace, isCommand, isInput, terminal, validReadDests, validWriteDests) + ExecutionChecker(workspace, isCommand, isInput, terminal, validReadDests, validWriteDests) val (streams, destFunc) = if (exclusive) (exclusiveSystemStreams, () => workspace) else (multiLogger.streams, () => destCreator.makeDest()) @@ -759,7 +759,7 @@ object GroupExecution { // For exclusive tasks, we print the task name once and then we disable the // prompt/ticker so the output of the exclusive task can "clean" while still // being identifiable - logger.prompt.logPrefixedLine(Seq(counterMsg), new ByteArrayOutputStream(), false) + logger.prompt.logPrefixedLine(Seq(counterMsg), ByteArrayOutputStream(), false) logger.prompt.withPromptPaused { t } diff --git a/core/exec/src/mill/exec/PlanImpl.scala b/core/exec/src/mill/exec/PlanImpl.scala index 4fe495a7daee..9fa9099db1ef 100644 --- a/core/exec/src/mill/exec/PlanImpl.scala +++ b/core/exec/src/mill/exec/PlanImpl.scala @@ -17,7 +17,7 @@ object PlanImpl { case t if goalSet.contains(t) => t } - new Plan(sortedGroups) + Plan(sortedGroups) } /** @@ -100,6 +100,6 @@ object PlanImpl { val sortedClusters = mill.internal.Tarjans(numberedEdges) assert(sortedClusters.count(_.length > 1) == 0, sortedClusters.filter(_.length > 1)) - new TopoSorted(sortedClusters.map(_(0)).map(indexed)) + TopoSorted(sortedClusters.map(_(0)).map(indexed)) } } diff --git a/core/exec/test/src/mill/exec/ExecutionTests.scala b/core/exec/test/src/mill/exec/ExecutionTests.scala index 04b4681a6568..aa985234dfe3 100644 --- a/core/exec/test/src/mill/exec/ExecutionTests.scala +++ b/core/exec/test/src/mill/exec/ExecutionTests.scala @@ -27,7 +27,7 @@ object ExecutionTests extends TestSuite { } object anonTaskFailure extends TestRootModule { - def anon = Task.Anon[Int] { throw new Exception("boom") } + def anon = Task.Anon[Int] { throw Exception("boom") } def task = Task[Int] { anon() } lazy val millDiscover = Discover[this.type] @@ -239,7 +239,7 @@ object ExecutionTests extends TestSuite { object build extends TestRootModule { def input = Task.Input { x } - def worker = Task.Worker { new MyWorker(input()) } + def worker = Task.Worker { MyWorker(input()) } lazy val millDiscover = Discover[this.type] } diff --git a/core/exec/test/src/mill/exec/OverrideTests.scala b/core/exec/test/src/mill/exec/OverrideTests.scala index 67e2e61de114..7db20dafc958 100644 --- a/core/exec/test/src/mill/exec/OverrideTests.scala +++ b/core/exec/test/src/mill/exec/OverrideTests.scala @@ -99,7 +99,7 @@ object OverrideTests extends TestSuite { // the main publicly-available task import canOverrideSuper._ - val checker = new Checker(canOverrideSuper) + val checker = Checker(canOverrideSuper) checker(foo, Seq("base", "object"), Seq(foo), extraEvaled = -1) val public = os.read(checker.execution.outPath / "foo.json") @@ -119,7 +119,7 @@ object OverrideTests extends TestSuite { // the main publicly-available command import canOverrideSuper._ - val checker = new Checker(canOverrideSuper) + val checker = Checker(canOverrideSuper) val runCmd = cmd(1) checker( runCmd, @@ -146,7 +146,7 @@ object OverrideTests extends TestSuite { // the main publicly-available command import StackableOverrides._ - val checker = new Checker(StackableOverrides) + val checker = Checker(StackableOverrides) checker( m.f, 6, @@ -168,7 +168,7 @@ object OverrideTests extends TestSuite { // When the supers have the same name, qualify them until they are distinct import StackableOverrides2._ - val checker = new Checker(StackableOverrides2) + val checker = Checker(StackableOverrides2) checker( m.f, 6, @@ -190,7 +190,7 @@ object OverrideTests extends TestSuite { // When the supers have the same name, qualify them until they are distinct import StackableOverrides3._ - val checker = new Checker(StackableOverrides3) + val checker = Checker(StackableOverrides3) checker( m.f, 6, @@ -213,7 +213,7 @@ object OverrideTests extends TestSuite { // disk regardless of whether or not the override is part of the current evaluation import OptionalOverride._ - val checker = new Checker(OptionalOverride) + val checker = Checker(OptionalOverride) test { checker(m.f, 11, Seq(m.f), extraEvaled = -1) assert( @@ -233,7 +233,7 @@ object OverrideTests extends TestSuite { // Make sure we can have private cached tasks in different trait with the same name, // and caching still works when these traits are mixed together import PrivateTasksInMixedTraits._ - val checker = new Checker(PrivateTasksInMixedTraits) + val checker = Checker(PrivateTasksInMixedTraits) checker( mod.bar, "foo-m1", diff --git a/core/exec/test/src/mill/exec/TaskTests.scala b/core/exec/test/src/mill/exec/TaskTests.scala index f68cb474bce9..5cf6a8ecfd71 100644 --- a/core/exec/test/src/mill/exec/TaskTests.scala +++ b/core/exec/test/src/mill/exec/TaskTests.scala @@ -90,7 +90,7 @@ trait TaskTests extends TestSuite { } def reevalTrigger = Task.Input { - new Object().hashCode() + Object().hashCode() } def staticWorkerDownstreamReeval = Task { val w = staticWorker() diff --git a/core/internal/src/mill/internal/FileLogger.scala b/core/internal/src/mill/internal/FileLogger.scala index 19506f8ce05b..aab27fe26e57 100644 --- a/core/internal/src/mill/internal/FileLogger.scala +++ b/core/internal/src/mill/internal/FileLogger.scala @@ -29,7 +29,7 @@ class FileLogger( folderCreated = true Files.newOutputStream(file.toNIO, options*) } - new PrintStream(new OutputStream { + PrintStream(new OutputStream { override def write(b: Int): Unit = inner.write(b) override def write(b: Array[Byte]): Unit = inner.write(b) @@ -42,7 +42,7 @@ class FileLogger( }) } - val streams = new SystemStreams(fileStream, fileStream, mill.api.DummyInputStream) + val streams = SystemStreams(fileStream, fileStream, mill.api.DummyInputStream) def info(s: String): Unit = streams.out.println(s) def warn(s: String): Unit = streams.out.println(s) def error(s: String): Unit = streams.out.println(s) diff --git a/core/internal/src/mill/internal/JsonArrayLogger.scala b/core/internal/src/mill/internal/JsonArrayLogger.scala index 9bf56e418c03..2ece4ad950e3 100644 --- a/core/internal/src/mill/internal/JsonArrayLogger.scala +++ b/core/internal/src/mill/internal/JsonArrayLogger.scala @@ -15,13 +15,13 @@ class JsonArrayLogger[T: upickle.Writer](outPath: os.Path, indent: Int) { Seq(StandardOpenOption.TRUNCATE_EXISTING) ).flatten os.makeDir.all(outPath / os.up) - new PrintStream(new BufferedOutputStream(Files.newOutputStream(outPath.toNIO, options*))) + PrintStream(BufferedOutputStream(Files.newOutputStream(outPath.toNIO, options*))) } // Log the JSON entries asynchronously on a separate thread to try and avoid blocking // the main execution, but keep the size bounded so if the logging falls behind the // main thread will get blocked until logging can catch up - val buffer = new ArrayBlockingQueue[Option[T]](100) + val buffer = ArrayBlockingQueue[Option[T]](100) val writeThread = mill.api.daemon.StartThread("JsonArrayLogger " + outPath.last) { // Make sure all writes to `traceStream` are synchronized, as we // have two threads writing to it (one while active, one on close() diff --git a/core/internal/src/mill/internal/LineBufferingOutputStream.scala b/core/internal/src/mill/internal/LineBufferingOutputStream.scala index 05923a8e521a..c6ee9c094866 100644 --- a/core/internal/src/mill/internal/LineBufferingOutputStream.scala +++ b/core/internal/src/mill/internal/LineBufferingOutputStream.scala @@ -13,7 +13,7 @@ import java.io.{ByteArrayOutputStream, OutputStream} class LineBufferingOutputStream(onLineComplete: ByteArrayOutputStream => Unit) extends OutputStream { - val buffer = new ByteArrayOutputStream() + val buffer = ByteArrayOutputStream() override def write(b: Array[Byte]): Unit = write(b, 0, b.length) diff --git a/core/internal/src/mill/internal/MultiLogger.scala b/core/internal/src/mill/internal/MultiLogger.scala index 87b8fc3117c7..333476f5aa15 100644 --- a/core/internal/src/mill/internal/MultiLogger.scala +++ b/core/internal/src/mill/internal/MultiLogger.scala @@ -10,15 +10,15 @@ class MultiLogger( val inStream0: InputStream ) extends Logger { override def toString: String = s"MultiLogger($logger1, $logger2)" - lazy val streams = new SystemStreams( - new MultiStream(logger1.streams.out, logger2.streams.out), - new MultiStream(logger1.streams.err, logger2.streams.err), + lazy val streams = SystemStreams( + MultiStream(logger1.streams.out, logger2.streams.out), + MultiStream(logger1.streams.err, logger2.streams.err), inStream0 ) - override lazy val unprefixedStreams: SystemStreams = new SystemStreams( - new MultiStream(logger1.unprefixedStreams.out, logger2.unprefixedStreams.out), - new MultiStream(logger1.unprefixedStreams.err, logger2.unprefixedStreams.err), + override lazy val unprefixedStreams: SystemStreams = SystemStreams( + MultiStream(logger1.unprefixedStreams.out, logger2.unprefixedStreams.out), + MultiStream(logger1.unprefixedStreams.err, logger2.unprefixedStreams.err), inStream0 ) @@ -131,13 +131,13 @@ class MultiLogger( override def keySuffix = logger1.keySuffix ++ logger2.keySuffix override def redirectOutToErr: Boolean = logger1.redirectOutToErr || logger1.redirectOutToErr - override def withRedirectOutToErr() = new MultiLogger( + override def withRedirectOutToErr() = MultiLogger( logger1.withRedirectOutToErr(), logger2.withRedirectOutToErr(), inStream0 ) override def withOutStream(outStream: PrintStream): Logger = { - new MultiLogger( + MultiLogger( logger1.withOutStream(outStream), logger2.withOutStream(outStream), inStream0 diff --git a/core/internal/src/mill/internal/PipeStreams.scala b/core/internal/src/mill/internal/PipeStreams.scala index 9719d4ed0894..69e8012d679c 100644 --- a/core/internal/src/mill/internal/PipeStreams.scala +++ b/core/internal/src/mill/internal/PipeStreams.scala @@ -62,7 +62,7 @@ class PipeStreams(val bufferSize: Int = 1024) { pipe => } private def checkStateForReceive(): Unit = { - if (closedByWriter || closedByReader) throw new IOException("Pipe closed") + if (closedByWriter || closedByReader) throw IOException("Pipe closed") } private def awaitSpace(): Unit = { @@ -88,7 +88,7 @@ class PipeStreams(val bufferSize: Int = 1024) { pipe => } override def read(): Int = synchronized { - if (closedByReader) throw new IOException("Pipe closed") + if (closedByReader) throw IOException("Pipe closed") while (in < 0) { if (closedByWriter) return -1 /* closed by writer, return EOF */ diff --git a/core/internal/src/mill/internal/PrefixLogger.scala b/core/internal/src/mill/internal/PrefixLogger.scala index 028818d886db..a3bd73eb3416 100644 --- a/core/internal/src/mill/internal/PrefixLogger.scala +++ b/core/internal/src/mill/internal/PrefixLogger.scala @@ -45,17 +45,17 @@ case class PrefixLogger( s"PrefixLogger($logger0, $key0)" def prefixPrintStream(logToOut: Boolean) = { - new PrintStream( - new LineBufferingOutputStream(logMsg => prompt.logPrefixedLine(logKey, logMsg, logToOut)) + PrintStream( + LineBufferingOutputStream(logMsg => prompt.logPrefixedLine(logKey, logMsg, logToOut)) ) } - val streams = new SystemStreams( + val streams = SystemStreams( out = prefixPrintStream(true && !redirectOutToErr), err = prefixPrintStream(false), logger0.streams.in ) - override val unprefixedStreams = new SystemStreams( + override val unprefixedStreams = SystemStreams( if (redirectOutToErr) logger0.unprefixedStreams.err else logger0.unprefixedStreams.out, logger0.unprefixedStreams.err, logger0.unprefixedStreams.in diff --git a/core/internal/src/mill/internal/PromptLogger.scala b/core/internal/src/mill/internal/PromptLogger.scala index d0a928fc17a6..1e39043138d3 100644 --- a/core/internal/src/mill/internal/PromptLogger.scala +++ b/core/internal/src/mill/internal/PromptLogger.scala @@ -128,7 +128,7 @@ class PromptLogger( ) } - val threadNumberer = new ThreadNumberer() + val threadNumberer = ThreadNumberer() override def setPromptHeaderPrefix(s: String): Unit = PromptLogger.this.synchronized { promptLineState.setHeaderPrefix(s) } @@ -188,7 +188,7 @@ class PromptLogger( // color. This ensures that any trailing colors in the original `bufferString` do not // get ignored since they would affect zero characters. val extendedString = fansi.Str.apply( - new String(continuationColoredLine) + "x", + String(continuationColoredLine) + "x", fansi.ErrorMode.Sanitize ) @@ -367,12 +367,12 @@ object PromptLogger { // `ProxyStream`, as we need to preserve the ordering of writes to each individual // stream, and also need to know when *both* streams are quiescent so that we can // print the prompt at the bottom - val pipe = new PipeStreams() + val pipe = PipeStreams() val proxyOut = new ProxyStream.Output(pipe.output, ProxyStream.OUT) val proxyErr = new ProxyStream.Output(pipe.output, ProxyStream.ERR) - val proxySystemStreams = new SystemStreams( - new PrintStream(proxyOut), - new PrintStream(proxyErr), + val proxySystemStreams = SystemStreams( + PrintStream(proxyOut), + PrintStream(proxyErr), systemStreams0.in ) @@ -384,7 +384,7 @@ object PromptLogger { if (!paused()) { val currentPrompt = getCurrentPrompt() systemStreams0.err.write(currentPrompt) - if (interactive()) lastPromptHeight = new String(currentPrompt).linesIterator.size + if (interactive()) lastPromptHeight = String(currentPrompt).linesIterator.size else lastPromptHeight = 0 } else lastPromptHeight = 0 @@ -458,7 +458,7 @@ object PromptLogger { } } - val pumperThread = new Thread(pumper, "prompt-logger-stream-pumper-thread") + val pumperThread = Thread(pumper, "prompt-logger-stream-pumper-thread") pumperThread.start() def close(): Unit = { diff --git a/core/internal/src/mill/internal/ProxyLogger.scala b/core/internal/src/mill/internal/ProxyLogger.scala index 923e4a48c1f5..60670cc31459 100644 --- a/core/internal/src/mill/internal/ProxyLogger.scala +++ b/core/internal/src/mill/internal/ProxyLogger.scala @@ -24,5 +24,5 @@ class ProxyLogger(logger: Logger) extends Logger { override def redirectOutToErr: Boolean = logger.redirectOutToErr - override def withRedirectOutToErr() = new ProxyLogger(logger.withRedirectOutToErr()) + override def withRedirectOutToErr() = ProxyLogger(logger.withRedirectOutToErr()) } diff --git a/core/internal/src/mill/internal/SimpleLogger.scala b/core/internal/src/mill/internal/SimpleLogger.scala index 121a01ed49da..89a36f09519c 100644 --- a/core/internal/src/mill/internal/SimpleLogger.scala +++ b/core/internal/src/mill/internal/SimpleLogger.scala @@ -13,10 +13,10 @@ class SimpleLogger( private val linePrefix: String = Logger.formatPrefix(logKey) private def prefixPrintStream(stream: java.io.OutputStream) = { - new PrintStream(new LineBufferingOutputStream(s => stream.write((linePrefix + s).getBytes))) + PrintStream(LineBufferingOutputStream(s => stream.write((linePrefix + s).getBytes))) } - val streams = new SystemStreams( + val streams = SystemStreams( out = prefixPrintStream(unprefixedStreams.out), err = prefixPrintStream(unprefixedStreams.err), unprefixedStreams.in diff --git a/core/internal/src/mill/internal/Util.scala b/core/internal/src/mill/internal/Util.scala index bd3825b10238..ea19f17a1bd7 100644 --- a/core/internal/src/mill/internal/Util.scala +++ b/core/internal/src/mill/internal/Util.scala @@ -196,9 +196,9 @@ object Util { import scala.jdk.CollectionConverters._ val settings = LoadSettings.builder().build() - val reader = new StreamReader(settings, headerData) - val parser = new ParserImpl(settings, reader) - val composer = new Composer(settings, parser) + val reader = StreamReader(settings, headerData) + val parser = ParserImpl(settings, reader) + val composer = Composer(settings, parser) // recursively convert Node using the visitor, preserving character offsets def rec[J](node: Node, v: upickle.core.Visitor[_, J]): J = { diff --git a/core/internal/test/src/mill/internal/LineBufferingOutputStreamTests.scala b/core/internal/test/src/mill/internal/LineBufferingOutputStreamTests.scala index f2f8db29bb13..dae3c75feb1f 100644 --- a/core/internal/test/src/mill/internal/LineBufferingOutputStreamTests.scala +++ b/core/internal/test/src/mill/internal/LineBufferingOutputStreamTests.scala @@ -7,27 +7,27 @@ import java.io.ByteArrayOutputStream object LineBufferingOutputStreamTests extends TestSuite { val tests = Tests { test("charByChar") { - val baos = new ByteArrayOutputStream() + val baos = ByteArrayOutputStream() val lpos = - new LineBufferingOutputStream(s => { baos.write("PREFIX".getBytes()); s.writeTo(baos) }) + LineBufferingOutputStream(s => { baos.write("PREFIX".getBytes()); s.writeTo(baos) }) for (b <- "hello\nworld\n!".getBytes()) lpos.write(b) lpos.close() assert(baos.toString == "PREFIXhello\nPREFIXworld\nPREFIX!") } test("charByCharTrailingNewline") { - val baos = new ByteArrayOutputStream() + val baos = ByteArrayOutputStream() val lpos = - new LineBufferingOutputStream(s => { baos.write("PREFIX".getBytes()); s.writeTo(baos) }) + LineBufferingOutputStream(s => { baos.write("PREFIX".getBytes()); s.writeTo(baos) }) for (b <- "hello\nworld\n".getBytes()) lpos.write(b) lpos.flush() assert(baos.toString == "PREFIXhello\nPREFIXworld\n") } test("allAtOnce") { - val baos = new ByteArrayOutputStream() + val baos = ByteArrayOutputStream() val lpos = - new LineBufferingOutputStream(s => { baos.write("PREFIX".getBytes()); s.writeTo(baos) }) + LineBufferingOutputStream(s => { baos.write("PREFIX".getBytes()); s.writeTo(baos) }) val arr = "hello\nworld\n!".getBytes() lpos.write(arr) lpos.close() @@ -36,9 +36,9 @@ object LineBufferingOutputStreamTests extends TestSuite { } test("allAtOnceTrailingNewline") { - val baos = new ByteArrayOutputStream() + val baos = ByteArrayOutputStream() val lpos = - new LineBufferingOutputStream(s => { baos.write("PREFIX".getBytes()); s.writeTo(baos) }) + LineBufferingOutputStream(s => { baos.write("PREFIX".getBytes()); s.writeTo(baos) }) val arr = "hello\nworld\n".getBytes() lpos.write(arr) lpos.flush() @@ -47,9 +47,9 @@ object LineBufferingOutputStreamTests extends TestSuite { } test("allAtOnceDoubleNewline") { - val baos = new ByteArrayOutputStream() + val baos = ByteArrayOutputStream() val lpos = - new LineBufferingOutputStream(s => { baos.write("PREFIX".getBytes()); s.writeTo(baos) }) + LineBufferingOutputStream(s => { baos.write("PREFIX".getBytes()); s.writeTo(baos) }) val arr = "hello\n\nworld\n\n".getBytes() lpos.write(arr) lpos.flush() @@ -64,8 +64,8 @@ object LineBufferingOutputStreamTests extends TestSuite { for (i1 <- Range(0, arr.length)) { for (i2 <- Range(i1, arr.length)) { for (i3 <- Range(i2, arr.length)) { - val baos = new ByteArrayOutputStream() - val lpos = new LineBufferingOutputStream(s => { + val baos = ByteArrayOutputStream() + val lpos = LineBufferingOutputStream(s => { baos.write("PREFIX".getBytes()); s.writeTo(baos) }) lpos.write(arr, 0, i1) diff --git a/core/internal/test/src/mill/internal/PipeStreamsTests.scala b/core/internal/test/src/mill/internal/PipeStreamsTests.scala index 152e658ba58c..0af0dd7997e1 100644 --- a/core/internal/test/src/mill/internal/PipeStreamsTests.scala +++ b/core/internal/test/src/mill/internal/PipeStreamsTests.scala @@ -10,19 +10,19 @@ import scala.concurrent.duration.Duration.* object PipeStreamsTests extends TestSuite { val tests = Tests { test("hello") { // Single write and read works - val pipe = new PipeStreams() + val pipe = PipeStreams() val data = Array[Byte](1, 2, 3, 4, 5, 0, 3) assert(data.length < pipe.bufferSize) pipe.output.write(data) - val out = new Array[Byte](7) + val out = Array[Byte](7) pipe.input.read(out) out ==> data } test("multiple") { // Single sequential write and read works - val pipe = new PipeStreams() + val pipe = PipeStreams() val chunkSize = 10 val chunkCount = 100 for (i <- Range(0, chunkCount)) { @@ -34,7 +34,7 @@ object PipeStreamsTests extends TestSuite { } } test("concurrentWriteRead") { // Single sequential write and read works - val pipe = new PipeStreams(bufferSize = 13) + val pipe = PipeStreams(bufferSize = 13) val chunkSize = 20 val chunkCount = 100 assert(pipe.bufferSize < chunkSize * chunkCount) // ensure it gets filled @@ -59,7 +59,7 @@ object PipeStreamsTests extends TestSuite { test("multiThreadWrite") { // multiple writes across different threads followed by read val chunkSize = 10 val chunkCount = 100 - val pipe = new PipeStreams() + val pipe = PipeStreams() assert(chunkSize * chunkCount < pipe.bufferSize) val writerPool = ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(40)) val writeFutures = @@ -84,7 +84,7 @@ object PipeStreamsTests extends TestSuite { ) { // multiple writes across different threads interleaved by reads val chunkSize = 20 val chunkCount = 100 - val pipe = new PipeStreams(bufferSize = 113) + val pipe = PipeStreams(bufferSize = 113) assert(chunkSize * chunkCount > pipe.bufferSize) val writerPool = ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(40)) for (i <- Range(0, chunkCount)) yield Future { @@ -105,7 +105,7 @@ object PipeStreamsTests extends TestSuite { // test("multiThreadWriteMultiThreadRead"){ // multiple writes across different threads interleaved by reads // val chunkSize = 20 // val chunkCount = 100 - // val pipe = new PipeStreams(bufferSize = 137) + // val pipe = PipeStreams(bufferSize = 137) // val writerPool = ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(100)) // val readerPool = ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(100)) // for(i <- Range(0, chunkCount)) yield Future{ diff --git a/core/internal/test/src/mill/internal/PromptLoggerTests.scala b/core/internal/test/src/mill/internal/PromptLoggerTests.scala index b1520dc9898a..540d998c1ee6 100644 --- a/core/internal/test/src/mill/internal/PromptLoggerTests.scala +++ b/core/internal/test/src/mill/internal/PromptLoggerTests.scala @@ -8,16 +8,16 @@ import java.io.{ByteArrayInputStream, ByteArrayOutputStream, PrintStream} object PromptLoggerTests extends TestSuite { def setup(now: () => Long, terminfoPath: os.Path) = { - val baos = new ByteArrayOutputStream() - val baosOut = new PrintStream(new ProxyStream.Output(baos, ProxyStream.OUT)) - val baosErr = new PrintStream(new ProxyStream.Output(baos, ProxyStream.ERR)) + val baos = ByteArrayOutputStream() + val baosOut = PrintStream(new ProxyStream.Output(baos, ProxyStream.OUT)) + val baosErr = PrintStream(new ProxyStream.Output(baos, ProxyStream.ERR)) val promptLogger = new PromptLogger( colored = false, enableTicker = true, infoColor = fansi.Attrs.Empty, warnColor = fansi.Attrs.Empty, errorColor = fansi.Attrs.Empty, - systemStreams0 = new SystemStreams(baosOut, baosErr, System.in), + systemStreams0 = SystemStreams(baosOut, baosErr, System.in), debugEnabled = false, titleText = "TITLE", terminfoPath = terminfoPath, @@ -32,7 +32,7 @@ object PromptLoggerTests extends TestSuite { super.refreshPrompt(ending) } } - val prefixLogger = new PrefixLogger(promptLogger, Seq("1")) + val prefixLogger = PrefixLogger(promptLogger, Seq("1")) (baos, promptLogger, prefixLogger) } @@ -42,11 +42,11 @@ object PromptLoggerTests extends TestSuite { width: Int = 80 )(expected: String*) = { promptLogger.streamsAwaitPumperEmpty() - val finalBaos = new ByteArrayOutputStream() + val finalBaos = ByteArrayOutputStream() val pumper = - new ProxyStream.Pumper(new ByteArrayInputStream(baos.toByteArray), finalBaos, finalBaos) + new ProxyStream.Pumper(ByteArrayInputStream(baos.toByteArray), finalBaos, finalBaos) pumper.run() - val term = new TestTerminal(width) + val term = TestTerminal(width) term.writeAll(finalBaos.toString) val lines = term.grid.map(_.stripSuffix("\r")) @@ -141,14 +141,14 @@ object PromptLoggerTests extends TestSuite { // Adding new ticker entries doesn't appear immediately, // Only after some time has passed do we start displaying the new ticker entry, // to ensure it is meaningful to read and not just something that will flash and disappear - val newPrefixLogger2 = new PrefixLogger(promptLogger, Seq("2")) + val newPrefixLogger2 = PrefixLogger(promptLogger, Seq("2")) newPrefixLogger2.prompt.setPromptLine(Seq("2"), "/456", "my-task-new") newPrefixLogger2.streams.err.println("I AM COW") newPrefixLogger2.streams.err.println("HEAR ME MOO") // For short-lived ticker entries that are removed quickly, they never // appear in the prompt at all even though they can run and generate logs - val newPrefixLogger3 = new PrefixLogger(promptLogger, Seq("3")) + val newPrefixLogger3 = PrefixLogger(promptLogger, Seq("3")) newPrefixLogger3.prompt.setPromptLine(Seq("3"), "/456", "my-task-short-lived") newPrefixLogger3.streams.err.println("hello short lived") newPrefixLogger3.streams.err.println("goodbye short lived") diff --git a/core/internal/test/src/mill/internal/PromptLoggerUtilTests.scala b/core/internal/test/src/mill/internal/PromptLoggerUtilTests.scala index 60c21e090bfa..d1c1ac5caeec 100644 --- a/core/internal/test/src/mill/internal/PromptLoggerUtilTests.scala +++ b/core/internal/test/src/mill/internal/PromptLoggerUtilTests.scala @@ -462,7 +462,7 @@ object PromptLoggerUtilTests extends TestSuite { } } test("streamToPrependNewlines") { - val baos = new ByteArrayOutputStream() + val baos = ByteArrayOutputStream() val input = "Hello\nworld\r\nI\tam\tcow\n".getBytes PromptLoggerUtil.streamToPrependNewlines(baos, input, input.length, "!!!".getBytes) baos.toByteArray ==> "Hello!!!\nworld!!!\r\nI!!!\tam!!!\tcow!!!\n".getBytes diff --git a/core/internal/test/src/mill/internal/TestTerminalTests.scala b/core/internal/test/src/mill/internal/TestTerminalTests.scala index c959390a4cd2..4b34bbb40b4f 100644 --- a/core/internal/test/src/mill/internal/TestTerminalTests.scala +++ b/core/internal/test/src/mill/internal/TestTerminalTests.scala @@ -79,7 +79,7 @@ object TestTerminalTests extends TestSuite { val tests = Tests { test("wrap") { - val t = new TestTerminal(width = 10) + val t = TestTerminal(width = 10) t.writeAll("1234567890abcdef") t.grid ==> Seq( "1234567890", @@ -87,7 +87,7 @@ object TestTerminalTests extends TestSuite { ) } test("newline") { - val t = new TestTerminal(width = 10) + val t = TestTerminal(width = 10) t.writeAll("12345\n67890") t.grid ==> Seq( "12345", @@ -95,7 +95,7 @@ object TestTerminalTests extends TestSuite { ) } test("trailingNewline") { - val t = new TestTerminal(width = 10) + val t = TestTerminal(width = 10) t.writeAll("12345\n") t.grid ==> Seq( "12345", @@ -103,7 +103,7 @@ object TestTerminalTests extends TestSuite { ) } test("wrapNewline") { - val t = new TestTerminal(width = 10) + val t = TestTerminal(width = 10) t.writeAll("1234567890\nabcdef") t.grid ==> Seq( "1234567890", @@ -111,7 +111,7 @@ object TestTerminalTests extends TestSuite { ) } test("wrapNewline2") { - val t = new TestTerminal(width = 10) + val t = TestTerminal(width = 10) t.writeAll("1234567890\n\nabcdef") t.grid ==> Seq( "1234567890", @@ -120,7 +120,7 @@ object TestTerminalTests extends TestSuite { ) } test("up") { - val t = new TestTerminal(width = 15) + val t = TestTerminal(width = 15) t.writeAll(s"1234567890\nabcdef${AnsiNav.up(1)}X") t.grid ==> Seq( "123456X890", @@ -128,7 +128,7 @@ object TestTerminalTests extends TestSuite { ) } test("left") { - val t = new TestTerminal(width = 15) + val t = TestTerminal(width = 15) t.writeAll(s"1234567890\nabcdef${AnsiNav.left(3)}X") t.grid ==> Seq( "1234567890", @@ -136,7 +136,7 @@ object TestTerminalTests extends TestSuite { ) } test("upLeftClearLine") { - val t = new TestTerminal(width = 15) + val t = TestTerminal(width = 15) t.writeAll(s"1234567890\nabcdef${AnsiNav.up(1)}${AnsiNav.left(3)}X${AnsiNav.clearLine(0)}") t.grid ==> Seq( "123X", @@ -144,12 +144,12 @@ object TestTerminalTests extends TestSuite { ) } test("upLeftClearScreen") { - val t = new TestTerminal(width = 15) + val t = TestTerminal(width = 15) t.writeAll(s"1234567890\nabcdef${AnsiNav.up(1)}${AnsiNav.left(3)}X${AnsiNav.clearScreen(0)}") t.grid ==> Seq("123X") } test("wrapUpClearLine") { - val t = new TestTerminal(width = 10) + val t = TestTerminal(width = 10) t.writeAll(s"1234567890abcdef${AnsiNav.up(1)}${AnsiNav.left(3)}X${AnsiNav.clearLine(0)}") t.grid ==> Seq( "123X", @@ -157,7 +157,7 @@ object TestTerminalTests extends TestSuite { ) } test("wrapUpClearScreen") { - val t = new TestTerminal(width = 10) + val t = TestTerminal(width = 10) t.writeAll(s"1234567890abcdef${AnsiNav.up(1)}${AnsiNav.left(3)}X${AnsiNav.clearScreen(0)}") t.grid ==> Seq("123X") } diff --git a/core/resolve/test/src/mill/resolve/ErrorTests.scala b/core/resolve/test/src/mill/resolve/ErrorTests.scala index ebf32509ee95..8888b2e6fb95 100644 --- a/core/resolve/test/src/mill/resolve/ErrorTests.scala +++ b/core/resolve/test/src/mill/resolve/ErrorTests.scala @@ -19,7 +19,7 @@ object ErrorTests extends TestSuite { def fooTask = Task { println(s"Running fooTask"); 123 } def fooCommand(@arg(positional = true) s: String) = Task.Command { println(s"Running fooCommand $s") } - throw new Exception("Foo Boom") + throw Exception("Foo Boom") } object bar extends Module { @@ -31,7 +31,7 @@ object ErrorTests extends TestSuite { def quxTask = Task { println(s"Running quxTask"); "quxTask Result" } def quxCommand(@arg(positional = true) s: String) = Task.Command { println(s"Running quxCommand $s") } - throw new Exception("Qux Boom") + throw Exception("Qux Boom") } } @@ -44,7 +44,7 @@ object ErrorTests extends TestSuite { def fooTask = Task { println(s"Running fooTask"); 123 } def fooCommand(@arg(positional = true) s: String) = Task.Command { println(s"Running fooCommand $s") } - throw new Exception("Foo Boom") + throw Exception("Foo Boom") } object bar extends Module { @@ -63,7 +63,7 @@ object ErrorTests extends TestSuite { object crossModuleSimpleInitError extends TestRootModule { object myCross extends Cross[MyCross](1, 2, 3, 4) { - throw new Exception(s"MyCross Boom") + throw Exception(s"MyCross Boom") } trait MyCross extends Cross.Module[Int] { def foo = Task { crossValue } @@ -74,14 +74,14 @@ object ErrorTests extends TestSuite { object crossModulePartialInitError extends TestRootModule { object myCross extends Cross[MyCross](1, 2, 3, 4) trait MyCross extends Cross.Module[Int] { - if (crossValue > 2) throw new Exception(s"MyCross Boom $crossValue") + if (crossValue > 2) throw Exception(s"MyCross Boom $crossValue") def foo = Task { crossValue } } lazy val millDiscover = Discover[this.type] } object crossModuleSelfInitError extends TestRootModule { - object myCross extends Cross[MyCross](1, 2, 3, throw new Exception(s"MyCross Boom")) + object myCross extends Cross[MyCross](1, 2, 3, throw Exception(s"MyCross Boom")) trait MyCross extends Cross.Module[Int] { def foo = Task { crossValue } } @@ -91,7 +91,7 @@ object ErrorTests extends TestSuite { object crossModuleParentInitError extends TestRootModule { object parent extends Module { - throw new Exception(s"Parent Boom") + throw Exception(s"Parent Boom") object myCross extends Cross[MyCross](1, 2, 3, 4) trait MyCross extends Cross.Module[Int] { def foo = Task { crossValue } @@ -221,12 +221,12 @@ object ErrorTests extends TestSuite { } val tests = Tests { - val errorGraphs = new ErrorGraphs() + val errorGraphs = ErrorGraphs() import errorGraphs.* test("moduleInitError") { test("simple") { - val check = new Checker(moduleInitError) + val check = Checker(moduleInitError) // We can resolve the root module tasks even when the // sub-modules fail to initialize test("rootTask") - check.checkSeq( @@ -283,7 +283,7 @@ object ErrorTests extends TestSuite { } test("dependency") { - val check = new Checker(moduleDependencyInitError) + val check = Checker(moduleDependencyInitError) test("fooTask") - check.checkSeq0( Seq("foo.fooTask"), @@ -314,7 +314,7 @@ object ErrorTests extends TestSuite { test("cross") { test("simple") { - val check = new Checker(crossModuleSimpleInitError) + val check = Checker(crossModuleSimpleInitError) check.checkSeq0( Seq("myCross[1].foo"), isShortError(_, "MyCross Boom"), @@ -332,7 +332,7 @@ object ErrorTests extends TestSuite { ) } test("partial") { - val check = new Checker(crossModulePartialInitError) + val check = Checker(crossModulePartialInitError) // If any one of the cross modules fails to initialize, even if it's // not the one you are asking for, we fail and make sure to catch and @@ -394,7 +394,7 @@ object ErrorTests extends TestSuite { ) } test("self") { - val check = new Checker(crossModuleSelfInitError) + val check = Checker(crossModuleSelfInitError) // When the cross module itself fails to initialize, even before its // children get a chance to init. Instantiating the tasks fails, but @@ -415,7 +415,7 @@ object ErrorTests extends TestSuite { } test("parent") { - val check = new Checker(crossModuleParentInitError) + val check = Checker(crossModuleParentInitError) // When the parent of the cross module fails to initialize, even // before the cross module or its children get a chance to init, @@ -435,7 +435,7 @@ object ErrorTests extends TestSuite { } } test("cyclicModuleRefInitError") { - val check = new Checker(CyclicModuleRefInitError) + val check = Checker(CyclicModuleRefInitError) test - check.checkSeq0( Seq("__"), isShortError(_, "Cyclic module reference detected at myA.a,") @@ -466,14 +466,14 @@ object ErrorTests extends TestSuite { ) } test("cyclicModuleRefInitError2") { - val check = new Checker(CyclicModuleRefInitError2) + val check = Checker(CyclicModuleRefInitError2) test - check.checkSeq0( Seq("__"), isShortError(_, "Cyclic module reference detected at A.myA.a,") ) } test("cyclicModuleRefInitError3") { - val check = new Checker(CyclicModuleRefInitError3) + val check = Checker(CyclicModuleRefInitError3) test - check.checkSeq0( Seq("__"), isShortError(_, "Cyclic module reference detected at A.b.a,") @@ -488,28 +488,28 @@ object ErrorTests extends TestSuite { ) } test("crossedCyclicModuleRefInitError") { - val check = new Checker(CrossedCyclicModuleRefInitError) + val check = Checker(CrossedCyclicModuleRefInitError) test - check.checkSeq0( Seq("__"), isShortError(_, "Cyclic module reference detected at cross[210].c2[210].c1,") ) } test("nonCyclicModules") { - val check = new Checker(NonCyclicModules) + val check = Checker(NonCyclicModules) test - check( "__", Result.Success(Set(_.foo)) ) } test("moduleRefWithNonModuleRefChild") { - val check = new Checker(ModuleRefWithNonModuleRefChild) + val check = Checker(ModuleRefWithNonModuleRefChild) test - check( "__", Result.Success(Set(_.foo)) ) } test("moduleRefCycle") { - val check = new Checker(ModuleRefCycle) + val check = Checker(ModuleRefCycle) test - check( "__", Result.Success(Set(_.foo)) diff --git a/core/resolve/test/src/mill/resolve/ModuleTests.scala b/core/resolve/test/src/mill/resolve/ModuleTests.scala index 4b0fe5edb29c..0bef1ea2e5b8 100644 --- a/core/resolve/test/src/mill/resolve/ModuleTests.scala +++ b/core/resolve/test/src/mill/resolve/ModuleTests.scala @@ -164,7 +164,7 @@ object ModuleTests extends TestSuite { val tests = Tests { test("cross") { test("single") { - val check = new Checker(singleCross) + val check = Checker(singleCross) test("pos1") - check( "cross[210].suffix", Result.Success(Set(_.cross("210").suffix)), @@ -235,7 +235,7 @@ object ModuleTests extends TestSuite { ) } test("double") { - val check = new Checker(doubleCross) + val check = Checker(doubleCross) test("pos1") - check( "cross[210,jvm].suffix", Result.Success(Set(_.cross("210", "jvm").suffix)), @@ -383,7 +383,7 @@ object ModuleTests extends TestSuite { } } test("nested") { - val check = new Checker(nestedCrosses) + val check = Checker(nestedCrosses) test("pos1") - check( "cross[210].cross2[js].suffix", Result.Success(Set(_.cross("210").cross2("js").suffix)), @@ -464,7 +464,7 @@ object ModuleTests extends TestSuite { } test("nestedCrossTaskModule") { - val check = new Checker(nestedTaskCrosses) + val check = Checker(nestedTaskCrosses) test("pos1") - check.checkSeq( Seq("cross1[210].cross2[js].suffixCmd"), Result.Success(Set(_.cross1("210").cross2("js").suffixCmd())), @@ -499,7 +499,7 @@ object ModuleTests extends TestSuite { } test("duplicate") { - val check = new Checker(duplicates) + val check = Checker(duplicates) def segments( found: Result[List[Task.Named[?]]], @@ -560,7 +560,7 @@ object ModuleTests extends TestSuite { } test("overriddenModule") { - val check = new Checker(overrideModule) + val check = Checker(overrideModule) test - check( "sub.inner.subTask", Result.Success(Set(_.sub.inner.subTask)), @@ -573,7 +573,7 @@ object ModuleTests extends TestSuite { ) } test("dynamicModule") { - val check = new Checker(dynamicModule) + val check = Checker(dynamicModule) test - check( "normal.inner.task", Result.Success(Set(_.normal.inner.task)), @@ -612,7 +612,7 @@ object ModuleTests extends TestSuite { ) } test("abstractModule") { - val check = new Checker(AbstractModule) + val check = Checker(AbstractModule) test - check( "__", Result.Success(Set(_.concrete.tests.inner.foo, _.concrete.tests.inner.innerer.bar)) diff --git a/core/resolve/test/src/mill/resolve/ResolveTests.scala b/core/resolve/test/src/mill/resolve/ResolveTests.scala index 5529ff035e70..4217f3b7c14f 100644 --- a/core/resolve/test/src/mill/resolve/ResolveTests.scala +++ b/core/resolve/test/src/mill/resolve/ResolveTests.scala @@ -28,7 +28,7 @@ object ResolveTests extends TestSuite { val tests = Tests { test("single") { - val check = new Checker(singleton) + val check = Checker(singleton) test("pos") - check("single", Result.Success(Set(_.single)), Set("single")) test("wildcard") - check("_", Result.Success(Set(_.single)), Set("single")) test("neg1") - check("sngle", Result.Failure("Cannot resolve sngle. Did you mean single?")) @@ -59,7 +59,7 @@ object ResolveTests extends TestSuite { ) } test("backtickIdentifiers") { - val check = new Checker(bactickIdentifiers) + val check = Checker(bactickIdentifiers) test("pos1") - check("up-task", Result.Success(Set(_.`up-task`)), Set("up-task")) test("pos2") - check( "a-down-task", @@ -111,7 +111,7 @@ object ResolveTests extends TestSuite { } } test("nested") { - val check = new Checker(nestedModule) + val check = Checker(nestedModule) test("pos1") - check("single", Result.Success(Set(_.single)), Set("single")) test("pos2") - check( "nested.single", @@ -222,7 +222,7 @@ object ResolveTests extends TestSuite { ) } test("doubleNested") { - val check = new Checker(doubleNestedModule) + val check = Checker(doubleNestedModule) test("pos1") - check("single", Result.Success(Set(_.single)), Set("single")) test("pos2") - check( "nested.single", diff --git a/core/resolve/test/src/mill/resolve/TypeSelectorTests.scala b/core/resolve/test/src/mill/resolve/TypeSelectorTests.scala index e1ee18cb75c5..272799570e42 100644 --- a/core/resolve/test/src/mill/resolve/TypeSelectorTests.scala +++ b/core/resolve/test/src/mill/resolve/TypeSelectorTests.scala @@ -80,7 +80,7 @@ object TypeSelectorTests extends TestSuite { val tests = Tests { test("typeSelector") { - val check = new Checker(TypedModules) + val check = Checker(TypedModules) test - check( "__", Result.Success(Set( @@ -183,7 +183,7 @@ object TypeSelectorTests extends TestSuite { ) } test("crossTypeSelector") { - val check = new Checker(TypedCrossModules) + val check = Checker(TypedCrossModules) test - check( "__", Result.Success(Set( @@ -258,7 +258,7 @@ object TypeSelectorTests extends TestSuite { )) ) test("innerTypeSelector") { - val check = new Checker(TypedInnerModules) + val check = Checker(TypedInnerModules) test - check( "__:TypeA._", Result.Success(Set( diff --git a/dist/scripts/test/src/MillVersionFrontmatterTests.scala b/dist/scripts/test/src/MillVersionFrontmatterTests.scala index 4d16046c8859..95d5f878c6d6 100644 --- a/dist/scripts/test/src/MillVersionFrontmatterTests.scala +++ b/dist/scripts/test/src/MillVersionFrontmatterTests.scala @@ -30,7 +30,7 @@ object MillVersionFrontmatterTests extends TestSuite { val output = res.out.text().trim if (res.exitCode != 0) { - throw new IllegalStateException(s"exitCode != 0 (actual = ${res.exitCode}") + throw IllegalStateException(s"exitCode != 0 (actual = ${res.exitCode}") } expectedVersion match { diff --git a/example/extending/plugins/2-plugin-integration-tests/myplugin/integration/src/mill/testkit/IntegrationTests.scala b/example/extending/plugins/2-plugin-integration-tests/myplugin/integration/src/mill/testkit/IntegrationTests.scala index beaff1bb5c42..973ef1c7e339 100644 --- a/example/extending/plugins/2-plugin-integration-tests/myplugin/integration/src/mill/testkit/IntegrationTests.scala +++ b/example/extending/plugins/2-plugin-integration-tests/myplugin/integration/src/mill/testkit/IntegrationTests.scala @@ -10,7 +10,7 @@ object IntegrationTests extends TestSuite { test("integration") { val resourceFolder = os.Path(sys.env("MILL_TEST_RESOURCE_DIR")) - val tester = new IntegrationTester( + val tester = IntegrationTester( daemonMode = true, workspaceSourcePath = resourceFolder / "integration-test-project", millExecutable = os.Path(sys.env("MILL_EXECUTABLE_PATH")) diff --git a/example/scalalib/dependencies/2-run-compile-deps/bar/src/Bar.scala b/example/scalalib/dependencies/2-run-compile-deps/bar/src/Bar.scala index e51a36f2867c..1f82a4f525d5 100644 --- a/example/scalalib/dependencies/2-run-compile-deps/bar/src/Bar.scala +++ b/example/scalalib/dependencies/2-run-compile-deps/bar/src/Bar.scala @@ -20,11 +20,11 @@ class BarServlet extends HttpServlet { object Bar { @throws[Exception] def main(args: Array[String]): Unit = { - val server = new Server(8079) + val server = Server(8079) val context = new ServletContextHandler context.setContextPath("/") server.setHandler(context) - context.addServlet(new ServletHolder(new BarServlet), "/*") + context.addServlet(ServletHolder(new BarServlet), "/*") server.start server.join } diff --git a/example/scalalib/dependencies/4-downloading-unmanaged-jars/src/Foo.scala b/example/scalalib/dependencies/4-downloading-unmanaged-jars/src/Foo.scala index f62a18da2a78..8c102532d336 100644 --- a/example/scalalib/dependencies/4-downloading-unmanaged-jars/src/Foo.scala +++ b/example/scalalib/dependencies/4-downloading-unmanaged-jars/src/Foo.scala @@ -5,7 +5,7 @@ object Foo { def main(args: Array[String]): Unit = { val filePath = args(0) - val fi = new InputReader(new java.io.FileInputStream(filePath)) + val fi = InputReader(new java.io.FileInputStream(filePath)) try { while ( fi.nextLine() match { diff --git a/example/scalalib/spark/3-semi-realistic/src/foo/Foo.scala b/example/scalalib/spark/3-semi-realistic/src/foo/Foo.scala index 69c35e87c23d..9b8d8f59e2ff 100644 --- a/example/scalalib/spark/3-semi-realistic/src/foo/Foo.scala +++ b/example/scalalib/spark/3-semi-realistic/src/foo/Foo.scala @@ -26,7 +26,7 @@ object Foo { // otherwise, use resources. val resourcePath: String = args.headOption .orElse(Option(getClass.getResource("/transactions.csv")).map(_.getPath)) - .getOrElse(throw new RuntimeException( + .getOrElse(throw RuntimeException( "transactions.csv not provided as argument and not found in resources" )) diff --git a/integration/bsp-util/src/BspServerTestUtil.scala b/integration/bsp-util/src/BspServerTestUtil.scala index 16e879d87aee..1d3424e15c37 100644 --- a/integration/bsp-util/src/BspServerTestUtil.scala +++ b/integration/bsp-util/src/BspServerTestUtil.scala @@ -48,7 +48,7 @@ object BspServerTestUtil { def onRunPrintStdout(params: b.PrintParams): Unit = () } - val gson: Gson = new GsonBuilder().setPrettyPrinting().create() + val gson: Gson = GsonBuilder().setPrettyPrinting().create() def compareWithGsonSnapshot[T: ClassTag]( value: T, snapshotPath: os.Path, @@ -100,7 +100,7 @@ object BspServerTestUtil { new ThreadFactory { val counter = new AtomicInteger def newThread(runnable: Runnable): Thread = { - val t = new Thread(runnable, s"mill-bsp-integration-${counter.incrementAndGet()}") + val t = Thread(runnable, s"mill-bsp-integration-${counter.incrementAndGet()}") t.setDaemon(true) t } diff --git a/integration/feature/publish-sonatype-central-snapshots/src/PublishSonatypeCentralSnapshotTests.scala b/integration/feature/publish-sonatype-central-snapshots/src/PublishSonatypeCentralSnapshotTests.scala index 44cfda34b3f1..f2abe220cd3b 100644 --- a/integration/feature/publish-sonatype-central-snapshots/src/PublishSonatypeCentralSnapshotTests.scala +++ b/integration/feature/publish-sonatype-central-snapshots/src/PublishSonatypeCentralSnapshotTests.scala @@ -95,7 +95,7 @@ object PublishSonatypeCentralSnapshotTests extends UtestIntegrationTestSuite { val timestampRegex = """(\d{8}\.\d{6})""".r val timestamp = timestampRegex.findFirstMatchIn(metadataContents).map(_.group(1)).getOrElse { - throw new Exception( + throw Exception( s"No timestamp found via $timestampRegex in $metadataFile:\n$metadataContents" ) } diff --git a/integration/ide/bsp-server/src/BspServerTests.scala b/integration/ide/bsp-server/src/BspServerTests.scala index 575c8f6bd872..f1aab8682ae9 100644 --- a/integration/ide/bsp-server/src/BspServerTests.scala +++ b/integration/ide/bsp-server/src/BspServerTests.scala @@ -286,11 +286,11 @@ object BspServerTests extends UtestIntegrationTestSuite { .getItems .asScala .map { item => - val shortId = os.Path(Paths.get(new URI(item.getTarget.getUri))) + val shortId = os.Path(Paths.get(URI(item.getTarget.getUri))) .relativeTo(workspacePath) .asSubPath val semDbs = findSemanticdbs( - os.Path(Paths.get(new URI(item.getClassDirectory))) + os.Path(Paths.get(URI(item.getClassDirectory))) ) shortId -> semDbs } @@ -324,11 +324,11 @@ object BspServerTests extends UtestIntegrationTestSuite { .getItems .asScala .map { item => - val shortId = os.Path(Paths.get(new URI(item.getTarget.getUri))) + val shortId = os.Path(Paths.get(URI(item.getTarget.getUri))) .relativeTo(workspacePath) .asSubPath val semDbs = findSemanticdbs( - os.Path(Paths.get(new URI(item.getClassDirectory))) + os.Path(Paths.get(URI(item.getClassDirectory))) ) shortId -> semDbs } @@ -474,7 +474,7 @@ object BspServerTests extends UtestIntegrationTestSuite { ) def uriAsSubPath(strUri: String): os.SubPath = - os.Path(Paths.get(new URI(strUri))).relativeTo(workspacePath).asSubPath + os.Path(Paths.get(URI(strUri))).relativeTo(workspacePath).asSubPath val normalizedLocalValues = normalizeLocalValuesForTesting(workspacePath) ++ scalaVersionNormalizedValues() diff --git a/integration/invalidation/multi-level-editing/src/MultiLevelBuildTests.scala b/integration/invalidation/multi-level-editing/src/MultiLevelBuildTests.scala index fcc18d2efd97..9af540efa22c 100644 --- a/integration/invalidation/multi-level-editing/src/MultiLevelBuildTests.scala +++ b/integration/invalidation/multi-level-editing/src/MultiLevelBuildTests.scala @@ -372,7 +372,7 @@ object MultiLevelBuildTestsRuntimeErrorEdits extends MultiLevelBuildTests { val runErrorSnippet = """{ |override def runClasspath = Task { - | throw new Exception("boom") + | throw Exception("boom") | super.runClasspath() |}""".stripMargin diff --git a/integration/invalidation/run-background/src/RunBackgroundTests.scala b/integration/invalidation/run-background/src/RunBackgroundTests.scala index 4b95463f8b2f..c7ab11a59ce8 100644 --- a/integration/invalidation/run-background/src/RunBackgroundTests.scala +++ b/integration/invalidation/run-background/src/RunBackgroundTests.scala @@ -14,7 +14,7 @@ object RunBackgroundTests extends UtestIntegrationTestSuite { implicit val retryInterval: RetryInterval = RetryInterval(50.millis) def probeLockAvailable(lock: os.Path): Boolean = { - val raf = new RandomAccessFile(lock.toIO, "rw"); + val raf = RandomAccessFile(lock.toIO, "rw"); val chan = raf.getChannel(); chan.tryLock() match { case null => false diff --git a/integration/invalidation/zinc-incremental-compilation/resources/app/src/main/scala/App.scala b/integration/invalidation/zinc-incremental-compilation/resources/app/src/main/scala/App.scala index b618fd09cf7e..3fb97890e1f6 100644 --- a/integration/invalidation/zinc-incremental-compilation/resources/app/src/main/scala/App.scala +++ b/integration/invalidation/zinc-incremental-compilation/resources/app/src/main/scala/App.scala @@ -4,7 +4,7 @@ import io.getquill._ object App { - val ctx = new SqlMirrorContext(PostgresDialect, SnakeCase) + val ctx = SqlMirrorContext(PostgresDialect, SnakeCase) import ctx._ case class Person(name: String, age: Int) diff --git a/libs/androidlib/databinding/impl/src/mill/androidlib/databinding/AndroidDataBindingImpl.scala b/libs/androidlib/databinding/impl/src/mill/androidlib/databinding/AndroidDataBindingImpl.scala index ab2830329767..7382fd0f77ea 100644 --- a/libs/androidlib/databinding/impl/src/mill/androidlib/databinding/AndroidDataBindingImpl.scala +++ b/libs/androidlib/databinding/impl/src/mill/androidlib/databinding/AndroidDataBindingImpl.scala @@ -37,10 +37,10 @@ class AndroidDataBindingImpl extends AndroidDataBindingWorker { val layoutInfoInputArgs = new LayoutInfoInput.Args( /* outOfDate */ Collections.emptyList(), /* removed */ Collections.emptyList(), - /* infoFolder */ new File(args.layoutInfoDir), - /* dependencyClassesFolders */ args.dependencyClassInfoDirs.map(new File(_)).toList.asJava, - /* artifactFolder */ new File(args.classInfoDir), - /* logFolder */ new File(args.logFolder), + /* infoFolder */ File(args.layoutInfoDir), + /* dependencyClassesFolders */ args.dependencyClassInfoDirs.map(File(_)).toList.asJava, + /* artifactFolder */ File(args.classInfoDir), + /* logFolder */ File(args.logFolder), /* packageName */ args.applicationPackageName, /* incremental */ false, /* v1ArtifactsFolder */ null, @@ -50,12 +50,12 @@ class AndroidDataBindingImpl extends AndroidDataBindingWorker { ) os.makeDir.all(os.Path(args.outputDir)) - val fileWriter = new DataBindingBuilder().createJavaFileWriter(os.Path(args.outputDir).toIO) + val fileWriter = DataBindingBuilder().createJavaFileWriter(os.Path(args.outputDir).toIO) val getRPackage: kotlin.jvm.functions.Function2[String, String, String] = null - new BaseDataBinder( - new LayoutInfoInput(layoutInfoInputArgs), + BaseDataBinder( + LayoutInfoInput(layoutInfoInputArgs), getRPackage ).generateAll(fileWriter) diff --git a/libs/androidlib/hilt/src/mill/androidlib/hilt/AndroidHiltTransformAsm.scala b/libs/androidlib/hilt/src/mill/androidlib/hilt/AndroidHiltTransformAsm.scala index 6ffb87f853af..57d76adc85df 100644 --- a/libs/androidlib/hilt/src/mill/androidlib/hilt/AndroidHiltTransformAsm.scala +++ b/libs/androidlib/hilt/src/mill/androidlib/hilt/AndroidHiltTransformAsm.scala @@ -52,7 +52,7 @@ object AndroidHiltTransformAsm { private def transform(`class`: os.Path, destination: os.Path): os.Path = { val originalClassBytes = os.read.bytes(`class`) - val crCheck = new ClassReader(originalClassBytes) + val crCheck = ClassReader(originalClassBytes) val dummyClassContext = new ClassContext { override def getCurrentClassData: ClassData = null @@ -60,15 +60,15 @@ object AndroidHiltTransformAsm { override def loadClassData(s: String): ClassData = null } - val scanner = new AnnotationScannerClassVisitor(Opcodes.ASM9) + val scanner = AnnotationScannerClassVisitor(Opcodes.ASM9) crCheck.accept(scanner, /* flags = */ 0) def isInstrumentable = scanner.isAndroidEntryPoint - val cr = new ClassReader(originalClassBytes) + val cr = ClassReader(originalClassBytes) if (isInstrumentable) { - val cw = new ClassWriter(cr, /* flags = */ 0) + val cw = ClassWriter(cr, /* flags = */ 0) val visitor = AndroidEntryPointClassVisitor( Opcodes.ASM9, diff --git a/libs/androidlib/keytool/src/mill/androidlib/keytool/CertUtil.scala b/libs/androidlib/keytool/src/mill/androidlib/keytool/CertUtil.scala index e2f57dc9b016..de6fa71f9b59 100644 --- a/libs/androidlib/keytool/src/mill/androidlib/keytool/CertUtil.scala +++ b/libs/androidlib/keytool/src/mill/androidlib/keytool/CertUtil.scala @@ -18,24 +18,24 @@ object CertUtil: keyPair: KeyPair, validity: FiniteDuration = FiniteDuration(10000, DAYS) ): X509Certificate = { - val now = new Date() - val notAfter = new Date(now.getTime + validity.toMillis) + val now = Date() + val notAfter = Date(now.getTime + validity.toMillis) val builder: X509v3CertificateBuilder = - new JcaX509v3CertificateBuilder( - new X500Principal(dname), // issuer + JcaX509v3CertificateBuilder( + X500Principal(dname), // issuer BigInteger.valueOf(System.currentTimeMillis()), // serial number now, // start date notAfter, // end date - new X500Principal(dname), // subject + X500Principal(dname), // subject keyPair.getPublic // public key ) - val signer = new JcaContentSignerBuilder("SHA256withRSA") - .setProvider(new BouncyCastleProvider()) + val signer = JcaContentSignerBuilder("SHA256withRSA") + .setProvider(BouncyCastleProvider()) .build(keyPair.getPrivate) - new JcaX509CertificateConverter() - .setProvider(new BouncyCastleProvider()) + JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider()) .getCertificate(builder.build(signer)) } diff --git a/libs/androidlib/keytool/src/mill/androidlib/keytool/Keystore.scala b/libs/androidlib/keytool/src/mill/androidlib/keytool/Keystore.scala index 6adf7df99a28..66b1597790d4 100644 --- a/libs/androidlib/keytool/src/mill/androidlib/keytool/Keystore.scala +++ b/libs/androidlib/keytool/src/mill/androidlib/keytool/Keystore.scala @@ -13,16 +13,16 @@ object Keystore: ks def saveKeystore(ks: KeyStore, filePath: String, password: String): Unit = - saveKeystore(ks, new File(os.Path(filePath, os.pwd).toString), password.toCharArray) + saveKeystore(ks, File(os.Path(filePath, os.pwd).toString), password.toCharArray) def saveKeystore(ks: KeyStore, filePath: os.Path, password: String): Unit = - saveKeystore(ks, new File(filePath.toString), password.toCharArray) + saveKeystore(ks, File(filePath.toString), password.toCharArray) private def saveKeystore(ks: KeyStore, file: File, password: Array[Char]): Unit = // Ensure the parent directory exists if (!file.getParentFile.exists()) - throw new IllegalArgumentException(s"Parent directory does not exist: ${file.getParentFile}") - val fos = new FileOutputStream(file) + throw IllegalArgumentException(s"Parent directory does not exist: ${file.getParentFile}") + val fos = FileOutputStream(file) try ks.store(fos, password) finally fos.close() @@ -35,11 +35,11 @@ object Keystore: saveKeystore(ks, filePath, password) def loadKeystore(filePath: String, password: String, ksType: String = "PKCS12"): KeyStore = - loadKeystore(new File(filePath), password.toCharArray, ksType) + loadKeystore(File(filePath), password.toCharArray, ksType) private def loadKeystore(file: File, password: Array[Char], ksType: String): KeyStore = val ks = KeyStore.getInstance(ksType) - val fis = new FileInputStream(file) + val fis = FileInputStream(file) try ks.load(fis, password) finally fis.close() ks diff --git a/libs/androidlib/keytool/src/mill/androidlib/keytool/Keytool.scala b/libs/androidlib/keytool/src/mill/androidlib/keytool/Keytool.scala index 9660a8d07f17..2e70a10f09fa 100644 --- a/libs/androidlib/keytool/src/mill/androidlib/keytool/Keytool.scala +++ b/libs/androidlib/keytool/src/mill/androidlib/keytool/Keytool.scala @@ -9,14 +9,14 @@ object Keytool { def shortName: String = "validity" def read(tokens: Seq[String]): Either[String, FiniteDuration] = { if (tokens.isEmpty) - throw new IllegalArgumentException("Duration cannot be empty") + throw IllegalArgumentException("Duration cannot be empty") val durationString = tokens.mkString(" ") val duration = Duration(durationString) if (duration < Duration.Zero) - throw new IllegalArgumentException(s"Duration cannot be negative: $durationString") + throw IllegalArgumentException(s"Duration cannot be negative: $durationString") duration match { case d: FiniteDuration => Right(d) - case _ => throw new IllegalArgumentException(s"Duration must be finite: $durationString") + case _ => throw IllegalArgumentException(s"Duration must be finite: $durationString") } } } diff --git a/libs/androidlib/keytool/src/mill/androidlib/keytool/RSAKeyGen.scala b/libs/androidlib/keytool/src/mill/androidlib/keytool/RSAKeyGen.scala index 71e5891c08b3..677674440a34 100644 --- a/libs/androidlib/keytool/src/mill/androidlib/keytool/RSAKeyGen.scala +++ b/libs/androidlib/keytool/src/mill/androidlib/keytool/RSAKeyGen.scala @@ -7,7 +7,7 @@ import java.security.{KeyPair, KeyPairGenerator} object RSAKeyGen { def generateKeyPair(keySize: Int = 2048): KeyPair = { - val generator = KeyPairGenerator.getInstance("RSA", new BouncyCastleProvider()) + val generator = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider()) generator.initialize(keySize) generator.generateKeyPair() } diff --git a/libs/androidlib/keytool/test/src/KeytoolTest.scala b/libs/androidlib/keytool/test/src/KeytoolTest.scala index 70ed8923479f..54695eb62cfd 100644 --- a/libs/androidlib/keytool/test/src/KeytoolTest.scala +++ b/libs/androidlib/keytool/test/src/KeytoolTest.scala @@ -94,10 +94,10 @@ def getKeytoolOutput(args: String*): String = { def removeFile(filename: String): Unit = { import java.io.File - val file = new File(filename) + val file = File(filename) if (file.exists()) { if (!file.delete()) { - throw new RuntimeException(s"Failed to delete file: $filename") + throw RuntimeException(s"Failed to delete file: $filename") } } } diff --git a/libs/androidlib/src/mill/androidlib/AndroidAppModule.scala b/libs/androidlib/src/mill/androidlib/AndroidAppModule.scala index 5bab22d92083..30610adba9e9 100644 --- a/libs/androidlib/src/mill/androidlib/AndroidAppModule.scala +++ b/libs/androidlib/src/mill/androidlib/AndroidAppModule.scala @@ -554,7 +554,7 @@ trait AndroidAppModule extends AndroidModule { outer => Task.log.error( s"Error trying to install android emulator system image ${installCall.err.text()}" ) - throw new Exception(s"Failed to install system image $image: ${installCall.exitCode}") + throw Exception(s"Failed to install system image $image: ${installCall.exitCode}") } image } @@ -577,7 +577,7 @@ trait AndroidAppModule extends AndroidModule { outer => )) if (command.exitCode != 0) { Task.log.error(s"Failed to create android virtual device: ${command.err.text()}") - throw new Exception(s"Failed to create android virtual device: ${command.exitCode}") + throw Exception(s"Failed to create android virtual device: ${command.exitCode}") } s"DeviceName: $androidVirtualDeviceIdentifier, DeviceId: $androidDeviceId" } @@ -646,7 +646,7 @@ trait AndroidAppModule extends AndroidModule { outer => }).findFirst().toScala if (bootMessage.isEmpty) { - throw new Exception(s"Emulator failed to start: ${startEmuCmd.exitCode()}") + throw Exception(s"Emulator failed to start: ${startEmuCmd.exitCode()}") } val emulator: String = waitForDevice(androidSdkModule().adbExe(), runningEmulator(), Task.log) @@ -840,7 +840,7 @@ trait AndroidAppModule extends AndroidModule { outer => if (bootflag == BootedIndicator) emulator else - throw new Exception("Device failed to boot") + throw Exception("Device failed to boot") } /** diff --git a/libs/androidlib/src/mill/androidlib/AndroidKotlinModule.scala b/libs/androidlib/src/mill/androidlib/AndroidKotlinModule.scala index c71449a631c6..a7501c0b60c1 100644 --- a/libs/androidlib/src/mill/androidlib/AndroidKotlinModule.scala +++ b/libs/androidlib/src/mill/androidlib/AndroidKotlinModule.scala @@ -40,7 +40,7 @@ trait AndroidKotlinModule extends KotlinModule with AndroidModule { outer => def androidDataBindingCompilerVersion: T[String] = Task { isBindingEnabled match { - case true => throw new Exception( + case true => throw Exception( "androidDataBindingCompilerVersion must be set (e.g. \"8.13.0\") when view or data binding is enabled." ) case false => "" diff --git a/libs/androidlib/src/mill/androidlib/AndroidLibModule.scala b/libs/androidlib/src/mill/androidlib/AndroidLibModule.scala index 001ce2025f44..58f5024eb1b4 100644 --- a/libs/androidlib/src/mill/androidlib/AndroidLibModule.scala +++ b/libs/androidlib/src/mill/androidlib/AndroidLibModule.scala @@ -66,7 +66,7 @@ trait AndroidLibModule extends AndroidModule with PublishModule { } case (otherPackagingType, otherModuleType) => - throw new IllegalArgumentException( + throw IllegalArgumentException( s"Packaging type $otherPackagingType not supported with $otherModuleType" ) } @@ -103,7 +103,7 @@ trait AndroidLibModule extends AndroidModule with PublishModule { ).call() if (compileResult.exitCode != 0) { - throw new RuntimeException( + throw RuntimeException( s"aapt2 failed to compile resources with error code ${compileResult.exitCode}" ) } @@ -121,7 +121,7 @@ trait AndroidLibModule extends AndroidModule with PublishModule { ).call(cwd = compiledRes) if (linkResult.exitCode != 0) { - throw new RuntimeException( + throw RuntimeException( s"aapt2 failed to link resources with error code ${linkResult.exitCode}" ) } diff --git a/libs/androidlib/src/mill/androidlib/AndroidSdkModule.scala b/libs/androidlib/src/mill/androidlib/AndroidSdkModule.scala index 9b0cb7834dc9..24e437a223db 100644 --- a/libs/androidlib/src/mill/androidlib/AndroidSdkModule.scala +++ b/libs/androidlib/src/mill/androidlib/AndroidSdkModule.scala @@ -295,7 +295,7 @@ trait AndroidSdkModule extends Module { case "17.0" => "12700392" case "19.0" => "13114758" case _ => - throw new IllegalArgumentException(s"Unsupported cmdline tools version: $versionShort") + throw IllegalArgumentException(s"Unsupported cmdline tools version: $versionShort") } } @@ -304,7 +304,7 @@ trait AndroidSdkModule extends Module { if (isWin) "win" else if (isMac) "mac" else if (isLinux) "linux" - else throw new IllegalStateException("Unknown platform") + else throw IllegalStateException("Unknown platform") s"https://dl.google.com/android/repository/commandlinetools-$platform-${versionLong}_latest.zip" } @@ -348,7 +348,7 @@ trait AndroidSdkModule extends Module { if (autoAcceptLicenses) { acceptLicenses(millSdkManagerExe) } else { - throw new IllegalStateException( + throw IllegalStateException( s"License for cmdline-tools;$versionShort is not accepted. " + s"Please run `${millSdkManagerExe.toString} --licenses` to review and accept the licenses" + ", or override `autoAcceptLicenses` to `true`." @@ -391,7 +391,7 @@ trait AndroidSdkModule extends Module { autoAcceptLicenses() ) } else if (!os.exists(sdkmanagerPath)) { - throw new IllegalStateException( + throw IllegalStateException( s"$basePath exists but is not setup correctly. " + "Please remove it and retry or fix the installation manually (e.g. via Android Studio)." ) @@ -527,7 +527,7 @@ trait AndroidSdkModule extends Module { Task.env.get("ANDROID_HOME") .orElse(Task.env.get("ANDROID_SDK_ROOT")) match { case Some(x) => os.Path(x) - case _ => throw new IllegalStateException("Android SDK location not found. Define a valid" + + case _ => throw IllegalStateException("Android SDK location not found. Define a valid" + " SDK location with an ANDROID_HOME environment variable.") } } @@ -583,7 +583,7 @@ trait AndroidSdkModule extends Module { private def sha1 = MessageDigest.getInstance("sha1") private def hexArray(arr: Array[Byte]) = - String.format("%0" + (arr.length << 1) + "x", new BigInteger(1, arr)) + String.format("%0" + (arr.length << 1) + "x", BigInteger(1, arr)) } diff --git a/libs/androidlib/test/src/mill/androidlib/InstrumentalOutputReportTest.scala b/libs/androidlib/test/src/mill/androidlib/InstrumentalOutputReportTest.scala index db73b21580c7..750f0b239a18 100644 --- a/libs/androidlib/test/src/mill/androidlib/InstrumentalOutputReportTest.scala +++ b/libs/androidlib/test/src/mill/androidlib/InstrumentalOutputReportTest.scala @@ -62,7 +62,7 @@ object InstrumentalOutputReportTest extends TestSuite { |INSTRUMENTATION_CODE: -1 """.stripMargin - val reader = new BufferedReader(new StringReader(testOutput)) + val reader = BufferedReader(StringReader(testOutput)) val (_, testResults) = parseTestOutputStream(reader)(DummyLogger) diff --git a/libs/daemon/server/src/mill/server/Server.scala b/libs/daemon/server/src/mill/server/Server.scala index c632e85633dd..323d376b8e0d 100644 --- a/libs/daemon/server/src/mill/server/Server.scala +++ b/libs/daemon/server/src/mill/server/Server.scala @@ -105,8 +105,8 @@ abstract class Server[Prepared, Handled](args: Server.Args) { socketPortFile: os.Path ): Option[Handled] = { serverLog("server file locked") - val serverSocket = new ServerSocket(0, 0, InetAddress.getByName(null)) - val exitCodeVar = new AtomicReference[Option[Handled]](None) + val serverSocket = ServerSocket(0, 0, InetAddress.getByName(null)) + val exitCodeVar = AtomicReference[Option[Handled]](None) def closeServer(exitCodeOpt: Option[Handled]) = { // Don't System.exit immediately, but instead store the exit code for later and close the // `serverSocket` so the methods return normally with a single exit point @@ -363,7 +363,7 @@ object Server { /// can detect when the Mill client goes away, which is necessary to handle /// the case when a Mill client that did *not* spawn the server gets `CTRL-C`ed def overrideSigIntHandling(handler: SignalHandler = _ => ()): Unit = { - Signal.handle(new Signal("INT"), handler) + Signal.handle(Signal("INT"), handler) } def computeProcessId(): Long = ProcessHandle.current().pid() diff --git a/libs/graphviz/src/mill/graphviz/GraphvizTools.scala b/libs/graphviz/src/mill/graphviz/GraphvizTools.scala index 832c39a3388d..74b41512b3e1 100644 --- a/libs/graphviz/src/mill/graphviz/GraphvizTools.scala +++ b/libs/graphviz/src/mill/graphviz/GraphvizTools.scala @@ -22,7 +22,7 @@ object GraphvizTools { new AbstractJsGraphvizEngine( true, () => { - threadLocalJsEngines.putIfAbsent(Thread.currentThread(), new V8JavascriptEngine()) + threadLocalJsEngines.putIfAbsent(Thread.currentThread(), V8JavascriptEngine()) threadLocalJsEngines.get(Thread.currentThread()) } ) {} @@ -54,7 +54,7 @@ class V8JavascriptEngine() extends AbstractJavascriptEngine { LOG.info("Starting V8 runtime...") LOG.info("Started V8 runtime. Initializing javascript...") val resultHandler = new ResultHandler - val javetStandardConsoleInterceptor = new JavetStandardConsoleInterceptor(v8Runtime) + val javetStandardConsoleInterceptor = JavetStandardConsoleInterceptor(v8Runtime) javetStandardConsoleInterceptor.register(v8Runtime.getGlobalObject) class ResultHandlerInterceptor(resultHandler: ResultHandler) { @@ -69,7 +69,7 @@ class V8JavascriptEngine() extends AbstractJavascriptEngine { } val v8ValueObject = v8Runtime.createV8ValueObject v8Runtime.getGlobalObject.set("resultHandlerInterceptor", v8ValueObject) - v8ValueObject.bind(new ResultHandlerInterceptor(resultHandler)) + v8ValueObject.bind(ResultHandlerInterceptor(resultHandler)) v8Runtime.getExecutor( "var result = resultHandlerInterceptor.result; " + diff --git a/libs/init/gradle/src/mill/main/gradle/GradleBuildGenMain.scala b/libs/init/gradle/src/mill/main/gradle/GradleBuildGenMain.scala index ddd08e3aa530..e900942eb7c1 100644 --- a/libs/init/gradle/src/mill/main/gradle/GradleBuildGenMain.scala +++ b/libs/init/gradle/src/mill/main/gradle/GradleBuildGenMain.scala @@ -31,7 +31,7 @@ object GradleBuildGenMain { println("converting Gradle build") val gradleWrapperProperties = { - val properties = new Properties() + val properties = Properties() val file = os.pwd / "gradle/wrapper/gradle-wrapper.properties" if (os.isFile(file)) Using.resource(os.read.inputStream(file))(properties.load) properties diff --git a/libs/init/maven/src/mill/main/maven/Modeler.scala b/libs/init/maven/src/mill/main/maven/Modeler.scala index fc275a6f8635..d4eb9ef0898e 100644 --- a/libs/init/maven/src/mill/main/maven/Modeler.scala +++ b/libs/init/maven/src/mill/main/maven/Modeler.scala @@ -33,7 +33,7 @@ class Modeler( /** Returns the [[ModelBuildingResult]] for `pomFile`. */ def build(pomFile: File): ModelBuildingResult = { - val request = new DefaultModelBuildingRequest() + val request = DefaultModelBuildingRequest() request.setPomFile(pomFile) request.setModelResolver(resolver.newCopy()) request.setSystemProperties(systemProperties) @@ -55,11 +55,11 @@ object Modeler { context: String = "", systemProperties: Properties = defaultSystemProperties ): Modeler = { - val builder = new DefaultModelBuilderFactory().newInstance() - val system = new RepositorySystemSupplier().get() + val builder = DefaultModelBuilderFactory().newInstance() + val system = RepositorySystemSupplier().get() val session = MavenRepositorySystemUtils.newSession() session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, local)) - val resolver = new Resolver(system, session, remotes, context) + val resolver = Resolver(system, session, remotes, context) new Modeler(builder, resolver, systemProperties) } @@ -73,7 +73,7 @@ object Modeler { ) def defaultSystemProperties: Properties = { - val props = new Properties(System.getProperties) + val props = Properties(System.getProperties) System.getenv().forEach((k, v) => props.put(s"env.$k", v)) props } diff --git a/libs/init/maven/src/mill/main/maven/Resolver.scala b/libs/init/maven/src/mill/main/maven/Resolver.scala index 8ddf5e6e0def..00aa26ec12cc 100644 --- a/libs/init/maven/src/mill/main/maven/Resolver.scala +++ b/libs/init/maven/src/mill/main/maven/Resolver.scala @@ -25,14 +25,14 @@ class Resolver( private var repositories = remotes override def resolveModel(groupId: String, artifactId: String, version: String): ModelSource = { - val artifact = new DefaultArtifact(groupId, artifactId, "", "pom", version) - val request = new ArtifactRequest(artifact, repositories.asJava, context) + val artifact = DefaultArtifact(groupId, artifactId, "", "pom", version) + val request = ArtifactRequest(artifact, repositories.asJava, context) try { val result = system.resolveArtifact(session, request) - new FileModelSource(result.getArtifact.getFile) + FileModelSource(result.getArtifact.getFile) } catch { case e: ArtifactResolutionException => - throw new UnresolvableModelException(e.getMessage, groupId, artifactId, version, e) + throw UnresolvableModelException(e.getMessage, groupId, artifactId, version, e) } } @@ -54,5 +54,5 @@ class Resolver( } override def newCopy(): ModelResolver = - new Resolver(system, session, repositories, context) + Resolver(system, session, repositories, context) } diff --git a/libs/init/src/mill/init/InitModule.scala b/libs/init/src/mill/init/InitModule.scala index 51d777f37b7c..fe241dababbb 100644 --- a/libs/init/src/mill/init/InitModule.scala +++ b/libs/init/src/mill/init/InitModule.scala @@ -70,7 +70,7 @@ trait InitModule extends Module { } yield rel if (conflicting.nonEmpty) { - throw new Exception( + throw Exception( "Unable to unpack example because it conflicts with existing file: " + conflicting.mkString(", ") ) diff --git a/libs/init/test/src/mill/init/InitModuleTests.scala b/libs/init/test/src/mill/init/InitModuleTests.scala index 68cf9100f98c..5df23594e5af 100644 --- a/libs/init/test/src/mill/init/InitModuleTests.scala +++ b/libs/init/test/src/mill/init/InitModuleTests.scala @@ -20,12 +20,12 @@ object InitModuleTests extends TestSuite { override def tests: Tests = Tests { test("no args") { - val outStream = new ByteArrayOutputStream() + val outStream = ByteArrayOutputStream() UnitTester( initmodule, null, - outStream = new PrintStream(outStream, true), - errStream = new PrintStream(OutputStream.nullOutputStream(), true) + outStream = PrintStream(outStream, true), + errStream = PrintStream(OutputStream.nullOutputStream(), true) ).scoped { evaluator => val results = evaluator.evaluator.execute(Seq(initmodule.init(None))).executionResults @@ -43,13 +43,13 @@ object InitModuleTests extends TestSuite { } } test("non existing example") { - val outStream = new ByteArrayOutputStream() - val errStream = new ByteArrayOutputStream() + val outStream = ByteArrayOutputStream() + val errStream = ByteArrayOutputStream() UnitTester( initmodule, null, - outStream = new PrintStream(outStream, true), - errStream = new PrintStream(errStream, true) + outStream = PrintStream(outStream, true), + errStream = PrintStream(errStream, true) ).scoped { evaluator => val nonExistingModuleId = "nonExistingExampleId" @@ -86,8 +86,8 @@ object InitModuleTests extends TestSuite { UnitTester( initmodule, null, - outStream = new PrintStream(outStream, true), - errStream = new PrintStream(OutputStream.nullOutputStream(), true) + outStream = PrintStream(outStream, true), + errStream = PrintStream(OutputStream.nullOutputStream(), true) ).scoped { evaluator => val results = evaluator.evaluator.execute( diff --git a/libs/javalib/api/src/mill/javalib/api/JvmWorkerUtil.scala b/libs/javalib/api/src/mill/javalib/api/JvmWorkerUtil.scala index 4df9c43413c7..e0ec519d6395 100644 --- a/libs/javalib/api/src/mill/javalib/api/JvmWorkerUtil.scala +++ b/libs/javalib/api/src/mill/javalib/api/JvmWorkerUtil.scala @@ -37,7 +37,7 @@ object JvmWorkerUtil { classPath.iterator .find(pathRef => mavenStyleMatch(pathRef.path.last) || ivyStyleMatch(pathRef.path)) - .getOrElse(throw new Exception( + .getOrElse(throw Exception( s"Cannot find **/$name-$versionPrefix*$suffix or **/$versionPrefix*/$dir/$name$suffix in ${classPath.iterator.mkString("[", ", ", "]")}" )) } @@ -71,7 +71,7 @@ object JvmWorkerUtil { def scalaJSBinaryVersion(scalaJSVersion: String): String = scalaJSVersion match { case _ if scalaJSVersion.startsWith("0.6.") => - throw new Exception("Scala.js 0.6 is not supported") + throw Exception("Scala.js 0.6 is not supported") case ScalaJSFullVersion(major, minor, patch, suffix) => if (suffix != null && minor == "0" && patch == "0") s"$major.$minor$suffix" @@ -81,7 +81,7 @@ object JvmWorkerUtil { def scalaJSWorkerVersion(scalaJSVersion: String): String = scalaJSVersion match { case _ if scalaJSVersion.startsWith("0.6.") => - throw new Exception("Scala.js 0.6 is not supported") + throw Exception("Scala.js 0.6 is not supported") case ScalaJSFullVersion(major, _, _, _) => major } diff --git a/libs/javalib/api/src/mill/javalib/api/internal/ZincCompilerBridgeProvider.scala b/libs/javalib/api/src/mill/javalib/api/internal/ZincCompilerBridgeProvider.scala index 2441d769a66f..8abe5582692b 100644 --- a/libs/javalib/api/src/mill/javalib/api/internal/ZincCompilerBridgeProvider.scala +++ b/libs/javalib/api/src/mill/javalib/api/internal/ZincCompilerBridgeProvider.scala @@ -69,7 +69,7 @@ object ZincCompilerBridgeProvider { ): Unit = { if (scalaVersion == "2.12.0") { // The Scala 2.10.0 compiler fails on compiling the compiler bridge - throw new IllegalArgumentException( + throw IllegalArgumentException( "The current version of Zinc is incompatible with Scala 2.12.0.\n" + "Use Scala 2.12.1 or greater (2.12.12 is recommended)." ) @@ -106,7 +106,7 @@ object ZincCompilerBridgeProvider { val javacExe: String = sys.props .get("java.home") - .map(h => new File(h, if (isWin) "bin\\javac.exe" else "bin/javac")) + .map(h => File(h, if (isWin) "bin\\javac.exe" else "bin/javac")) .filter(f => f.exists()) .fold("javac")(_.getAbsolutePath()) @@ -120,7 +120,7 @@ object ZincCompilerBridgeProvider { .getMethod("process", classOf[Array[String]]) .invoke(null, argsArray ++ Array("-nowarn")) } else { - throw new IllegalArgumentException("Currently not implemented case.") + throw IllegalArgumentException("Currently not implemented case.") } } finally classloader.close() } diff --git a/libs/javalib/classgraph-worker/src/mill/javalib/classgraph/impl/ClassgraphWorkerImpl.scala b/libs/javalib/classgraph-worker/src/mill/javalib/classgraph/impl/ClassgraphWorkerImpl.scala index f47a38592858..f6f1e5b15c5a 100644 --- a/libs/javalib/classgraph-worker/src/mill/javalib/classgraph/impl/ClassgraphWorkerImpl.scala +++ b/libs/javalib/classgraph-worker/src/mill/javalib/classgraph/impl/ClassgraphWorkerImpl.scala @@ -17,7 +17,7 @@ class ClassgraphWorkerImpl() extends ClassgraphWorker { ctx.log.debug(s"Scanning for mainclasses: ${cp}") val mainClasses = Using.resource( - new ClassGraph() + ClassGraph() .overrideClasspath(cp) .enableMethodInfo() .scan() diff --git a/libs/javalib/scalameta-worker/src/SemanticdbProcessor.scala b/libs/javalib/scalameta-worker/src/SemanticdbProcessor.scala index a29a443748f1..e7123eb93909 100644 --- a/libs/javalib/scalameta-worker/src/SemanticdbProcessor.scala +++ b/libs/javalib/scalameta-worker/src/SemanticdbProcessor.scala @@ -111,7 +111,7 @@ object SemanticdbProcessor { private def md5(content: String): String = { val md = MessageDigest.getInstance("MD5") val digest = md.digest(content.getBytes(StandardCharsets.UTF_8)) - val res = new BigInteger(1, digest).toString(16) + val res = BigInteger(1, digest).toString(16) if (res.length < 32) ("0" * (32 - res.length)) + res else diff --git a/libs/javalib/spotless-worker/src/mill/javalib/spotless/converters.scala b/libs/javalib/spotless-worker/src/mill/javalib/spotless/converters.scala index 753998daf3de..1bf5a0dda302 100644 --- a/libs/javalib/spotless-worker/src/mill/javalib/spotless/converters.scala +++ b/libs/javalib/spotless-worker/src/mill/javalib/spotless/converters.scala @@ -73,7 +73,7 @@ class ToFormatterStep(charset: Charset, provisioner: Provisioner) .build() case step: NativeCmd => import step.* - NativeCmdStep.create(name, new File(pathToExe), arguments.asJava) + NativeCmdStep.create(name, File(pathToExe), arguments.asJava) case step: ReplaceRegex => import step.* ReplaceRegexStep.create(name, regex, replacement) diff --git a/libs/javalib/spring-boot-worker/src/mill/javalib/spring/boot/worker/impl/SpringBootToolsImpl.scala b/libs/javalib/spring-boot-worker/src/mill/javalib/spring/boot/worker/impl/SpringBootToolsImpl.scala index c27a6ff3ce16..b435cd3c1363 100644 --- a/libs/javalib/spring-boot-worker/src/mill/javalib/spring/boot/worker/impl/SpringBootToolsImpl.scala +++ b/libs/javalib/spring-boot-worker/src/mill/javalib/spring/boot/worker/impl/SpringBootToolsImpl.scala @@ -42,12 +42,12 @@ class SpringBootToolsImpl() extends SpringBootTools { libs: Seq[Path], launchScript: Option[String] )(using ctx: TaskCtx): Unit = { - val repack = new Repackager(base.toIO) + val repack = Repackager(base.toIO) repack.setMainClass(mainClass) val libraries: Libraries = { libCallback => libs.foreach { lib => - libCallback.library(new Library(lib.toIO, LibraryScope.RUNTIME)) + libCallback.library(Library(lib.toIO, LibraryScope.RUNTIME)) } } diff --git a/libs/javalib/src/mill/javalib/Assembly.scala b/libs/javalib/src/mill/javalib/Assembly.scala index f5f1fa1e1022..ec16249d0be2 100644 --- a/libs/javalib/src/mill/javalib/Assembly.scala +++ b/libs/javalib/src/mill/javalib/Assembly.scala @@ -50,7 +50,7 @@ object Assembly { override def productElement(n: Int): Any = n match { case 0 => pattern case 1 => separator - case _ => throw new IndexOutOfBoundsException(n.toString) + case _ => throw IndexOutOfBoundsException(n.toString) } override def canEqual(that: Any): Boolean = that.isInstanceOf[AppendPattern] override def hashCode(): Int = scala.runtime.ScalaRunTime._hashCode(this) @@ -118,7 +118,7 @@ object Assembly { ): (Generator[(String, UnopenedInputStream)], ResourceCloser) = { val pathsWithResources = inputPaths.filter(os.exists).map { path => - if (os.isFile(path)) path -> Some(new JarFile(path.toIO)) + if (os.isFile(path)) path -> Some(JarFile(path.toIO)) else path -> None } @@ -205,10 +205,10 @@ object Assembly { case entry: AppendEntry => val separated = entry.inputStreams .flatMap(inputStream => - Seq(new ByteArrayInputStream(entry.separator.getBytes), inputStream()) + Seq(ByteArrayInputStream(entry.separator.getBytes), inputStream()) ) val cleaned = if (os.exists(path)) separated else separated.drop(1) - Using.resource(new SequenceInputStream(Collections.enumeration(cleaned.asJava))) { + Using.resource(SequenceInputStream(Collections.enumeration(cleaned.asJava))) { concatenated => addedEntryCount += 1 writeEntry(path, concatenated, append = true) diff --git a/libs/javalib/src/mill/javalib/Dep.scala b/libs/javalib/src/mill/javalib/Dep.scala index d6ddc6b05925..6ebd6d6ddd09 100644 --- a/libs/javalib/src/mill/javalib/Dep.scala +++ b/libs/javalib/src/mill/javalib/Dep.scala @@ -116,8 +116,8 @@ object Dep { case Array("classifier", v) => as.withClassifier(coursier.Classifier(v)) case Array("type", v) => as.withType(coursier.Type(v)) case Array("exclude", s"${org}:${name}") => exclusions ++= Seq((org, name)); as - case Array(_, _) => throw new Exception(s"Unrecognized attribute: [$s]") - case _ => throw new Exception(s"Unable to parse attribute specifier: [$s]") + case Array(_, _) => throw Exception(s"Unrecognized attribute: [$s]") + case _ => throw Exception(s"Unable to parse attribute specifier: [$s]") } } @@ -130,7 +130,7 @@ object Dep { case Array(a, "", b, "", c) => Dep(a, b, c, cross = Binary(platformed = true)) case Array(a, "", "", b, c) => Dep(a, b, c, cross = Full(platformed = false)) case Array(a, "", "", b, "", c) => Dep(a, b, c, cross = Full(platformed = true)) - case _ => throw new Exception(s"Unable to parse signature: [$signature]") + case _ => throw Exception(s"Unable to parse signature: [$signature]") }) .exclude(exclusions.sorted*) .configure(attributes = attributes) diff --git a/libs/javalib/src/mill/javalib/JavaModule.scala b/libs/javalib/src/mill/javalib/JavaModule.scala index db6d50f21576..2b07e86a5e99 100644 --- a/libs/javalib/src/mill/javalib/JavaModule.scala +++ b/libs/javalib/src/mill/javalib/JavaModule.scala @@ -184,7 +184,7 @@ trait JavaModule case Right(bomDep) => bomDep } else - throw new Exception( + throw Exception( "Found Bill of Material (BOM) dependencies with invalid parameters:" + System.lineSeparator() + malformed.map("- " + _.dep + System.lineSeparator()).mkString + "Only organization, name, and version are accepted." @@ -251,7 +251,7 @@ trait JavaModule if (errors.isEmpty) keyValuesOrErrors.collect { case Right(kv) => kv } else - throw new Exception( + throw Exception( "Found dependency management entries with invalid values. Only organization, name, version, type, classifier, exclusions, and optionality can be specified" + System.lineSeparator() + errors.map("- " + _ + System.lineSeparator()).mkString ) @@ -1643,7 +1643,7 @@ object JavaModule { } try { if (Class.forName(mod).isInstance(outer) && !Class.forName(testMod).isInstance(self)) - throw new MillException( + throw MillException( s"$outer is a `${mod}`. $self needs to extend `${testModShort}`." ) } catch { @@ -1711,14 +1711,14 @@ trait BomModule extends JavaModule { abstract override def compile: T[CompilationResult] = Task { val sources = allSourceFiles() if (sources.nonEmpty) - throw new Exception("A BomModule cannot have sources") + throw Exception("A BomModule cannot have sources") CompilationResult(Task.dest / "zinc", PathRef(Task.dest / "classes")) } abstract override def resources: T[Seq[PathRef]] = Task { val value = super.resources() if (value.nonEmpty) - throw new Exception("A BomModule cannot have resources") + throw Exception("A BomModule cannot have resources") Seq.empty[PathRef] } diff --git a/libs/javalib/src/mill/javalib/NativeImageModule.scala b/libs/javalib/src/mill/javalib/NativeImageModule.scala index a4a6138467a9..c854670d87ad 100644 --- a/libs/javalib/src/mill/javalib/NativeImageModule.scala +++ b/libs/javalib/src/mill/javalib/NativeImageModule.scala @@ -117,9 +117,9 @@ trait NativeImageModule extends WithJvmWorkerModule { if (os.exists(path)) // native-image is externally managed, better revalidate it at least once PathRef(path).withRevalidateOnce - else throw new RuntimeException(s"$path not found") + else throw RuntimeException(s"$path not found") case None => - throw new RuntimeException("JvmWorkerModule.javaHome/GRAALVM_HOME not defined") + throw RuntimeException("JvmWorkerModule.javaHome/GRAALVM_HOME not defined") } } } diff --git a/libs/javalib/src/mill/javalib/PublishModule.scala b/libs/javalib/src/mill/javalib/PublishModule.scala index b4ad7397ebac..e504fb63ea07 100644 --- a/libs/javalib/src/mill/javalib/PublishModule.scala +++ b/libs/javalib/src/mill/javalib/PublishModule.scala @@ -18,7 +18,7 @@ trait PublishModule extends JavaModule { outer => override def moduleDeps: Seq[PublishModule] = super.moduleDeps.map { case m: PublishModule => m case other => - throw new Exception( + throw Exception( s"PublishModule moduleDeps need to be also PublishModules. $other is not a PublishModule" ) } @@ -26,7 +26,7 @@ trait PublishModule extends JavaModule { outer => override def bomModuleDeps: Seq[BomModule & PublishModule] = super.bomModuleDeps.map { case m: (BomModule & PublishModule) => m case other => - throw new Exception( + throw Exception( s"PublishModule bomModuleDeps need to be also PublishModules. $other is not a PublishModule" ) } @@ -393,7 +393,7 @@ trait PublishModule extends JavaModule { outer => val contents = publishLocalContentsTask(sources = sources, doc = doc)() val publisher = localIvyRepo() match { case None => LocalIvyPublisher - case Some(path) => new LocalIvyPublisher(path) + case Some(path) => LocalIvyPublisher(path) } publisher.publishLocal(contents.artifact, contents.contents) } @@ -469,7 +469,7 @@ trait PublishModule extends JavaModule { outer => val path = m2RepoPath() val contents = publishM2LocalContentsTask(sources = sources, docs = docs)() - new LocalM2Publisher(path) + LocalM2Publisher(path) .publish(contents.artifact, contents.contents) .map(PathRef(_).withRevalidateOnce) } @@ -582,7 +582,7 @@ trait PublishModule extends JavaModule { outer => Task.env, GpgArgs.fromUserProvided(gpgArgs) ) - new SonatypePublisher( + SonatypePublisher( uri = sonatypeLegacyOssrhUri, snapshotUri = sonatypeCentralSnapshotUri, checkSonatypeCreds(sonatypeCreds)(), @@ -621,7 +621,7 @@ trait PublishModule extends JavaModule { outer => * for example. */ def publishLocalTestRepo: Task[PathRef] = Task { - val publisher = new LocalM2Publisher(Task.dest) + val publisher = LocalM2Publisher(Task.dest) val publishInfos = defaultPublishInfos(sources = false, docs = false)() ++ Seq(PublishInfo.sourcesJar(sourceJar())) ++ extraPublish() @@ -751,7 +751,7 @@ object PublishModule extends ExternalModule with DefaultTaskModule { GpgArgs.fromUserProvided(gpgArgs) ) - new SonatypePublisher( + SonatypePublisher( sonatypeUri, sonatypeSnapshotUri, internal.PublishModule.checkSonatypeCreds(sonatypeCreds)(), diff --git a/libs/javalib/src/mill/javalib/RunModule.scala b/libs/javalib/src/mill/javalib/RunModule.scala index 66a11d04b6ad..1f8391a4ff43 100644 --- a/libs/javalib/src/mill/javalib/RunModule.scala +++ b/libs/javalib/src/mill/javalib/RunModule.scala @@ -268,9 +268,9 @@ object RunModule { method.setAccessible(true) val modifiers = method.getModifiers if (!Modifier.isPublic(modifiers)) - throw new NoSuchMethodException(mainClassName + ".main is not public") + throw NoSuchMethodException(mainClassName + ".main is not public") if (!Modifier.isStatic(modifiers)) - throw new NoSuchMethodException(mainClassName + ".main is not static") + throw NoSuchMethodException(mainClassName + ".main is not static") method } diff --git a/libs/javalib/src/mill/javalib/SonatypeCentralPublishModule.scala b/libs/javalib/src/mill/javalib/SonatypeCentralPublishModule.scala index 0f85b33d33d5..3a26dc16a42f 100644 --- a/libs/javalib/src/mill/javalib/SonatypeCentralPublishModule.scala +++ b/libs/javalib/src/mill/javalib/SonatypeCentralPublishModule.scala @@ -60,7 +60,7 @@ trait SonatypeCentralPublishModule extends PublishModule, MavenWorkerSupport, val maybeKeyId = internal.PublishModule.pgpImportSecretIfProvidedOrThrow(Task.env) def makeGpgArgs() = - sonatypeCentralGpgArgsForKey()(maybeKeyId.getOrElse(throw new IllegalArgumentException( + sonatypeCentralGpgArgsForKey()(maybeKeyId.getOrElse(throw IllegalArgumentException( s"Publishing to Sonatype Central requires a PGP key. Please set the " + s"'${internal.PublishModule.EnvVarPgpSecretBase64}' and '${internal.PublishModule.EnvVarPgpPassphrase}' " + s"(if needed) environment variables." @@ -173,7 +173,7 @@ object SonatypeCentralPublishModule extends ExternalModule, DefaultTaskModule, M } def publishReleases(artifacts: Seq[PublishData], gpgArgs: GpgArgs): Unit = { - val publisher = new SonatypeCentralPublisher( + val publisher = SonatypeCentralPublisher( credentials = SonatypeCredentials(credentials.username, credentials.password), gpgArgs = gpgArgs, connectTimeout = connectTimeout, @@ -206,7 +206,7 @@ object SonatypeCentralPublishModule extends ExternalModule, DefaultTaskModule, M val (snapshots, releases) = publishArtifacts.partition(_.meta.isSnapshot) bundleName.filter(_ => snapshots.nonEmpty).foreach { bundleName => - throw new IllegalArgumentException( + throw IllegalArgumentException( s"Publishing SNAPSHOT versions when bundle name ($bundleName) is specified is not supported.\n\n" + s"SNAPSHOT versions: ${pprint.apply(snapshots)}" ) diff --git a/libs/javalib/src/mill/javalib/SonatypeCentralPublisher.scala b/libs/javalib/src/mill/javalib/SonatypeCentralPublisher.scala index 7bac0c2b56e7..80e2770c279e 100644 --- a/libs/javalib/src/mill/javalib/SonatypeCentralPublisher.scala +++ b/libs/javalib/src/mill/javalib/SonatypeCentralPublisher.scala @@ -53,7 +53,7 @@ class SonatypeCentralPublisher( ) private val sonatypeCentralClient = - new SyncSonatypeClient( + SyncSonatypeClient( credentials = STCreds(credentials.username, credentials.password), readTimeout = readTimeout, connectTimeout = connectTimeout @@ -206,7 +206,7 @@ class SonatypeCentralPublisher( } } catch { case ex: Throwable => { - throw new RuntimeException( + throw RuntimeException( s"Failed to publish ${deploymentName.unapply} to Sonatype Central", ex ) @@ -223,7 +223,7 @@ class SonatypeCentralPublisher( val zipFile = (wd / s"$fileNameWithoutExtension.zip") val fileOutputStream = Files.newOutputStream(zipFile.toNIO) - val jarOutputStream = new JarOutputStream(fileOutputStream) + val jarOutputStream = JarOutputStream(fileOutputStream) try { func(jarOutputStream) } finally { @@ -237,7 +237,7 @@ class SonatypeCentralPublisher( jarOutputStream: JarOutputStream ): Unit = { files.foreach { case (filename, fileAsBytes) => - val zipEntry = new ZipEntry(filename.toString) + val zipEntry = ZipEntry(filename.toString) jarOutputStream.putNextEntry(zipEntry) jarOutputStream.write(fileAsBytes) jarOutputStream.closeEntry() diff --git a/libs/javalib/src/mill/javalib/TestModule.scala b/libs/javalib/src/mill/javalib/TestModule.scala index 3478adddfdab..d83d8dde6898 100644 --- a/libs/javalib/src/mill/javalib/TestModule.scala +++ b/libs/javalib/src/mill/javalib/TestModule.scala @@ -243,7 +243,7 @@ trait TestModule globSelectors: Task[Seq[String]] ): Task[(msg: String, results: Seq[TestResult])] = Task.Anon { - val testModuleUtil = new TestModuleUtil( + val testModuleUtil = TestModuleUtil( testUseArgsFile(), forkArgs(), globSelectors(), diff --git a/libs/javalib/src/mill/javalib/checkstyle/CheckstyleModule.scala b/libs/javalib/src/mill/javalib/checkstyle/CheckstyleModule.scala index c7ee10c4b789..017640c3f8b9 100644 --- a/libs/javalib/src/mill/javalib/checkstyle/CheckstyleModule.scala +++ b/libs/javalib/src/mill/javalib/checkstyle/CheckstyleModule.scala @@ -70,9 +70,9 @@ trait CheckstyleModule extends JavaModule { Task.log.error( s"checkstyle exit($exitCode); please check command arguments, plugin settings or try with another version" ) - throw new UnsupportedOperationException(s"checkstyle exit($exitCode)") + throw UnsupportedOperationException(s"checkstyle exit($exitCode)") } else if (check) { - throw new RuntimeException(s"checkstyle found $exitCode violation(s)") + throw RuntimeException(s"checkstyle found $exitCode violation(s)") } else { Task.log.error(s"checkstyle found $exitCode violation(s)") } diff --git a/libs/javalib/src/mill/javalib/checkstyle/CheckstyleXsltModule.scala b/libs/javalib/src/mill/javalib/checkstyle/CheckstyleXsltModule.scala index a3dfd3ec3bbc..bec4f13286c5 100644 --- a/libs/javalib/src/mill/javalib/checkstyle/CheckstyleXsltModule.scala +++ b/libs/javalib/src/mill/javalib/checkstyle/CheckstyleXsltModule.scala @@ -21,16 +21,16 @@ trait CheckstyleXsltModule extends CheckstyleModule { if (os.exists(checkOutput)) { checkstyleXsltReports().foreach { case CheckstyleXsltReport(xslt, output) => - val xsltSource = new StreamSource(xslt.path.getInputStream) + val xsltSource = StreamSource(xslt.path.getInputStream) xsltSource.setSystemId( xslt.path.toIO ) // so that relative URI references can be resolved val checkSource = - new StreamSource(checkOutput.getInputStream) + StreamSource(checkOutput.getInputStream) val outputResult = - new StreamResult(os.write.outputStream(output.path, createFolders = true)) + StreamResult(os.write.outputStream(output.path, createFolders = true)) Task.log.info(s"transforming checkstyle output report with $xslt") diff --git a/libs/javalib/src/mill/javalib/dependency/versions/VersionsFinder.scala b/libs/javalib/src/mill/javalib/dependency/versions/VersionsFinder.scala index 2898e88304b8..b23f9dd395eb 100644 --- a/libs/javalib/src/mill/javalib/dependency/versions/VersionsFinder.scala +++ b/libs/javalib/src/mill/javalib/dependency/versions/VersionsFinder.scala @@ -31,18 +31,18 @@ private[dependency] object VersionsFinder { val clock = Clock.fixed(Instant.now(), ZoneId.systemDefault()) val resolvedDependencies = evaluator.execute { - val progress = new Progress(javaModules.size) + val progress = Progress(javaModules.size) javaModules.map(classpath(progress, ctx.offline, clock, coursierConfigModule)) }.values.get evaluator.execute { - val progress = new Progress(resolvedDependencies.map(_._3.size).sum) + val progress = Progress(resolvedDependencies.map(_._3.size).sum) resolvedDependencies.map(resolveVersions(progress)) }.values.get } class Progress(val count: Int) { - private val counter = new AtomicInteger(1) + private val counter = AtomicInteger(1) def next(): Int = counter.getAndIncrement() } diff --git a/libs/javalib/src/mill/javalib/internal/PublishModule.scala b/libs/javalib/src/mill/javalib/internal/PublishModule.scala index e3b1057b07df..036f22d3bc37 100644 --- a/libs/javalib/src/mill/javalib/internal/PublishModule.scala +++ b/libs/javalib/src/mill/javalib/internal/PublishModule.scala @@ -27,7 +27,7 @@ private[mill] object PublishModule { /** Imports a Base64 encoded GPG secret, if one is provided in the environment. Throws if the import fails. */ def pgpImportSecretIfProvidedOrThrow(env: Map[String, String]): Option[String] = pgpImportSecretIfProvided(env).map(_.fold( - err => throw new IllegalArgumentException(err), + err => throw IllegalArgumentException(err), identity )) @@ -110,11 +110,11 @@ private[mill] object PublishModule { /** Creates an instance if the passphrase is not empty. */ def apply(keyId: String, passphrase: Option[String]): GpgKey = - new GpgKey(keyId = keyId, passphrase = passphrase.filter(_.nonEmpty)) + GpgKey(keyId = keyId, passphrase = passphrase.filter(_.nonEmpty)) /** Creates an instance if the passphrase is not empty. */ def apply(keyId: String, passphrase: String): GpgKey = - new GpgKey(keyId = keyId, passphrase = if (passphrase.isEmpty) None else Some(passphrase)) + GpgKey(keyId = keyId, passphrase = if (passphrase.isEmpty) None else Some(passphrase)) /** * @param maybeKeyId will be [[None]] if the PGP key was not provided in the environment. @@ -137,7 +137,7 @@ private[mill] object PublishModule { maybePassphrase: Option[String] ): Option[GpgKey] = createFromEnvVars(maybeKeyId, maybePassphrase) - .map(_.fold(err => throw new IllegalArgumentException(err), identity)) + .map(_.fold(err => throw IllegalArgumentException(err), identity)) def gpgArgsForPassphrase(passphrase: Option[String]): Seq[PossiblySecret[String]] = passphrase.iterator.flatMap(p => Iterator("--passphrase", Secret(p))).toSeq diff --git a/libs/javalib/src/mill/javalib/palantirformat/PalantirFormatModule.scala b/libs/javalib/src/mill/javalib/palantirformat/PalantirFormatModule.scala index f5b82110d528..b74730ad041f 100644 --- a/libs/javalib/src/mill/javalib/palantirformat/PalantirFormatModule.scala +++ b/libs/javalib/src/mill/javalib/palantirformat/PalantirFormatModule.scala @@ -121,7 +121,7 @@ object PalantirFormatModule extends ExternalModule with PalantirFormatBaseModule ctx.log.error( "palantirformat aborted due to format error(s) (or invalid plugin settings/palantirformat options)" ) - throw new RuntimeException(s"palantirformat exit($exitCode)") + throw RuntimeException(s"palantirformat exit($exitCode)") } } diff --git a/libs/javalib/src/mill/javalib/publish/Ivy.scala b/libs/javalib/src/mill/javalib/publish/Ivy.scala index 678df024a661..1bbcaaa7e337 100644 --- a/libs/javalib/src/mill/javalib/publish/Ivy.scala +++ b/libs/javalib/src/mill/javalib/publish/Ivy.scala @@ -79,7 +79,7 @@ object Ivy { - val pp = new PrettyPrinter(120, 4) + val pp = PrettyPrinter(120, 4) head + pp.format(xml).replaceAll(">", ">") } diff --git a/libs/javalib/src/mill/javalib/publish/Licence.scala b/libs/javalib/src/mill/javalib/publish/Licence.scala index 2dc3d3e9e1a7..d0fc74630d1c 100644 --- a/libs/javalib/src/mill/javalib/publish/Licence.scala +++ b/libs/javalib/src/mill/javalib/publish/Licence.scala @@ -436,7 +436,7 @@ object License { case class Data(licenses: List[License]) - val json = new String(Files.readAllBytes(Paths.get("data.json"))) + val json = String(Files.readAllBytes(Paths.get("data.json"))) val licences = decode[Data](json).right.get.licenses diff --git a/libs/javalib/src/mill/javalib/publish/Pom.scala b/libs/javalib/src/mill/javalib/publish/Pom.scala index ea28c6975f74..9359d8cd9a4f 100644 --- a/libs/javalib/src/mill/javalib/publish/Pom.scala +++ b/libs/javalib/src/mill/javalib/publish/Pom.scala @@ -18,7 +18,7 @@ object Pom { case None => NodeSeq.Empty case Some(x) => e.copy(child = x match { case n: NodeSeq => n - case x => new Atom(x) + case x => Atom(x) }) } case _ => e @@ -118,7 +118,7 @@ object Pom { {depMgmtSection} - val pp = new PrettyPrinter(120, 4) + val pp = PrettyPrinter(120, 4) head + pp.format(xml) } diff --git a/libs/javalib/src/mill/javalib/publish/SonatypeHelpers.scala b/libs/javalib/src/mill/javalib/publish/SonatypeHelpers.scala index 2a10ceb00c9d..3cf16f178642 100644 --- a/libs/javalib/src/mill/javalib/publish/SonatypeHelpers.scala +++ b/libs/javalib/src/mill/javalib/publish/SonatypeHelpers.scala @@ -90,5 +90,5 @@ object SonatypeHelpers { private def sha1 = MessageDigest.getInstance("sha1") private def hexArray(arr: Array[Byte]) = - String.format("%0" + (arr.length << 1) + "x", new BigInteger(1, arr)) + String.format("%0" + (arr.length << 1) + "x", BigInteger(1, arr)) } diff --git a/libs/javalib/src/mill/javalib/publish/SonatypeHttpApi.scala b/libs/javalib/src/mill/javalib/publish/SonatypeHttpApi.scala index 15ef4ed695e0..1a6d3a1ee0f6 100644 --- a/libs/javalib/src/mill/javalib/publish/SonatypeHttpApi.scala +++ b/libs/javalib/src/mill/javalib/publish/SonatypeHttpApi.scala @@ -42,7 +42,7 @@ class SonatypeHttpApi( ) if (!response.is2xx) { - throw new Exception( + throw Exception( s"$uri/staging/profiles returned ${response.statusCode}\n${response.text()}" ) } @@ -55,7 +55,7 @@ class SonatypeHttpApi( .map(_("resourceURI").str) resourceUri.getOrElse( - throw new RuntimeException( + throw RuntimeException( s"Could not find staging profile for groupId: ${groupId}" ) ) @@ -70,7 +70,7 @@ class SonatypeHttpApi( ujson.read(response.text())("type").str } catch { case e: ParseException => - throw new RuntimeException( + throw RuntimeException( s"Could not parse HTTP response. ${e.getMessage()}" + "\n" + s"Raw response: ${response}", e ) @@ -86,7 +86,7 @@ class SonatypeHttpApi( )) if (!response.is2xx) { - throw new RuntimeException( + throw RuntimeException( s"$uri/staging/profiles returned ${response.statusCode}\n${response.text()}" ) } @@ -166,6 +166,6 @@ class SonatypeHttpApi( } private def base64(s: String) = - new String(Base64.getEncoder.encode(s.getBytes)) + String(Base64.getEncoder.encode(s.getBytes)) } diff --git a/libs/javalib/src/mill/javalib/publish/SonatypePublisher.scala b/libs/javalib/src/mill/javalib/publish/SonatypePublisher.scala index f7c64ee314ee..d6012213371d 100644 --- a/libs/javalib/src/mill/javalib/publish/SonatypePublisher.scala +++ b/libs/javalib/src/mill/javalib/publish/SonatypePublisher.scala @@ -57,7 +57,7 @@ class SonatypePublisher( stagingRelease = stagingRelease ) - private val api = new SonatypeHttpApi( + private val api = SonatypeHttpApi( uri, credentials, readTimeout = readTimeout, @@ -175,7 +175,7 @@ class SonatypePublisher( val errors = publishResults.filterNot(_.is2xx).map { response => s"Code: ${response.statusCode}, message: ${response.text()}" } - throw new RuntimeException( + throw RuntimeException( s"Failed to publish ${artifacts.map(_.id).mkString(", ")} to Sonatype. Errors: \n${errors.mkString("\n")}" ) } @@ -191,7 +191,7 @@ class SonatypePublisher( Thread.sleep(3000) attemptsLeft -= 1 if (attemptsLeft == 0) { - throw new RuntimeException( + throw RuntimeException( s"Couldn't wait for staging repository to be ${status}. Failing" ) } diff --git a/libs/javalib/src/mill/javalib/spring/boot/SpringBootModule.scala b/libs/javalib/src/mill/javalib/spring/boot/SpringBootModule.scala index 4d30ef6cbe79..9fe64fea5f56 100644 --- a/libs/javalib/src/mill/javalib/spring/boot/SpringBootModule.scala +++ b/libs/javalib/src/mill/javalib/spring/boot/SpringBootModule.scala @@ -179,7 +179,7 @@ trait SpringBootModule extends JavaModule { val nativeImageArgs: Seq[String] = val nativeImageProps = outer.springBootAOTNativeProperties().path if (os.exists(nativeImageProps) && os.isFile(nativeImageProps)) { - val properties = new Properties() + val properties = Properties() Using.resource[ java.io.InputStream, Unit diff --git a/libs/javalib/test/src/mill/javalib/TestModuleUtilTests.scala b/libs/javalib/test/src/mill/javalib/TestModuleUtilTests.scala index fc0b23df8592..c9c7d2f7aa25 100644 --- a/libs/javalib/test/src/mill/javalib/TestModuleUtilTests.scala +++ b/libs/javalib/test/src/mill/javalib/TestModuleUtilTests.scala @@ -48,13 +48,13 @@ object TestModuleUtilTests extends TestSuite { Some("utest.AssertionError"), Some("assert(1 == 2)"), Some(Seq( - new StackTraceElement( + StackTraceElement( "utest.asserts.Util$", "$anonfun$makeAssertError$1", "Util.scala", 26 ), - new StackTraceElement( + StackTraceElement( "utest.framework.StackMarker$", "dropInside", "StackMarker.scala", @@ -115,15 +115,15 @@ object TestModuleUtilTests extends TestSuite { 2400, "Error", Some("java.lang.RuntimeException"), - Some("throw new RuntimeException()"), + Some("throw RuntimeException()"), Some(Seq( - new StackTraceElement( + StackTraceElement( "utest.asserts.Util$", "$anonfun$makeAssertError$1", "Util.scala", 26 ), - new StackTraceElement( + StackTraceElement( "utest.framework.StackMarker$", "dropInside", "StackMarker.scala", @@ -133,7 +133,7 @@ object TestModuleUtilTests extends TestSuite { ) val errorTestCaseElement = - java.lang.RuntimeException: throw new RuntimeException() at utest.asserts.Util$.$anonfun$makeAssertError$1(Util.scala:26) at utest.framework.StackMarker$.dropInside(StackMarker.scala:11) + java.lang.RuntimeException: throw RuntimeException() at utest.asserts.Util$.$anonfun$makeAssertError$1(Util.scala:26) at utest.framework.StackMarker$.dropInside(StackMarker.scala:11) test("error") - { val expectedReport = @@ -408,5 +408,5 @@ object TestModuleUtilTests extends TestSuite { assert(exp == act) } - private def asString(elem: Elem) = new PrettyPrinter(Int.MaxValue, 0, true).format(elem) + private def asString(elem: Elem) = PrettyPrinter(Int.MaxValue, 0, true).format(elem) } diff --git a/libs/javalib/test/src/mill/javalib/publish/IvyTests.scala b/libs/javalib/test/src/mill/javalib/publish/IvyTests.scala index 7ffac87e1bc7..6b670b800f7a 100644 --- a/libs/javalib/test/src/mill/javalib/publish/IvyTests.scala +++ b/libs/javalib/test/src/mill/javalib/publish/IvyTests.scala @@ -92,10 +92,10 @@ object IvyTests extends TestSuite { } private def singleNode(seq: NodeSeq): Node = - seq.headOption.getOrElse(throw new RuntimeException("empty seq")) + seq.headOption.getOrElse(throw RuntimeException("empty seq")) private def mandatoryAttr(node: Node, attr: String): String = - optionalAttr(node, attr).getOrElse(throw new RuntimeException(s"empty attr $attr")) + optionalAttr(node, attr).getOrElse(throw RuntimeException(s"empty attr $attr")) private def optionalAttr(node: Node, attr: String): Option[String] = { node.attributes.asAttrMap.get(attr) diff --git a/libs/javalib/test/src/mill/javalib/publish/LocalM2PublisherTests.scala b/libs/javalib/test/src/mill/javalib/publish/LocalM2PublisherTests.scala index ed74055d5041..c5b878de943e 100644 --- a/libs/javalib/test/src/mill/javalib/publish/LocalM2PublisherTests.scala +++ b/libs/javalib/test/src/mill/javalib/publish/LocalM2PublisherTests.scala @@ -21,7 +21,7 @@ object LocalM2PublisherTests extends TestSuite { os.write(repo / "pom", "POM") os.write(repo / "extra", "EXTRA") - val publisher = new LocalM2Publisher(repo) + val publisher = LocalM2Publisher(repo) val artifact = Artifact("group.org", "id", "version") val res = publisher.publish( repo / "pom", diff --git a/libs/javalib/test/src/mill/javalib/publish/PomTests.scala b/libs/javalib/test/src/mill/javalib/publish/PomTests.scala index 163ff315bf1b..c19b7f87fe0f 100644 --- a/libs/javalib/test/src/mill/javalib/publish/PomTests.scala +++ b/libs/javalib/test/src/mill/javalib/publish/PomTests.scala @@ -282,7 +282,7 @@ object PomTests extends TestSuite { seq .map(_.text) .headOption - .getOrElse(throw new RuntimeException("seq was empty")) + .getOrElse(throw RuntimeException("seq was empty")) def optText(seq: NodeSeq) = seq.map(_.text).headOption diff --git a/libs/javalib/testrunner/src/mill/javalib/testrunner/TestRunnerUtils.scala b/libs/javalib/testrunner/src/mill/javalib/testrunner/TestRunnerUtils.scala index d4836e190a81..4fa2547554d4 100644 --- a/libs/javalib/testrunner/src/mill/javalib/testrunner/TestRunnerUtils.scala +++ b/libs/javalib/testrunner/src/mill/javalib/testrunner/TestRunnerUtils.scala @@ -25,7 +25,7 @@ import scala.math.Ordering.Implicits.* if (os.isDir(base)) { os.walk.stream(base).filter(_.ext == "class").map(_.relativeTo(base).toString) } else { - val zip = new ZipInputStream(Files.newInputStream(base.toNIO)) + val zip = ZipInputStream(Files.newInputStream(base.toNIO)) geny.Generator.selfClosing( ( Iterator.continually(zip.getNextEntry) @@ -124,7 +124,7 @@ import scala.math.Ordering.Implicits.* val tasks = runner.tasks( for ((cls, fingerprint) <- testClasses.iterator.toArray if classFilter(cls)) - yield new TaskDef( + yield TaskDef( cls.getName.stripSuffix("$"), fingerprint, false, @@ -148,7 +148,7 @@ import scala.math.Ordering.Implicits.* events: ConcurrentLinkedQueue[Event], systemOut: PrintStream ): Boolean = { - val taskStatus = new AtomicBoolean(true) + val taskStatus = AtomicBoolean(true) val taskQueue = tasks.to(mutable.Queue) while (taskQueue.nonEmpty) { val next = @@ -241,7 +241,7 @@ import scala.math.Ordering.Implicits.* // Capture this value outside of the task event handler so it // isn't affected by a test framework's stream redirects val systemOut = System.out - val events = new ConcurrentLinkedQueue[Event]() + val events = ConcurrentLinkedQueue[Event]() var successCounter = 0L var failureCounter = 0L @@ -296,7 +296,7 @@ import scala.math.Ordering.Implicits.* // Capture this value outside of the task event handler so it // isn't affected by a test framework's stream redirects val systemOut = System.out - val events = new ConcurrentLinkedQueue[Event]() + val events = ConcurrentLinkedQueue[Event]() val globSelectorCache = testClasses.view .map { case (cls, fingerprint) => cls.getName.stripSuffix("$") -> (cls, fingerprint) } .toMap @@ -311,7 +311,7 @@ import scala.math.Ordering.Implicits.* .get(testClassName) .map { case (cls, fingerprint) => val clsName = cls.getName.stripSuffix("$") - new TaskDef(clsName, fingerprint, false, Array(new SuiteSelector)) + TaskDef(clsName, fingerprint, false, Array(new SuiteSelector)) } val tasks = runner.tasks(taskDefs.toArray) diff --git a/libs/javalib/worker/src/mill/javalib/worker/JvmWorkerImpl.scala b/libs/javalib/worker/src/mill/javalib/worker/JvmWorkerImpl.scala index 6b3e91edfab2..4c850380e6cf 100644 --- a/libs/javalib/worker/src/mill/javalib/worker/JvmWorkerImpl.scala +++ b/libs/javalib/worker/src/mill/javalib/worker/JvmWorkerImpl.scala @@ -37,7 +37,7 @@ class JvmWorkerImpl(args: JvmWorkerArgs) extends InternalJvmWorkerApi with AutoC val zincApi = if (javaRuntimeOptions.isEmpty && javaHome.isEmpty) localZincApi(zincCtx, log) - else new SubprocessZincApi( + else SubprocessZincApi( javaHome, javaRuntimeOptions, zincCtx, diff --git a/libs/javalib/worker/src/mill/javalib/zinc/ForwardingReporter.scala b/libs/javalib/worker/src/mill/javalib/zinc/ForwardingReporter.scala index 2c22b6071e16..88cfcd53a7da 100644 --- a/libs/javalib/worker/src/mill/javalib/zinc/ForwardingReporter.scala +++ b/libs/javalib/worker/src/mill/javalib/zinc/ForwardingReporter.scala @@ -5,17 +5,17 @@ import sbt.internal.inc.ManagedLoggedReporter private trait ForwardingReporter(forwarder: CompileProblemReporter) extends ManagedLoggedReporter { override def logError(problem: xsbti.Problem): Unit = { - forwarder.logError(new ZincProblem(problem)) + forwarder.logError(ZincProblem(problem)) super.logError(problem) } override def logWarning(problem: xsbti.Problem): Unit = { - forwarder.logWarning(new ZincProblem(problem)) + forwarder.logWarning(ZincProblem(problem)) super.logWarning(problem) } override def logInfo(problem: xsbti.Problem): Unit = { - forwarder.logInfo(new ZincProblem(problem)) + forwarder.logInfo(ZincProblem(problem)) super.logInfo(problem) } diff --git a/libs/javalib/worker/src/mill/javalib/zinc/PositionMapper.scala b/libs/javalib/worker/src/mill/javalib/zinc/PositionMapper.scala index c7bbc5aef79e..9c26c5a8fafa 100644 --- a/libs/javalib/worker/src/mill/javalib/zinc/PositionMapper.scala +++ b/libs/javalib/worker/src/mill/javalib/zinc/PositionMapper.scala @@ -28,7 +28,7 @@ object PositionMapper { def create(sources: Array[VirtualFile]) : (Map[os.Path, os.Path], Option[xsbti.Position => xsbti.Position]) = { val buildSources0 = sources.flatMap { vf => - val str = new String(vf.input().readAllBytes(), StandardCharsets.UTF_8) + val str = String(vf.input().readAllBytes(), StandardCharsets.UTF_8) val lines = str.linesWithSeparators.toVector lines .collectFirst { case s"//SOURCECODE_ORIGINAL_FILE_PATH=$rest" => rest.trim } diff --git a/libs/javalib/worker/src/mill/javalib/zinc/ZincProblem.scala b/libs/javalib/worker/src/mill/javalib/zinc/ZincProblem.scala index ceac7984a345..6abbd8881374 100644 --- a/libs/javalib/worker/src/mill/javalib/zinc/ZincProblem.scala +++ b/libs/javalib/worker/src/mill/javalib/zinc/ZincProblem.scala @@ -16,7 +16,7 @@ class ZincProblem(base: xsbti.Problem) extends Problem { override def message: String = base.message() - override def position: ProblemPosition = new ZincProblemPosition(base.position()) + override def position: ProblemPosition = ZincProblemPosition(base.position()) override def diagnosticCode: Option[DiagnosticCode] = base.diagnosticCode().toScala.map(ZincDiagnosticCode(_)) diff --git a/libs/javalib/worker/src/mill/javalib/zinc/ZincWorker.scala b/libs/javalib/worker/src/mill/javalib/zinc/ZincWorker.scala index 18f3cac691f8..d216f629ce67 100644 --- a/libs/javalib/worker/src/mill/javalib/zinc/ZincWorker.scala +++ b/libs/javalib/worker/src/mill/javalib/zinc/ZincWorker.scala @@ -379,7 +379,7 @@ class ZincWorker(jobs: Int) extends AutoCloseable { self => .toArray val incOptions = IncOptions.of().withAuxiliaryClassFiles( - auxiliaryClassFileExtensions.map(new AuxiliaryClassFileExtension(_)).toArray + auxiliaryClassFileExtensions.map(AuxiliaryClassFileExtension(_)).toArray ) val compileProgress = reporter.map { reporter => new CompileProgress { @@ -504,9 +504,9 @@ class ZincWorker(jobs: Int) extends AutoCloseable { self => // Use a double-lock here because we need mutex both between threads within this // process, as well as between different processes since sometimes we are initializing // the compiler bridge inside a separate `ZincWorkerMain` subprocess - val doubleLock = new DoubleLock( + val doubleLock = DoubleLock( memoryLock, - new FileLock( + FileLock( (compilerBridgeProvider.workspace / "compiler-bridge-locks" / scalaVersion).toString ) ) diff --git a/libs/javascriptlib/test/src/mill/javascriptlib/HelloWorldTests.scala b/libs/javascriptlib/test/src/mill/javascriptlib/HelloWorldTests.scala index d1c4cd7a5937..f08c9e2d6abf 100644 --- a/libs/javascriptlib/test/src/mill/javascriptlib/HelloWorldTests.scala +++ b/libs/javascriptlib/test/src/mill/javascriptlib/HelloWorldTests.scala @@ -28,8 +28,8 @@ object HelloWorldTests extends TestSuite { def tests: Tests = Tests { test("run") { - val baos = new ByteArrayOutputStream() - UnitTester(HelloWorldJavascript, resourcePath, outStream = new PrintStream(baos)).scoped { + val baos = ByteArrayOutputStream() + UnitTester(HelloWorldJavascript, resourcePath, outStream = PrintStream(baos)).scoped { eval => val Right(_) = eval.apply(HelloWorldJavascript.qux.run(Args("James"))): @unchecked diff --git a/libs/kotlinlib/ksp2/src/mill/kotlinlib/ksp2/worker/KspWorkerImpl.scala b/libs/kotlinlib/ksp2/src/mill/kotlinlib/ksp2/worker/KspWorkerImpl.scala index 83a09c71558e..0165fa52df8f 100644 --- a/libs/kotlinlib/ksp2/src/mill/kotlinlib/ksp2/worker/KspWorkerImpl.scala +++ b/libs/kotlinlib/ksp2/src/mill/kotlinlib/ksp2/worker/KspWorkerImpl.scala @@ -54,12 +54,12 @@ class KspWorkerImpl extends KspWorker { val processorProviders: List[SymbolProcessorProvider] = processorProvidersSearch.asInstanceOf[List[SymbolProcessorProvider]] - val logger = new KspGradleLogger(gradleLogLevel) + val logger = KspGradleLogger(gradleLogLevel) - val exitCode = new KotlinSymbolProcessing(config, processorProviders.asJava, logger).execute() + val exitCode = KotlinSymbolProcessing(config, processorProviders.asJava, logger).execute() if (exitCode.getCode != 0) { - throw new Exception(s"KSP failed with exit code ${exitCode.getCode} ($exitCode)") + throw Exception(s"KSP failed with exit code ${exitCode.getCode} ($exitCode)") } } diff --git a/libs/kotlinlib/src/mill/kotlinlib/KotlinWorkerManager.scala b/libs/kotlinlib/src/mill/kotlinlib/KotlinWorkerManager.scala index 025aa19409d8..ba82b5eced37 100644 --- a/libs/kotlinlib/src/mill/kotlinlib/KotlinWorkerManager.scala +++ b/libs/kotlinlib/src/mill/kotlinlib/KotlinWorkerManager.scala @@ -18,7 +18,7 @@ class KotlinWorkerManager()(using ctx: TaskCtx) object KotlinWorkerManager extends ExternalModule { def kotlinWorker: Worker[KotlinWorkerManager] = Task.Worker { - new KotlinWorkerManager() + KotlinWorkerManager() } def get(toolsClassLoader: ClassLoader)(using ctx: TaskCtx): KotlinWorker = { diff --git a/libs/kotlinlib/src/mill/kotlinlib/detekt/DetektModule.scala b/libs/kotlinlib/src/mill/kotlinlib/detekt/DetektModule.scala index fec9b3ce0bd1..d148bb4430d3 100644 --- a/libs/kotlinlib/src/mill/kotlinlib/detekt/DetektModule.scala +++ b/libs/kotlinlib/src/mill/kotlinlib/detekt/DetektModule.scala @@ -45,17 +45,17 @@ trait DetektModule extends KotlinModule { if (exitCode == 0) {} // do nothing else if (exitCode == 1) { - throw new RuntimeException("detekt: An unexpected error occurred") + throw RuntimeException("detekt: An unexpected error occurred") } else if (exitCode == 2) { if (check) { - throw new RuntimeException("detekt: Max issues was reached") + throw RuntimeException("detekt: Max issues was reached") } else { Task.log.error("detekt: Max issues was reached") } } else if (exitCode == 3) { - throw new RuntimeException("detekt: Invalid configuration file detected") + throw RuntimeException("detekt: Invalid configuration file detected") } else { - throw new RuntimeException(s"detekt exited abnormally with exit code = $exitCode") + throw RuntimeException(s"detekt exited abnormally with exit code = $exitCode") } } diff --git a/libs/kotlinlib/src/mill/kotlinlib/js/KotlinJsModule.scala b/libs/kotlinlib/src/mill/kotlinlib/js/KotlinJsModule.scala index 6971f6501082..7e43eeedaff2 100644 --- a/libs/kotlinlib/src/mill/kotlinlib/js/KotlinJsModule.scala +++ b/libs/kotlinlib/src/mill/kotlinlib/js/KotlinJsModule.scala @@ -444,7 +444,7 @@ trait KotlinJsModule extends KotlinModule { outer => } else if (path.ext == "jar") { try { // TODO cache these lookups. May be a big performance penalty. - val zipFile = new ZipFile(path.toIO) + val zipFile = ZipFile(path.toIO) zipFile.stream() .anyMatch(entry => entry.getName.endsWith(".meta.js") || entry.getName.endsWith(".kjsm")) } catch { @@ -544,7 +544,7 @@ trait KotlinJsModule extends KotlinModule { outer => ): Task[(msg: String, results: Seq[TestResult])] = Task.Anon { val runTarget = kotlinJsRunTarget() if (runTarget.isEmpty) { - throw new IllegalStateException( + throw IllegalStateException( "Cannot run Kotlin/JS tests, because run target is not specified." ) } @@ -614,7 +614,7 @@ trait KotlinJsModule extends KotlinModule { outer => private def parseTestResults(path: os.Path): Seq[TestResult] = { if (!os.exists(path)) { - throw new FileNotFoundException(s"Test results file $path wasn't found") + throw FileNotFoundException(s"Test results file $path wasn't found") } val xml = XML.loadFile(path.toIO) (xml \ "testcase") @@ -670,14 +670,14 @@ trait KotlinJsModule extends KotlinModule { outer => // drop closing ), then after split drop position on the line val locationElements = location.dropRight(1).split(":").dropRight(1) if (locationElements.length >= 2) { - new StackTraceElement( + StackTraceElement( declaringClass, method, locationElements(locationElements.length - 2), locationElements.last.toInt ) } else { - new StackTraceElement(declaringClass, method, "", 0) + StackTraceElement(declaringClass, method, "", 0) } } } diff --git a/libs/kotlinlib/src/mill/kotlinlib/ksp/KspModule.scala b/libs/kotlinlib/src/mill/kotlinlib/ksp/KspModule.scala index 7b8b707ad793..60786d570f43 100644 --- a/libs/kotlinlib/src/mill/kotlinlib/ksp/KspModule.scala +++ b/libs/kotlinlib/src/mill/kotlinlib/ksp/KspModule.scala @@ -152,7 +152,7 @@ trait KspModule extends KotlinModule { outer => */ def ksp1KotlincOptions: T[Seq[String]] = Task { if (!kspLanguageVersion().startsWith("1.")) { - throw new RuntimeException("KSP needs a compatible language version <= 1.9 to be set!") + throw RuntimeException("KSP needs a compatible language version <= 1.9 to be set!") } kotlincOptions() ++ Seq( "-Xallow-unstable-dependencies", diff --git a/libs/kotlinlib/src/mill/kotlinlib/ktfmt/KtfmtModule.scala b/libs/kotlinlib/src/mill/kotlinlib/ktfmt/KtfmtModule.scala index 30c1de6f2262..8069dd28244b 100644 --- a/libs/kotlinlib/src/mill/kotlinlib/ktfmt/KtfmtModule.scala +++ b/libs/kotlinlib/src/mill/kotlinlib/ktfmt/KtfmtModule.scala @@ -111,7 +111,7 @@ object KtfmtModule extends ExternalModule with KtfmtBaseModule with DefaultTaskM case "kotlin" => "--kotlinlang-style" case "google" => "--google-style" case "meta" => "--meta-style" - case _ => throw new IllegalArgumentException(s"Unknown style ktfmt style: $style") + case _ => throw IllegalArgumentException(s"Unknown style ktfmt style: $style") }) if (!format) { args += "--dry-run" @@ -134,7 +134,7 @@ object KtfmtModule extends ExternalModule with KtfmtBaseModule with DefaultTaskM if (exitCode == 0) {} // do nothing else { - throw new RuntimeException(s"ktfmt exited abnormally with exit code = $exitCode") + throw RuntimeException(s"ktfmt exited abnormally with exit code = $exitCode") } } } diff --git a/libs/kotlinlib/src/mill/kotlinlib/ktlint/KtlintModule.scala b/libs/kotlinlib/src/mill/kotlinlib/ktlint/KtlintModule.scala index 50efc30bed78..ec1dc81bc66f 100644 --- a/libs/kotlinlib/src/mill/kotlinlib/ktlint/KtlintModule.scala +++ b/libs/kotlinlib/src/mill/kotlinlib/ktlint/KtlintModule.scala @@ -141,7 +141,7 @@ object KtlintModule extends ExternalModule with KtlintModule with DefaultTaskMod if (exitCode == 0) {} // do nothing else { if (ktlintArgs.check) { - throw new RuntimeException(s"ktlint exited abnormally with exit code = $exitCode") + throw RuntimeException(s"ktlint exited abnormally with exit code = $exitCode") } else { ctx.log.error(s"ktlint exited abnormally with exit code = $exitCode") } diff --git a/libs/kotlinlib/worker/src/mill/kotlinlib/worker/impl/JsCompileImpl.scala b/libs/kotlinlib/worker/src/mill/kotlinlib/worker/impl/JsCompileImpl.scala index 3c84b15cea9d..e74fc9646d0a 100644 --- a/libs/kotlinlib/worker/src/mill/kotlinlib/worker/impl/JsCompileImpl.scala +++ b/libs/kotlinlib/worker/src/mill/kotlinlib/worker/impl/JsCompileImpl.scala @@ -12,7 +12,7 @@ class JsCompileImpl extends Compiler() { ctx: TaskCtx ): (Int, String) = { - val compiler = new K2JSCompiler() + val compiler = K2JSCompiler() val allArgs = args ++ sources.map(_.toString) val exitCode = compiler.exec(ctx.log.streams.err, allArgs*) diff --git a/libs/kotlinlib/worker/src/mill/kotlinlib/worker/impl/JvmCompileImpl.scala b/libs/kotlinlib/worker/src/mill/kotlinlib/worker/impl/JvmCompileImpl.scala index 0898e54a6caf..9e7af69cbec1 100644 --- a/libs/kotlinlib/worker/src/mill/kotlinlib/worker/impl/JvmCompileImpl.scala +++ b/libs/kotlinlib/worker/src/mill/kotlinlib/worker/impl/JvmCompileImpl.scala @@ -14,7 +14,7 @@ class JvmCompileImpl() extends Compiler { val allArgs = args ++ sources.map(_.toString) - val compiler = new K2JVMCompiler() + val compiler = K2JVMCompiler() val exitCode = compiler.exec(ctx.log.streams.err, allArgs*) (exitCode.getCode(), exitCode.name()) diff --git a/libs/pythonlib/src/mill/pythonlib/PublishModule.scala b/libs/pythonlib/src/mill/pythonlib/PublishModule.scala index 70f715df41d4..85d531dd3d31 100644 --- a/libs/pythonlib/src/mill/pythonlib/PublishModule.scala +++ b/libs/pythonlib/src/mill/pythonlib/PublishModule.scala @@ -12,7 +12,7 @@ trait PublishModule extends PythonModule { override def moduleDeps: Seq[PublishModule] = super.moduleDeps.map { case m: PublishModule => m case other => - throw new Exception( + throw Exception( s"PublishModule moduleDeps need to be also PublishModules. $other is not a PublishModule" ) } diff --git a/libs/pythonlib/test/src/mill/pythonlib/HelloWorldTests.scala b/libs/pythonlib/test/src/mill/pythonlib/HelloWorldTests.scala index 52022b3597a2..c00dc241b75f 100644 --- a/libs/pythonlib/test/src/mill/pythonlib/HelloWorldTests.scala +++ b/libs/pythonlib/test/src/mill/pythonlib/HelloWorldTests.scala @@ -27,8 +27,8 @@ object HelloWorldTests extends TestSuite { val resourcePath = os.Path(sys.env("MILL_TEST_RESOURCE_DIR")) / "hello-world-python" def tests: Tests = Tests { test("run") { - val baos = new ByteArrayOutputStream() - UnitTester(HelloWorldPython, resourcePath, outStream = new PrintStream(baos)).scoped { eval => + val baos = ByteArrayOutputStream() + UnitTester(HelloWorldPython, resourcePath, outStream = PrintStream(baos)).scoped { eval => val Right(_) = eval.apply(HelloWorldPython.qux.run(Args())): @unchecked diff --git a/libs/pythonlib/test/src/mill/pythonlib/RunBackgroundTests.scala b/libs/pythonlib/test/src/mill/pythonlib/RunBackgroundTests.scala index 35d6c32dcda9..0ea83c78a5db 100644 --- a/libs/pythonlib/test/src/mill/pythonlib/RunBackgroundTests.scala +++ b/libs/pythonlib/test/src/mill/pythonlib/RunBackgroundTests.scala @@ -29,7 +29,7 @@ object RunBackgroundTests extends TestSuite { def sleepIfTimeAvailable(error: String) = { Thread.sleep(100) - if (System.currentTimeMillis() - now1 > maxSleep) throw new Exception(error) + if (System.currentTimeMillis() - now1 > maxSleep) throw Exception(error) } Thread.sleep(1000) // Make sure that the file remains locked even after a significant sleep diff --git a/libs/rpc/src/mill/rpc/MillRpcClient.scala b/libs/rpc/src/mill/rpc/MillRpcClient.scala index 5e281402b113..f491ba1bf5c6 100644 --- a/libs/rpc/src/mill/rpc/MillRpcClient.scala +++ b/libs/rpc/src/mill/rpc/MillRpcClient.scala @@ -50,7 +50,7 @@ object MillRpcClient { // we try to parse into `MillRpcServerToClient[A]` we will get an error if it's an `Ask`. wireTransport.readAndTryToParse[MillRpcServerToClient[ujson.Value]](logDebug) match { case None => - throw new IllegalStateException( + throw IllegalStateException( s"RPC wire has broken (${wireTransport.name}). The server probably crashed." ) case Some(MillRpcServerToClient.Ask(dataJson)) => @@ -69,7 +69,7 @@ object MillRpcClient { responseReceived match { case Some(value) => value - case None => throw new IllegalStateException("this should never happen") + case None => throw IllegalStateException("this should never happen") } } diff --git a/libs/rpc/src/mill/rpc/MillRpcServer.scala b/libs/rpc/src/mill/rpc/MillRpcServer.scala index 1d25538e5aad..c39c54145d17 100644 --- a/libs/rpc/src/mill/rpc/MillRpcServer.scala +++ b/libs/rpc/src/mill/rpc/MillRpcServer.scala @@ -82,7 +82,7 @@ trait MillRpcServer[ while (responseReceived.isEmpty) { val clientToServerMsg = readAndTryToParse[MillRpcClientToServer[R]]().getOrElse( - throw new InterruptedException( + throw InterruptedException( s"Transport wire broken while waiting for response to request." ) ) @@ -116,7 +116,7 @@ trait MillRpcServer[ private def createServerToClientChannel(): MillRpcChannel[ServerToClient] = { (msg: ServerToClient) => - val clientToServer = initializedOnClientMessage.getOrElse(throw new IllegalStateException( + val clientToServer = initializedOnClientMessage.getOrElse(throw IllegalStateException( "Client to server channel should have been initialized" )) diff --git a/libs/scalajslib/src/mill/scalajslib/api/JsEnvConfig.scala b/libs/scalajslib/src/mill/scalajslib/api/JsEnvConfig.scala index 869c941013f6..e6a901916a3e 100644 --- a/libs/scalajslib/src/mill/scalajslib/api/JsEnvConfig.scala +++ b/libs/scalajslib/src/mill/scalajslib/api/JsEnvConfig.scala @@ -75,14 +75,14 @@ object JsEnvConfig { Mirrors.autoRoot[Capabilities] def apply(capabilities: Capabilities): Selenium = - new Selenium(capabilities = capabilities) + Selenium(capabilities = capabilities) sealed trait Capabilities class ChromeOptions private (val headless: Boolean) extends Capabilities { def withHeadless(value: Boolean): Unit = copy(headless = value) private def copy( headless: Boolean - ): ChromeOptions = new ChromeOptions( + ): ChromeOptions = ChromeOptions( headless = headless ) } @@ -90,13 +90,13 @@ object JsEnvConfig { implicit def rw: RW[ChromeOptions] = macroRW def apply(headless: Boolean): ChromeOptions = - new ChromeOptions(headless = headless) + ChromeOptions(headless = headless) } class FirefoxOptions private (val headless: Boolean) extends Capabilities { def withHeadless(value: Boolean): Unit = copy(headless = value) private def copy( headless: Boolean - ): FirefoxOptions = new FirefoxOptions( + ): FirefoxOptions = FirefoxOptions( headless = headless ) } @@ -104,9 +104,9 @@ object JsEnvConfig { implicit def rw: RW[FirefoxOptions] = macroRW def apply(): FirefoxOptions = - new FirefoxOptions(headless = false) + FirefoxOptions(headless = false) def apply(headless: Boolean): FirefoxOptions = - new FirefoxOptions(headless = headless) + FirefoxOptions(headless = headless) } class SafariOptions private () extends Capabilities @@ -114,7 +114,7 @@ object JsEnvConfig { implicit def rw: RW[SafariOptions] = macroRW def apply(): SafariOptions = - new SafariOptions() + SafariOptions() } } @@ -126,7 +126,7 @@ object JsEnvConfig { Mirrors.autoRoot[Capabilities] def apply(capabilities: Capabilities): Playwright = - new Playwright(capabilities = capabilities) + Playwright(capabilities = capabilities) sealed trait Capabilities @@ -154,7 +154,7 @@ object JsEnvConfig { debug = debug, launchOptions = launchOptions ) - new Playwright(options) + Playwright(options) case class ChromeOptions( headless: Boolean = true, @@ -192,7 +192,7 @@ object JsEnvConfig { debug = debug, firefoxUserPrefs = firefoxUserPrefs ) - new Playwright(options) + Playwright(options) case class FirefoxOptions( headless: Boolean = true, showLogs: Boolean = false, @@ -219,7 +219,7 @@ object JsEnvConfig { json.numOpt ).orElse( json.strOpt.map(_.toString) - ).getOrElse(throw new Exception("Invalid value")) + ).getOrElse(throw Exception("Invalid value")) ) given rw: RW[FirefoxOptions] = macroRW @@ -246,7 +246,7 @@ object JsEnvConfig { debug = debug, launchOptions = launchOptions ) - new Playwright(options) + Playwright(options) case class WebkitOptions( headless: Boolean = true, diff --git a/libs/scalajslib/src/mill/scalajslib/api/OutputPatterns.scala b/libs/scalajslib/src/mill/scalajslib/api/OutputPatterns.scala index a160285b6e8a..93e0df433daa 100644 --- a/libs/scalajslib/src/mill/scalajslib/api/OutputPatterns.scala +++ b/libs/scalajslib/src/mill/scalajslib/api/OutputPatterns.scala @@ -49,7 +49,7 @@ class OutputPatterns private ( jsFileURI: String = jsFileURI, sourceMapURI: String = sourceMapURI ): OutputPatterns = { - new OutputPatterns(jsFile, sourceMapFile, moduleName, jsFileURI, sourceMapURI) + OutputPatterns(jsFile, sourceMapFile, moduleName, jsFileURI, sourceMapURI) } } @@ -68,7 +68,7 @@ object OutputPatterns { * - `sourceMapURI`: relative URI (same as `sourceMapFile`). */ def fromJSFile(jsFile: String): OutputPatterns = { - new OutputPatterns( + OutputPatterns( jsFile = jsFile, sourceMapFile = s"$jsFile.map", moduleName = s"./$jsFile", @@ -84,7 +84,7 @@ object OutputPatterns { moduleName: String, jsFileURI: String, sourceMapURI: String - ): OutputPatterns = new OutputPatterns( + ): OutputPatterns = OutputPatterns( jsFile, sourceMapFile, moduleName, diff --git a/libs/scalajslib/src/mill/scalajslib/api/Report.scala b/libs/scalajslib/src/mill/scalajslib/api/Report.scala index 353642ae64eb..88ebc2b499fd 100644 --- a/libs/scalajslib/src/mill/scalajslib/api/Report.scala +++ b/libs/scalajslib/src/mill/scalajslib/api/Report.scala @@ -33,7 +33,7 @@ object Report { sourceMapName: Option[String], moduleKind: ModuleKind ): Module = - new Module( + Module( moduleID = moduleID, jsFileName = jsFileName, sourceMapName = sourceMapName, @@ -45,7 +45,7 @@ object Report { Mirrors.autoRoot[Module] } def apply(publicModules: Iterable[Report.Module], dest: mill.PathRef): Report = - new Report(publicModules = publicModules, dest = dest) + Report(publicModules = publicModules, dest = dest) implicit val rw: RW[Report] = macroRW[Report] private given Root_Module: Mirrors.Root[Report] = diff --git a/libs/scalajslib/src/mill/scalajslib/worker/ScalaJSWorker.scala b/libs/scalajslib/src/mill/scalajslib/worker/ScalaJSWorker.scala index a32180f1e824..5d27b46b9b14 100644 --- a/libs/scalajslib/src/mill/scalajslib/worker/ScalaJSWorker.scala +++ b/libs/scalajslib/src/mill/scalajslib/worker/ScalaJSWorker.scala @@ -259,6 +259,6 @@ private[scalajslib] class ScalaJSWorker(jobs: Int) private[scalajslib] object ScalaJSWorkerExternalModule extends mill.api.ExternalModule { def scalaJSWorker: Worker[ScalaJSWorker] = - Task.Worker { new ScalaJSWorker(Task.ctx().jobs) } + Task.Worker { ScalaJSWorker(Task.ctx().jobs) } lazy val millDiscover = Discover[this.type] } diff --git a/libs/scalajslib/test/src/mill/scalajslib/JarPublishRunTests.scala b/libs/scalajslib/test/src/mill/scalajslib/JarPublishRunTests.scala index 8aa76abfbf0f..84ae82dde8c7 100644 --- a/libs/scalajslib/test/src/mill/scalajslib/JarPublishRunTests.scala +++ b/libs/scalajslib/test/src/mill/scalajslib/JarPublishRunTests.scala @@ -18,7 +18,7 @@ object JarPublishRunTests extends TestSuite { val Right(result) = eval(HelloJSWorld.build(scala, scalaJS).jar): @unchecked val jar = result.value.path - val jarFile = new JarFile(jar.toIO) + val jarFile = JarFile(jar.toIO) try { val entries = jarFile.entries().asScala.map(_.getName) assert(entries.contains("Main$.sjsir")) diff --git a/libs/scalajslib/worker/1/src/mill/scalajslib/worker/ScalaJSWorkerImpl.scala b/libs/scalajslib/worker/1/src/mill/scalajslib/worker/ScalaJSWorkerImpl.scala index 1b6ceaee2038..84c28768a39d 100644 --- a/libs/scalajslib/worker/1/src/mill/scalajslib/worker/ScalaJSWorkerImpl.scala +++ b/libs/scalajslib/worker/1/src/mill/scalajslib/worker/ScalaJSWorkerImpl.scala @@ -65,7 +65,7 @@ class ScalaJSWorkerImpl(jobs: Int) extends ScalaJSWorkerApi { val useECMAScript2015: Boolean = input.esFeatures.esVersion match { case ESVersion.ES5_1 => false case ESVersion.ES2015 => true - case v => throw new Exception( + case v => throw Exception( s"ESVersion $v is not supported with Scala.js < 1.6. Either update Scala.js or use one of ESVersion.ES5_1 or ESVersion.ES2015" ) } @@ -113,7 +113,7 @@ class ScalaJSWorkerImpl(jobs: Int) extends ScalaJSWorkerApi { case v @ ModuleSplitStyle.SmallModulesFor(packages*) => if (minorIsGreaterThanOrEqual(10)) ScalaJSModuleSplitStyle.SmallModulesFor(packages.toList) - else throw new Exception( + else throw Exception( s"ModuleSplitStyle $v is not supported with Scala.js < 1.10. Either update Scala.js or use one of ModuleSplitStyle.SmallestModules or ModuleSplitStyle.FewestModules" ) } @@ -123,7 +123,7 @@ class ScalaJSWorkerImpl(jobs: Int) extends ScalaJSWorkerApi { def withModuleSplitStyle_1_2_minus(config: StandardConfig): StandardConfig = { input.moduleSplitStyle match { case ModuleSplitStyle.FewestModules => - case v => throw new Exception( + case v => throw Exception( s"ModuleSplitStyle $v is not supported with Scala.js < 1.2. Either update Scala.js or use ModuleSplitStyle.FewestModules" ) } @@ -157,7 +157,7 @@ class ScalaJSWorkerImpl(jobs: Int) extends ScalaJSWorkerApi { case (_, false) => withMinify case (true, true) => withMinify.withExperimentalUseWebAssembly(true) case (false, true) => - throw new Exception("Emitting wasm is not supported with Scala.js < 1.17") + throw Exception("Emitting wasm is not supported with Scala.js < 1.17") } val linker = StandardImpl.clearableLinker(withWasm) @@ -230,7 +230,7 @@ class ScalaJSWorkerImpl(jobs: Int) extends ScalaJSWorkerApi { irFiles0 } else { if (!minorIsGreaterThanOrEqual(16)) { - throw new Exception("scalaJSImportMap is not supported with Scala.js < 1.16.") + throw Exception("scalaJSImportMap is not supported with Scala.js < 1.16.") } val remapFunction = (rawImport: String) => { importMap @@ -246,7 +246,7 @@ class ScalaJSWorkerImpl(jobs: Int) extends ScalaJSWorkerApi { report <- if (useLegacy) { val jsFileName = "out.js" - val jsFile = new File(dest, jsFileName).toPath() + val jsFile = File(dest, jsFileName).toPath() var linkerOutput = LinkerOutput(PathOutputFile(jsFile)) .withJSFileURI(java.net.URI.create(jsFile.getFileName.toString)) val sourceMapNameOpt = Option.when(sourceMap)(s"${jsFile.getFileName}.map") @@ -318,7 +318,7 @@ class ScalaJSWorkerImpl(jobs: Int) extends ScalaJSWorkerApi { ) for ((std, dest, name, checkAvailable) <- sources) { - val t = new Thread( + val t = Thread( new InputPumper(() => std, () => dest, checkAvailable), name ) @@ -340,7 +340,7 @@ class ScalaJSWorkerImpl(jobs: Int) extends ScalaJSWorkerApi { val logger = createLogger() val tconfig = TestAdapter.Config().withLogger(logger) - val adapter = new TestAdapter(env, input, tconfig) + val adapter = TestAdapter(env, input, tconfig) ( () => adapter.close(), @@ -348,7 +348,7 @@ class ScalaJSWorkerImpl(jobs: Int) extends ScalaJSWorkerApi { .loadFrameworks(List(List(frameworkName))) .flatten .headOption - .getOrElse(throw new RuntimeException( + .getOrElse(throw RuntimeException( """|Test framework class was not found. Please check that: |- the correct Scala.js dependency of the framework is used (like mvn"group::artifact::version", instead of mvn"group::artifact:version" for JVM Scala. Note the extra : before the version.) |- there are no typos in the framework class name. @@ -374,12 +374,12 @@ class ScalaJSWorkerImpl(jobs: Int) extends ScalaJSWorkerApi { } def jsEnvInput(report: Report): Seq[Input] = { - val mainModule = report.publicModules.find(_.moduleID == "main").getOrElse(throw new Exception( + val mainModule = report.publicModules.find(_.moduleID == "main").getOrElse(throw Exception( "Cannot determine `jsEnvInput`: Linking result does not have a " + "module named `main`.\n" + s"Full report:\n$report" )) - val path = new File(report.dest, mainModule.jsFileName).toPath + val path = File(report.dest, mainModule.jsFileName).toPath val input = mainModule.moduleKind match { case ModuleKind.NoModule => Input.Script(path) case ModuleKind.ESModule => Input.ESModule(path) diff --git a/libs/scalalib/src/mill/scalalib/CrossModuleBase.scala b/libs/scalalib/src/mill/scalalib/CrossModuleBase.scala index 073b8ba61be6..cecaeb2ba41b 100644 --- a/libs/scalalib/src/mill/scalalib/CrossModuleBase.scala +++ b/libs/scalalib/src/mill/scalalib/CrossModuleBase.scala @@ -35,7 +35,7 @@ trait CrossModuleBase extends ScalaModule with Cross.Module[String] { ) .collectFirst { case x => x } .getOrElse( - throw new Exception( + throw Exception( s"Unable to find compatible cross version between $crossScalaVersion and " + c.crossModules.map(_.crossScalaVersion).mkString(",") ) diff --git a/libs/scalalib/src/mill/scalalib/scalafmt/ScalafmtWorker.scala b/libs/scalalib/src/mill/scalalib/scalafmt/ScalafmtWorker.scala index a16f32d8141e..c14e33d65b71 100644 --- a/libs/scalalib/src/mill/scalalib/scalafmt/ScalafmtWorker.scala +++ b/libs/scalalib/src/mill/scalalib/scalafmt/ScalafmtWorker.scala @@ -22,7 +22,7 @@ object ScalafmtWorkerModule extends ExternalModule with JavaModule { mill.util.Jvm.createClassLoader(scalafmtClasspath().map(_.path)) } - def worker: Worker[ScalafmtWorker] = Task.Worker { new ScalafmtWorker(scalafmtClassLoader()) } + def worker: Worker[ScalafmtWorker] = Task.Worker { ScalafmtWorker(scalafmtClassLoader()) } lazy val millDiscover = Discover[this.type] } diff --git a/libs/scalalib/test/resources/hello-world/core/src/Main.scala b/libs/scalalib/test/resources/hello-world/core/src/Main.scala index 3377b3d8e54c..e8dd3c163e2d 100644 --- a/libs/scalalib/test/resources/hello-world/core/src/Main.scala +++ b/libs/scalalib/test/resources/hello-world/core/src/Main.scala @@ -14,7 +14,7 @@ object Main0 { object Main extends App { // testing correct loading of java standard modules in java 9 // https://github.com/lihaoyi/mill/issues/251 - new JButton("hello from javax") + JButton("hello from javax") val now = Date.valueOf(LocalDate.now()) println(s"Today is the date: ${now}") val person = Person.fromString("rockjam:25") diff --git a/libs/scalalib/test/resources/testrunner/doneMessageFailure/src/DoneMessageFailureFramework.scala b/libs/scalalib/test/resources/testrunner/doneMessageFailure/src/DoneMessageFailureFramework.scala index 9a53bf6a63cc..5733072bafb9 100644 --- a/libs/scalalib/test/resources/testrunner/doneMessageFailure/src/DoneMessageFailureFramework.scala +++ b/libs/scalalib/test/resources/testrunner/doneMessageFailure/src/DoneMessageFailureFramework.scala @@ -22,9 +22,9 @@ class DoneMessageFailureFramework extends Framework { eventHandler.handle(new Event { override def fullyQualifiedName(): String = "foo.bar" override def fingerprint(): Fingerprint = new Fingerprint {} - override def selector(): Selector = new TestSelector("foo.bar") + override def selector(): Selector = TestSelector("foo.bar") override def status(): Status = Status.Failure - override def throwable(): OptionalThrowable = new OptionalThrowable() + override def throwable(): OptionalThrowable = OptionalThrowable() override def duration(): Long = 0L }) Array.empty diff --git a/libs/scalalib/test/src/mill/scalalib/HelloWorldTests.scala b/libs/scalalib/test/src/mill/scalalib/HelloWorldTests.scala index 2cc28fbb00fb..46adc3701c7d 100644 --- a/libs/scalalib/test/src/mill/scalalib/HelloWorldTests.scala +++ b/libs/scalalib/test/src/mill/scalalib/HelloWorldTests.scala @@ -101,9 +101,9 @@ object HelloWorldTests extends TestSuite { def readFileFromJar(jar: JarFile, name: String): String = { Using.resource(jar.getInputStream(jar.getEntry(name))) { is => - val baos = new ByteArrayOutputStream() + val baos = ByteArrayOutputStream() os.Internals.transfer(is, baos) - new String(baos.toByteArray) + String(baos.toByteArray) } } @@ -273,7 +273,7 @@ object HelloWorldTests extends TestSuite { result.evalCount > 0 ) - Using.resource(new JarFile(result.value.path.toIO)) { jarFile => + Using.resource(JarFile(result.value.path.toIO)) { jarFile => val entries = jarFile.entries().asScala.map(_.getName).toSeq.sorted val otherFiles = Seq( diff --git a/libs/scalalib/test/src/mill/scalalib/JavaHomeTests.scala b/libs/scalalib/test/src/mill/scalalib/JavaHomeTests.scala index c323718b7a41..b397c7574647 100644 --- a/libs/scalalib/test/src/mill/scalalib/JavaHomeTests.scala +++ b/libs/scalalib/test/src/mill/scalalib/JavaHomeTests.scala @@ -43,8 +43,8 @@ object JavaHomeTests extends TestSuite { module: TestRootModule, task: Task[A] )(f: (Either[ExecResult.Failing[A], UnitTester.Result[A]], String) => R): R = { - val errStream = new ByteArrayOutputStream() - UnitTester(module, resourcePathCompile, errStream = new PrintStream(errStream)).scoped { + val errStream = ByteArrayOutputStream() + UnitTester(module, resourcePathCompile, errStream = PrintStream(errStream)).scoped { eval => val result = eval.apply(task) val stderr = errStream.toString() diff --git a/libs/scalalib/test/src/mill/scalalib/ScalaAssemblyAppendTests.scala b/libs/scalalib/test/src/mill/scalalib/ScalaAssemblyAppendTests.scala index d334c5189435..72dfb95f6d6a 100644 --- a/libs/scalalib/test/src/mill/scalalib/ScalaAssemblyAppendTests.scala +++ b/libs/scalalib/test/src/mill/scalalib/ScalaAssemblyAppendTests.scala @@ -15,7 +15,7 @@ object ScalaAssemblyAppendTests extends TestSuite with ScalaAssemblyTestUtils { UnitTester(module, resourcePath).scoped { eval => val Right(result) = eval.apply(task): @unchecked - Using.resource(new JarFile(result.value.path.toIO)) { jarFile => + Using.resource(JarFile(result.value.path.toIO)) { jarFile => assert(jarEntries(jarFile).contains("reference.conf")) val referenceContent = readFileFromJar(jarFile, "reference.conf") @@ -44,7 +44,7 @@ object ScalaAssemblyAppendTests extends TestSuite with ScalaAssemblyTestUtils { ).scoped { eval => val Right(result) = eval.apply(task): @unchecked - Using.resource(new JarFile(result.value.path.toIO)) { jarFile => + Using.resource(JarFile(result.value.path.toIO)) { jarFile => assert(jarEntries(jarFile).contains("reference.conf")) val referenceContent = readFileFromJar(jarFile, "reference.conf") @@ -70,7 +70,7 @@ object ScalaAssemblyAppendTests extends TestSuite with ScalaAssemblyTestUtils { ).scoped { eval => val Right(result) = eval.apply(task): @unchecked - Using.resource(new JarFile(result.value.path.toIO)) { jarFile => + Using.resource(JarFile(result.value.path.toIO)) { jarFile => assert(jarEntries(jarFile).contains("without-new-line.conf")) val result = readFileFromJar(jarFile, "without-new-line.conf").split('\n').toSet diff --git a/libs/scalalib/test/src/mill/scalalib/ScalaAssemblyExcludeTests.scala b/libs/scalalib/test/src/mill/scalalib/ScalaAssemblyExcludeTests.scala index d583ed6c1ca0..7ce193ebca21 100644 --- a/libs/scalalib/test/src/mill/scalalib/ScalaAssemblyExcludeTests.scala +++ b/libs/scalalib/test/src/mill/scalalib/ScalaAssemblyExcludeTests.scala @@ -18,7 +18,7 @@ object ScalaAssemblyExcludeTests extends TestSuite with ScalaAssemblyTestUtils { ) = UnitTester(module, resourcePath).scoped { eval => val Right(result) = eval.apply(task): @unchecked - Using.resource(new JarFile(result.value.path.toIO)) { jarFile => + Using.resource(JarFile(result.value.path.toIO)) { jarFile => assert(!jarEntries(jarFile).contains("reference.conf")) } } @@ -48,7 +48,7 @@ object ScalaAssemblyExcludeTests extends TestSuite with ScalaAssemblyTestUtils { resourcePath: os.Path = resourcePath ) = UnitTester(module, resourcePath).scoped { eval => val Right(result) = eval.apply(task): @unchecked - Using.resource(new JarFile(result.value.path.toIO)) { jarFile => + Using.resource(JarFile(result.value.path.toIO)) { jarFile => assert(!jarEntries(jarFile).contains("akka/http/scaladsl/model/HttpEntity.class")) assert( jarEntries(jarFile).contains("shaded/akka/http/scaladsl/model/HttpEntity.class") @@ -75,7 +75,7 @@ object ScalaAssemblyExcludeTests extends TestSuite with ScalaAssemblyTestUtils { test("withDeps") - UnitTester(HelloWorldAkkaHttpNoRules, null).scoped { eval => val Right(result) = eval.apply(HelloWorldAkkaHttpNoRules.core.assembly): @unchecked - Using.resource(new JarFile(result.value.path.toIO)) { jarFile => + Using.resource(JarFile(result.value.path.toIO)) { jarFile => assert(jarEntries(jarFile).contains("reference.conf")) val referenceContent = readFileFromJar(jarFile, "reference.conf") @@ -100,7 +100,7 @@ object ScalaAssemblyExcludeTests extends TestSuite with ScalaAssemblyTestUtils { ).scoped { eval => val Right(result) = eval.apply(HelloWorldMultiNoRules.core.assembly): @unchecked - Using.resource(new JarFile(result.value.path.toIO)) { jarFile => + Using.resource(JarFile(result.value.path.toIO)) { jarFile => assert(jarEntries(jarFile).contains("reference.conf")) val referenceContent = readFileFromJar(jarFile, "reference.conf") diff --git a/libs/scalalib/test/src/mill/scalalib/ScalaAssemblyTests.scala b/libs/scalalib/test/src/mill/scalalib/ScalaAssemblyTests.scala index 017bf1a98f97..0df67d303340 100644 --- a/libs/scalalib/test/src/mill/scalalib/ScalaAssemblyTests.scala +++ b/libs/scalalib/test/src/mill/scalalib/ScalaAssemblyTests.scala @@ -20,7 +20,7 @@ object ScalaAssemblyTests extends TestSuite with ScalaAssemblyTestUtils { os.exists(result.value.path), result.evalCount > 0 ) - val jarFile = new JarFile(result.value.path.toIO) + val jarFile = JarFile(result.value.path.toIO) try { val entries = jarEntries(jarFile) diff --git a/libs/scalalib/test/src/mill/scalalib/ScalaColorOutputTests.scala b/libs/scalalib/test/src/mill/scalalib/ScalaColorOutputTests.scala index 34cdcb9e9a01..ac2e0763a20a 100644 --- a/libs/scalalib/test/src/mill/scalalib/ScalaColorOutputTests.scala +++ b/libs/scalalib/test/src/mill/scalalib/ScalaColorOutputTests.scala @@ -24,12 +24,12 @@ object ScalaColorOutputTests extends TestSuite { def tests: Tests = Tests { test("color-output") { - val errStream = new ByteArrayOutputStream() + val errStream = ByteArrayOutputStream() UnitTester( HelloWorldColorOutput, sourceRoot = os.Path(sys.env("MILL_TEST_RESOURCE_DIR")) / "hello-world-color-output", - errStream = new PrintStream(errStream, true) + errStream = PrintStream(errStream, true) ).scoped { eval => val Left(ExecResult.Failure(msg = "Compilation failed")) = eval.apply(HelloWorldColorOutput.core.compile): @unchecked diff --git a/libs/scalalib/test/src/mill/scalalib/ScalaCompilerBridgeTests.scala b/libs/scalalib/test/src/mill/scalalib/ScalaCompilerBridgeTests.scala index a936f3e22a0b..7da9dd7fb7bb 100644 --- a/libs/scalalib/test/src/mill/scalalib/ScalaCompilerBridgeTests.scala +++ b/libs/scalalib/test/src/mill/scalalib/ScalaCompilerBridgeTests.scala @@ -57,7 +57,7 @@ object ScalaCompilerBridgeTests extends TestSuite { wrongRes0.throwable match { case _: ClassNotFoundException => case other => - throw new Exception( + throw Exception( "Unexpected exception when passing wrong compiler bridge, expected ClassNotFoundException", other ) diff --git a/libs/scalalib/test/src/mill/scalalib/TestRunnerScalatestTests.scala b/libs/scalalib/test/src/mill/scalalib/TestRunnerScalatestTests.scala index 685bbc332253..ee58a6828f12 100644 --- a/libs/scalalib/test/src/mill/scalalib/TestRunnerScalatestTests.scala +++ b/libs/scalalib/test/src/mill/scalalib/TestRunnerScalatestTests.scala @@ -25,7 +25,7 @@ object TestRunnerScalatestTests extends TestSuite { } test("testOnly") - { - scala.util.Using.resource(new TestOnlyTester(_.scalatest)) { tester => + scala.util.Using.resource(TestOnlyTester(_.scalatest)) { tester => // Run all tests re-using the same `tester` object for performance reasons // singleClass diff --git a/libs/scalalib/test/src/mill/scalalib/TestRunnerTests.scala b/libs/scalalib/test/src/mill/scalalib/TestRunnerTests.scala index 0c8cf5b9073c..8d14b3f2a511 100644 --- a/libs/scalalib/test/src/mill/scalalib/TestRunnerTests.scala +++ b/libs/scalalib/test/src/mill/scalalib/TestRunnerTests.scala @@ -12,28 +12,28 @@ object TestRunnerTests extends TestSuite { test("doneMessage") { test("failure") { - val outStream = new ByteArrayOutputStream() + val outStream = ByteArrayOutputStream() UnitTester( testrunner, - outStream = new PrintStream(outStream, true), + outStream = PrintStream(outStream, true), sourceRoot = resourcePath ).scoped { eval => val Right(UnitTester.Result(("test failure done message", Nil), _)) = eval.apply(testrunner.doneMessageFailure.testForked()): @unchecked - val stdout = new String(outStream.toByteArray) + val stdout = String(outStream.toByteArray) assert(stdout.contains("test failure done message")) } } test("success") { - val outStream = new ByteArrayOutputStream() + val outStream = ByteArrayOutputStream() UnitTester( testrunner, - outStream = new PrintStream(outStream, true), + outStream = PrintStream(outStream, true), sourceRoot = resourcePath ).scoped { eval => val Right(_) = eval(testrunner.doneMessageSuccess.testForked()): @unchecked - val stdout = new String(outStream.toByteArray) + val stdout = String(outStream.toByteArray) assert(stdout.contains("test success done message")) } } diff --git a/libs/scalalib/test/src/mill/scalalib/TestRunnerUtestTests.scala b/libs/scalalib/test/src/mill/scalalib/TestRunnerUtestTests.scala index 14b65a033a98..8bab382ee40b 100644 --- a/libs/scalalib/test/src/mill/scalalib/TestRunnerUtestTests.scala +++ b/libs/scalalib/test/src/mill/scalalib/TestRunnerUtestTests.scala @@ -28,7 +28,7 @@ object TestRunnerUtestTests extends TestSuite { expected } test("testOnly") - { - scala.util.Using.resource(new TestOnlyTester(_.utest)) { tester => + scala.util.Using.resource(TestOnlyTester(_.utest)) { tester => // suffix tester.testOnly(Seq("*arTests"), 2) // prefix diff --git a/libs/scalalib/test/src/mill/scalalib/spotless/SpotlessTests.scala b/libs/scalalib/test/src/mill/scalalib/spotless/SpotlessTests.scala index 7169317ef399..fb76ced7e21c 100644 --- a/libs/scalalib/test/src/mill/scalalib/spotless/SpotlessTests.scala +++ b/libs/scalalib/test/src/mill/scalalib/spotless/SpotlessTests.scala @@ -116,7 +116,7 @@ object SpotlessTests extends TestSuite { test("ratchet") - retry(3) { object module extends singleModule - val logStream = new ByteArrayOutputStream() + val logStream = ByteArrayOutputStream() val errStream = PrintStream(logStream, true) UnitTester(module, resources / "ratchet", errStream = errStream).scoped { eval => import module.moduleDir diff --git a/libs/scalanativelib/src/mill/scalanativelib/ScalaNativeModule.scala b/libs/scalanativelib/src/mill/scalanativelib/ScalaNativeModule.scala index f813f02ac918..2c4343131c90 100644 --- a/libs/scalanativelib/src/mill/scalanativelib/ScalaNativeModule.scala +++ b/libs/scalanativelib/src/mill/scalanativelib/ScalaNativeModule.scala @@ -150,7 +150,7 @@ trait ScalaNativeModule extends ScalaModule with ScalaNativeModuleApi { outer => } } private[scalanativelib] def withScalaNativeBridge = Task.Anon { - new ScalaNativeBridge( + ScalaNativeBridge( ScalaNativeWorkerExternalModule.scalaNativeWorker(), bridgeFullClassPath() ) @@ -385,7 +385,7 @@ trait ScalaNativeModule extends ScalaModule with ScalaNativeModuleApi { outer => } override def runner: Task[RunModule.Runner] = Task.Anon { - new NativeRunner( + NativeRunner( mainClassDefault = finalMainClassOpt(), nativeExe = nativeLink(), forkArgsDefault = forkArgs(), @@ -395,7 +395,7 @@ trait ScalaNativeModule extends ScalaModule with ScalaNativeModuleApi { outer => } def nativeRunnerOtherMain(mainClass: String): Task[RunModule.Runner] = Task.Anon { - new NativeRunner( + NativeRunner( mainClassDefault = Right(mainClass), nativeExe = nativeLinkOtherMain(mainClass)(), forkArgsDefault = forkArgs(), diff --git a/libs/scalanativelib/src/mill/scalanativelib/api/ScalaNativeApi.scala b/libs/scalanativelib/src/mill/scalanativelib/api/ScalaNativeApi.scala index bd8fa273ef55..f6de63444657 100644 --- a/libs/scalanativelib/src/mill/scalanativelib/api/ScalaNativeApi.scala +++ b/libs/scalanativelib/src/mill/scalanativelib/api/ScalaNativeApi.scala @@ -59,7 +59,7 @@ object NativeLogLevel { class NativeConfig(val config: Object) object NativeConfig { def apply(config: Object): NativeConfig = - new NativeConfig(config) + NativeConfig(config) } sealed trait BuildTarget diff --git a/libs/scalanativelib/src/mill/scalanativelib/worker/ScalaNativeWorker.scala b/libs/scalanativelib/src/mill/scalanativelib/worker/ScalaNativeWorker.scala index dc5e03b76686..39dbec15b917 100644 --- a/libs/scalanativelib/src/mill/scalanativelib/worker/ScalaNativeWorker.scala +++ b/libs/scalanativelib/src/mill/scalanativelib/worker/ScalaNativeWorker.scala @@ -17,6 +17,6 @@ private[scalanativelib] class ScalaNativeWorker(jobs: Int) private[scalanativelib] object ScalaNativeWorkerExternalModule extends mill.api.ExternalModule { def scalaNativeWorker: Worker[ScalaNativeWorker] = - Task.Worker { new ScalaNativeWorker(Task.ctx().jobs) } + Task.Worker { ScalaNativeWorker(Task.ctx().jobs) } lazy val millDiscover = Discover[this.type] } diff --git a/libs/scalanativelib/test/src/mill/scalanativelib/CompileRunTests.scala b/libs/scalanativelib/test/src/mill/scalanativelib/CompileRunTests.scala index 5e2987700a3d..1059cedbe7a8 100644 --- a/libs/scalanativelib/test/src/mill/scalanativelib/CompileRunTests.scala +++ b/libs/scalanativelib/test/src/mill/scalanativelib/CompileRunTests.scala @@ -124,7 +124,7 @@ object CompileRunTests extends TestSuite { ReleaseMode.ReleaseFast ).jar): @unchecked val jar = result.value.path - val entries = new JarFile(jar.toIO).entries().asScala.map(_.getName) + val entries = JarFile(jar.toIO).entries().asScala.map(_.getName) assert(entries.contains("hello/Main$.nir")) } } diff --git a/libs/scalanativelib/worker/0.5/src/mill/scalanativelib/worker/ScalaNativeWorkerImpl.scala b/libs/scalanativelib/worker/0.5/src/mill/scalanativelib/worker/ScalaNativeWorkerImpl.scala index d7beb642e5ca..06b0fcc9ae8b 100644 --- a/libs/scalanativelib/worker/0.5/src/mill/scalanativelib/worker/ScalaNativeWorkerImpl.scala +++ b/libs/scalanativelib/worker/0.5/src/mill/scalanativelib/worker/ScalaNativeWorkerImpl.scala @@ -143,7 +143,7 @@ class ScalaNativeWorkerImpl extends mill.scalanativelib.worker.api.ScalaNativeWo .withEnvVars(envVars) .withLogger(logger(logLevel)) - val adapter = new TestAdapter(config) + val adapter = TestAdapter(config) ( () => adapter.close(), @@ -151,7 +151,7 @@ class ScalaNativeWorkerImpl extends mill.scalanativelib.worker.api.ScalaNativeWo .loadFrameworks(List(List(frameworkName))) .flatten .headOption - .getOrElse(throw new RuntimeException("Failed to get framework")) + .getOrElse(throw RuntimeException("Failed to get framework")) ) } } diff --git a/libs/tabcomplete/test/src/mill/tabcomplete/TabCompleteTests.scala b/libs/tabcomplete/test/src/mill/tabcomplete/TabCompleteTests.scala index 0cb2ecbec89b..d1a2c17f59fc 100644 --- a/libs/tabcomplete/test/src/mill/tabcomplete/TabCompleteTests.scala +++ b/libs/tabcomplete/test/src/mill/tabcomplete/TabCompleteTests.scala @@ -33,15 +33,15 @@ object TabCompleteTests extends TestSuite { } override def tests: Tests = Tests { - val outStream = new ByteArrayOutputStream() - val errStream = new ByteArrayOutputStream() + val outStream = ByteArrayOutputStream() + val errStream = ByteArrayOutputStream() def evalComplete(s: String*) = { UnitTester( mainModule, null, - outStream = new PrintStream(outStream), - errStream = new PrintStream(errStream) + outStream = PrintStream(outStream), + errStream = PrintStream(errStream) ).scoped { tester => os.write(tester.evaluator.workspace / "file1.txt", "") os.write(tester.evaluator.workspace / "file2.txt", "") diff --git a/libs/util/src/mill/util/Inspect.scala b/libs/util/src/mill/util/Inspect.scala index 76e2d057894d..fd84dad6735c 100644 --- a/libs/util/src/mill/util/Inspect.scala +++ b/libs/util/src/mill/util/Inspect.scala @@ -246,14 +246,14 @@ private[mill] object Inspect { case Right(task) => pprintTask(task, evaluator) } val defaults = pprint.PPrinter() - val renderer = new Renderer( + val renderer = Renderer( defaults.defaultWidth, defaults.colorApplyPrefix, defaults.colorLiteral, defaults.defaultIndent ) val rendered = renderer.rec(tree, 0, 0).iter - val truncated = new Truncated(rendered, defaults.defaultWidth, defaults.defaultHeight) + val truncated = Truncated(rendered, defaults.defaultWidth, defaults.defaultHeight) (truncated ++ Iterator("\n")).mkString } val output = output0.mkString("\n") diff --git a/libs/util/src/mill/util/Jvm.scala b/libs/util/src/mill/util/Jvm.scala index 5838b75fb8c3..4eb5b74ce36e 100644 --- a/libs/util/src/mill/util/Jvm.scala +++ b/libs/util/src/mill/util/Jvm.scala @@ -197,8 +197,8 @@ object Jvm { .map(_.toString()) .orElse(sys.props.get("java.home")) .map(h => - if (isWin) new File(h, s"bin\\${toolName}.exe") - else new File(h, s"bin/${toolName}") + if (isWin) File(h, s"bin\\${toolName}.exe") + else File(h, s"bin/${toolName}") ) .filter(f => f.exists()) .fold(toolName)(_.getAbsolutePath()) @@ -304,8 +304,8 @@ object Jvm { val seen = mutable.Set.empty[os.RelPath] val _ = seen.add(os.sub / "META-INF/MANIFEST.MF") - val jarStream = new JarOutputStream( - new BufferedOutputStream(Files.newOutputStream(jar.toNIO)), + val jarStream = JarOutputStream( + BufferedOutputStream(Files.newOutputStream(jar.toNIO)), manifest.build ) @@ -314,7 +314,7 @@ object Jvm { if (includeDirs) { val _ = seen.add(os.sub / "META-INF") - val entry = new JarEntry("META-INF/") + val entry = JarEntry("META-INF/") entry.setTime(curTime) jarStream.putNextEntry(entry) jarStream.closeEntry() @@ -330,7 +330,7 @@ object Jvm { } { val _ = seen.add(mapping) val name = mapping.toString() + (if (os.isDir(file)) "/" else "") - val entry = new JarEntry(name) + val entry = JarEntry(name) entry.setTime(mTime(file)) jarStream.putNextEntry(entry) if (os.isFile(file)) jarStream.write(os.read.bytes(file)) @@ -456,7 +456,7 @@ object Jvm { coursierCacheCustomizer.fold(cache)(c => c.apply(cache)) } .pipe { cache => - ctx.fold(cache)(c => cache.withLogger(new CoursierTickerResolutionLogger(c))) + ctx.fold(cache)(c => cache.withLogger(CoursierTickerResolutionLogger(c))) } .pipe { cache => if (ctx.fold(false)(_.offline)) cache.withCachePolicies(Seq(CachePolicy.LocalOnly)) diff --git a/libs/util/src/mill/util/Retry.scala b/libs/util/src/mill/util/Retry.scala index e0af1db352d1..3ba411de913b 100644 --- a/libs/util/src/mill/util/Retry.scala +++ b/libs/util/src/mill/util/Retry.scala @@ -75,7 +75,7 @@ object Retry { private def printException(ex: Throwable): String = { val baos = new ByteArrayOutputStream - ex.printStackTrace(new PrintStream(baos, true, StandardCharsets.UTF_8)) - new String(baos.toByteArray, StandardCharsets.UTF_8) + ex.printStackTrace(PrintStream(baos, true, StandardCharsets.UTF_8)) + String(baos.toByteArray, StandardCharsets.UTF_8) } } diff --git a/libs/util/src/mill/util/TokenReaders.scala b/libs/util/src/mill/util/TokenReaders.scala index 687cc53a735d..6b7f965ed93a 100644 --- a/libs/util/src/mill/util/TokenReaders.scala +++ b/libs/util/src/mill/util/TokenReaders.scala @@ -29,14 +29,14 @@ trait TokenReaders { implicit def millArgsTokenReader: mainargs.TokensReader.ShortNamed[Args] = new TokensReader.Leftover[Args, String] { - def read(strs: Seq[String]) = Right(new Args(strs)) + def read(strs: Seq[String]) = Right(Args(strs)) def shortName = summon[TokensReader.ShortNamed[String]].shortName } implicit def millTaskTokenReader[T](using tokensReaderOfT: TokensReader.ShortNamed[T] ): TokensReader[Task[T]] = tokensReaderOfT match { - case t: TokensReader.Simple[_] => new SimpleTaskTokenReader[T](t) - case t: TokensReader.Leftover[_, _] => new LeftoverTaskTokenReader[T](t) + case t: TokensReader.Simple[_] => SimpleTaskTokenReader[T](t) + case t: TokensReader.Leftover[_, _] => LeftoverTaskTokenReader[T](t) } } diff --git a/libs/util/src/mill/util/Version.scala b/libs/util/src/mill/util/Version.scala index 6307d9388c30..e7e99aa405cc 100644 --- a/libs/util/src/mill/util/Version.scala +++ b/libs/util/src/mill/util/Version.scala @@ -28,9 +28,9 @@ class Version private ( def isAtLeast(other: Version)(using ordering: Ordering[Version]): Boolean = ordering.compare(this, other) >= 0 - def asMaven: MavenVersion = new MavenVersion(this) - def asOsgiVersion: OsgiVersion = new OsgiVersion(this) - def asIgnoreQualifierVersion: IgnoreQualifierVersion = new IgnoreQualifierVersion(this) + def asMaven: MavenVersion = MavenVersion(this) + def asOsgiVersion: OsgiVersion = OsgiVersion(this) + def asIgnoreQualifierVersion: IgnoreQualifierVersion = IgnoreQualifierVersion(this) } final class MavenVersion(val underlying: Version) extends AnyVal { @@ -130,7 +130,7 @@ object Version { def parse(version: String): Version = { version match { case Pattern(major, _, minor, _, micro, _, qualifierSep, qualifier) => - new Version( + Version( major.toInt, Option(minor).map(_.toInt), Option(micro).map(_.toInt), diff --git a/libs/util/src/mill/util/VisualizeModule.scala b/libs/util/src/mill/util/VisualizeModule.scala index db6886deb8f9..62b17e36bf5c 100644 --- a/libs/util/src/mill/util/VisualizeModule.scala +++ b/libs/util/src/mill/util/VisualizeModule.scala @@ -103,14 +103,14 @@ object VisualizeModule extends ExternalModule { LinkedBlockingQueue[Result[Seq[PathRef]]] )] = mill.api.Task.Worker { val in = - new LinkedBlockingQueue[( + LinkedBlockingQueue[( scala.Seq[Task.Named[Any]], scala.Seq[Task.Named[Any]], MultiBiMap[Task.Named[Any], Task[?]], mill.api.Plan, os.Path )]() - val out = new LinkedBlockingQueue[Result[Seq[PathRef]]]() + val out = LinkedBlockingQueue[Result[Seq[PathRef]]]() val visualizeThread = new java.lang.Thread(() => while (true) { val res = Result.Success { diff --git a/libs/util/test/src/mill/util/JvmTests.scala b/libs/util/test/src/mill/util/JvmTests.scala index d5b250aaadcc..09919be468e6 100644 --- a/libs/util/test/src/mill/util/JvmTests.scala +++ b/libs/util/test/src/mill/util/JvmTests.scala @@ -22,7 +22,7 @@ object JvmTests extends TestSuite { Jvm.createClasspathPassingJar(aJar, Seq(dep1, dep2)) assert(os.exists(aJar)) - val jar = new JarFile(aJar.toIO) + val jar = JarFile(aJar.toIO) assert(jar.getManifest().getMainAttributes().containsKey(Attributes.Name.CLASS_PATH)) assert(jar.getManifest().getMainAttributes().getValue(Attributes.Name.CLASS_PATH) == Seq(dep1, dep2).map(_.toURL.toExternalForm()).mkString(" ")) diff --git a/libs/util/test/src/mill/util/MainModuleTests.scala b/libs/util/test/src/mill/util/MainModuleTests.scala index 4fc698ae1639..db19774cf063 100644 --- a/libs/util/test/src/mill/util/MainModuleTests.scala +++ b/libs/util/test/src/mill/util/MainModuleTests.scala @@ -115,7 +115,7 @@ object MainModuleTests extends TestSuite { trait Cleanable extends Module { def theWorker = Task.Worker { - new TestWorker("shared", workers) + TestWorker("shared", workers) } } @@ -124,7 +124,7 @@ object MainModuleTests extends TestSuite { } object bar extends Cleanable { override def theWorker = Task.Worker { - new TestWorker("bar", workers) + TestWorker("bar", workers) } } object bazz extends Cross[Bazz]("1", "2", "3") @@ -237,13 +237,13 @@ object MainModuleTests extends TestSuite { } test("single") { - val outStream = new ByteArrayOutputStream() - val errStream = new ByteArrayOutputStream() + val outStream = ByteArrayOutputStream() + val errStream = ByteArrayOutputStream() UnitTester( mainModule, null, - outStream = new PrintStream(outStream, true), - errStream = new PrintStream(errStream, true) + outStream = PrintStream(outStream, true), + errStream = PrintStream(errStream, true) ).scoped { evaluator => val results = @@ -270,13 +270,13 @@ object MainModuleTests extends TestSuite { } } test("multi") { - val outStream = new ByteArrayOutputStream() - val errStream = new ByteArrayOutputStream() + val outStream = ByteArrayOutputStream() + val errStream = ByteArrayOutputStream() UnitTester( mainModule, null, - outStream = new PrintStream(outStream, true), - errStream = new PrintStream(errStream, true) + outStream = PrintStream(outStream, true), + errStream = PrintStream(errStream, true) ).scoped { evaluator => val results = @@ -317,8 +317,8 @@ object MainModuleTests extends TestSuite { UnitTester( mainModule, null, - outStream = new PrintStream(OutputStream.nullOutputStream(), true), - errStream = new PrintStream(OutputStream.nullOutputStream(), true) + outStream = PrintStream(OutputStream.nullOutputStream(), true), + errStream = PrintStream(OutputStream.nullOutputStream(), true) ).scoped { evaluator => val Left(ExecResult.Failure(msg = failureMsg)) = @@ -340,8 +340,8 @@ object MainModuleTests extends TestSuite { UnitTester( mainModule, null, - outStream = new PrintStream(OutputStream.nullOutputStream(), true), - errStream = new PrintStream(OutputStream.nullOutputStream(), true) + outStream = PrintStream(OutputStream.nullOutputStream(), true), + errStream = PrintStream(OutputStream.nullOutputStream(), true) ).scoped { evaluator => val Right(result) = evaluator.apply("show", "helloWorker"): @unchecked @@ -487,7 +487,7 @@ object MainModuleTests extends TestSuite { test("cleanWorker") { test("all") { val workers = new mutable.HashSet[TestWorker] - val workerModule = new WorkerModule(workers) + val workerModule = WorkerModule(workers) UnitTester(workerModule, null).scoped { ev => val r1 = ev.evaluator.execute(Seq(workerModule.all)).executionResults @@ -502,7 +502,7 @@ object MainModuleTests extends TestSuite { test("single-task") { val workers = new mutable.HashSet[TestWorker] - val workerModule = new WorkerModule(workers) + val workerModule = WorkerModule(workers) UnitTester(workerModule, null).scoped { ev => val r1 = ev.evaluator.execute(Seq(workerModule.all)).executionResults @@ -534,7 +534,7 @@ object MainModuleTests extends TestSuite { test("single-task via rm") { val workers = new mutable.HashSet[TestWorker] - val workerModule = new WorkerModule(workers) + val workerModule = WorkerModule(workers) UnitTester(workerModule, null).scoped { ev => ev.evaluator.execute(Seq(workerModule.foo.theWorker)).executionResults @@ -583,7 +583,7 @@ object MainModuleTests extends TestSuite { } test("single-module") { val workers = new mutable.HashSet[TestWorker] - val workerModule = new WorkerModule(workers) + val workerModule = WorkerModule(workers) UnitTester(workerModule, null).scoped { ev => val r1 = ev.evaluator.execute(Seq(workerModule.all)).executionResults diff --git a/libs/util/test/src/mill/util/RetryTests.scala b/libs/util/test/src/mill/util/RetryTests.scala index 718b139c6d8b..a8f84f51da54 100644 --- a/libs/util/test/src/mill/util/RetryTests.scala +++ b/libs/util/test/src/mill/util/RetryTests.scala @@ -10,7 +10,7 @@ object RetryTests extends TestSuite { try { Retry(logger = Retry.printStreamLogger(System.err)) { count += 1 - throw new Exception("boom") + throw Exception("boom") } } catch { case ex => @@ -23,7 +23,7 @@ object RetryTests extends TestSuite { var count = 0 Retry(logger = Retry.printStreamLogger(System.err)) { count += 1 - if (count < 3) throw new Exception("boom") + if (count < 3) throw Exception("boom") } assert(count == 3) } @@ -38,8 +38,8 @@ object RetryTests extends TestSuite { } ) { count += 1 - if (count < 3) throw new RuntimeException("boom") - else throw new Exception("foo") + if (count < 3) throw RuntimeException("boom") + else throw Exception("foo") } } catch { case e: Exception => diff --git a/runner/bsp/src/mill/bsp/BSP.scala b/runner/bsp/src/mill/bsp/BSP.scala index 4cfeb2dd9bba..b0bbdecc2457 100644 --- a/runner/bsp/src/mill/bsp/BSP.scala +++ b/runner/bsp/src/mill/bsp/BSP.scala @@ -35,7 +35,7 @@ object BSP { private def bspConnectionJson(jobs: Int, debug: Boolean): String = { val millPath = sys.env.get("MILL_EXECUTABLE_PATH") - .getOrElse(throw new IllegalStateException("Env 'MILL_EXECUTABLE_PATH' not set")) + .getOrElse(throw IllegalStateException("Env 'MILL_EXECUTABLE_PATH' not set")) upickle.write( BspConfigJson( diff --git a/runner/bsp/worker/src/mill/bsp/worker/BspCompileProblemReporter.scala b/runner/bsp/worker/src/mill/bsp/worker/BspCompileProblemReporter.scala index a6416070af3d..0b20eb857c2b 100644 --- a/runner/bsp/worker/src/mill/bsp/worker/BspCompileProblemReporter.scala +++ b/runner/bsp/worker/src/mill/bsp/worker/BspCompileProblemReporter.scala @@ -56,7 +56,7 @@ private class BspCompileProblemReporter( // are sent at least once, even when there are none map.getOrElseUpdate( textDocument, - new Details(new java.util.ArrayList, new mutable.HashSet, true) + Details(new java.util.ArrayList, new mutable.HashSet, true) ) def add(textDocument: TextDocumentIdentifier, diagnostic: Diagnostic): Boolean = details(textDocument).add(diagnostic) @@ -92,14 +92,14 @@ private class BspCompileProblemReporter( case mill.api.daemon.internal.Warn => MessageType.WARNING case mill.api.daemon.internal.Info => MessageType.INFO } - val msgParam = new LogMessageParams(messagesType, problem.message).tap { it => + val msgParam = LogMessageParams(messagesType, problem.message).tap { it => it.setTask(taskId) } client.onBuildLogMessage(msgParam) case Some(f) => val diagnostic = toDiagnostic(problem) - val textDocument = new TextDocumentIdentifier( + val textDocument = TextDocumentIdentifier( // The extra step invoking `toPath` results in a nicer URI starting with `file:///` f.toPath.toUri.toString ) @@ -165,7 +165,7 @@ private class BspCompileProblemReporter( override def fileVisited(file: java.nio.file.Path): Unit = { val uri = file.toUri.toString - val textDocument = new TextDocumentIdentifier(uri) + val textDocument = TextDocumentIdentifier(uri) val (diagnostics0, hasNewDiagnostics) = diagnostics.getAll(textDocument) if (hasNewDiagnostics) sendBuildPublishDiagnostics(textDocument, diagnostics0, reset = true) @@ -176,9 +176,9 @@ private class BspCompileProblemReporter( } override def start(): Unit = { - val taskStartParams = new TaskStartParams(taskId).tap { it => + val taskStartParams = TaskStartParams(taskId).tap { it => it.setEventTime(System.currentTimeMillis()) - it.setData(new CompileTask(targetId)) + it.setData(CompileTask(targetId)) it.setDataKind(TaskStartDataKind.COMPILE_TASK) it.setMessage(s"Compiling target ${targetDisplayName}") } @@ -186,9 +186,9 @@ private class BspCompileProblemReporter( } override def notifyProgress(progress: Long, total: Long): Unit = { - val params = new TaskProgressParams(taskId).tap { it => + val params = TaskProgressParams(taskId).tap { it => it.setEventTime(System.currentTimeMillis()) - it.setData(new CompileTask(targetId)) + it.setData(CompileTask(targetId)) it.setDataKind("compile-progress") it.setMessage(s"Compiling target ${targetDisplayName} (${progress * 100 / total}%)") // Not a percentage, but the # of units done, @@ -201,11 +201,11 @@ private class BspCompileProblemReporter( override def finish(): Unit = { val taskFinishParams = - new TaskFinishParams(taskId, if (errors > 0) StatusCode.ERROR else StatusCode.OK).tap { it => + TaskFinishParams(taskId, if (errors > 0) StatusCode.ERROR else StatusCode.OK).tap { it => it.setEventTime(System.currentTimeMillis()) it.setMessage(s"Compiled ${targetDisplayName}") it.setDataKind(TaskFinishDataKind.COMPILE_REPORT) - val compileReport = new CompileReport(targetId, errors, warnings).tap { it => + val compileReport = CompileReport(targetId, errors, warnings).tap { it => compilationOriginId.foreach(id => it.setOriginId(id)) } it.setData(compileReport) diff --git a/runner/bsp/worker/src/mill/bsp/worker/BspEvaluators.scala b/runner/bsp/worker/src/mill/bsp/worker/BspEvaluators.scala index 60437e5ac8e9..deb93efe79bb 100644 --- a/runner/bsp/worker/src/mill/bsp/worker/BspEvaluators.scala +++ b/runner/bsp/worker/src/mill/bsp/worker/BspEvaluators.scala @@ -89,7 +89,7 @@ class BspEvaluators( false } } - } yield (new BuildTargetIdentifier(uri), (bspModule, eval)) + } yield (BuildTargetIdentifier(uri), (bspModule, eval)) val nonScriptSources = evaluators.flatMap { ev => val bspSourceTasks: Seq[TaskApi[(sources: Seq[Path], generatedSources: Seq[Path])]] = @@ -149,9 +149,9 @@ class BspEvaluators( // Create IgnoreNode from bspScriptIgnore patterns val ignoreRules = bspScriptIgnore .filter(l => !l.startsWith("#")) - .map(pattern => (pattern, new FastIgnoreRule(pattern))) + .map(pattern => (pattern, FastIgnoreRule(pattern))) - val ignoreNode = new IgnoreNode(ignoreRules.map(_._2).asJava) + val ignoreNode = IgnoreNode(ignoreRules.map(_._2).asJava) // Extract directory prefixes from negation patterns (patterns starting with !) // These directories need to be walked even if they're ignored, because they contain @@ -223,7 +223,7 @@ class BspEvaluators( result.flatMap { case (scriptPath: java.nio.file.Path, mill.api.Result.Success(module: BspModuleApi)) => - Some((new BuildTargetIdentifier(Utils.sanitizeUri(scriptPath)), (module, eval))) + Some((BuildTargetIdentifier(Utils.sanitizeUri(scriptPath)), (module, eval))) case (scriptPath: java.nio.file.Path, f: mill.api.Result.Failure) => println(s"Failed to instantiate script module for BSP: $scriptPath failed with ${f.error}") None diff --git a/runner/bsp/worker/src/mill/bsp/worker/BspTestReporter.scala b/runner/bsp/worker/src/mill/bsp/worker/BspTestReporter.scala index 351e38471d2f..cfc1420eb2e9 100644 --- a/runner/bsp/worker/src/mill/bsp/worker/BspTestReporter.scala +++ b/runner/bsp/worker/src/mill/bsp/worker/BspTestReporter.scala @@ -51,10 +51,10 @@ private class BspTestReporter( var totalTime: Long = 0 override def logStart(event: Event): Unit = { - val taskStartParams = new TaskStartParams(taskId) + val taskStartParams = TaskStartParams(taskId) taskStartParams.setEventTime(System.currentTimeMillis()) taskStartParams.setDataKind(TaskStartDataKind.TEST_START) - taskStartParams.setData(new TestStart(getDisplayName(event))) + taskStartParams.setData(TestStart(getDisplayName(event))) taskStartParams.setMessage("Starting running: " + getDisplayName(event)) client.onBuildTaskStart(taskStartParams) } @@ -73,7 +73,7 @@ private class BspTestReporter( override def logFinish(event: Event): Unit = { totalTime += event.duration() - val taskFinishParams = new TaskFinishParams( + val taskFinishParams = TaskFinishParams( taskId, event.status() match { case sbt.testing.Status.Canceled => StatusCode.CANCELLED @@ -107,7 +107,7 @@ private class BspTestReporter( taskFinishParams.setDataKind(TaskFinishDataKind.TEST_FINISH) taskFinishParams.setData({ - val testFinish = new TestFinish(getDisplayName(event), status) + val testFinish = TestFinish(getDisplayName(event), status) if (event.throwable.isDefined) testFinish.setMessage(throwableToString(event.throwable().get())) testFinish @@ -118,7 +118,7 @@ private class BspTestReporter( private def throwableToString(t: Throwable): String = { val sw = new StringWriter - val pw = new PrintWriter(sw) + val pw = PrintWriter(sw) t.printStackTrace(pw) sw.toString } @@ -126,7 +126,7 @@ private class BspTestReporter( // Compute the test report data structure that will go into // the task finish notification after all tests are ran. def getTestReport: TestReport = { - val report = new TestReport(targetId, passed, failed, ignored, cancelled, skipped) + val report = TestReport(targetId, passed, failed, ignored, cancelled, skipped) report.setTime(totalTime) report } diff --git a/runner/bsp/worker/src/mill/bsp/worker/BspWorkerImpl.scala b/runner/bsp/worker/src/mill/bsp/worker/BspWorkerImpl.scala index 270dd586553e..e2fff5259e5c 100644 --- a/runner/bsp/worker/src/mill/bsp/worker/BspWorkerImpl.scala +++ b/runner/bsp/worker/src/mill/bsp/worker/BspWorkerImpl.scala @@ -113,7 +113,7 @@ object BspWorkerImpl { val executorCount = executorCounter.incrementAndGet() val counter = new AtomicInteger def newThread(runnable: Runnable): Thread = { - val t = new Thread( + val t = Thread( runnable, s"mill-bsp-jsonrpc-$executorCount-thread-${counter.incrementAndGet()}" ) diff --git a/runner/bsp/worker/src/mill/bsp/worker/MillBspLogger.scala b/runner/bsp/worker/src/mill/bsp/worker/MillBspLogger.scala index faaee3e4b5a9..3bdb7c56c63c 100644 --- a/runner/bsp/worker/src/mill/bsp/worker/MillBspLogger.scala +++ b/runner/bsp/worker/src/mill/bsp/worker/MillBspLogger.scala @@ -25,7 +25,7 @@ private class MillBspLogger(client: BuildClient, taskId: Int, logger: Logger) try { val progressString = s.split(" ")(0) val progress = progressString.substring(1, progressString.length - 1).split("/") - val params = new TaskProgressParams(new TaskId(taskId.toString)) + val params = TaskProgressParams(TaskId(taskId.toString)) params.setEventTime(System.currentTimeMillis()) params.setMessage(s) params.setUnit(s.split(" ")(1)) diff --git a/runner/bsp/worker/src/mill/bsp/worker/MillBuildServer.scala b/runner/bsp/worker/src/mill/bsp/worker/MillBuildServer.scala index 47d76865618a..11767adeaf5c 100644 --- a/runner/bsp/worker/src/mill/bsp/worker/MillBuildServer.scala +++ b/runner/bsp/worker/src/mill/bsp/worker/MillBuildServer.scala @@ -141,7 +141,7 @@ private class MillBuildServer( evaluators // update the evaluator promise for the thread processing requests to pick it up - val evaluators0 = new BspEvaluators( + val evaluators0 = BspEvaluators( topLevelProjectRoot, updatedEvaluators, s => baseLogger.debug(s()), @@ -231,8 +231,8 @@ private class MillBuildServer( capabilities.setBuildTargetChangedProvider(true) capabilities.setCanReload(canReload) - capabilities.setCompileProvider(new CompileProvider(supportedLangs)) - capabilities.setDebugProvider(new DebugProvider(Seq().asJava)) + capabilities.setCompileProvider(CompileProvider(supportedLangs)) + capabilities.setDebugProvider(DebugProvider(Seq().asJava)) capabilities.setDependencyModulesProvider(true) capabilities.setDependencySourcesProvider(true) capabilities.setInverseSourcesProvider(true) @@ -241,8 +241,8 @@ private class MillBuildServer( capabilities.setJvmTestEnvironmentProvider(true) capabilities.setOutputPathsProvider(true) capabilities.setResourcesProvider(true) - capabilities.setRunProvider(new RunProvider(supportedLangs)) - capabilities.setTestProvider(new TestProvider(supportedLangs)) + capabilities.setRunProvider(RunProvider(supportedLangs)) + capabilities.setTestProvider(TestProvider(supportedLangs)) def readVersion(json: JsonObject, name: String): Option[String] = if (json.has(name)) { @@ -276,7 +276,7 @@ private class MillBuildServer( clientWantsSemanticDb = clientWantsSemanticDb, enableJvmCompileClasspathProvider = enableJvmCompileClasspathProvider ) - new InitializeBuildResult(serverName, serverVersion, bspVersion, capabilities) + InitializeBuildResult(serverName, serverVersion, bspVersion, capabilities) } override def onBuildInitialized(): Unit = { @@ -338,7 +338,7 @@ private class MillBuildServer( makeBuildTarget(id, depsIds, bt, data) } { (targets, state) => - new WorkspaceBuildTargetsResult( + WorkspaceBuildTargetsResult( (targets.asScala ++ state.syntheticRootBspBuildTarget.map(_.target)) .sortBy(_.getId.getUri) .asJava @@ -362,7 +362,7 @@ private class MillBuildServer( override def buildTargetSources(sourcesParams: SourcesParams) : CompletableFuture[SourcesResult] = { - def sourceItem(source: os.Path, generated: Boolean) = new SourceItem( + def sourceItem(source: os.Path, generated: Boolean) = SourceItem( sanitizeUri(source.toNIO), if (source.toIO.isFile) SourceItemKind.FILE else SourceItemKind.DIRECTORY, generated @@ -375,7 +375,7 @@ private class MillBuildServer( s"Getting sources of ${sourcesParams.getTargets.asScala.map(_.getUri).mkString(", ")}", originId = "" ) { - case (_, _, id, _, result) => new SourcesItem( + case (_, _, id, _, result) => SourcesItem( id, ( result.sources.map(p => sourceItem(os.Path(p), false)) ++ @@ -383,7 +383,7 @@ private class MillBuildServer( ).asJava ) } { (sourceItems, state) => - new SourcesResult( + SourcesResult( (sourceItems.asScala ++ state.syntheticRootBspBuildTarget.map(_.synthSources)) .sortBy(_.getTarget.getUri) .asJava @@ -417,7 +417,7 @@ private class MillBuildServer( } .flatten - new InverseSourcesResult(ids.asJava) + InverseSourcesResult(ids.asJava) } } @@ -445,10 +445,10 @@ private class MillBuildServer( ) { case (_, _, id, _, result) => val cp = (result.resolvedDepsSources ++ result.unmanagedClasspath).map(sanitizeUri) - new DependencySourcesItem(id, cp.asJava) + DependencySourcesItem(id, cp.asJava) } { values => - new DependencySourcesResult(values.asScala.sortBy(_.getTarget.getUri).asJava) + DependencySourcesResult(values.asScala.sortBy(_.getTarget.getUri).asJava) } /** @@ -470,16 +470,16 @@ private class MillBuildServer( case (_, _, id, _, result) => val deps = result.mvnDeps.collect { case (org, repr, version) if org != "mill-internal" => - new DependencyModule(repr, version) + DependencyModule(repr, version) } val unmanaged = result.unmanagedClasspath.map { dep => - new DependencyModule(s"unmanaged-${dep.getFileName}", "") + DependencyModule(s"unmanaged-${dep.getFileName}", "") } - new DependencyModulesItem(id, (deps ++ unmanaged).asJava) + DependencyModulesItem(id, (deps ++ unmanaged).asJava) } { values => - new DependencyModulesResult(values.asScala.sortBy(_.getTarget.getUri).asJava) + DependencyModulesResult(values.asScala.sortBy(_.getTarget.getUri).asJava) } override def buildTargetResources(p: ResourcesParams): CompletableFuture[ResourcesResult] = @@ -492,10 +492,10 @@ private class MillBuildServer( case (_, _, id, _, resources) => val resourcesUrls = resources.map(os.Path(_)).filter(os.exists).map(p => sanitizeUri(p.toNIO)) - new ResourcesItem(id, resourcesUrls.asJava) + ResourcesItem(id, resourcesUrls.asJava) } { values => - new ResourcesResult(values.asScala.sortBy(_.getTarget.getUri).asJava) + ResourcesResult(values.asScala.sortBy(_.getTarget.getUri).asJava) } // TODO: if the client wants to give compilation arguments and the module @@ -549,7 +549,7 @@ private class MillBuildServer( ) } .toSeq - val compileResult = new CompileResult(Utils.getStatusCode(result)) + val compileResult = CompileResult(Utils.getStatusCode(result)) compileResult.setOriginId(p.getOriginId) compileResult // TODO: See in what form IntelliJ expects data about products of compilation in order to set data field } @@ -561,7 +561,7 @@ private class MillBuildServer( synthTarget <- state.syntheticRootBspBuildTarget if params.getTargets.contains(synthTarget.id) baseDir <- synthTarget.bt.baseDirectory - } yield new OutputPathsItem( + } yield OutputPathsItem( synthTarget.id, outputPaths(os.Path(baseDir), topLevelProjectRoot).asJava ) @@ -575,7 +575,7 @@ private class MillBuildServer( topLevelProjectRoot ) - new OutputPathsItem(target, items.asJava) + OutputPathsItem(target, items.asJava) } new OutputPathsResult((items ++ synthOutpaths).sortBy(_.getTarget.getUri).asJava) @@ -598,8 +598,8 @@ private class MillBuildServer( Utils.getBspLoggedReporterPool(runParams.getOriginId, state.bspIdByModule, client) ) val response = runResult.transitiveResultsApi(runTask) match { - case r if r.asSuccess.isDefined => new RunResult(StatusCode.OK) - case _ => new RunResult(StatusCode.ERROR) + case r if r.asSuccess.isDefined => RunResult(StatusCode.OK) + case _ => RunResult(StatusCode.ERROR) } params.getOriginId match { case Some(id) => response.setOriginId(id) @@ -642,18 +642,18 @@ private class MillBuildServer( val testTask = testModule.testLocal(argsMap(targetId.getUri)*) // notifying the client that the testing of this build target started - val taskStartParams = new TaskStartParams(new TaskId(testTask.hashCode().toString)) + val taskStartParams = TaskStartParams(TaskId(testTask.hashCode().toString)) taskStartParams.setEventTime(System.currentTimeMillis()) taskStartParams.setMessage("Testing target: " + targetId) taskStartParams.setDataKind(TaskStartDataKind.TEST_TASK) - taskStartParams.setData(new TestTask(targetId)) + taskStartParams.setData(TestTask(targetId)) client.onBuildTaskStart(taskStartParams) val testReporter = - new BspTestReporter( + BspTestReporter( client, targetId, - new TaskId(testTask.hashCode().toString) + TaskId(testTask.hashCode().toString) ) val results = evaluate( @@ -672,7 +672,7 @@ private class MillBuildServer( // Notifying the client that the testing of this build target ended val taskFinishParams = - new TaskFinishParams(new TaskId(testTask.hashCode().toString), statusCode) + TaskFinishParams(TaskId(testTask.hashCode().toString), statusCode) taskFinishParams.setEventTime(System.currentTimeMillis()) taskFinishParams.setMessage( s"Finished testing target${testModule.bspBuildTarget.displayName}" @@ -691,7 +691,7 @@ private class MillBuildServer( } } - val testResult = new TestResult(overallStatusCode) + val testResult = TestResult(overallStatusCode) params.getOriginId match { case None => testResult case Some(id) => @@ -743,7 +743,7 @@ private class MillBuildServer( } } - new CleanCacheResult(cleaned).tap { it => + CleanCacheResult(cleaned).tap { it => it.setMessage(msg) } } @@ -752,7 +752,7 @@ private class MillBuildServer( : CompletableFuture[DebugSessionAddress] = handlerEvaluators() { (state, _) => debugParams.setTargets(state.filterNonSynthetic(debugParams.getTargets)) - throw new NotImplementedError("debugSessionStart endpoint is not implemented") + throw NotImplementedError("debugSessionStart endpoint is not implemented") } /** @@ -831,7 +831,7 @@ private class MillBuildServer( def logError(id: BuildTargetIdentifier, errorMsg: String): Unit = { val msg = s"Request '$prefix' failed for ${id.getUri}: ${errorMsg}" logger.error(msg) - client.onBuildLogMessage(new LogMessageParams(MessageType.ERROR, msg)) + client.onBuildLogMessage(LogMessageParams(MessageType.ERROR, msg)) } resultsById.flatMap { @@ -849,7 +849,7 @@ private class MillBuildServer( } } - private val queue = new LinkedBlockingQueue[(BspEvaluators => Unit, Logger, String)] + private val queue = LinkedBlockingQueue[(BspEvaluators => Unit, Logger, String)] private var stopped = false private val evaluatorRequestsThread: Thread = // Make this a daemon thread so if the main thread exits this doesn't keep the process alive @@ -906,7 +906,7 @@ private class MillBuildServer( if (checkInitialized && !initialized) { val msg = s"Can not respond to $prefix request before receiving the `initialize` request." logger.error(msg) - future.completeExceptionally(new Exception(msg)) + future.completeExceptionally(Exception(msg)) } else { val proceed: BspEvaluators => Unit = { evaluators => if (future.isCancelled()) @@ -977,10 +977,10 @@ private class MillBuildServer( protected def createLogger()(using enclosing: sourcecode.Enclosing): Logger = { val requestCount0 = requestCount.incrementAndGet() val name = enclosingRequestName - new MillBspLogger( + MillBspLogger( client, requestCount0, - new PrefixLogger( + PrefixLogger( new ProxyLogger(baseLogger) { override def logKey: Seq[String] = { val logKey0 = super.logKey @@ -1020,7 +1020,7 @@ private class MillBuildServer( case Some(error) => logger.warn(error) logger.info("Failed") - client.onBuildLogMessage(new LogMessageParams(MessageType.WARNING, error)) + client.onBuildLogMessage(LogMessageParams(MessageType.WARNING, error)) } result.executionResults } diff --git a/runner/bsp/worker/src/mill/bsp/worker/MillJavaBuildServer.scala b/runner/bsp/worker/src/mill/bsp/worker/MillJavaBuildServer.scala index a96f39da832a..8f6e82508ac7 100644 --- a/runner/bsp/worker/src/mill/bsp/worker/MillJavaBuildServer.scala +++ b/runner/bsp/worker/src/mill/bsp/worker/MillJavaBuildServer.scala @@ -32,7 +32,7 @@ private trait MillJavaBuildServer extends JavaBuildServer { this: MillBuildServe ) { case (ev, _, id, _, f) => val res = f(ev) - new JavacOptionsItem( + JavacOptionsItem( id, res.javacOptions.asJava, res.classpath.asJava, @@ -40,6 +40,6 @@ private trait MillJavaBuildServer extends JavaBuildServer { this: MillBuildServe ) } { - new JavacOptionsResult(_) + JavacOptionsResult(_) } } diff --git a/runner/bsp/worker/src/mill/bsp/worker/MillJvmBuildServer.scala b/runner/bsp/worker/src/mill/bsp/worker/MillJvmBuildServer.scala index d214d7f215ca..653887115db3 100644 --- a/runner/bsp/worker/src/mill/bsp/worker/MillJvmBuildServer.scala +++ b/runner/bsp/worker/src/mill/bsp/worker/MillJvmBuildServer.scala @@ -25,7 +25,7 @@ private trait MillJvmBuildServer extends JvmBuildServer { this: MillBuildServer : CompletableFuture[JvmRunEnvironmentResult] = { jvmRunEnvironmentFor( params.getTargets.asScala, - new JvmRunEnvironmentResult(_), + JvmRunEnvironmentResult(_), params.getOriginId ) } @@ -34,7 +34,7 @@ private trait MillJvmBuildServer extends JvmBuildServer { this: MillBuildServer : CompletableFuture[JvmTestEnvironmentResult] = { jvmTestEnvironmentFor( params.getTargets.asScala, - new JvmTestEnvironmentResult(_), + JvmTestEnvironmentResult(_), params.getOriginId ) } @@ -68,14 +68,14 @@ private trait MillJvmBuildServer extends JvmBuildServer { this: MillBuildServer ) => val fullMainArgs: List[String] = List(testEnvVars.testRunnerClasspathArg, testEnvVars.argsFile) - val item = new JvmEnvironmentItem( + val item = JvmEnvironmentItem( id, testEnvVars.classpath.map(sanitizeUri).asJava, forkArgs.asJava, forkWorkingDir.toString(), forkEnv.asJava ) - item.setMainClasses(List(testEnvVars.mainClass).map(new JvmMainClass( + item.setMainClasses(List(testEnvVars.mainClass).map(JvmMainClass( _, fullMainArgs.asJava )).asJava) @@ -104,7 +104,7 @@ private trait MillJvmBuildServer extends JvmBuildServer { this: MillBuildServer res ) => val classpath = res.runClasspath.map(sanitizeUri) - val item = new JvmEnvironmentItem( + val item = JvmEnvironmentItem( id, classpath.asJava, res.forkArgs.asJava, @@ -113,7 +113,7 @@ private trait MillJvmBuildServer extends JvmBuildServer { this: MillBuildServer ) val classes = res.mainClass.toList ++ res.localMainClasses - item.setMainClasses(classes.map(new JvmMainClass(_, Nil.asJava)).asJava) + item.setMainClasses(classes.map(JvmMainClass(_, Nil.asJava)).asJava) item } { agg @@ -132,8 +132,8 @@ private trait MillJvmBuildServer extends JvmBuildServer { this: MillBuildServer originId = "" ) { case (ev, _, id, _, compileClasspath) => - new JvmCompileClasspathItem(id, compileClasspath(ev).asJava) + JvmCompileClasspathItem(id, compileClasspath(ev).asJava) } { - new JvmCompileClasspathResult(_) + JvmCompileClasspathResult(_) } } diff --git a/runner/bsp/worker/src/mill/bsp/worker/MillScalaBuildServer.scala b/runner/bsp/worker/src/mill/bsp/worker/MillScalaBuildServer.scala index ef2e0bdaaae0..cbd0a3db17d7 100644 --- a/runner/bsp/worker/src/mill/bsp/worker/MillScalaBuildServer.scala +++ b/runner/bsp/worker/src/mill/bsp/worker/MillScalaBuildServer.scala @@ -43,7 +43,7 @@ private trait MillScalaBuildServer extends ScalaBuildServer { this: MillBuildSer _, (allScalacOptions, compileClasspath, classesPathTask) ) => - new ScalacOptionsItem( + ScalacOptionsItem( id, allScalacOptions.asJava, compileClasspath(ev).asJava, @@ -51,7 +51,7 @@ private trait MillScalaBuildServer extends ScalaBuildServer { this: MillBuildSer ) } { values => - new ScalacOptionsResult(values.asScala.sortBy(_.getTarget.getUri).asJava) + ScalacOptionsResult(values.asScala.sortBy(_.getTarget.getUri).asJava) } override def buildTargetScalaMainClasses(p: ScalaMainClassesParams) @@ -67,14 +67,14 @@ private trait MillScalaBuildServer extends ScalaBuildServer { this: MillBuildSer val mainClasses = res.classes // val mainMain = m.mainClass().orElse(if(mainClasses.size == 1) mainClasses.headOption else None) val items = mainClasses.map { mc => - val scalaMc = new ScalaMainClass(mc, Seq().asJava, res.forkArgs.asJava) + val scalaMc = ScalaMainClass(mc, Seq().asJava, res.forkArgs.asJava) scalaMc.setEnvironmentVariables(res.forkEnv.map(e => s"${e._1}=${e._2}").toSeq.asJava) scalaMc } - new ScalaMainClassesItem(id, items.asJava) + ScalaMainClassesItem(id, items.asJava) } { - new ScalaMainClassesResult(_) + ScalaMainClassesResult(_) } override def buildTargetScalaTestClasses(p: ScalaTestClassesParams) @@ -88,15 +88,15 @@ private trait MillScalaBuildServer extends ScalaBuildServer { this: MillBuildSer originId = p.getOriginId ) { case (_, _, id, _, (frameworkName, classes)) => - val item = new ScalaTestClassesItem(id, classes.asJava) + val item = ScalaTestClassesItem(id, classes.asJava) item.setFramework(frameworkName) item case (_, _, id, _, _) => // Not a test module, so no test classes - new ScalaTestClassesItem(id, Seq.empty[String].asJava) + ScalaTestClassesItem(id, Seq.empty[String].asJava) } { - new ScalaTestClassesResult(_) + ScalaTestClassesResult(_) } } diff --git a/runner/bsp/worker/src/mill/bsp/worker/SyntheticRootBspBuildTargetData.scala b/runner/bsp/worker/src/mill/bsp/worker/SyntheticRootBspBuildTargetData.scala index cde5c2255e78..56863eafab55 100644 --- a/runner/bsp/worker/src/mill/bsp/worker/SyntheticRootBspBuildTargetData.scala +++ b/runner/bsp/worker/src/mill/bsp/worker/SyntheticRootBspBuildTargetData.scala @@ -15,7 +15,7 @@ import mill.api.daemon.internal.bsp.BspBuildTarget * will be created */ class SyntheticRootBspBuildTargetData(topLevelProjectRoot: os.Path) { - val id: BuildTargetIdentifier = new BuildTargetIdentifier( + val id: BuildTargetIdentifier = BuildTargetIdentifier( Utils.sanitizeUri((topLevelProjectRoot / "mill-synthetic-root-target").toNIO) ) @@ -32,12 +32,12 @@ class SyntheticRootBspBuildTargetData(topLevelProjectRoot: os.Path) { val target: BuildTarget = makeBuildTarget(id, Seq.empty, bt, None) private val sourcePath = topLevelProjectRoot / "src" - def synthSources = new SourcesItem( + def synthSources = SourcesItem( id, - Seq(new SourceItem(sanitizeUri(sourcePath.toNIO), SourceItemKind.DIRECTORY, false)).asJava + Seq(SourceItem(sanitizeUri(sourcePath.toNIO), SourceItemKind.DIRECTORY, false)).asJava ) // intellijBSP does not create contentRootData for module with only outputPaths (this is probably a bug) } object SyntheticRootBspBuildTargetData { def makeIfNeeded(workspaceDir: os.Path): Option[SyntheticRootBspBuildTargetData] = - Some(new SyntheticRootBspBuildTargetData(workspaceDir)) + Some(SyntheticRootBspBuildTargetData(workspaceDir)) } diff --git a/runner/bsp/worker/src/mill/bsp/worker/Utils.scala b/runner/bsp/worker/src/mill/bsp/worker/Utils.scala index 57577ecf00c0..2fdd1371e78b 100644 --- a/runner/bsp/worker/src/mill/bsp/worker/Utils.scala +++ b/runner/bsp/worker/src/mill/bsp/worker/Utils.scala @@ -34,8 +34,8 @@ object Utils { bspIdsByModule.find(_._1.hashCode == moduleHashCode).map { case (module, targetId) => val buildTarget = module.bspBuildTarget - val taskId = new TaskId(module.hashCode.toString) - new BspCompileProblemReporter( + val taskId = TaskId(module.hashCode.toString) + BspCompileProblemReporter( client, targetId, buildTarget.displayName.getOrElse(targetId.getUri), @@ -62,12 +62,12 @@ object Utils { bt: BspBuildTarget, data: Option[(String, Object)] ): BuildTarget = { - val buildTarget = new BuildTarget( + val buildTarget = BuildTarget( id, bt.tags.asJava, bt.languageIds.asJava, depsIds.asJava, - new BuildTargetCapabilities().tap { it => + BuildTargetCapabilities().tap { it => it.setCanCompile(bt.canCompile) it.setCanTest(bt.canTest) it.setCanRun(bt.canRun) @@ -92,7 +92,7 @@ object Utils { def outputPathItem(path: os.Path) = // Spec says, a directory must end with a forward slash - new OutputPathItem(sanitizeUri(path.toNIO) + "/", OutputPathItemKind.DIRECTORY) + OutputPathItem(sanitizeUri(path.toNIO) + "/", OutputPathItemKind.DIRECTORY) if (topLevelProjectRoot.startsWith(buildTargetBaseDir)) Seq( diff --git a/runner/codesig/src/mill/codesig/CodeSig.scala b/runner/codesig/src/mill/codesig/CodeSig.scala index 43db76fea32b..6040a2b45fc7 100644 --- a/runner/codesig/src/mill/codesig/CodeSig.scala +++ b/runner/codesig/src/mill/codesig/CodeSig.scala @@ -10,7 +10,7 @@ object CodeSig { logger: Logger, prevTransitiveCallGraphHashesOpt: () => Option[Map[String, Int]] ): CallGraphAnalysis = { - implicit val st: SymbolTable = new SymbolTable() + implicit val st: SymbolTable = SymbolTable() val localSummary = LocalSummary.apply(classFiles.iterator.map(os.read.inputStream(_))) logger.log(localSummary) @@ -21,7 +21,7 @@ object CodeSig { val resolvedMethodCalls = ResolvedCalls.apply(localSummary, externalSummary) logger.log(resolvedMethodCalls) - new CallGraphAnalysis( + CallGraphAnalysis( localSummary, resolvedMethodCalls, externalSummary, diff --git a/runner/codesig/src/mill/codesig/ExternalSummary.scala b/runner/codesig/src/mill/codesig/ExternalSummary.scala index d79adbc21c4a..46d2fbe42720 100644 --- a/runner/codesig/src/mill/codesig/ExternalSummary.scala +++ b/runner/codesig/src/mill/codesig/ExternalSummary.scala @@ -49,11 +49,11 @@ object ExternalSummary { def load(cls: JCls): Unit = methodsPerCls.getOrElse(cls, load0(cls)) def load0(cls: JCls): Unit = { - val visitor = new MyClassVisitor() + val visitor = MyClassVisitor() val resourcePath = os.resource(using upstreamClassloader) / os.SubPath(cls.name.replace('.', '/') + ".class") - new ClassReader(os.read.inputStream(resourcePath)).accept( + ClassReader(os.read.inputStream(resourcePath)).accept( visitor, ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG ) diff --git a/runner/codesig/src/mill/codesig/JvmModel.scala b/runner/codesig/src/mill/codesig/JvmModel.scala index 1363b3b40a26..4bef8b3cd974 100644 --- a/runner/codesig/src/mill/codesig/JvmModel.scala +++ b/runner/codesig/src/mill/codesig/JvmModel.scala @@ -28,18 +28,18 @@ object JvmModel { } object MethodDef extends Table[(JType.Cls, MethodSig), MethodDef] { - def create: ((JType.Cls, MethodSig)) => MethodDef = (new MethodDef(_, _)).tupled + def create: ((JType.Cls, MethodSig)) => MethodDef = (MethodDef(_, _)).tupled def apply(cls: JType.Cls, method: MethodSig): MethodDef = get((cls, method)) } object MethodSig extends Table[(Boolean, String, Desc), MethodSig] { - def create: ((Boolean, String, Desc)) => MethodSig = (new MethodSig(_, _, _)).tupled + def create: ((Boolean, String, Desc)) => MethodSig = (MethodSig(_, _, _)).tupled def apply(static: Boolean, name: String, desc: Desc): MethodSig = get((static, name, desc)) } object MethodCall extends Table[(JType.Cls, InvokeType, String, Desc), MethodCall] { def create: ((JType.Cls, InvokeType, String, Desc)) => MethodCall = - (new MethodCall(_, _, _, _)).tupled + (MethodCall(_, _, _, _)).tupled def apply(cls: JType.Cls, invokeType: InvokeType, name: String, desc: Desc): MethodCall = get((cls, invokeType, name, desc)) } @@ -225,7 +225,7 @@ object JvmModel { args.addOne(JType.read(s.substring(index, split + 1))) index = split + 1 } - new Desc( + Desc( ArraySeq.unsafeWrapArray(args.result()), JType.read(s.substring(closeParenIndex + 1)) ) diff --git a/runner/codesig/src/mill/codesig/LocalSummary.scala b/runner/codesig/src/mill/codesig/LocalSummary.scala index 4211218320f0..accc7b0de8a0 100644 --- a/runner/codesig/src/mill/codesig/LocalSummary.scala +++ b/runner/codesig/src/mill/codesig/LocalSummary.scala @@ -49,8 +49,8 @@ object LocalSummary { def apply(classStreams: Iterator[java.io.InputStream])(using st: SymbolTable): LocalSummary = { val visitors = classStreams .map { cs => - val visitor = new MyClassVisitor() - new ClassReader(cs).accept(visitor, ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG) + val visitor = MyClassVisitor() + ClassReader(cs).accept(visitor, ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG) visitor } .toVector @@ -118,7 +118,7 @@ object LocalSummary { signature: String, exceptions: Array[String] ): MethodVisitor = { - new MyMethodVisitor(clsType, this, name, descriptor, access) + MyMethodVisitor(clsType, this, name, descriptor, access) } override def visitEnd(): Unit = {} diff --git a/runner/codesig/test/cases/callgraph/complicated/10-iterator-foreach-scala/src/Hello.scala b/runner/codesig/test/cases/callgraph/complicated/10-iterator-foreach-scala/src/Hello.scala index 6f1c17f51c39..834c5ea4eeeb 100644 --- a/runner/codesig/test/cases/callgraph/complicated/10-iterator-foreach-scala/src/Hello.scala +++ b/runner/codesig/test/cases/callgraph/complicated/10-iterator-foreach-scala/src/Hello.scala @@ -13,7 +13,7 @@ class SubTestIter() extends TestIter[Nothing] { object Hello { def minimizedIterator(): Array[Int] = { - val iterator = new SubTestIter() + val iterator = SubTestIter() val holder = Array(1) iterator.foreach(x => holder(0) = x) holder diff --git a/runner/codesig/test/cases/callgraph/complicated/11-iterator-callback-class-scala/src/Hello.scala b/runner/codesig/test/cases/callgraph/complicated/11-iterator-callback-class-scala/src/Hello.scala index 2f79e6947793..21692e6c0ce8 100644 --- a/runner/codesig/test/cases/callgraph/complicated/11-iterator-callback-class-scala/src/Hello.scala +++ b/runner/codesig/test/cases/callgraph/complicated/11-iterator-callback-class-scala/src/Hello.scala @@ -16,7 +16,7 @@ object Hello { } def staticSpecialInterfaceMethods(): Int = { - new TestElements().run(new TestCallbackImpl()) + TestElements().run(TestCallbackImpl()) } } diff --git a/runner/codesig/test/cases/callgraph/complicated/12-iterator-inherit-external-scala/src/Hello.scala b/runner/codesig/test/cases/callgraph/complicated/12-iterator-inherit-external-scala/src/Hello.scala index b394b2a0519e..8f8913668fa5 100644 --- a/runner/codesig/test/cases/callgraph/complicated/12-iterator-inherit-external-scala/src/Hello.scala +++ b/runner/codesig/test/cases/callgraph/complicated/12-iterator-inherit-external-scala/src/Hello.scala @@ -18,7 +18,7 @@ object Hello { } def manualIterator(n: Int): Int = { - val iter = new Elements(Array(0, 1, 2, 3)) + val iter = Elements(Array(0, 1, 2, 3)) iter.map(_ + getInt()).next() } @@ -26,7 +26,7 @@ object Hello { def manualIterator2(n: Int): Int = { val box = Array(0) - val iter = new Elements(Array(0, 1, 2, 3)) + val iter = Elements(Array(0, 1, 2, 3)) iter.map(_ + n).foreach(x => box(0) += x + getInt()) box(0) } diff --git a/runner/codesig/test/cases/callgraph/complicated/13-iterator-inherit-external-filter-scala/src/Hello.scala b/runner/codesig/test/cases/callgraph/complicated/13-iterator-inherit-external-filter-scala/src/Hello.scala index dede25713536..ec4ef98c2de4 100644 --- a/runner/codesig/test/cases/callgraph/complicated/13-iterator-inherit-external-filter-scala/src/Hello.scala +++ b/runner/codesig/test/cases/callgraph/complicated/13-iterator-inherit-external-filter-scala/src/Hello.scala @@ -17,7 +17,7 @@ object Hello { def next(): A - def filter(p: A => Boolean): BigTestIterator[A] = new FilterBigTestIterator[A](this, p) + def filter(p: A => Boolean): BigTestIterator[A] = FilterBigTestIterator[A](this, p) } class FilterBigTestIterator[A](parent: BigTestIterator[A], pred: A => Boolean) @@ -41,7 +41,7 @@ object Hello { } def manualIterator3(n: Int): Int = { - val iter = new SingletonBigTestIterator(n).filter(_ % 2 == 0) + val iter = SingletonBigTestIterator(n).filter(_ % 2 == 0) if (iter.hasNext) iter.next() else n } diff --git a/runner/codesig/test/cases/callgraph/complicated/6-classes-misc-scala/src/Hello.scala b/runner/codesig/test/cases/callgraph/complicated/6-classes-misc-scala/src/Hello.scala index a724d7d6d3bd..be5543ebbbd2 100644 --- a/runner/codesig/test/cases/callgraph/complicated/6-classes-misc-scala/src/Hello.scala +++ b/runner/codesig/test/cases/callgraph/complicated/6-classes-misc-scala/src/Hello.scala @@ -33,7 +33,7 @@ class DoubleDetMatrix(aa: Float, ab: Float, ba: Float, bb: Float) class LinkedList { def push(i: Int): Unit = { - val n = new Inner(i, head) + val n = Inner(i, head) head = n } diff --git a/runner/codesig/test/cases/callgraph/complicated/7-manifest-scala/src/Hello.scala b/runner/codesig/test/cases/callgraph/complicated/7-manifest-scala/src/Hello.scala index 9dc587d80e1c..fb17b1fcee22 100644 --- a/runner/codesig/test/cases/callgraph/complicated/7-manifest-scala/src/Hello.scala +++ b/runner/codesig/test/cases/callgraph/complicated/7-manifest-scala/src/Hello.scala @@ -5,7 +5,7 @@ import scala.collection.AbstractIterator object Hello { object TestManifestFactory { - val Nothing = new PhantomManifest() + val Nothing = PhantomManifest() class PhantomManifest() extends ClassTypeManifest(None) class ClassTypeManifest(prefix: Option[Int]) } diff --git a/runner/codesig/test/cases/callgraph/complicated/8-linked-list-scala/src/Hello.scala b/runner/codesig/test/cases/callgraph/complicated/8-linked-list-scala/src/Hello.scala index 5235986b9203..c08a7a172c30 100644 --- a/runner/codesig/test/cases/callgraph/complicated/8-linked-list-scala/src/Hello.scala +++ b/runner/codesig/test/cases/callgraph/complicated/8-linked-list-scala/src/Hello.scala @@ -20,8 +20,8 @@ object Hello { object TestNil extends TestList[Nothing] { def isEmpty = true - def head = throw new Exception() - override def tail: Nothing = throw new Exception() + def head = throw Exception() + override def tail: Nothing = throw Exception() } class TestCons[B](val head: B, val tl: TestList[B]) extends TestList[B] { @@ -32,8 +32,8 @@ object Hello { def simpleLinkedListForeach(): Array[Int] = { val holder = Array(1) - new TestCons(1, new TestCons(2, new TestCons(3, TestNil))).foreach(x => holder(0) += x) - new TestCons(1L, new TestCons(2L, new TestCons(3L, TestNil))).foreach(x => holder(0) += x.toInt) + TestCons(1, TestCons(2, TestCons(3, TestNil))).foreach(x => holder(0) += x) + TestCons(1L, TestCons(2L, TestCons(3L, TestNil))).foreach(x => holder(0) += x.toInt) holder } } diff --git a/runner/codesig/test/cases/callgraph/complicated/9-array-seq-scala/src/Hello.scala b/runner/codesig/test/cases/callgraph/complicated/9-array-seq-scala/src/Hello.scala index ace325a3280b..484a969b39e4 100644 --- a/runner/codesig/test/cases/callgraph/complicated/9-array-seq-scala/src/Hello.scala +++ b/runner/codesig/test/cases/callgraph/complicated/9-array-seq-scala/src/Hello.scala @@ -15,7 +15,7 @@ object Hello { def simpleArraySeqForeach(): Array[Int] = { val holder = Array(1) - val arr = new TestArraySeq[String](Array("a", "bb", "CCC")) + val arr = TestArraySeq[String](Array("a", "bb", "CCC")) arr.foreach(x => holder(0) += x.length) holder diff --git a/runner/codesig/test/cases/callgraph/realistic/4-actors/src/Hello.scala b/runner/codesig/test/cases/callgraph/realistic/4-actors/src/Hello.scala index cb7e49db1e3f..fd489fcec469 100644 --- a/runner/codesig/test/cases/callgraph/realistic/4-actors/src/Hello.scala +++ b/runner/codesig/test/cases/callgraph/realistic/4-actors/src/Hello.scala @@ -41,11 +41,11 @@ object Hello { def main() = { implicit val cc = new castor.Context.Test() - val diskActor = new DiskActor(os.pwd / "log.txt") - val uploadActor = new UploadActor("https://httpbin.org/post") + val diskActor = DiskActor(os.pwd / "log.txt") + val uploadActor = UploadActor("https://httpbin.org/post") - val base64Actor = new Base64Actor(diskActor) - val sanitizeActor = new SanitizeActor(uploadActor) + val base64Actor = Base64Actor(diskActor) + val sanitizeActor = SanitizeActor(uploadActor) val logger = new castor.SplitActor(base64Actor, sanitizeActor) } diff --git a/runner/codesig/test/cases/callgraph/realistic/5-parser/src/Hello.scala b/runner/codesig/test/cases/callgraph/realistic/5-parser/src/Hello.scala index 77ed42e114f5..46b991b7aa15 100644 --- a/runner/codesig/test/cases/callgraph/realistic/5-parser/src/Hello.scala +++ b/runner/codesig/test/cases/callgraph/realistic/5-parser/src/Hello.scala @@ -6,16 +6,16 @@ class Word(s: String) extends Phrase class Pair(lhs: Phrase, rhs: Phrase) extends Phrase object Parser { - def prefix[$: P] = P("hello" | "goodbye").!.map(new Word(_)) + def prefix[$: P] = P("hello" | "goodbye").!.map(Word(_)) - def suffix[$: P] = P("world" | "seattle").!.map(new Word(_)) + def suffix[$: P] = P("world" | "seattle").!.map(Word(_)) def ws[$: P] = P(" ".rep(1)) def parened[$: P] = P("(" ~ parser ~ ")") def parser[$: P]: P[Phrase] = P((parened | prefix) ~ ws ~ (parened | suffix)).map { - case (lhs, rhs) => new Pair(lhs, rhs) + case (lhs, rhs) => Pair(lhs, rhs) } } diff --git a/runner/codesig/test/src/MethodHashTests.scala b/runner/codesig/test/src/MethodHashTests.scala index d98e9b2180c3..e39799c35c58 100644 --- a/runner/codesig/test/src/MethodHashTests.scala +++ b/runner/codesig/test/src/MethodHashTests.scala @@ -52,7 +52,7 @@ object MethodHashTests extends TestSuite { ) val hash1 = sig1.transitiveCallGraphHashes(mainMethod.toString) val hash2 = sig2.transitiveCallGraphHashes(mainMethod.toString) - if (hash1 == hash2) throw new Exception( + if (hash1 == hash2) throw Exception( s"main methods for $c1 and $c2 have identical main method hash: $hash1" ) diff --git a/runner/codesig/test/src/TestUtil.scala b/runner/codesig/test/src/TestUtil.scala index 503f1dfb3b6f..0700722f9163 100644 --- a/runner/codesig/test/src/TestUtil.scala +++ b/runner/codesig/test/src/TestUtil.scala @@ -19,7 +19,7 @@ object TestUtil { .map(os.Path(_)) ), (_, _) => false, - new Logger(testLogFolder, Some(testLogFolder)), + Logger(testLogFolder, Some(testLogFolder)), () => None ) } diff --git a/runner/daemon/src/mill/daemon/MillBuildBootstrap.scala b/runner/daemon/src/mill/daemon/MillBuildBootstrap.scala index 41937f0f68d7..7e11334caad0 100644 --- a/runner/daemon/src/mill/daemon/MillBuildBootstrap.scala +++ b/runner/daemon/src/mill/daemon/MillBuildBootstrap.scala @@ -470,7 +470,7 @@ object MillBuildBootstrap { ) val outPath = recOut(output, depth) - val baseLogger = new PrefixLogger(logger, bootLogPrefix) + val baseLogger = PrefixLogger(logger, bootLogPrefix) val cl = rootModule.getClass.getClassLoader val evalImplCls = cl.loadClass("mill.eval.EvaluatorImpl") val execCls = cl.loadClass("mill.exec.Execution") diff --git a/runner/daemon/src/mill/daemon/MillDaemonMain0.scala b/runner/daemon/src/mill/daemon/MillDaemonMain0.scala index 15d2131005c1..6e3735b35dd4 100644 --- a/runner/daemon/src/mill/daemon/MillDaemonMain0.scala +++ b/runner/daemon/src/mill/daemon/MillDaemonMain0.scala @@ -50,7 +50,7 @@ object MillDaemonMain0 { val acceptTimeout = Try(System.getProperty("mill.server_timeout").toInt.millis).getOrElse(30.minutes) - val exitCode = new MillDaemonMain0( + val exitCode = MillDaemonMain0( daemonDir = args.daemonDir, acceptTimeout = acceptTimeout, Locks.files(args.daemonDir.toString), diff --git a/runner/daemon/src/mill/daemon/MillMain0.scala b/runner/daemon/src/mill/daemon/MillMain0.scala index f22fc72244b5..8a7d28216ac4 100644 --- a/runner/daemon/src/mill/daemon/MillMain0.scala +++ b/runner/daemon/src/mill/daemon/MillMain0.scala @@ -47,7 +47,7 @@ object MillMain0 { (false, onError) case e => val str = new StringWriter - e.printStackTrace(new PrintWriter(str)) + e.printStackTrace(PrintWriter(str)) err.println(str) throw e } @@ -81,9 +81,9 @@ object MillMain0 { ) try { - val streams0 = new SystemStreams( - out = new MultiStream(streams.err, outFileStream), - err = new MultiStream(streams.err, errFileStream), + val streams0 = SystemStreams( + out = MultiStream(streams.err, outFileStream), + err = MultiStream(streams.err, errFileStream), in = InputStream.nullInputStream() ) mill.api.SystemStreamsUtils.withStreams(streams0) { @@ -245,7 +245,7 @@ object MillMain0 { else Some(mill.exec.ExecutionContexts.createExecutor(threadCount)) val out = os.Path(OutFiles.outFor(outMode), BuildCtx.workspaceRoot) - Using.resources(new TailManager(daemonDir), createEc()) { (tailManager, ec) => + Using.resources(TailManager(daemonDir), createEc()) { (tailManager, ec) => def runMillBootstrap( skipSelectiveExecution: Boolean, prevState: Option[RunnerState], @@ -279,7 +279,7 @@ object MillMain0 { !config.noFilesystemChecker.value ) { tailManager.withOutErr(logger.streams.out, logger.streams.err) { - new MillBuildBootstrap( + MillBuildBootstrap( topLevelProjectRoot = BuildCtx.workspaceRoot, output = out, // In BSP server, we want to evaluate as many tasks as possible, @@ -363,8 +363,8 @@ object MillMain0 { startBspServer(streams0, outLock, bspLogger) var keepGoing = true var errored = false - val initCommandLogger = new PrefixLogger(bspLogger, Seq("init")) - val watchLogger = new PrefixLogger(bspLogger, Seq("watch")) + val initCommandLogger = PrefixLogger(bspLogger, Seq("init")) + val watchLogger = PrefixLogger(bspLogger, Seq("watch")) while (keepGoing) { val watchRes = runMillBootstrap( skipSelectiveExecution = false, @@ -587,7 +587,7 @@ object MillMain0 { colors: Colors, out: os.Path ): Logger & AutoCloseable = { - new PromptLogger( + PromptLogger( colored = colored, enableTicker = enableTicker, infoColor = colors.info, @@ -606,8 +606,8 @@ object MillMain0 { streams: SystemStreams, config: MillCliConfig ): Logger = - new PrefixLogger( - new SimpleLogger( + PrefixLogger( + SimpleLogger( streams, Seq("bsp"), debugEnabled = config.debugLog.value diff --git a/runner/daemon/src/mill/daemon/MillScalaParserImpl.scala b/runner/daemon/src/mill/daemon/MillScalaParserImpl.scala index fdcc643f23e5..659327700df3 100644 --- a/runner/daemon/src/mill/daemon/MillScalaParserImpl.scala +++ b/runner/daemon/src/mill/daemon/MillScalaParserImpl.scala @@ -56,7 +56,7 @@ object MillScalaParserImpl extends MillScalaParser { "" case _ => if (!trees.head.startPos.exists) "" - else new String(source.file.toByteArray).take(trees.head.startPos.start) + else String(source.file.toByteArray).take(trees.head.startPos.start) } (prefix, pkgs, stmts) diff --git a/runner/daemon/src/mill/daemon/TailManager.scala b/runner/daemon/src/mill/daemon/TailManager.scala index aba119d35a53..3b53f80b0c03 100644 --- a/runner/daemon/src/mill/daemon/TailManager.scala +++ b/runner/daemon/src/mill/daemon/TailManager.scala @@ -14,16 +14,16 @@ class TailManager(daemonDir: os.Path) extends AutoCloseable { // do not affect the tailers which run on their own separate threads @volatile var tailerOut: OutputStream = System.out @volatile var tailerErr: OutputStream = System.err - val stdoutTailer = new FileToStreamTailer( + val stdoutTailer = FileToStreamTailer( (daemonDir / DaemonFiles.stdout).toIO, - new PrintStream(new ThreadLocalStreams.ProxyOutputStream { + PrintStream(new ThreadLocalStreams.ProxyOutputStream { def delegate(): OutputStream = tailerOut }), tailerRefreshIntervalMillis ) - val stderrTailer = new FileToStreamTailer( + val stderrTailer = FileToStreamTailer( (daemonDir / DaemonFiles.stderr).toIO, - new PrintStream(new ThreadLocalStreams.ProxyOutputStream { + PrintStream(new ThreadLocalStreams.ProxyOutputStream { def delegate(): OutputStream = tailerErr }), tailerRefreshIntervalMillis diff --git a/runner/daemon/src/mill/daemon/Watching.scala b/runner/daemon/src/mill/daemon/Watching.scala index 588d8f7cc389..a4a768fd4bb3 100644 --- a/runner/daemon/src/mill/daemon/Watching.scala +++ b/runner/daemon/src/mill/daemon/Watching.scala @@ -90,7 +90,7 @@ object Watching { watchArgs.setIdle(false) } } - throw new IllegalStateException("unreachable") + throw IllegalStateException("unreachable") } } diff --git a/runner/eclipse/src/mill/eclipse/GenEclipseImpl.scala b/runner/eclipse/src/mill/eclipse/GenEclipseImpl.scala index a698bb35d60c..98ae2a6c0b8b 100644 --- a/runner/eclipse/src/mill/eclipse/GenEclipseImpl.scala +++ b/runner/eclipse/src/mill/eclipse/GenEclipseImpl.scala @@ -422,7 +422,7 @@ object GenEclipseImpl { */ private def moduleName(segments: Segments, path: Path): String = { val name = segments.value - .foldLeft(new StringBuilder()) { + .foldLeft(StringBuilder()) { case (sb, Segment.Label(s)) if sb.isEmpty => sb.append(s) case (sb, Segment.Cross(s)) if sb.isEmpty => sb.append(s.mkString("-")) case (sb, Segment.Label(s)) => sb.append(".").append(s) diff --git a/runner/idea/src/mill/idea/GenIdeaImpl.scala b/runner/idea/src/mill/idea/GenIdeaImpl.scala index 3b2b80f2c9ff..09ec01baf2c3 100755 --- a/runner/idea/src/mill/idea/GenIdeaImpl.scala +++ b/runner/idea/src/mill/idea/GenIdeaImpl.scala @@ -293,7 +293,7 @@ class GenIdeaImpl( */ def sbtLibraryNameFromPom(pomPath: os.Path): String = { val pom = xmlParseDom(os.read(pomPath)).flatMap(Pom.project) - .getOrElse(throw new RuntimeException(s"Could not parse pom file: ${pomPath}")) + .getOrElse(throw RuntimeException(s"Could not parse pom file: ${pomPath}")) val artifactId = pom.module.name.value val scalaArtifactRegex = ".*_[23]\\.[0-9]{1,2}".r @@ -354,9 +354,9 @@ class GenIdeaImpl( // Create IgnoreNode from bspScriptIgnore patterns val ignoreRules = bspScriptIgnore .filter(l => !l.startsWith("#")) - .map(pattern => (pattern, new FastIgnoreRule(pattern))) + .map(pattern => (pattern, FastIgnoreRule(pattern))) - val ignoreNode = new IgnoreNode(ignoreRules.map(_._2).asJava) + val ignoreNode = IgnoreNode(ignoreRules.map(_._2).asJava) // Extract directory prefixes from negation patterns (patterns starting with !) // These directories need to be walked even if they're ignored, because they contain @@ -617,7 +617,7 @@ class GenIdeaImpl( else element.attributes.toSeq.reverse.foldLeft(Null.asInstanceOf[MetaData]) { case (prevAttr, (k, v)) => - new UnprefixedAttribute(k, v, prevAttr) + UnprefixedAttribute(k, v, prevAttr) } new Elem( @@ -925,7 +925,7 @@ object GenIdeaImpl { */ def moduleName(p: Segments): String = p.value - .foldLeft(new StringBuilder()) { + .foldLeft(StringBuilder()) { case (sb, Segment.Label(s)) if sb.isEmpty => sb.append(s) case (sb, Segment.Cross(s)) if sb.isEmpty => sb.append(s.mkString("-")) case (sb, Segment.Label(s)) => sb.append(".").append(s) diff --git a/runner/launcher/src/mill/launcher/ConfigReader.scala b/runner/launcher/src/mill/launcher/ConfigReader.scala index 448197c83930..2867ee167aae 100644 --- a/runner/launcher/src/mill/launcher/ConfigReader.scala +++ b/runner/launcher/src/mill/launcher/ConfigReader.scala @@ -4,7 +4,7 @@ import org.snakeyaml.engine.v2.api.{Load, LoadSettings} object ConfigReader { def readYaml(buildFile: java.nio.file.Path, errorFileName: String) = { - val loaded = new Load(LoadSettings.builder().build()) + val loaded = Load(LoadSettings.builder().build()) .loadFromString(mill.constants.Util.readBuildHeader(buildFile, errorFileName)) loaded diff --git a/runner/meta/src/mill/meta/AsmPositionUpdater.scala b/runner/meta/src/mill/meta/AsmPositionUpdater.scala index 701d54e344c5..df492bc66911 100644 --- a/runner/meta/src/mill/meta/AsmPositionUpdater.scala +++ b/runner/meta/src/mill/meta/AsmPositionUpdater.scala @@ -28,7 +28,7 @@ object AsmPositionUpdater { exceptions: Array[String] ): asm.MethodVisitor = { val main = super.visitMethod(access, name, descriptor, signature, exceptions) - new LineNumberTableMethodVisitor(lineNumberOffset, main) + LineNumberTableMethodVisitor(lineNumberOffset, main) } } @@ -36,7 +36,7 @@ object AsmPositionUpdater { def postProcess(lineNumberOffset: Int, clsInputStream: InputStream): Array[Byte] = { val reader = new asm.ClassReader(clsInputStream) val writer = new asm.ClassWriter(reader, 0) - val checker = new LineNumberTableClassVisitor(lineNumberOffset, writer) + val checker = LineNumberTableClassVisitor(lineNumberOffset, writer) reader.accept(checker, 0) writer.toByteArray } diff --git a/runner/meta/src/mill/meta/FileImportGraph.scala b/runner/meta/src/mill/meta/FileImportGraph.scala index ba7b176c22ed..1d513d365213 100644 --- a/runner/meta/src/mill/meta/FileImportGraph.scala +++ b/runner/meta/src/mill/meta/FileImportGraph.scala @@ -97,7 +97,7 @@ object FileImportGraph { walked.filter(_ != foundRootBuildFile).foreach(processScript(_)) - new FileImportGraph(seenScripts.toMap, errors.toSeq) + FileImportGraph(seenScripts.toMap, errors.toSeq) } def findRootBuildFiles(projectRoot: os.Path) = { diff --git a/runner/server/src/mill/server/MillDaemonServer.scala b/runner/server/src/mill/server/MillDaemonServer.scala index ce832474cab3..bb4ae1b06667 100644 --- a/runner/server/src/mill/server/MillDaemonServer.scala +++ b/runner/server/src/mill/server/MillDaemonServer.scala @@ -64,12 +64,12 @@ abstract class MillDaemonServer[State]( stopServer: Server.StopServer ): DaemonServerData = { val stdout = - new PrintStream( + PrintStream( new ProxyStream.Output(connectionData.serverToClient, ProxyStream.OUT), true ) val stderr = - new PrintStream( + PrintStream( new ProxyStream.Output(connectionData.serverToClient, ProxyStream.ERR), true ) @@ -94,8 +94,8 @@ abstract class MillDaemonServer[State]( out = outFolder, millActiveCommandMessage = "checking server mill version and java version", streams = new mill.api.daemon.SystemStreams( - new PrintStream(mill.api.daemon.DummyOutputStream), - new PrintStream(mill.api.daemon.DummyOutputStream), + PrintStream(mill.api.daemon.DummyOutputStream), + PrintStream(mill.api.daemon.DummyOutputStream), mill.api.daemon.DummyInputStream ), outLock = outLock, @@ -134,7 +134,7 @@ abstract class MillDaemonServer[State]( data.clientData.args, stateCache, data.clientData.interactive, - new SystemStreams(data.stdout, data.stderr, connectionData.clientToServer), + SystemStreams(data.stdout, data.stderr, connectionData.clientToServer), data.clientData.env.asScala.toMap, setIdle(_), data.clientData.userSpecifiedProperties.asScala.toMap, @@ -219,14 +219,14 @@ object MillDaemonServer { Using.resource { val tryLocked = outLock.tryLock() if (tryLocked.isLocked) tryLocked - else if (noWaitForBuildLock) throw new Exception(s"$activeTaskPrefix failing") + else if (noWaitForBuildLock) throw Exception(s"$activeTaskPrefix failing") else { streams.err.println(s"$activeTaskPrefix waiting for it to be done...") outLock.lock() } } { _ => setIdle(false) - if (Thread.interrupted()) throw new InterruptedException() + if (Thread.interrupted()) throw InterruptedException() os.write.over(out / OutFiles.millActiveCommand, millActiveCommandMessage) try t finally os.remove.all(out / OutFiles.millActiveCommand) diff --git a/runner/server/test/src/mill/server/ClientServerTests.scala b/runner/server/test/src/mill/server/ClientServerTests.scala index d5ce210e4399..6b03ecdf60aa 100644 --- a/runner/server/test/src/mill/server/ClientServerTests.scala +++ b/runner/server/test/src/mill/server/ClientServerTests.scala @@ -62,7 +62,7 @@ object ClientServerTests extends TestSuite { ) = { Thread.sleep(commandSleepMillis) if (!runCompleted) { - val reader = new BufferedReader(new InputStreamReader(streams.in)) + val reader = BufferedReader(InputStreamReader(streams.in)) val str = reader.readLine() Thread.sleep(200) if (args.nonEmpty) { @@ -96,9 +96,9 @@ object ClientServerTests extends TestSuite { args: Array[String] = Array(), forceFailureForTestingMillisDelay: Int = -1 ) = { - val in = new ByteArrayInputStream(s"hello$ENDL".getBytes()) - val out = new ByteArrayOutputStream() - val err = new ByteArrayOutputStream() + val in = ByteArrayInputStream(s"hello$ENDL".getBytes()) + val out = ByteArrayOutputStream() + val err = ByteArrayOutputStream() val daemonDir = outDir / "server-0" val result = new MillServerLauncher( ServerLauncher.Streams(in, out, err), @@ -178,7 +178,7 @@ object ClientServerTests extends TestSuite { test("hello") - { // Continue logging when out folder is deleted so we can see the logs // and ensure the correct code path is taken as the server exits - val tester = new Tester(testLogEvenWhenServerIdWrong = true) + val tester = Tester(testLogEvenWhenServerIdWrong = true) val res1 = tester(args = Array("world")) assert( @@ -218,7 +218,7 @@ object ClientServerTests extends TestSuite { } } test("dontLogWhenOutFolderDeleted") - retry(3) { - val tester = new Tester(testLogEvenWhenServerIdWrong = false) + val tester = Tester(testLogEvenWhenServerIdWrong = false) val res1 = tester(args = Array("world")) assert( @@ -238,7 +238,7 @@ object ClientServerTests extends TestSuite { } test("concurrency") { - val tester = new Tester(testLogEvenWhenServerIdWrong = false) + val tester = Tester(testLogEvenWhenServerIdWrong = false) // Make sure concurrently running client commands results in multiple processes // being spawned, running in different folders import concurrent.* @@ -263,7 +263,7 @@ object ClientServerTests extends TestSuite { } test("clientLockReleasedOnFailure") { - val tester = new Tester(testLogEvenWhenServerIdWrong = false) + val tester = Tester(testLogEvenWhenServerIdWrong = false) // When the client gets interrupted via Ctrl-C, we exit the server immediately. This // is because Mill ends up executing arbitrary JVM code, and there is no generic way // to interrupt such an execution. The two options are to leave the server running @@ -292,7 +292,7 @@ object ClientServerTests extends TestSuite { // Make sure that when the command at 3000ms takes longer than the server // timeout at 1000ms, the command still finishes running and the server doesn't // shut down half way through - val tester = new Tester(testLogEvenWhenServerIdWrong = true, commandSleepMillis = 3000) + val tester = Tester(testLogEvenWhenServerIdWrong = true, commandSleepMillis = 3000) val res1 = tester(args = Array("world")) assert( res1.out == s"helloworld$ENDL", @@ -301,7 +301,7 @@ object ClientServerTests extends TestSuite { } test("envVars") - retry(3) { - val tester = new Tester(testLogEvenWhenServerIdWrong = false) + val tester = Tester(testLogEvenWhenServerIdWrong = false) // Make sure the simple "have the client start a server and // exchange one message" workflow works from end to end. diff --git a/testkit/src/mill/testkit/BashTokenizer.scala b/testkit/src/mill/testkit/BashTokenizer.scala index 1606d4cc77d1..bf99d9e78b80 100644 --- a/testkit/src/mill/testkit/BashTokenizer.scala +++ b/testkit/src/mill/testkit/BashTokenizer.scala @@ -6,12 +6,12 @@ import scala.jdk.CollectionConverters._ object BashTokenizer { def tokenize(string: CharSequence): Seq[String] = { // taken from https://stackoverflow.com/a/20725050 - val tokens: List[String] = new ArrayList[String]() + val tokens: List[String] = ArrayList[String]() var escaping = false var quoteChar = ' ' var quoting = false var lastCloseQuoteIndex = Integer.MIN_VALUE - val current = new StringBuilder() + val current = StringBuilder() for (i <- 0 until string.length()) { val c = string.charAt(i) if (escaping) { diff --git a/testkit/src/mill/testkit/ExampleTester.scala b/testkit/src/mill/testkit/ExampleTester.scala index 1418ef1fc74a..cbb763d316f5 100644 --- a/testkit/src/mill/testkit/ExampleTester.scala +++ b/testkit/src/mill/testkit/ExampleTester.scala @@ -63,7 +63,7 @@ object ExampleTester { bashExecutable: String = defaultBashExecutable(), workspacePath: os.Path = os.pwd ): os.Path = { - val tester = new ExampleTester( + val tester = ExampleTester( daemonMode, workspaceSourcePath, millExecutable, diff --git a/testkit/src/mill/testkit/IntegrationTestSuite.scala b/testkit/src/mill/testkit/IntegrationTestSuite.scala index 3853cdc741fa..d80ddba89192 100644 --- a/testkit/src/mill/testkit/IntegrationTestSuite.scala +++ b/testkit/src/mill/testkit/IntegrationTestSuite.scala @@ -48,7 +48,7 @@ trait IntegrationTestSuite { count = if (sys.env.contains("CI")) 1 else 0, timeoutMillis = 10.minutes.toMillis ) { - val tester = new IntegrationTester( + val tester = IntegrationTester( daemonMode, workspaceSourcePath, millExecutable, diff --git a/testkit/src/mill/testkit/IntegrationTester.scala b/testkit/src/mill/testkit/IntegrationTester.scala index 64cf1bbe3854..03fa8374f056 100644 --- a/testkit/src/mill/testkit/IntegrationTester.scala +++ b/testkit/src/mill/testkit/IntegrationTester.scala @@ -292,7 +292,7 @@ object IntegrationTester { * Helpers to read the `.json` metadata files belonging to a particular task * (specified by [[selector0]]) from the `out/` folder. */ - def out(selector0: String): Meta = new Meta(selector0) + def out(selector0: String): Meta = Meta(selector0) class Meta(selector0: String) { diff --git a/testkit/src/mill/testkit/UnitTester.scala b/testkit/src/mill/testkit/UnitTester.scala index 6917a0cde5ce..d2178e855c4e 100644 --- a/testkit/src/mill/testkit/UnitTester.scala +++ b/testkit/src/mill/testkit/UnitTester.scala @@ -78,7 +78,7 @@ class UnitTester( } else { sourceRoot match { case Some(sourceRoot) => - throw new IllegalArgumentException( + throw IllegalArgumentException( s"Cannot provide sourceRoot=$sourceRoot when resetSourcePath=false" ) case None => // ok @@ -91,7 +91,7 @@ class UnitTester( infoColor = mill.internal.Colors.Default.info, warnColor = mill.internal.Colors.Default.warn, errorColor = mill.internal.Colors.Default.error, - systemStreams0 = new SystemStreams(out = outStream, err = errStream, in = inStream), + systemStreams0 = SystemStreams(out = outStream, err = errStream, in = inStream), debugEnabled = debugEnabled, titleText = "", terminfoPath = os.temp(), @@ -132,7 +132,7 @@ class UnitTester( codeSignatures = Map(), systemExit = (reason, exitCode) => throw Exception(s"systemExit called: reason=$reason, exitCode=$exitCode"), - exclusiveSystemStreams = new SystemStreams(outStream, errStream, inStream), + exclusiveSystemStreams = SystemStreams(outStream, errStream, inStream), getEvaluator = () => evaluator, offline = offline, enableTicker = false, @@ -197,7 +197,7 @@ class UnitTester( val res = evaluator.execute(Seq(task)).executionResults val cleaned = res.results.map { - case ExecResult.Exception(ex, _) => ExecResult.Exception(ex, new OuterStack(Nil)) + case ExecResult.Exception(ex, _) => ExecResult.Exception(ex, OuterStack(Nil)) case x => x.map(_.value) } From f9110ab90f29ca5a1b96a51baf87500b4a34e3eb Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Thu, 4 Dec 2025 22:22:58 +0000 Subject: [PATCH 2/2] [autofix.ci] apply automated fixes --- core/exec/src/mill/exec/CodeSigUtils.scala | 2 +- core/internal/src/mill/internal/FileLogger.scala | 2 +- core/internal/src/mill/internal/PrefixLogger.scala | 2 +- core/internal/test/src/mill/internal/PromptLoggerTests.scala | 1 - libs/javalib/src/mill/javalib/JavaModule.scala | 2 +- testkit/src/mill/testkit/UnitTester.scala | 2 +- 6 files changed, 5 insertions(+), 6 deletions(-) diff --git a/core/exec/src/mill/exec/CodeSigUtils.scala b/core/exec/src/mill/exec/CodeSigUtils.scala index d6181c4707ab..b524297dbf49 100644 --- a/core/exec/src/mill/exec/CodeSigUtils.scala +++ b/core/exec/src/mill/exec/CodeSigUtils.scala @@ -1,6 +1,6 @@ package mill.exec -import mill.api.{BuildInfo, MillException} +import mill.api.BuildInfo import mill.api.{Task, Segment} import scala.reflect.NameTransformer.encode diff --git a/core/internal/src/mill/internal/FileLogger.scala b/core/internal/src/mill/internal/FileLogger.scala index aab27fe26e57..429908cf8a56 100644 --- a/core/internal/src/mill/internal/FileLogger.scala +++ b/core/internal/src/mill/internal/FileLogger.scala @@ -1,6 +1,6 @@ package mill.internal -import mill.api.{Logger, SystemStreams} +import mill.api.Logger import mill.api.BuildCtx import java.io.{OutputStream, PrintStream} import java.nio.file.{Files, StandardOpenOption} diff --git a/core/internal/src/mill/internal/PrefixLogger.scala b/core/internal/src/mill/internal/PrefixLogger.scala index a3bd73eb3416..8ceb7712431f 100644 --- a/core/internal/src/mill/internal/PrefixLogger.scala +++ b/core/internal/src/mill/internal/PrefixLogger.scala @@ -1,6 +1,6 @@ package mill.internal -import mill.api.{Logger, SystemStreams} +import mill.api.Logger import java.io.PrintStream diff --git a/core/internal/test/src/mill/internal/PromptLoggerTests.scala b/core/internal/test/src/mill/internal/PromptLoggerTests.scala index 540d998c1ee6..04d59b4cd2c9 100644 --- a/core/internal/test/src/mill/internal/PromptLoggerTests.scala +++ b/core/internal/test/src/mill/internal/PromptLoggerTests.scala @@ -1,6 +1,5 @@ package mill.internal -import mill.api.SystemStreams import mill.constants.ProxyStream import utest.* diff --git a/libs/javalib/src/mill/javalib/JavaModule.scala b/libs/javalib/src/mill/javalib/JavaModule.scala index 2b07e86a5e99..19787fbf3545 100644 --- a/libs/javalib/src/mill/javalib/JavaModule.scala +++ b/libs/javalib/src/mill/javalib/JavaModule.scala @@ -7,7 +7,7 @@ import coursier.params.ResolutionParams import coursier.parse.{JavaOrScalaModule, ModuleParser} import coursier.util.{EitherT, ModuleMatcher, Monad} import mainargs.Flag -import mill.api.{MillException, Result} +import mill.api.Result import mill.api.daemon.internal.{EvaluatorApi, JavaModuleApi, internal} import mill.api.daemon.internal.bsp.{ BspBuildTarget, diff --git a/testkit/src/mill/testkit/UnitTester.scala b/testkit/src/mill/testkit/UnitTester.scala index d2178e855c4e..3db06cdf0782 100644 --- a/testkit/src/mill/testkit/UnitTester.scala +++ b/testkit/src/mill/testkit/UnitTester.scala @@ -1,7 +1,7 @@ package mill.testkit import mill.Task -import mill.api.{BuildCtx, DummyInputStream, ExecResult, Result, SystemStreams, Val} +import mill.api.{BuildCtx, DummyInputStream, ExecResult, Result, Val} import mill.api.ExecResult.OuterStack import mill.constants.OutFiles.OutFiles.millChromeProfile import mill.constants.OutFiles.OutFiles.millProfile