Fix absolutePath to correctly handle absolute paths

This commit is contained in:
Winston Chang
2018-06-21 15:48:39 -05:00
parent ae5deae6e9
commit 9af2775539
2 changed files with 57 additions and 4 deletions

View File

@@ -293,6 +293,18 @@ dirRemove <- function(path) {
# difference is that a canonical path follows symlinks and doesn't have any
# `..`, while an absolute path here is simply one that starts with `/`.
absolutePath <- function(path) {
if (!is.character(path) || length(path) != 1 || path == "") {
stop("path must be a single non-empty string.")
}
if (substr(path, 1, 1) == "/") {
return(path)
}
if (isWindows()) {
# C:/abcd or c:\abcd
if (grepl("^[A-Za-z]:[/\\]", path)) {
return(path)
}
}
norm_path <- normalizePath(path, mustWork = FALSE)
if (path == norm_path) {
file.path(getwd(), path)
@@ -1711,14 +1723,14 @@ createVarPromiseDomain <- function(env, name, value) {
force(env)
force(name)
force(value)
promises::new_promise_domain(
wrapOnFulfilled = function(onFulfilled) {
function(...) {
orig <- env[[name]]
env[[name]] <- value
on.exit(env[[name]] <- orig)
onFulfilled(...)
}
},
@@ -1727,7 +1739,7 @@ createVarPromiseDomain <- function(env, name, value) {
orig <- env[[name]]
env[[name]] <- value
on.exit(env[[name]] <- orig)
onRejected(...)
}
},
@@ -1739,4 +1751,4 @@ createVarPromiseDomain <- function(env, name, value) {
force(expr)
}
)
}
}

View File

@@ -191,3 +191,44 @@ test_that("Callbacks fire in predictable order", {
cb$invoke()
expect_equal(x, c(1, 2, 3))
})
test_that("absolutePath works as expected", {
# Relative paths that don't exist
expect_identical(absolutePath("foo9484"), file.path(getwd(), "foo9484"))
expect_identical(absolutePath("foo9484/bar"), file.path(getwd(), "foo9484/bar"))
# Absolute path that exists and does NOT have a symlink
expect_identical(absolutePath("/"), "/")
# Find a path that is not a symlink and test it.
# Use paste0 instead of file.path("/", ...) or dir(full.names=T) because
# those can result in two leading slashes.
paths <- paste0("/", dir("/"))
symlink_idx <- (Sys.readlink(paths) != "")
paths <- paths[!symlink_idx]
if (length(paths) != 0) {
test_path <- paths[1]
expect_identical(absolutePath(test_path), test_path)
}
# On Windows, absolute paths can start with a drive letter.
if (isWindows()) {
expect_identical(absolutePath("z:/foo9484"), "z:/foo9484")
expect_identical(absolutePath("c:\\foo9484"), "c:\\foo9484")
expect_identical(absolutePath("d:\\"), "d:\\")
expect_identical(absolutePath("d:/"), "d:/")
}
# Absolute path that doesn't exist
expect_identical(absolutePath("/foo9484"), "/foo9484")
expect_identical(absolutePath("/foo9484/bar"), "/foo9484/bar")
# Invalid input
expect_error(absolutePath(NULL))
expect_error(absolutePath(NA))
expect_error(absolutePath(character(0)))
expect_error(absolutePath(""))
expect_error(absolutePath(12))
expect_error(absolutePath(c("a", "b")))
expect_error(absolutePath(list("abc")))
})