Debian Codegraph @

R/app_template.R

raw
1 #' Generate a Shiny application from a template
2 #'
3 #' This function populates a directory with files for a Shiny application.
4 #'
5 #' In an interactive R session, this function will, by default, prompt the user
6 #' to select which components to add to the application. Choices are
7 #'
8 #' ```
9 #' 1: All
10 #' 2: app.R : Main application file
11 #' 3: R/example.R : Helper file with R code
12 #' 4: R/example-module.R : Example module
13 #' 5: tests/testthat/ : Tests using the testthat and shinytest2 package
14 #' ```
15 #'
16 #' If option 1 is selected, the full example application including the
17 #' following files and directories is created:
18 #'
19 #' ```
20 #' appdir/
21 #' |- app.R
22 #' |- R
23 #' | |- example-module.R
24 #' | `- example.R
25 #' `- tests
26 #' |- testthat.R
27 #' `- testthat
28 #' |- setup-shinytest2.R
29 #' |- test-examplemodule.R
30 #' |- test-server.R
31 #' |- test-shinytest2.R
32 #' `- test-sort.R
33 #' ```
34 #'
35 #' Some notes about these files:
36 #' * `app.R` is the main application file.
37 #' * All files in the `R/` subdirectory are automatically sourced when the
38 #' application is run.
39 #' * `R/example.R` and `R/example-module.R` are automatically sourced when
40 #' the application is run. The first contains a function `lexical_sort()`,
41 #' and the second contains code for module created by the
42 #' [moduleServer()] function, which is used in the application.
43 #' * `tests/` contains various tests for the application. You may
44 #' choose to use or remove any of them. They can be executed by the
45 #' [runTests()] function.
46 #' * `tests/testthat.R` is a test runner for test files in the
47 #' `tests/testthat/` directory using the
48 #' [shinytest2](https://rstudio.github.io/shinytest2/reference/test_app.html)
49 #' package.
50 #' * `tests/testthat/setup-shinytest2.R` is setup file to source your `./R` folder into the testing environment.
51 #' * `tests/testthat/test-examplemodule.R` is a test for an application's module server function.
52 #' * `tests/testthat/test-server.R` is a test for the application's server code
53 #' * `tests/testthat/test-shinytest2.R` is a test that uses the
54 #' [shinytest2](https://rstudio.github.io/shinytest2/) package to do
55 #' snapshot-based testing.
56 #' * `tests/testthat/test-sort.R` is a test for a supporting function in the `R/` directory.
57 #'
58 #' @param path Path to create new shiny application template.
59 #' @param examples Either one of "default", "ask", "all", or any combination of
60 #' "app", "rdir", "module", and "tests". In an
61 #' interactive session, "default" falls back to "ask"; in a non-interactive
62 #' session, "default" falls back to "all". With "ask", this function will
63 #' prompt the user to select which template items will be added to the new app
64 #' directory. With "all", all template items will be added to the app
65 #' directory.
66 #' @param dryrun If `TRUE`, don't actually write any files; just print out which
67 #' files would be written.
68 #'
69 #' @export
70 shinyAppTemplate <- function(path = NULL, examples = "default", dryrun = FALSE)
71 {
72 if (is.null(path)) {
73 stop("Please provide a `path`.")
74 }
75
76 # =======================================================
77 # Option handling
78 # =======================================================
79
80 choices <- c(
81 app = "app.R : Main application file",
82 rdir = "R/example.R : Helper file with R code",
83 module = "R/example-module.R : Example module",
84 tests = "tests/testthat/ : Tests using {testthat} and {shinytest2}"
85 )
86
87 # Support legacy value
88 examples[examples == "shinytest"] <- "tests"
89 examples[examples == "testthat"] <- "tests"
90 examples <- unique(examples)
91
92 if (identical(examples, "default")) {
93 if (rlang::is_interactive()) {
94 examples <- "ask"
95 } else {
96 examples <- "all"
97 }
98 }
99
100 if (!identical(examples, "ask") &&
101 !identical(examples, "all") &&
102 any(! examples %in% names(choices)))
103 {
104 stop('`examples` must be one of "default", "ask", "all", or any combination of "',
105 paste(names(choices), collapse = '", "'), '".')
106 }
107
108 if (identical(examples, "ask")) {
109 response <- select_menu(
110 c(all = "All", choices),
111 title = paste0(
112 "Select which of the following to add at ", path, "/ :"
113 ),
114 msg = "Enter one or more numbers (with spaces), or an empty line to exit: \n"
115 )
116
117 examples <- names(response)
118 }
119
120 examples <- unique(examples)
121
122 if ("all" %in% examples) {
123 examples <- names(choices)
124 }
125
126 if (length(examples) == 0) {
127 return(invisible())
128 }
129
130 if ("tests" %in% examples) {
131 rlang::check_installed("shinytest2", "for {testthat} tests to work as expected", version = "0.2.0")
132 }
133
134 # =======================================================
135 # Utility functions
136 # =======================================================
137
138 # Check if a directory is empty, ignoring certain files
139 dir_is_empty <- function(path) {
140 files <- list.files(path, all.files = TRUE, no.. = TRUE)
141 # Ignore .DS_Store files, which are sometimes automatically created on macOS
142 files <- setdiff(files, ".DS_Store")
143 return(length(files) != 0)
144 }
145
146 # Helper to resolve paths relative to our template
147 template_path <- function(...) {
148 system_file("app_template", ..., package = "shiny")
149 }
150
151 # Resolve path relative to destination
152 dest_path <- function(...) {
153 file.path(path, ...)
154 }
155
156 mkdir <- function(path) {
157 if (!dirExists(path)) {
158 message("Creating ", ensure_trailing_slash(path))
159 if (!dryrun) {
160 dir.create(path, recursive = TRUE)
161 }
162 }
163 }
164
165 # Copy a file from the template directory to the destination directory. If the
166 # file has templating code (it contains `{{` in the text), then run it through
167 # the htmlTemplate().
168 copy_file_one <- function(name) {
169 from <- template_path(name)
170 to <- dest_path(name)
171
172 message("Creating ", to)
173 if (file.exists(to)) {
174 stop(to, " already exists. Please remove it and try again.", call. = FALSE)
175 }
176
177 if (!dryrun) {
178 is_template <- any(grepl("{{", readLines(from), fixed = TRUE))
179
180 if (is_template) {
181 writeChar(
182 as.character(htmlTemplate(
183 from,
184 rdir = "rdir" %in% examples,
185 module = "module" %in% examples
186 )),
187 con = to,
188 eos = NULL
189 )
190 } else {
191 file.copy(from, to)
192 }
193 }
194 }
195
196 # Copy multiple files from template to destination.
197 copy_file <- function(names) {
198 for (name in names) {
199 copy_file_one(name)
200 }
201 }
202
203 # Copy the files for a tests/ subdirectory
204 copy_test_dir <- function() {
205 files <- dir(template_path("tests"), recursive = TRUE)
206
207 # Filter out files that are not module files in the R directory.
208 if (! "rdir" %in% examples) {
209 # find all files in the testthat folder that are not module or server files
210 is_r_folder_file <- !grepl("module|server|shinytest2|testthat", basename(files))
211 files <- files[!is_r_folder_file]
212 }
213
214 # Filter out module files, if applicable.
215 if (! "module" %in% examples) {
216 files <- files[!grepl("module", files)]
217 }
218
219 mkdir(dest_path("tests"))
220
221 # Create any subdirectories if needed
222 dirs <- setdiff(unique(dirname(files)), ".")
223 for (dir in dirs) {
224 mkdir(dest_path("tests", dir))
225 }
226
227 copy_file(file.path("tests", files))
228 }
229
230 # =======================================================
231 # Main function
232 # =======================================================
233
234 if (is.null(path)) {
235 stop("`path` is missing.")
236 }
237 if (file.exists(path) && !dirExists(path)) {
238 stop(path, " exists but is not a directory.")
239 }
240
241 if (dirExists(path) && dir_is_empty(path)) {
242 if (interactive()) {
243 response <- readline(paste0(
244 ensure_trailing_slash(path),
245 " is not empty. Do you want to use this directory anyway? [y/n] "
246 ))
247 if (tolower(response) != "y") {
248 return(invisible())
249 }
250 }
251 } else {
252 mkdir(path)
253 }
254
255 if ("app" %in% examples) {
256 copy_file("app.R")
257 }
258
259 # R/ dir with non-module files
260 if ("rdir" %in% examples) {
261 files <- dir(template_path("R"))
262 non_module_files <- files[!grepl("module.R$", files)]
263 mkdir(dest_path("R"))
264 copy_file(file.path("R", non_module_files))
265 }
266
267 # R/ dir with module files
268 if ("module" %in% examples) {
269 files <- dir(template_path("R"))
270 module_files <- files[grepl("module.R$", files)]
271 mkdir(dest_path("R"))
272 copy_file(file.path("R", module_files))
273 }
274
275 # tests/testthat dir
276 if ("tests" %in% examples) {
277 copy_test_dir()
278 }
279
280 invisible()
281 }