Skip to content

Instantly share code, notes, and snippets.

@mschmidty
Created February 8, 2025 04:00
Show Gist options
  • Select an option

  • Save mschmidty/5ac635583ef4f929ef82cf4efdfd9d33 to your computer and use it in GitHub Desktop.

Select an option

Save mschmidty/5ac635583ef4f929ef82cf4efdfd9d33 to your computer and use it in GitHub Desktop.
A simple cli in R to make a project_config.yml
library(cli)
library(yaml)
# Function to prompt user for input with an optional default value using readline()
ask_question <- function(question, default = NULL) {
if (!is.null(default)) {
prompt <- paste0(question, " (default: ", default, "): ")
} else {
prompt <- paste0(question, ": ")
}
answer <- readline(prompt)
if (answer == "" && !is.null(default)) {
return(default)
}
return(answer)
}
# Function to capture multiple dependencies interactively using readline()
ask_list <- function(question) {
cli::cli_alert_info("{question} (Press Enter after each item, type 'done' to finish)")
items <- character()
repeat {
item <- readline("> ")
if (tolower(item) == "done" || item == "") break
items <- c(items, item)
}
return(items)
}
# Start interactive session
cli::cli_h1("Project Setup")
project_name <- ask_question("Enter project name", "my_project")
author_name <- ask_question("Enter your name", "Anonymous")
version <- ask_question("Enter project version", "0.1.0")
license <- ask_question("Enter license type", "MIT")
# Collect dependencies interactively
dependencies <- ask_list("Enter project dependencies (one per line)")
# Structure collected data into a list
project_config <- list(
project = list(
name = project_name,
version = version,
author = author_name,
license = license,
dependencies = dependencies
)
)
# Convert list to YAML format
yaml_output <- as.yaml(project_config)
# Save the YAML configuration to a file
yaml_file <- "project_config.yaml"
writeLines(yaml_output, yaml_file)
cli::cli_alert_success("Configuration saved to '{yaml_file}'")
project:
name: Tri State Project
version: 0.1.0
author: Michael Schmidt
license: MIT
dependencies:
- dplyr
- MetBrewer
- cli
- sf
- terra
source("cli_test_1.R")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment