Skip to content

Commit

Permalink
Fix find_root() algorithm
Browse files Browse the repository at this point in the history
This should preserve the function's original intentions while still a) checking all criterion subdirs and b) offering the `logical` param.
  • Loading branch information
salim-b authored and krlmlr committed Dec 31, 2023
1 parent e42f5e5 commit 801bc5e
Showing 1 changed file with 20 additions and 8 deletions.
28 changes: 20 additions & 8 deletions R/root.R
Original file line number Diff line number Diff line change
Expand Up @@ -93,12 +93,17 @@ print.root_criterion <- function(x, ...) {
find_root <- function(criterion, path = ".", logical = FALSE) {
criterion <- as_root_criterion(criterion)
path <- normalizePath(path, winslash = "/", mustWork = !logical)
start_paths <- path
if (length(criterion$subdir)) {
start_paths <- file.path(path, criterion$subdir)
start_paths <- path[dir.exists(path)]
if (length(criterion$subdir) > 0L) {
sub_paths <- file.path(path, criterion$subdir)
sub_paths <- sub_paths[dir.exists(sub_paths)]
if (length(sub_paths) > 0L) {
start_paths <- sub_paths
}
}
start_paths <- start_paths[dir.exists(start_paths)]
root <- NULL
max_depth_reached <- FALSE
max_depth_path <- NULL

for (s in start_paths) {
path <- s
Expand All @@ -111,18 +116,21 @@ find_root <- function(criterion, path = ".", logical = FALSE) {
}
}

if (length(root)) {
if (length(root) > 0L || is_root(path)) {
break
}

if (i == .MAX_DEPTH) {
max_depth_reached <- TRUE
max_depth_path <- path
}

path <- dirname(path)
}

if (length(root) || logical) {
if (length(root) > 0L) {
break
}

stop("Maximum search of ", .MAX_DEPTH, " exceeded. Last path: ", path, call. = FALSE)
}

if (logical) {
Expand All @@ -131,6 +139,10 @@ find_root <- function(criterion, path = ".", logical = FALSE) {
return(path)
}

if (max_depth_reached) {
stop("Maximum search of ", .MAX_DEPTH, " exceeded. Last path: ", max_depth_path, call. = FALSE)
}

stop("No root directory found in ", paste0(start_paths, collapse = ", "), " or ", ifelse(length(start_paths) > 1L, "their", "its"), " parent directories. ",
paste(format(criterion), collapse = "\n"),
call. = FALSE
Expand Down

0 comments on commit 801bc5e

Please sign in to comment.