Extracting relative file paths.

getRelative(path, relativeToPath)

makeRelative(files, absoluteBase)

Arguments

path

character vector or list specifying file paths

relativeToPath

directory against which path will be relativized.

files

character vector or list specifying file paths

absoluteBase

base directory (as absolute path) to prepend to files

Details

  • getRelative() searches path "from the right" (instead of "from the left") and tries to reconstruct it relative to directory specified by relativeToPath. This is useful when dealing with symlinked paths.

  • makeRelative() checks to see if files and normPath(absoluteBase) share a common path (i.e., "from the left"), otherwise it returns files.

Examples


## create a project directory (e.g., on a hard drive)
(tmp1 <- tempdir2("myProject", create = TRUE))
#> [1] "/tmp/RtmpxA3jdR/reproducible/myProject"

## create a cache directory elsewhere (e.g., on an SSD)
(tmp2 <- tempdir2("my_cache", create = TRUE))
#> [1] "/tmp/RtmpxA3jdR/reproducible/my_cache"

## symlink the project cache directory to tmp2
## files created here are actually stored in tmp2
prjCache <- file.path(tmp1, "cache")
file.symlink(tmp2, prjCache)
#> [1] TRUE

## create a dummy cache object file in the project cache dir
(tmpf <- tempfile("cache_", prjCache))
#> [1] "/tmp/RtmpxA3jdR/reproducible/myProject/cache/cache_21253e91f929"
cat(rnorm(100), file = tmpf)
file.exists(tmpf)
#> [1] TRUE
normPath(tmpf) ## note the 'real' location (i.e., symlink resolved)
#> [1] "/tmp/RtmpxA3jdR/reproducible/my_cache/cache_21253e91f929"

getRelative(tmpf, prjCache) ## relative path
#> /tmp/RtmpxA3jdR/reproducible/myProject/cache/cache_21253e91f929 
#>                                            "cache_21253e91f929" 
getRelative(tmpf, tmp2) ## relative path
#> /tmp/RtmpxA3jdR/reproducible/myProject/cache/cache_21253e91f929 
#>                            "myProject/cache/cache_21253e91f929" 

makeRelative(tmpf, tmp2) ## abs path; tmpf and normPath(tmp2) don't share common path
#> [1] "/tmp/RtmpxA3jdR/reproducible/myProject/cache/cache_21253e91f929"
makeRelative(tmpf, prjCache) ## abs path; tmpf and normPath(tmp2) don't share common path
#> [1] "/tmp/RtmpxA3jdR/reproducible/myProject/cache/cache_21253e91f929"
makeRelative(normPath(tmpf), prjCache) ## rel path; share common path when both normPath-ed
#> [1] "cache_21253e91f929"

unlink(tmp1, recursive = TRUE)
unlink(tmp2, recursive = TRUE)