pacs
pacs copied to clipboard
Find exported functions usage
Example code:
# Improved function to get only exported functions from a package
get_exported_functions <- function(package_name) {
exported_objects <- getNamespaceExports(package_name)
exported_functions <- exported_objects[sapply(exported_objects, function(name) {
is.function(get(name, envir = asNamespace(package_name)))
})]
return(exported_functions)
}
# Function to recursively list all files in a directory remains unchanged
list_files_recursively <- function(path) {
all_files <- list.files(path, full.names = TRUE, recursive = TRUE)
return(all_files)
}
# Improved function to search for a regex pattern in files
search_pattern_in_files <- function(files, patterns) {
results <- list()
# Compile a single regex pattern from all patterns for efficiency
compiled_pattern <- paste0("\\b(", paste(patterns, collapse = "|"), ")\\b\\s*\\(")
for (file_path in files) {
# Process only R and Rmd files
if (grepl("\\.R$", file_path) || grepl("\\.Rmd$", file_path)) {
tryCatch({
content <- readLines(file_path, warn = FALSE)
for (i in seq_along(content)) {
if (grepl(compiled_pattern, content[i], perl = TRUE)) {
matched_function <- regmatches(content[i], regexpr(compiled_pattern, content[i]))
results[[length(results) + 1]] <- list(file = file_path, line = i, text = content[i], pattern = matched_function)
}
}
}, error = function(e) {
message(sprintf("Error reading %s: %s", file_path, e$message))
})
}
}
return(results)
}
# Main execution function remains conceptually the same but with improved internal logic
search_for_exported_functions_usage <- function(package_name, directories) {
exported_functions <- get_exported_functions(package_name)
all_files <- unlist(lapply(directories, list_files_recursively))
search_results <- search_pattern_in_files(all_files, exported_functions)
if (length(search_results) > 0) {
for (result in search_results) {
cat(sprintf("File: %s, Line: %d, Pattern: %s, Text: %s\n", result$file, result$line, result$pattern, result$text))
}
} else {
cat("No matches found.\n")
}
}
# Define directories to search and execute the search
directories <- c("R", "vignettes", "tests/testthat")
search_for_exported_functions_usage("dplyr", directories)