diff --git a/R/add_r_files.R b/R/add_r_files.R index 29fa5108..897d393b 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 @@ -100,17 +100,10 @@ add_r_files <- function( "_" ) } - - where <- fs_path( - "R", - paste0( - module, - ext, - "_", - name, - ".R" - ) - ) + tmp_name <- paste0(module, ext, "_", name, ".R") + # Only if the fct. name is "". + if(name == "" && grepl("_.R$", tmp_name)) tmp_name <- gsub("_.R$", ".R", tmp_name) + where <- fs_path("R", tmp_name) if ( !fs_file_exists( diff --git a/R/utils.R b/R/utils.R index baadf0b9..9f620ece 100644 --- a/R/utils.R +++ b/R/utils.R @@ -331,6 +331,20 @@ 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 <- "" + 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)) + ) + }) +})