From e7aa7c726216a97778c522b81f3dcca672cbffe2 Mon Sep 17 00:00:00 2001 From: Som Snytt Date: Fri, 6 Dec 2019 22:34:10 -0800 Subject: [PATCH] sys.env lookup falls back on System.getenv(_) The latter is case-insensitive on certain platforms --- src/library/scala/sys/package.scala | 14 +++++++++++--- test/junit/scala/sys/env.scala | 18 ++++++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) create mode 100644 test/junit/scala/sys/env.scala diff --git a/src/library/scala/sys/package.scala b/src/library/scala/sys/package.scala index be90092cae66..9feec12991a7 100644 --- a/src/library/scala/sys/package.scala +++ b/src/library/scala/sys/package.scala @@ -12,8 +12,9 @@ package scala -import scala.collection.immutable +import scala.collection.immutable.ArraySeq import scala.jdk.CollectionConverters._ +import java.util.NoSuchElementException /** The package object `scala.sys` contains methods for reading * and altering core aspects of the virtual machine as well as the @@ -58,10 +59,17 @@ package object sys { // def prop(p: String) = Option(System.getProperty(p)) /** An immutable Map representing the current system environment. + * + * If lookup fails, use `System.getenv(_)` for case-insensitive lookup + * on a certain platform. If that also fails, throw `NoSuchElementException`. * * @return a Map containing the system environment variables. */ - def env: immutable.Map[String, String] = immutable.Map.from(System.getenv().asScala) + def env: Map[String, String] = Map.from(System.getenv().asScala).withDefault { v => + val s = System.getenv(v) + if (s == null) throw new NoSuchElementException(v) + s + } /** Register a shutdown hook to be run when the VM exits. * The hook is automatically registered: the returned value can be ignored, @@ -85,6 +93,6 @@ package object sys { val tarray = new Array[Thread](num) val got = Thread.enumerate(tarray) - immutable.ArraySeq.unsafeWrapArray(tarray).take(got) + ArraySeq.unsafeWrapArray(tarray).take(got) } } diff --git a/test/junit/scala/sys/env.scala b/test/junit/scala/sys/env.scala new file mode 100644 index 000000000000..38acdedfa452 --- /dev/null +++ b/test/junit/scala/sys/env.scala @@ -0,0 +1,18 @@ +package scala.sys + +import org.junit.Test +import org.junit.Assert._ + +import java.util.NoSuchElementException + +import scala.util.Properties.isWin +import scala.tools.testkit.AssertUtil.assertThrows + +class EnvTest { + @Test def `env is case insensitive`(): Unit = { + assertTrue(sys.env("PATH") != null) + if (isWin) assertTrue(sys.env("path") != null) + } + @Test def `env throws if not found`(): Unit = + assertThrows[NoSuchElementException](sys.env("junk"), _ == "junk") +}