diff --git a/R/add_r_files.R b/R/add_r_files.R index 29fa5108..4c10b87a 100644 --- a/R/add_r_files.R +++ b/R/add_r_files.R @@ -18,9 +18,9 @@ add_r_files <- function( ), "pkg" ) - name <- file_path_sans_ext( + name <- sanitize_r_name(file_path_sans_ext( name - ) + )) check_name_length_is_one( name diff --git a/R/utils.R b/R/utils.R index baadf0b9..bfa18327 100644 --- a/R/utils.R +++ b/R/utils.R @@ -331,6 +331,22 @@ check_name_length_is_one <- function( ) } +# Convert filename to lowercase and replace space/special with underscores +# Similar to janitor::make_clean_names() but without the dependency +sanitize_r_name <- function(name) { + name <- tolower(name) + name <- gsub("[^a-z0-9_]", "_", name) + name <- gsub("^_+|_+$", "", name) + name <- gsub("_+", "_", name) + if (grepl("^[0-9]", name)) { + name <- paste0("x", name) + } + if (name == "" || is.na(name)) { + name <- "unnamed" + } + name +} + do_if_unquiet <- function( expr ) { diff --git a/tests/testthat/test-add_r_files.R b/tests/testthat/test-add_r_files.R index 3a798601..fe957b71 100644 --- a/tests/testthat/test-add_r_files.R +++ b/tests/testthat/test-add_r_files.R @@ -112,3 +112,70 @@ test_that("add_fct and add_utils", { } ) }) + +test_that("add_fct sanitizes names correctly", { + run_quietly_in_a_dummy_golem({ + # Name with spaces + + add_fct( + "ma fonction", + open = FALSE + ) + expect_exists( + file.path( + "R", + "fct_ma_fonction.R" + ) + ) + + # Name with special characters + + add_fct( + "my-special@function!", + open = FALSE + ) + expect_exists( + file.path( + "R", + "fct_my_special_function.R" + ) + ) + + file_content2 <- readLines( + file.path( + "R", + "fct_my_special_function.R" + ) + ) + expect_true( + any(grepl( + "my_special_function <- function", + file_content2, + fixed = TRUE + )) + ) + + # Name starting with number + + add_fct( + "123function", + open = FALSE + ) + expect_exists( + file.path( + "R", + "fct_x123function.R" + ) + ) + + file_content3 <- readLines( + file.path( + "R", + "fct_x123function.R" + ) + ) + expect_true( + any(grepl("x123function <- function", file_content3, fixed = TRUE)) + ) + }) +})