Skip to content

Commit

Permalink
add depth, uri-encoding handling
Browse files Browse the repository at this point in the history
  • Loading branch information
ryan-williams committed Aug 4, 2017
1 parent ca2fc30 commit 71d14e2
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 8 deletions.
28 changes: 20 additions & 8 deletions src/main/scala/org/hammerlab/paths/Path.scala
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package org.hammerlab.paths

import java.io.{ InputStream, ObjectStreamException, OutputStream, PrintWriter }
import java.net.URI
import java.net.{ URI, URISyntaxException }
import java.nio.file.Files.{ newDirectoryStream, newInputStream, newOutputStream, readAllBytes }
import java.nio.file.{ DirectoryStream, Files, Paths, Path JPath }

Expand Down Expand Up @@ -35,6 +35,14 @@ case class Path(path: JPath) {
def parent: Path = parentOpt.getOrElse(this)
def parentOpt: Option[Path] = Option(path.getParent).map(Path(_))

def depth: Int =
if (path.isAbsolute)
parentOpt
.map(_.depth + 1)
.getOrElse(0)
else
Path(path.toAbsolutePath).depth

def basename: String = path.getFileName.toString

def size: Long = Files.size(path)
Expand Down Expand Up @@ -134,13 +142,17 @@ object Path {
Paths.get(uri)
}

def apply(pathStr: String): Path = {
val uri = new URI(pathStr)
if (uri.getScheme == null)
new Path(get(pathStr))
else
Path(uri)
}
def apply(pathStr: String): Path =
try {
val uri = new URI(pathStr)
if (uri.getScheme == null)
new Path(get(pathStr))
else
Path(uri)
} catch {
case _: URISyntaxException
new Path(get(pathStr))
}

def apply(uri: URI): Path = Path(get(uri))

Expand Down
21 changes: 21 additions & 0 deletions src/test/scala/org/hammerlab/paths/PathTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -176,4 +176,25 @@ class PathTest
Path("a").parent should be(Path("a"))
Path("a/b").parent should be(Path("a"))
}

val testDirDepth = Path(".").depth

test("depth") {
Path("/").depth should be(0)
Path("/a").depth should be(1)
Path("/a/b").depth should be(2)

Path("a").depth should be(testDirDepth)
Path("a/b").depth should be(testDirDepth + 1)
}

test("with spaces") {
Path("a b").depth should be(testDirDepth)
Path("a b/c d").depth should be(testDirDepth + 1)
Path("/a b").depth should be(1)
Path("/a b/c d").depth should be(2)

// Invalid characters for URI, interpret as local file
Path("hdfs:///a b").uri.getScheme should be("file")
}
}

0 comments on commit 71d14e2

Please sign in to comment.