Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sys.env now throws on null environment variable #8579

Merged
merged 1 commit into from Dec 9, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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")
}