expand tilde prefix

This commit is contained in:
kai-chi 2018-09-19 15:39:42 +02:00
parent fbce3232a8
commit 3f1ce8b9a0
2 changed files with 84 additions and 1 deletions

View File

@ -78,7 +78,29 @@ object BuildPaths {
def getFileProperty(name: String): Option[File] = Option(System.getProperty(name)) flatMap {
path =>
if (path.isEmpty) None else Some(new File(path))
if (path.isEmpty) None
else {
if (path.head == '~') {
val tildePath = expandTildePrefix(path)
Some(new File(tildePath))
} else {
Some(new File(path))
}
}
}
def expandTildePrefix(path: String): String = {
val tildePath = path.split("\\/").headOption match {
case Some("~") => sys.env.getOrElse("HOME", "")
case Some("~+") => sys.env.getOrElse("PWD", "")
case Some("~-") => sys.env.getOrElse("OLDPWD", "")
case _ => ""
}
path.indexOf("/") match {
case -1 => tildePath
case _ => tildePath + path.substring(path.indexOf("/"))
}
}
def defaultVersionedGlobalBase(sbtVersion: String): File = defaultGlobalBase / sbtVersion

View File

@ -0,0 +1,61 @@
/*
* sbt
* Copyright 2011 - 2018, Lightbend, Inc.
* Copyright 2008 - 2010, Mark Harrah
* Licensed under Apache License 2.0 (see LICENSE)
*/
package sbt
import org.specs2.mutable.Specification
import sbt.BuildPaths
object BuildPathsTest extends Specification {
private def assertExpandedPath(given: String, expected: String) = {
val actual = BuildPaths.expandTildePrefix(given)
actual must be equalTo (expected)
}
"expandTildePrefix" should {
"expand empty path to itself" in {
assertExpandedPath("", "")
}
"expand /home/user/path to itself" in {
assertExpandedPath("/home/user/path", "/home/user/path")
}
"expand /~/foo/ to itself" in {
assertExpandedPath("/~/foo/", "/~/foo/")
}
"expand ~ to $HOME" in {
assertExpandedPath("~", sys.env.getOrElse("HOME", ""))
}
"expand ~/foo/bar to $HOME/foo/bar" in {
assertExpandedPath("~/foo/bar", sys.env.getOrElse("HOME", "") + "/foo/bar")
}
"expand ~+ to $PWD" in {
assertExpandedPath("~+", sys.env.getOrElse("PWD", ""))
}
"expand ~+/foo/bar to $PWD/foo/bar" in {
assertExpandedPath("~+/foo/bar", sys.env.getOrElse("PWD", "") + "/foo/bar")
}
"expand ~- to $OLDPWD" in {
assertExpandedPath("~-", sys.env.getOrElse("OLDPWD", ""))
}
"expand ~-/foo/bar to $OLDPWD/foo/bar" in {
assertExpandedPath("~-/foo/bar", sys.env.getOrElse("OLDPWD", "") + "/foo/bar")
}
}
}