Skip to content

Commit 15aa933

Browse files
authored
Add a PathConvertible for URI (#142)
Only the "file" protocol is supported. Other protocols and unsupported URIs will throw a `IllegalArgumentException`. Pull request: #142
1 parent c9f042e commit 15aa933

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

os/src/Path.scala

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
package os
22

3+
import java.net.URI
4+
import java.nio.file.Paths
5+
36
import collection.JavaConverters._
47
import scala.language.implicitConversions
58

@@ -501,12 +504,21 @@ sealed trait PathConvertible[T] {
501504

502505
object PathConvertible {
503506
implicit object StringConvertible extends PathConvertible[String] {
504-
def apply(t: String) = java.nio.file.Paths.get(t)
507+
def apply(t: String) = Paths.get(t)
505508
}
506509
implicit object JavaIoFileConvertible extends PathConvertible[java.io.File] {
507-
def apply(t: java.io.File) = java.nio.file.Paths.get(t.getPath)
510+
def apply(t: java.io.File) = Paths.get(t.getPath)
508511
}
509512
implicit object NioPathConvertible extends PathConvertible[java.nio.file.Path] {
510513
def apply(t: java.nio.file.Path) = t
511514
}
515+
implicit object UriPathConvertible extends PathConvertible[URI] {
516+
def apply(uri: URI) = uri.getScheme() match {
517+
case "file" => Paths.get(uri)
518+
case uriType =>
519+
throw new IllegalArgumentException(
520+
s"""os.Path can only be created from a "file" URI scheme, but found "${uriType}""""
521+
)
522+
}
523+
}
512524
}

os/test/src/PathTests.scala

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import java.nio.file.Paths
44

55
import os._
66
import utest.{assert => _, _}
7+
import java.net.URI
78
object PathTests extends TestSuite{
89
val tests = Tests {
910
test("Basic"){
@@ -19,6 +20,20 @@ object PathTests extends TestSuite{
1920
assert(rel/"omg" == RelPath(Paths.get("omg")))
2021
assert(sub/"omg" == SubPath(Paths.get("omg")))
2122

23+
// URI to os.Path
24+
assert(root / "omg" == Path(Paths.get("/omg").toUri()))
25+
26+
// We only support file schemes like above, but nothing else
27+
val httpUri = URI.create(
28+
"https://[email protected]:123/forum/questions/?tag=networking&order=newest#top"
29+
)
30+
val ldapUri = URI.create(
31+
"ldap://[2001:db8::7]/c=GB?objectClass?one"
32+
)
33+
intercept[IllegalArgumentException](Path(httpUri))
34+
intercept[IllegalArgumentException](Path(ldapUri))
35+
36+
2237
// os.Path to String
2338
assert((root/"omg").toString == "/omg")
2439
assert((rel/"omg").toString == "omg")

0 commit comments

Comments
 (0)