Skip to content

Instantly share code, notes, and snippets.

@alex-gable
Last active June 3, 2021 14:44
Show Gist options
  • Save alex-gable/783f1d680d2f1938e9dde00d23bf2736 to your computer and use it in GitHub Desktop.
Save alex-gable/783f1d680d2f1938e9dde00d23bf2736 to your computer and use it in GitHub Desktop.
R project Init with usethis + renv
#' initialize_project
#'
#' @param database_user defaulted to `NULL`. if you use a database in your
#' project, this parameter takes your username as its value
#' prompts for creation if not
#' @param use_renv should the project use renv?
#' @param use_vscode do you use vscode for your project?
#' @param include_readme creates a README.md file
#' @param include_sql creates a directory for sql files
#' @param include_data creates a directory for data in, out, and temporary
#' @param include_img creates a directory for images
#' @param include_tmp creates a tmp directory and adds it to git ignore
#'
#' @description Initializes a new R Project
#'
#' @importFrom usethis create_project use_readme_md use_git use_git_ignore
#' @importFrom fs path_join path_wd dir_create
#'
#' @export
initialize_project <- function(database_user = NULL,
use_renv = TRUE,
use_vscode = FALSE,
include_readme = TRUE,
include_sql = TRUE,
include_data = TRUE,
include_img = TRUE,
include_tmp = TRUE) {
# helper functions for file/path creation
.create_path <- function(sub_dir, root_dir = NULL) {
if (is.null(root_dir)) root_dir <- fs::path_wd()
fs::path_join(c(root_dir, sub_dir))
}
.create_dir_at_path <- function(path, root = fs::path_wd()) {
p <- .create_path(path, root)
if (!fs::dir_exists(p)) fs::dir_create(p)
}
# begin project scaffolding..
usethis::create_project(fs::path_wd(),
rstudio = FALSE,
open = TRUE)
if (use_renv) {
if (!requireNamespace("renv", quietly = TRUE)) {
install.packages("renv")
}
renv::init()
}
usethis::use_readme_md(open = FALSE)
fs::file_create(.create_path(".Renviron"))
if (use_renv) {
cat(
c("RENV_CONFIG_AUTO_SNAPSHOT = TRUE"),
file = .create_path(".Renviron"),
sep = "\n",
append = TRUE
)
}
default_ignores <- c("*.Rproj", ".vscode", ".Rhistory", ".DS_Store",
".Ruserdata", ".Renviron", ".here", "tmp")
usethis::use_git("initial commit")
usethis::use_git_ignore(default_ignores)
.create_dir_at_path("R")
if (include_sql) .create_dir_at_path("sql")
if (include_data) {
.create_dir_at_path("data")
data_path <- .create_path("data")
date_paths <- c("in", "tmp", "out")
invisible(lapply(date_paths, .create_dir_at_path, root = data_path))
}
if (include_img) .create_dir_at_path("img")
if (include_tmp) .create_dir_at_path("tmp")
if (!is.null(database_user)) {
if (!database_credentials_exist(database_user)) {
database_set_credentials(database_user)
}
}
if (use_vscode) {
if (!requireNamespace("language-server", quietly = TRUE)) {
install.packages("language-server")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment