Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions R/add_r_files.R
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -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
) {
Expand Down
67 changes: 67 additions & 0 deletions tests/testthat/test-add_r_files.R
Original file line number Diff line number Diff line change
Expand Up @@ -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))
)
})
})
Loading