| 1 |
|
| 2 |
#' Relative path utility function |
| 3 |
#' |
| 4 |
#' Given a directory and a file, return a relative path from the directory to |
| 5 |
#' the file, or the unmodified file path if the file does not appear to be in |
| 6 |
#' the directory. |
| 7 |
#' |
| 8 |
#' @param dir Directory |
| 9 |
#' @param file File |
| 10 |
#' |
| 11 |
#' @return Relative path from the directory to the file (or the unmodified file |
| 12 |
#' path if the file does not appear to be in the directory). |
| 13 |
#' |
| 14 |
#' @export |
| 15 |
relative_to <- function(dir, file) { |
| 16 |
# ensure directory ends with a / |
| 17 |
dir <- sub('/+$', '/', paste0(dir, '/')) |
| 18 |
|
| 19 |
# if the file is prefixed with the directory, return a relative path |
| 20 |
if (identical(substr(file, 1, nchar(dir)), dir)) |
| 21 |
file <- substr(file, nchar(dir) + 1, nchar(file)) |
| 22 |
|
| 23 |
# simplify ./ |
| 24 |
sub('^[.]/', '', file) |
| 25 |
} |
| 26 |
|
| 27 |
# A variant of relative_to that normalizes its inputs. |
| 28 |
normalized_relative_to <- function(dir, file) { |
| 29 |
relative_to( |
| 30 |
normalize_path(dir, must_work = FALSE), |
| 31 |
normalize_path(file, must_work = FALSE)) |
| 32 |
} |
| 33 |
|
| 34 |
# If a path is a relative path, it should be the same as ./path |
| 35 |
is_relative <- function(path) { |
| 36 |
same_path(path, file.path('.', path), must_work = FALSE) |
| 37 |
} |