R/load_fork.R

#' @title Fork a Dataset or Load a Pre-existing Fork
#'
#' @description If a fork of dataset \code{ds0} named \code{name} exists, load that dataset,
#' else create that fork.
#'
#' @param origin_dataset A Crunch dataset or the name of a dataset. The original dataset to be forked. If a
#' character is provided, the original dataset will only be loaded if a fork does not exist and
#' needs to be created.
#' @param fork_name character, the name of the dataset fork to be loaded or created.
#' @param origin_project \code{ProjectFolder} entity, character name (path) to a project, or NULL, the
#' default. Project folder for the original dataset if \code{origin_dataset} is supplied as a character.
#' If a Project entity or reference is supplied, either here or as a path in dataset, the
#' dataset lookup will be limited to that project only.
#' @param fork_project \code{ProjectFolder} entity, character name (path) to a project, or NULL, the
#' default. If a Project entity or reference is supplied, either here or as a path in dataset, the
#' dataset lookup will be limited to that project only.
#' @param kind character specifying whether to look in active, archived, or all datasets. Default is
#' "active", i.e. non-archived.
#' @param refresh logical; should the function check the Crunch API for new datasets? Default is
#' FALSE.
#' @export
load_fork <- function(
    origin_dataset,
    fork_name,
    origin_project = NULL,
    fork_project = NULL,
    kind = c("active", "all", "archived"),
    refresh = FALSE
) {
  if (fork_name %in% listDatasets(kind, fork_project, refresh)) {
    ds <- loadDataset(fork_name, kind, fork_project, refresh)
    return(ds)
  }
  if (is.character(origin_dataset)) {
    origin_dataset <- loadDataset(dataset = origin_dataset, project = origin_project)
  }
  ds <- forkDataset(
    dataset = origin_dataset,
    name = fork_name
  )
  if (!is.null(fork_project)) {
    if (is.character(fork_project)) {
      fork_project <- cd(projects(), fork_project)
    }
    datasets(fork_project) <- ds
  }
  return(ds)
}
domjarkey/crunchscripts documentation built on June 6, 2019, 7:43 p.m.