Skip to content

Commit 8e7c30d

Browse files
committed
fix 1207
1 parent ab09e64 commit 8e7c30d

File tree

3 files changed

+85
-2
lines changed

3 files changed

+85
-2
lines changed

R/add_r_files.R

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@ add_r_files <- function(
1818
),
1919
"pkg"
2020
)
21-
name <- file_path_sans_ext(
21+
name <- sanitize_r_name(file_path_sans_ext(
2222
name
23-
)
23+
))
2424

2525
check_name_length_is_one(
2626
name

R/utils.R

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,22 @@ check_name_length_is_one <- function(
331331
)
332332
}
333333

334+
# Convert filename to lowercase and replace space/special with underscores
335+
# Similar to janitor::make_clean_names() but without the dependency
336+
sanitize_r_name <- function(name) {
337+
name <- tolower(name)
338+
name <- gsub("[^a-z0-9_]", "_", name)
339+
name <- gsub("^_+|_+$", "", name)
340+
name <- gsub("_+", "_", name)
341+
if (grepl("^[0-9]", name)) {
342+
name <- paste0("x", name)
343+
}
344+
if (name == "" || is.na(name)) {
345+
name <- "unnamed"
346+
}
347+
name
348+
}
349+
334350
do_if_unquiet <- function(
335351
expr
336352
) {

tests/testthat/test-add_r_files.R

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,3 +112,70 @@ test_that("add_fct and add_utils", {
112112
}
113113
)
114114
})
115+
116+
test_that("add_fct sanitizes names correctly", {
117+
run_quietly_in_a_dummy_golem({
118+
# Name with spaces
119+
120+
add_fct(
121+
"ma fonction",
122+
open = FALSE
123+
)
124+
expect_exists(
125+
file.path(
126+
"R",
127+
"fct_ma_fonction.R"
128+
)
129+
)
130+
131+
# Name with special characters
132+
133+
add_fct(
134+
"my-special@function!",
135+
open = FALSE
136+
)
137+
expect_exists(
138+
file.path(
139+
"R",
140+
"fct_my_special_function.R"
141+
)
142+
)
143+
144+
file_content2 <- readLines(
145+
file.path(
146+
"R",
147+
"fct_my_special_function.R"
148+
)
149+
)
150+
expect_true(
151+
any(grepl(
152+
"my_special_function <- function",
153+
file_content2,
154+
fixed = TRUE
155+
))
156+
)
157+
158+
# Name starting with number
159+
160+
add_fct(
161+
"123function",
162+
open = FALSE
163+
)
164+
expect_exists(
165+
file.path(
166+
"R",
167+
"fct_x123function.R"
168+
)
169+
)
170+
171+
file_content3 <- readLines(
172+
file.path(
173+
"R",
174+
"fct_x123function.R"
175+
)
176+
)
177+
expect_true(
178+
any(grepl("x123function <- function", file_content3, fixed = TRUE))
179+
)
180+
})
181+
})

0 commit comments

Comments
 (0)