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

Add root to Path & root constructor #196

Merged
merged 13 commits into from
Oct 18, 2023
6 changes: 6 additions & 0 deletions os/src-jvm/package.scala
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ package object os {
*/
val root: Path = Path(java.nio.file.Paths.get(".").toAbsolutePath.getRoot)

def root(root: String): Path = {
val path = Path(root)
assert(path.root == root, s"$root is not a root path")
path
}

def resource(implicit resRoot: ResourceRoot = Thread.currentThread().getContextClassLoader) = {
os.ResourcePath.resource(resRoot)
}
Expand Down
6 changes: 6 additions & 0 deletions os/src-native/package.scala
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ package object os {
*/
val root: Path = Path(java.nio.file.Paths.get(".").toAbsolutePath.getRoot)

def root(root: String): Path = {
val path = Path(root)
assert(path.root == root, s"$root is not a root path")
path
}

/**
* The user's home directory
*/
Expand Down
1 change: 1 addition & 0 deletions os/src/Path.scala
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,7 @@ class Path private[os] (val wrapped: java.nio.file.Path)
new SeekableSource.ChannelSource(java.nio.file.Files.newByteChannel(wrapped))

require(wrapped.isAbsolute || Path.driveRelative(wrapped), s"$wrapped is not an absolute path")
def root = Option(wrapped.getRoot).map(_.toString).getOrElse("")
lihaoyi marked this conversation as resolved.
Show resolved Hide resolved
def segments: Iterator[String] = wrapped.iterator().asScala.map(_.toString)
def getSegment(i: Int): String = wrapped.getName(i).toString
def segmentCount = wrapped.getNameCount
Expand Down
9 changes: 9 additions & 0 deletions os/test/src/PathTests.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package test.os

import java.nio.file.Paths
import java.io.File

import os._
import os.Path.{driveRoot}
Expand Down Expand Up @@ -420,6 +421,14 @@ object PathTests extends TestSuite {
assert(result1 == expected)
assert(result2 == expected)
}
test("custom root") {
assert(os.root == os.root(os.root.root))
File.listRoots().foreach { root =>
val path = os.root(root.toPath().toString) / "test" / "dir"
assert(path.root == root.toString)
assert(path.relativeTo(os.root(root.toPath().toString)) == rel / "test" / "dir")
}
}
test("issue201") {
val p = Path("/omg") // driveRelative path does not throw exception.
System.err.printf("p[%s]\n", posix(p))
Expand Down