Created
October 1, 2023 04:10
-
-
Save ttnsy/680eb948c5bfb30895f0953d2eb972ad to your computer and use it in GitHub Desktop.
Generates a DataFrame mapping functions to their source and target files, with optional box::use() formatting.
This file contains 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
library(stringr) | |
library(glue) | |
get_target_files <- function(path_target) { | |
filenames <- list.files( | |
path = path_source, | |
full.names = TRUE, | |
include.dirs = FALSE | |
) | |
dat <- tibble( | |
file = NA, | |
func = NA | |
) | |
for (filename in filenames){ | |
src_cd <- readLines(filename) | |
pattern <- "\\b\\w+\\b(?=\\s*<-\\s*function\\b)" | |
out <- dplyr::tibble( | |
file = filename, | |
func = na.omit(str_extract(src_cd, pattern)) %>% as.vector() | |
) | |
dat <- rbind( | |
dat, | |
out | |
) | |
} | |
dat | |
} | |
#' Return a DataFrame containing: | |
#' - file_src: The source file where the function is stored | |
#' - file_target: The file that utilizes the function | |
#' - func: Name of the function. If return_as_box_mod is set to TRUE, | |
#' it will be returned in the format of box::use() instead. | |
detect_function <- function(path_source, path_target, target_exclude, return_as_box_mod = FALSE) { | |
dat <- get_target_files(path_target) %>% | |
tidyr::drop_na() | |
dat_res <- tibble( | |
file_target = NA, | |
file_src = NA, | |
func = NA | |
) | |
for (i in 1:nrow(dat)){ | |
file <- dat[i,]$file | |
func <- dat[i,]$func | |
file_target <- list.files( | |
path = path_target, | |
full.names = TRUE, | |
include.dirs = FALSE | |
) | |
file_target <- file_target[file_target!=target_exclude] | |
targets <- c() | |
for(filename in file_target){ | |
if (length(grep(glue::glue("{func}\\("), readLines(filename))) > 0){ | |
targets <- append(filename, targets) | |
} | |
} | |
if(!is.null(targets)){ | |
file_src <- gsub('.R','', file) | |
dat_res <- rbind( | |
dat_res, | |
tibble( | |
file_target = targets, | |
file_src = file_src, | |
func = func | |
) | |
) | |
} | |
} | |
out <- dat_res %>% | |
arrange(func) %>% | |
group_by(file_target, file_src) %>% | |
summarise( | |
func = glue_collapse(func, sep = ", ") | |
) %>% | |
ungroup() | |
if(isTRUE(return_as_box_mod)) { | |
out <- out %>% | |
group_by(file_target) %>% | |
summarise( | |
module = glue::glue("{file_src}[{func}]"), | |
module = glue::glue_collapse(module, sep = ", \n"), | |
module = glue("box::use(\n {module} \n)") | |
) %>% | |
distinct() | |
} | |
out | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment