From 1daf5e28a63657652a723cf9238197d248898fe4 Mon Sep 17 00:00:00 2001 From: yangjie01 Date: Wed, 20 Mar 2024 15:19:33 +0800 Subject: [PATCH] [SPARK-47455][BUILD] Fix resource leak during the initialization of `scalaStyleOnCompileConfig` in `SparkBuild.scala` ### What changes were proposed in this pull request? https://github.com/apache/spark/blob/e01ed0da22f24204fe23143032ff39be7f4b56af/project/SparkBuild.scala#L157-L173 `Source.fromFile(in)` opens a `BufferedSource` resource handle, but it does not close it, this pr fix this issue. ### Why are the changes needed? Close resource after used. ### Does this PR introduce _any_ user-facing change? No ### How was this patch tested? Pass GitHub Actions ### Was this patch authored or co-authored using generative AI tooling? No Closes #45582 from LuciferYang/SPARK-47455. Authored-by: yangjie01 Signed-off-by: yangjie01 (cherry picked from commit 85bf7615f85eea3e9192a7684ef711cf44042e05) Signed-off-by: yangjie01 --- project/SparkBuild.scala | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/project/SparkBuild.scala b/project/SparkBuild.scala index 0c3f2a85a69c7..36e8be589b7ea 100644 --- a/project/SparkBuild.scala +++ b/project/SparkBuild.scala @@ -159,16 +159,21 @@ object SparkBuild extends PomBuild { val replacements = Map( """customId="println" level="error"""" -> """customId="println" level="warn"""" ) - var contents = Source.fromFile(in).getLines.mkString("\n") - for ((k, v) <- replacements) { - require(contents.contains(k), s"Could not rewrite '$k' in original scalastyle config.") - contents = contents.replace(k, v) - } - new PrintWriter(out) { - write(contents) - close() + val source = Source.fromFile(in) + try { + var contents = source.getLines.mkString("\n") + for ((k, v) <- replacements) { + require(contents.contains(k), s"Could not rewrite '$k' in original scalastyle config.") + contents = contents.replace(k, v) + } + new PrintWriter(out) { + write(contents) + close() + } + out + } finally { + source.close() } - out } // Return a cached scalastyle task for a given configuration (usually Compile or Test)