Skip to content

Commit

Permalink
sys.env lookup falls back on System.getenv(_)
Browse files Browse the repository at this point in the history
The latter is case-insensitive on certain platforms
  • Loading branch information
som-snytt authored and lrytz committed Dec 9, 2019
1 parent 049417e commit e7aa7c7
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
14 changes: 11 additions & 3 deletions src/library/scala/sys/package.scala
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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)
}
}
18 changes: 18 additions & 0 deletions 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")
}

0 comments on commit e7aa7c7

Please sign in to comment.