Skip to content

Instantly share code, notes, and snippets.

@hadley
Created August 8, 2012 17:21
Show Gist options
  • Save hadley/3296792 to your computer and use it in GitHub Desktop.
Save hadley/3296792 to your computer and use it in GitHub Desktop.
document <- function(pkg = NULL, clean = FALSE, roclets = c("collate", "namespace", "rd")) {
require("roxygen2")
man_path <- file.path(pkg$path)
if (!file.path(pkg$path)) dir.create(man_path)
message("Updating ", pkg$package, " documentation")
pkg <- as.package(pkg)
if (clean) {
clear_caches()
file.remove(dir(file.path(pkg$path, "man"), full.names = TRUE))
load_all(pkg, reset = TRUE)
} else {
load_all(pkg)
}
# Could avoid this duplication if load_all returned a list combining
# the results of all the individual load functions
r_files <- find_code(pkg$path)
env <- pkg_env(pkg)
env_hash <- suppressWarnings(digest(env))
parsed <- lapply(paths, parse.file, env = env, env_hash = env_hash),
recursive = FALSE)
roclets <- str_c(roclets, "_roclet", sep = "")
for (roclet in roclets) {
roc <- match.fun(roclet)()
results <- roc_process(roc, parsed, roxygen.dir)
roc_output(roc, results, roxygen.dir)
}
invisible()
}
load_code <- function(pkg = NULL, env = pkg_env(pkg)) {
pkg <- as.package(pkg)
r_files <- find_code(pkg)
paths <- changed_files(r_files)
tryCatch(
lapply(paths, sys.source, envir = env, chdir = TRUE,
keep.source = TRUE),
error = function(e) {
clear_cache()
stop(e)
}
)
# Load .onLoad if it's defined
if (exists(".onLoad", env, inherits = FALSE) &&
!exists("__loaded", env, inherits = FALSE)) {
env$.onLoad()
env$`__loaded` <- TRUE
}
invisible(paths)
}
#' Parse collate string into vector of function names.
#' @keywords internal
parse_collate <- function(string) {
con <- textConnection(string)
on.exit(close(con))
scan(con, "character", sep = " ", quiet = TRUE)
}
#' Find all R files in given directory.
#' @keywords internal
find_code <- function(pkg) {
path_r <- file.path(pkg$path, "R")
code_paths <- dir(path_r, "\\.[Rrq]$", full.names = TRUE)
r_files <- with_collate("C", sort(code_paths))
if (!is.null(pkg$collate)) {
collate <- file.path(path_r, parse_collate(pkg$collate))
missing <- setdiff(collate, r_files)
files <- function(x) paste(basename(x), collapse = ", ")
if (length(missing) > 0) {
message("Skipping missing files: ", files(missing))
}
extra <- setdiff(r_files, collate)
if (length(extra) > 0) {
message("Adding files missing in collate: ", files(extra))
}
r_files <- union(collate, r_files)
}
r_files
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment