Created
February 9, 2025 19:36
-
-
Save JosiahParry/e40e0e800fb686832ecdd72149ef75fb to your computer and use it in GitHub Desktop.
Function to list all files based on globs, file names, and directories.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
list_all_files <- function(include = "*") { | |
# list all files in the current directory recursing | |
all_files <- fs::dir_ls(recurse = TRUE, all = TRUE, type = "any") | |
# Identify directory patterns explicitly mentioned | |
matched_dirs <- include[fs::dir_exists(include)] | |
# Get *all* files inside matched directories | |
extra_files <- unlist( | |
lapply( | |
matched_dirs, | |
function(d) fs::dir_ls(d, recurse = TRUE, all = TRUE) | |
) | |
) | |
# Convert glob patterns to regex | |
regex_patterns <- sapply(include, function(p) { | |
if (grepl("\\*", p)) { | |
utils::glob2rx(p) # Convert glob to regex | |
} else { | |
paste0("^", p, "$") # Match exact filenames | |
} | |
}) | |
# Match files against regex patterns | |
matched_files <- all_files[sapply(all_files, function(file) { | |
any(stringr::str_detect(file, regex_patterns)) | |
})] | |
# Combine matched files and all directory contents | |
unique(c(matched_files, extra_files)) | |
} | |
include <- c( | |
"*.Rmd", | |
"*.tex", | |
"_book", | |
"_output.yml", | |
"\\.R$", | |
"*.html", | |
"book.bib", | |
"thumbnail.jpeg", | |
"README.*" | |
) | |
list_all_files(include) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment